File:  [LON-CAPA] / loncom / interface / loncommon.pm
Revision 1.1075.2.161.2.10: download - view: text, annotated - select for diffs
Mon Sep 19 19:23:12 2022 UTC (20 months, 1 week ago) by raeburn
Branches: version_2_11_4_msu
- For 2.11.4 (modified)
  Include changes in 1.1387, 1.1388

    1: # The LearningOnline Network with CAPA
    2: # a pile of common routines
    3: #
    4: # $Id: loncommon.pm,v 1.1075.2.161.2.10 2022/09/19 19:23:12 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: # -----------------------------------------------------------------------------
 3838: 
 3839: sub track_student_link {
 3840:     my ($linktext,$sname,$sdom,$target,$start,$only_body) = @_;
 3841:     my $link ="/adm/trackstudent?";
 3842:     my $title = 'View recent activity';
 3843:     if (defined($sname) && $sname !~ /^\s*$/ &&
 3844:         defined($sdom)  && $sdom  !~ /^\s*$/) {
 3845:         $link .= "selected_student=$sname:$sdom";
 3846:         $title .= ' of this student';
 3847:     } 
 3848:     if (defined($target) && $target !~ /^\s*$/) {
 3849:         $target = qq{target="$target"};
 3850:     } else {
 3851:         $target = '';
 3852:     }
 3853:     if ($start) { $link.='&amp;start='.$start; }
 3854:     if ($only_body) { $link .= '&amp;only_body=1'; }
 3855:     $title = &mt($title);
 3856:     $linktext = &mt($linktext);
 3857:     return qq{<a href="$link" title="$title" $target>$linktext</a>}.
 3858: 	&help_open_topic('View_recent_activity');
 3859: }
 3860: 
 3861: sub slot_reservations_link {
 3862:     my ($linktext,$sname,$sdom,$target) = @_;
 3863:     my $link ="/adm/slotrequest?command=showresv&amp;origin=aboutme";
 3864:     my $title = 'View slot reservation history';
 3865:     if (defined($sname) && $sname !~ /^\s*$/ &&
 3866:         defined($sdom)  && $sdom  !~ /^\s*$/) {
 3867:         $link .= "&amp;uname=$sname&amp;udom=$sdom";
 3868:         $title .= ' of this student';
 3869:     }
 3870:     if (defined($target) && $target !~ /^\s*$/) {
 3871:         $target = qq{target="$target"};
 3872:     } else {
 3873:         $target = '';
 3874:     }
 3875:     $title = &mt($title);
 3876:     $linktext = &mt($linktext);
 3877:     return qq{<a href="$link" title="$title" $target>$linktext</a>};
 3878: # FIXME uncomment when help item created: &help_open_topic('Slot_Reservation_History');
 3879: 
 3880: }
 3881: 
 3882: # ===================================================== Display a student photo
 3883: 
 3884: 
 3885: sub student_image_tag {
 3886:     my ($domain,$user)=@_;
 3887:     my $imgsrc=&Apache::lonnet::studentphoto($domain,$user,'jpg');
 3888:     if (($imgsrc) && ($imgsrc ne '/adm/lonKaputt/lonlogo_broken.gif')) {
 3889: 	return '<img src="'.$imgsrc.'" align="right" />';
 3890:     } else {
 3891: 	return '';
 3892:     }
 3893: }
 3894: 
 3895: =pod
 3896: 
 3897: =back
 3898: 
 3899: =head1 Access .tab File Data
 3900: 
 3901: =over 4
 3902: 
 3903: =item * &languageids() 
 3904: 
 3905: returns list of all language ids
 3906: 
 3907: =cut
 3908: 
 3909: sub languageids {
 3910:     return sort(keys(%language));
 3911: }
 3912: 
 3913: =pod
 3914: 
 3915: =item * &languagedescription() 
 3916: 
 3917: returns description of a specified language id
 3918: 
 3919: =cut
 3920: 
 3921: sub languagedescription {
 3922:     my $code=shift;
 3923:     return  ($supported_language{$code}?'* ':'').
 3924:             $language{$code}.
 3925: 	    ($supported_language{$code}?' ('.&mt('interface available').')':'');
 3926: }
 3927: 
 3928: =pod
 3929: 
 3930: =item * &plainlanguagedescription
 3931: 
 3932: Returns both the plain language description (e.g. 'Creoles and Pidgins, English-based (Other)')
 3933: and the language character encoding (e.g. ISO) separated by a ' - ' string.
 3934: 
 3935: =cut
 3936: 
 3937: sub plainlanguagedescription {
 3938:     my $code=shift;
 3939:     return $language{$code};
 3940: }
 3941: 
 3942: =pod
 3943: 
 3944: =item * &supportedlanguagecode
 3945: 
 3946: Returns the supported language code (e.g. sptutf maps to pt) given a language
 3947: code.
 3948: 
 3949: =cut
 3950: 
 3951: sub supportedlanguagecode {
 3952:     my $code=shift;
 3953:     return $supported_language{$code};
 3954: }
 3955: 
 3956: =pod
 3957: 
 3958: =item * &latexlanguage()
 3959: 
 3960: Given a language key code returns the correspondnig language to use
 3961: to select the correct hyphenation on LaTeX printouts.  This is undef if there
 3962: is no supported hyphenation for the language code.
 3963: 
 3964: =cut
 3965: 
 3966: sub latexlanguage {
 3967:     my $code = shift;
 3968:     return $latex_language{$code};
 3969: }
 3970: 
 3971: =pod
 3972: 
 3973: =item * &latexhyphenation()
 3974: 
 3975: Same as above but what's supplied is the language as it might be stored
 3976: in the metadata.
 3977: 
 3978: =cut
 3979: 
 3980: sub latexhyphenation {
 3981:     my $key = shift;
 3982:     return $latex_language_bykey{$key};
 3983: }
 3984: 
 3985: =pod
 3986: 
 3987: =item * &copyrightids() 
 3988: 
 3989: returns list of all copyrights
 3990: 
 3991: =cut
 3992: 
 3993: sub copyrightids {
 3994:     return sort(keys(%cprtag));
 3995: }
 3996: 
 3997: =pod
 3998: 
 3999: =item * &copyrightdescription() 
 4000: 
 4001: returns description of a specified copyright id
 4002: 
 4003: =cut
 4004: 
 4005: sub copyrightdescription {
 4006:     return &mt($cprtag{shift(@_)});
 4007: }
 4008: 
 4009: =pod
 4010: 
 4011: =item * &source_copyrightids() 
 4012: 
 4013: returns list of all source copyrights
 4014: 
 4015: =cut
 4016: 
 4017: sub source_copyrightids {
 4018:     return sort(keys(%scprtag));
 4019: }
 4020: 
 4021: =pod
 4022: 
 4023: =item * &source_copyrightdescription() 
 4024: 
 4025: returns description of a specified source copyright id
 4026: 
 4027: =cut
 4028: 
 4029: sub source_copyrightdescription {
 4030:     return &mt($scprtag{shift(@_)});
 4031: }
 4032: 
 4033: =pod
 4034: 
 4035: =item * &filecategories() 
 4036: 
 4037: returns list of all file categories
 4038: 
 4039: =cut
 4040: 
 4041: sub filecategories {
 4042:     return sort(keys(%category_extensions));
 4043: }
 4044: 
 4045: =pod
 4046: 
 4047: =item * &filecategorytypes() 
 4048: 
 4049: returns list of file types belonging to a given file
 4050: category
 4051: 
 4052: =cut
 4053: 
 4054: sub filecategorytypes {
 4055:     my ($cat) = @_;
 4056:     return @{$category_extensions{lc($cat)}};
 4057: }
 4058: 
 4059: =pod
 4060: 
 4061: =item * &fileembstyle() 
 4062: 
 4063: returns embedding style for a specified file type
 4064: 
 4065: =cut
 4066: 
 4067: sub fileembstyle {
 4068:     return $fe{lc(shift(@_))};
 4069: }
 4070: 
 4071: sub filemimetype {
 4072:     return $fm{lc(shift(@_))};
 4073: }
 4074: 
 4075: 
 4076: sub filecategoryselect {
 4077:     my ($name,$value)=@_;
 4078:     return &select_form($value,$name,
 4079:                         {'' => &mt('Any category'), map { $_,$_ } sort(keys(%category_extensions))});
 4080: }
 4081: 
 4082: =pod
 4083: 
 4084: =item * &filedescription() 
 4085: 
 4086: returns description for a specified file type
 4087: 
 4088: =cut
 4089: 
 4090: sub filedescription {
 4091:     my $file_description = $fd{lc(shift())};
 4092:     $file_description =~ s:([\[\]]):~$1:g;
 4093:     return &mt($file_description);
 4094: }
 4095: 
 4096: =pod
 4097: 
 4098: =item * &filedescriptionex() 
 4099: 
 4100: returns description for a specified file type with
 4101: extra formatting
 4102: 
 4103: =cut
 4104: 
 4105: sub filedescriptionex {
 4106:     my $ex=shift;
 4107:     my $file_description = $fd{lc($ex)};
 4108:     $file_description =~ s:([\[\]]):~$1:g;
 4109:     return '.'.$ex.' '.&mt($file_description);
 4110: }
 4111: 
 4112: # End of .tab access
 4113: =pod
 4114: 
 4115: =back
 4116: 
 4117: =cut
 4118: 
 4119: # ------------------------------------------------------------------ File Types
 4120: sub fileextensions {
 4121:     return sort(keys(%fe));
 4122: }
 4123: 
 4124: # ----------------------------------------------------------- Display Languages
 4125: # returns a hash with all desired display languages
 4126: #
 4127: 
 4128: sub display_languages {
 4129:     my %languages=();
 4130:     foreach my $lang (&Apache::lonlocal::preferred_languages()) {
 4131: 	$languages{$lang}=1;
 4132:     }
 4133:     &get_unprocessed_cgi($ENV{'QUERY_STRING'},['displaylanguage']);
 4134:     if ($env{'form.displaylanguage'}) {
 4135: 	foreach my $lang (split(/\s*(\,|\;|\:)\s*/,$env{'form.displaylanguage'})) {
 4136: 	    $languages{$lang}=1;
 4137:         }
 4138:     }
 4139:     return %languages;
 4140: }
 4141: 
 4142: sub languages {
 4143:     my ($possible_langs) = @_;
 4144:     my @preferred_langs = &Apache::lonlocal::preferred_languages();
 4145:     if (!ref($possible_langs)) {
 4146: 	if( wantarray ) {
 4147: 	    return @preferred_langs;
 4148: 	} else {
 4149: 	    return $preferred_langs[0];
 4150: 	}
 4151:     }
 4152:     my %possibilities = map { $_ => 1 } (@$possible_langs);
 4153:     my @preferred_possibilities;
 4154:     foreach my $preferred_lang (@preferred_langs) {
 4155: 	if (exists($possibilities{$preferred_lang})) {
 4156: 	    push(@preferred_possibilities, $preferred_lang);
 4157: 	}
 4158:     }
 4159:     if( wantarray ) {
 4160: 	return @preferred_possibilities;
 4161:     }
 4162:     return $preferred_possibilities[0];
 4163: }
 4164: 
 4165: sub user_lang {
 4166:     my ($touname,$toudom,$fromcid) = @_;
 4167:     my @userlangs;
 4168:     if (($fromcid ne '') && ($env{'course.'.$fromcid.'.languages'} ne '')) {
 4169:         @userlangs=(@userlangs,split(/\s*(\,|\;|\:)\s*/,
 4170:                     $env{'course.'.$fromcid.'.languages'}));
 4171:     } else {
 4172:         my %langhash = &getlangs($touname,$toudom);
 4173:         if ($langhash{'languages'} ne '') {
 4174:             @userlangs = split(/\s*(\,|\;|\:)\s*/,$langhash{'languages'});
 4175:         } else {
 4176:             my %domdefs = &Apache::lonnet::get_domain_defaults($toudom);
 4177:             if ($domdefs{'lang_def'} ne '') {
 4178:                 @userlangs = ($domdefs{'lang_def'});
 4179:             }
 4180:         }
 4181:     }
 4182:     my @languages=&Apache::lonlocal::get_genlanguages(@userlangs);
 4183:     my $user_lh = Apache::localize->get_handle(@languages);
 4184:     return $user_lh;
 4185: }
 4186: 
 4187: 
 4188: ###############################################################
 4189: ##               Student Answer Attempts                     ##
 4190: ###############################################################
 4191: 
 4192: =pod
 4193: 
 4194: =head1 Alternate Problem Views
 4195: 
 4196: =over 4
 4197: 
 4198: =item * &get_previous_attempt($symb, $username, $domain, $course,
 4199:     $getattempt, $regexp, $gradesub, $usec, $identifier)
 4200: 
 4201: Return string with previous attempt on problem. Arguments:
 4202: 
 4203: =over 4
 4204: 
 4205: =item * $symb: Problem, including path
 4206: 
 4207: =item * $username: username of the desired student
 4208: 
 4209: =item * $domain: domain of the desired student
 4210: 
 4211: =item * $course: Course ID
 4212: 
 4213: =item * $getattempt: Leave blank for all attempts, otherwise put
 4214:     something
 4215: 
 4216: =item * $regexp: if string matches this regexp, the string will be
 4217:     sent to $gradesub
 4218: 
 4219: =item * $gradesub: routine that processes the string if it matches $regexp
 4220: 
 4221: =item * $usec: section of the desired student
 4222: 
 4223: =item * $identifier: counter for student (multiple students one problem) or
 4224:     problem (one student; whole sequence).
 4225: 
 4226: =back
 4227: 
 4228: The output string is a table containing all desired attempts, if any.
 4229: 
 4230: =cut
 4231: 
 4232: sub get_previous_attempt {
 4233:   my ($symb,$username,$domain,$course,$getattempt,$regexp,$gradesub,$usec,$identifier)=@_;
 4234:   my $prevattempts='';
 4235:   no strict 'refs';
 4236:   if ($symb) {
 4237:     my (%returnhash)=
 4238:       &Apache::lonnet::restore($symb,$course,$domain,$username);
 4239:     if ($returnhash{'version'}) {
 4240:       my %lasthash=();
 4241:       my $version;
 4242:       for ($version=1;$version<=$returnhash{'version'};$version++) {
 4243:         foreach my $key (reverse(sort(split(/\:/,$returnhash{$version.':keys'})))) {
 4244:             if ($key =~ /\.rawrndseed$/) {
 4245:                 my ($id) = ($key =~ /^(.+)\.rawrndseed$/);
 4246:                 $lasthash{$id.'.rndseed'} = $returnhash{$version.':'.$key};
 4247:             } else {
 4248:                 $lasthash{$key}=$returnhash{$version.':'.$key};
 4249:             }
 4250:         }
 4251:       }
 4252:       $prevattempts=&start_data_table().&start_data_table_header_row();
 4253:       $prevattempts.='<th>'.&mt('History').'</th>';
 4254:       my (%typeparts,%lasthidden,%regraded,%hidestatus);
 4255:       my $showsurv=&Apache::lonnet::allowed('vas',$env{'request.course.id'});
 4256:       foreach my $key (sort(keys(%lasthash))) {
 4257: 	my ($ign,@parts) = split(/\./,$key);
 4258: 	if ($#parts > 0) {
 4259: 	  my $data=$parts[-1];
 4260:           next if ($data eq 'foilorder');
 4261: 	  pop(@parts);
 4262:           $prevattempts.='<th>'.&mt('Part ').join('.',@parts).'<br />'.$data.'&nbsp;</th>';
 4263:           if ($data eq 'type') {
 4264:               unless ($showsurv) {
 4265:                   my $id = join(',',@parts);
 4266:                   $typeparts{$ign.'.'.$id} = $lasthash{$key};
 4267:                   if (($lasthash{$key} eq 'anonsurvey') || ($lasthash{$key} eq 'anonsurveycred')) {
 4268:                       $lasthidden{$ign.'.'.$id} = 1;
 4269:                   }
 4270:               }
 4271:               if ($identifier ne '') {
 4272:                   my $id = join(',',@parts);
 4273:                   if (&Apache::lonnet::EXT("resource.$id.problemstatus",$symb,
 4274:                                                $domain,$username,$usec,undef,$course) =~ /^no/) {
 4275:                       $hidestatus{$ign.'.'.$id} = 1;
 4276:                   }
 4277:               }
 4278:           } elsif ($data eq 'regrader') {
 4279:               if (($identifier ne '') && (@parts)) {
 4280:                   my $id = join(',',@parts);
 4281:                   $regraded{$ign.'.'.$id} = 1;
 4282:               }
 4283:           } 
 4284: 	} else {
 4285: 	  if ($#parts == 0) {
 4286: 	    $prevattempts.='<th>'.$parts[0].'</th>';
 4287: 	  } else {
 4288: 	    $prevattempts.='<th>'.$ign.'</th>';
 4289: 	  }
 4290: 	}
 4291:       }
 4292:       $prevattempts.=&end_data_table_header_row();
 4293:       if ($getattempt eq '') {
 4294:         my (%solved,%resets,%probstatus);
 4295:         if (($identifier ne '') && (keys(%regraded) > 0)) {
 4296:             for ($version=1;$version<=$returnhash{'version'};$version++) {
 4297:                 foreach my $id (keys(%regraded)) {
 4298:                     if (($returnhash{$version.':'.$id.'.regrader'}) &&
 4299:                         ($returnhash{$version.':'.$id.'.tries'} eq '') &&
 4300:                         ($returnhash{$version.':'.$id.'.award'} eq '')) {
 4301:                         push(@{$resets{$id}},$version);
 4302:                     }
 4303:                 }
 4304:             }
 4305:         }
 4306: 	for ($version=1;$version<=$returnhash{'version'};$version++) {
 4307:             my (@hidden,@unsolved);
 4308:             if (%typeparts) {
 4309:                 foreach my $id (keys(%typeparts)) {
 4310:                     if (($returnhash{$version.':'.$id.'.type'} eq 'anonsurvey') ||
 4311:                         ($returnhash{$version.':'.$id.'.type'} eq 'anonsurveycred')) {
 4312:                         push(@hidden,$id);
 4313:                     } elsif ($identifier ne '') {
 4314:                         unless (($returnhash{$version.':'.$id.'.type'} eq 'survey') ||
 4315:                                 ($returnhash{$version.':'.$id.'.type'} eq 'surveycred') ||
 4316:                                 ($hidestatus{$id})) {
 4317:                             next if ((ref($resets{$id}) eq 'ARRAY') && grep(/^\Q$version\E$/,@{$resets{$id}}));
 4318:                             if ($returnhash{$version.':'.$id.'.solved'} eq 'correct_by_student') {
 4319:                                 push(@{$solved{$id}},$version);
 4320:                             } elsif (($returnhash{$version.':'.$id.'.solved'} ne '') &&
 4321:                                      (ref($solved{$id}) eq 'ARRAY')) {
 4322:                                 my $skip;
 4323:                                 if (ref($resets{$id}) eq 'ARRAY') {
 4324:                                     foreach my $reset (@{$resets{$id}}) {
 4325:                                         if ($reset > $solved{$id}[-1]) {
 4326:                                             $skip=1;
 4327:                                             last;
 4328:                                         }
 4329:                                     }
 4330:                                 }
 4331:                                 unless ($skip) {
 4332:                                     my ($ign,$partslist) = split(/\./,$id,2);
 4333:                                     push(@unsolved,$partslist);
 4334:                                 }
 4335:                             }
 4336:                         }
 4337:                     }
 4338:                 }
 4339:             }
 4340:             $prevattempts.=&start_data_table_row().
 4341:                            '<td>'.&mt('Transaction [_1]',$version);
 4342:             if (@unsolved) {
 4343:                 $prevattempts .= '<span class="LC_nobreak"><label>'.
 4344:                                  '<input type="checkbox" name="HIDE'.$identifier.'" value="'.$version.':'.join('_',@unsolved).'" />'.
 4345:                                  &mt('Hide').'</label></span>';
 4346:             }
 4347:             $prevattempts .= '</td>';
 4348:             if (@hidden) {
 4349:                 foreach my $key (sort(keys(%lasthash))) {
 4350:                     next if ($key =~ /\.foilorder$/);
 4351:                     my $hide;
 4352:                     foreach my $id (@hidden) {
 4353:                         if ($key =~ /^\Q$id\E/) {
 4354:                             $hide = 1;
 4355:                             last;
 4356:                         }
 4357:                     }
 4358:                     if ($hide) {
 4359:                         my ($id,$data) = ($key =~ /^(.+)\.([^.]+)$/);
 4360:                         if (($data eq 'award') || ($data eq 'awarddetail')) {
 4361:                             my $value = &format_previous_attempt_value($key,
 4362:                                              $returnhash{$version.':'.$key});
 4363:                             $prevattempts.='<td>'.$value.'&nbsp;</td>';
 4364:                         } else {
 4365:                             $prevattempts.='<td>&nbsp;</td>';
 4366:                         }
 4367:                     } else {
 4368:                         if ($key =~ /\./) {
 4369:                             my $value = $returnhash{$version.':'.$key};
 4370:                             if ($key =~ /\.rndseed$/) {
 4371:                                 my ($id) = ($key =~ /^(.+)\.rndseed$/);
 4372:                                 if (exists($returnhash{$version.':'.$id.'.rawrndseed'})) {
 4373:                                     $value = $returnhash{$version.':'.$id.'.rawrndseed'};
 4374:                                 }
 4375:                             }
 4376:                             $prevattempts.='<td>'.&format_previous_attempt_value($key,$value).
 4377:                                            '&nbsp;</td>';
 4378:                         } else {
 4379:                             $prevattempts.='<td>&nbsp;</td>';
 4380:                         }
 4381:                     }
 4382:                 }
 4383:             } else {
 4384: 	        foreach my $key (sort(keys(%lasthash))) {
 4385:                     next if ($key =~ /\.foilorder$/);
 4386:                     my $value = $returnhash{$version.':'.$key};
 4387:                     if ($key =~ /\.rndseed$/) {
 4388:                         my ($id) = ($key =~ /^(.+)\.rndseed$/);
 4389:                         if (exists($returnhash{$version.':'.$id.'.rawrndseed'})) {
 4390:                             $value = $returnhash{$version.':'.$id.'.rawrndseed'};
 4391:                         }
 4392:                     }
 4393:                     $prevattempts.='<td>'.&format_previous_attempt_value($key,$value).
 4394:                                    '&nbsp;</td>';
 4395: 	        }
 4396:             }
 4397: 	    $prevattempts.=&end_data_table_row();
 4398: 	 }
 4399:       }
 4400:       my @currhidden = keys(%lasthidden);
 4401:       $prevattempts.=&start_data_table_row().'<td>'.&mt('Current').'</td>';
 4402:       foreach my $key (sort(keys(%lasthash))) {
 4403:           next if ($key =~ /\.foilorder$/);
 4404:           if (%typeparts) {
 4405:               my $hidden;
 4406:               foreach my $id (@currhidden) {
 4407:                   if ($key =~ /^\Q$id\E/) {
 4408:                       $hidden = 1;
 4409:                       last;
 4410:                   }
 4411:               }
 4412:               if ($hidden) {
 4413:                   my ($id,$data) = ($key =~ /^(.+)\.([^.]+)$/);
 4414:                   if (($data eq 'award') || ($data eq 'awarddetail')) {
 4415:                       my $value = &format_previous_attempt_value($key,$lasthash{$key});
 4416:                       if ($key =~/$regexp$/ && (defined &$gradesub)) {
 4417:                           $value = &$gradesub($value);
 4418:                       }
 4419:                       $prevattempts.='<td>'.$value.'&nbsp;</td>';
 4420:                   } else {
 4421:                       $prevattempts.='<td>&nbsp;</td>';
 4422:                   }
 4423:               } else {
 4424:                   my $value = &format_previous_attempt_value($key,$lasthash{$key});
 4425:                   if ($key =~/$regexp$/ && (defined &$gradesub)) {
 4426:                       $value = &$gradesub($value);
 4427:                   }
 4428:                   $prevattempts.='<td>'.$value.'&nbsp;</td>';
 4429:               }
 4430:           } else {
 4431: 	      my $value = &format_previous_attempt_value($key,$lasthash{$key});
 4432: 	      if ($key =~/$regexp$/ && (defined &$gradesub)) {
 4433:                   $value = &$gradesub($value);
 4434:               }
 4435: 	      $prevattempts.='<td>'.$value.'&nbsp;</td>';
 4436:           }
 4437:       }
 4438:       $prevattempts.= &end_data_table_row().&end_data_table();
 4439:     } else {
 4440:       $prevattempts=
 4441: 	  &start_data_table().&start_data_table_row().
 4442: 	  '<td>'.&mt('Nothing submitted - no attempts.').'</td>'.
 4443: 	  &end_data_table_row().&end_data_table();
 4444:     }
 4445:   } else {
 4446:     $prevattempts=
 4447: 	  &start_data_table().&start_data_table_row().
 4448: 	  '<td>'.&mt('No data.').'</td>'.
 4449: 	  &end_data_table_row().&end_data_table();
 4450:   }
 4451: }
 4452: 
 4453: sub format_previous_attempt_value {
 4454:     my ($key,$value) = @_;
 4455:     if (($key =~ /timestamp/) || ($key=~/duedate/)) {
 4456: 	$value = &Apache::lonlocal::locallocaltime($value);
 4457:     } elsif (ref($value) eq 'ARRAY') {
 4458: 	$value = '('.join(', ', @{ $value }).')';
 4459:     } elsif ($key =~ /answerstring$/) {
 4460:         my %answers = &Apache::lonnet::str2hash($value);
 4461:         my @anskeys = sort(keys(%answers));
 4462:         if (@anskeys == 1) {
 4463:             my $answer = $answers{$anskeys[0]};
 4464:             if ($answer =~ m{\0}) {
 4465:                 $answer =~ s{\0}{,}g;
 4466:             }
 4467:             my $tag_internal_answer_name = 'INTERNAL';
 4468:             if ($anskeys[0] eq $tag_internal_answer_name) {
 4469:                 $value = $answer; 
 4470:             } else {
 4471:                 $value = $anskeys[0].'='.$answer;
 4472:             }
 4473:         } else {
 4474:             foreach my $ans (@anskeys) {
 4475:                 my $answer = $answers{$ans};
 4476:                 if ($answer =~ m{\0}) {
 4477:                     $answer =~ s{\0}{,}g;
 4478:                 }
 4479:                 $value .=  $ans.'='.$answer.'<br />';;
 4480:             } 
 4481:         }
 4482:     } else {
 4483: 	$value = &unescape($value);
 4484:     }
 4485:     return $value;
 4486: }
 4487: 
 4488: 
 4489: sub relative_to_absolute {
 4490:     my ($url,$output)=@_;
 4491:     my $parser=HTML::TokeParser->new(\$output);
 4492:     my $token;
 4493:     my $thisdir=$url;
 4494:     my @rlinks=();
 4495:     while ($token=$parser->get_token) {
 4496: 	if ($token->[0] eq 'S') {
 4497: 	    if ($token->[1] eq 'a') {
 4498: 		if ($token->[2]->{'href'}) {
 4499: 		    $rlinks[$#rlinks+1]=$token->[2]->{'href'};
 4500: 		}
 4501: 	    } elsif ($token->[1] eq 'img' || $token->[1] eq 'embed' ) {
 4502: 		$rlinks[$#rlinks+1]=$token->[2]->{'src'};
 4503: 	    } elsif ($token->[1] eq 'base') {
 4504: 		$thisdir=$token->[2]->{'href'};
 4505: 	    }
 4506: 	}
 4507:     }
 4508:     $thisdir=~s-/[^/]*$--;
 4509:     foreach my $link (@rlinks) {
 4510: 	unless (($link=~/^https?\:\/\//i) ||
 4511: 		($link=~/^\//) ||
 4512: 		($link=~/^javascript:/i) ||
 4513: 		($link=~/^mailto:/i) ||
 4514: 		($link=~/^\#/)) {
 4515: 	    my $newlocation=&Apache::lonnet::hreflocation($thisdir,$link);
 4516: 	    $output=~s/(\"|\'|\=\s*)\Q$link\E(\"|\'|\s|\>)/$1$newlocation$2/;
 4517: 	}
 4518:     }
 4519: # -------------------------------------------------- Deal with Applet codebases
 4520:     $output=~s/(\<applet[^\>]+)(codebase\=[^\S\>]+)*([^\>]*)\>/$1.($2?$2:' codebase="'.$thisdir.'"').$3.'>'/gei;
 4521:     return $output;
 4522: }
 4523: 
 4524: =pod
 4525: 
 4526: =item * &get_student_view()
 4527: 
 4528: show a snapshot of what student was looking at
 4529: 
 4530: =cut
 4531: 
 4532: sub get_student_view {
 4533:   my ($symb,$username,$domain,$courseid,$target,$moreenv) = @_;
 4534:   my ($map,$id,$feedurl) = &Apache::lonnet::decode_symb($symb);
 4535:   my (%form);
 4536:   my @elements=('symb','courseid','domain','username');
 4537:   foreach my $element (@elements) {
 4538:       $form{'grade_'.$element}=eval '$'.$element #'
 4539:   }
 4540:   if (defined($moreenv)) {
 4541:       %form=(%form,%{$moreenv});
 4542:   }
 4543:   if (defined($target)) { $form{'grade_target'} = $target; }
 4544:   $feedurl=&Apache::lonnet::clutter($feedurl);
 4545:   my ($userview,$response)=&Apache::lonnet::ssi_body($feedurl,%form);
 4546:   $userview=~s/\<body[^\>]*\>//gi;
 4547:   $userview=~s/\<\/body\>//gi;
 4548:   $userview=~s/\<html\>//gi;
 4549:   $userview=~s/\<\/html\>//gi;
 4550:   $userview=~s/\<head\>//gi;
 4551:   $userview=~s/\<\/head\>//gi;
 4552:   $userview=~s/action\s*\=/would_be_action\=/gi;
 4553:   $userview=&relative_to_absolute($feedurl,$userview);
 4554:   if (wantarray) {
 4555:      return ($userview,$response);
 4556:   } else {
 4557:      return $userview;
 4558:   }
 4559: }
 4560: 
 4561: sub get_student_view_with_retries {
 4562:   my ($symb,$retries,$username,$domain,$courseid,$target,$moreenv) = @_;
 4563: 
 4564:     my $ok = 0;                 # True if we got a good response.
 4565:     my $content;
 4566:     my $response;
 4567: 
 4568:     # Try to get the student_view done. within the retries count:
 4569:     
 4570:     do {
 4571:          ($content, $response) = &get_student_view($symb,$username,$domain,$courseid,$target,$moreenv);
 4572:          $ok      = $response->is_success;
 4573:          if (!$ok) {
 4574:             &Apache::lonnet::logthis("Failed get_student_view_with_retries on $symb: ".$response->is_success.', '.$response->code.', '.$response->message);
 4575:          }
 4576:          $retries--;
 4577:     } while (!$ok && ($retries > 0));
 4578:     
 4579:     if (!$ok) {
 4580:        $content = '';          # On error return an empty content.
 4581:     }
 4582:     if (wantarray) {
 4583:        return ($content, $response);
 4584:     } else {
 4585:        return $content;
 4586:     }
 4587: }
 4588: 
 4589: sub css_links {
 4590:     my ($currsymb,$level) = @_;
 4591:     my ($links,@symbs,%cssrefs,%httpref);
 4592:     if ($level eq 'map') {
 4593:         my $navmap = Apache::lonnavmaps::navmap->new();
 4594:         if (ref($navmap)) {
 4595:             my ($map,undef,$url)=&Apache::lonnet::decode_symb($currsymb);
 4596:             my @resources = $navmap->retrieveResources($map,sub { $_[0]->is_problem() },0,0);
 4597:             foreach my $res (@resources) {
 4598:                 if (ref($res) && $res->symb()) {
 4599:                     push(@symbs,$res->symb());
 4600:                 }
 4601:             }
 4602:         }
 4603:     } else {
 4604:         @symbs = ($currsymb);
 4605:     }
 4606:     foreach my $symb (@symbs) {
 4607:         my $css_href = &Apache::lonnet::EXT('resource.0.cssfile',$symb);
 4608:         if ($css_href =~ /\S/) {
 4609:             unless ($css_href =~ m{https?://}) {
 4610:                 my $url = (&Apache::lonnet::decode_symb($symb))[-1];
 4611:                 my $proburl =  &Apache::lonnet::clutter($url);
 4612:                 my ($probdir) = ($proburl =~ m{(.+)/[^/]+$});
 4613:                 unless ($css_href =~ m{^/}) {
 4614:                     $css_href = &Apache::lonnet::hreflocation($probdir,$css_href);
 4615:                 }
 4616:                 if ($css_href =~ m{^/(res|uploaded)/}) {
 4617:                     unless (($httpref{'httpref.'.$css_href}) ||
 4618:                             (&Apache::lonnet::is_on_map($css_href))) {
 4619:                         my $thisurl = $proburl;
 4620:                         if ($env{'httpref.'.$proburl}) {
 4621:                             $thisurl = $env{'httpref.'.$proburl};
 4622:                         }
 4623:                         $httpref{'httpref.'.$css_href} = $thisurl;
 4624:                     }
 4625:                 }
 4626:             }
 4627:             $cssrefs{$css_href} = 1;
 4628:         }
 4629:     }
 4630:     if (keys(%httpref)) {
 4631:         &Apache::lonnet::appenv(\%httpref);
 4632:     }
 4633:     if (keys(%cssrefs)) {
 4634:         foreach my $css_href (keys(%cssrefs)) {
 4635:             next unless ($css_href =~ m{^(/res/|/uploaded/|https?://)});
 4636:             $links .= '<link rel="stylesheet" type="text/css" href="'.$css_href.'" />'."\n";
 4637:         }
 4638:     }
 4639:     return $links;
 4640: }
 4641: 
 4642: =pod
 4643: 
 4644: =item * &get_student_answers() 
 4645: 
 4646: show a snapshot of how student was answering problem
 4647: 
 4648: =cut
 4649: 
 4650: sub get_student_answers {
 4651:   my ($symb,$username,$domain,$courseid,%form) = @_;
 4652:   my ($map,$id,$feedurl) = &Apache::lonnet::decode_symb($symb);
 4653:   my (%moreenv);
 4654:   my @elements=('symb','courseid','domain','username');
 4655:   foreach my $element (@elements) {
 4656:     $moreenv{'grade_'.$element}=eval '$'.$element #'
 4657:   }
 4658:   $moreenv{'grade_target'}='answer';
 4659:   %moreenv=(%form,%moreenv);
 4660:   $feedurl = &Apache::lonnet::clutter($feedurl);
 4661:   my $userview=&Apache::lonnet::ssi($feedurl,%moreenv);
 4662:   return $userview;
 4663: }
 4664: 
 4665: =pod
 4666: 
 4667: =item * &submlink()
 4668: 
 4669: Inputs: $text $uname $udom $symb $target
 4670: 
 4671: Returns: A link to grades.pm such as to see the SUBM view of a student
 4672: 
 4673: =cut
 4674: 
 4675: ###############################################
 4676: sub submlink {
 4677:     my ($text,$uname,$udom,$symb,$target)=@_;
 4678:     if (!($uname && $udom)) {
 4679: 	(my $cursymb, my $courseid,$udom,$uname)=
 4680: 	    &Apache::lonnet::whichuser($symb);
 4681: 	if (!$symb) { $symb=$cursymb; }
 4682:     }
 4683:     if (!$symb) { $symb=&Apache::lonnet::symbread(); }
 4684:     $symb=&escape($symb);
 4685:     if ($target) { $target=" target=\"$target\""; }
 4686:     return
 4687:         '<a href="/adm/grades?command=submission'.
 4688:         '&amp;symb='.$symb.
 4689:         '&amp;student='.$uname.
 4690:         '&amp;userdom='.$udom.'"'.
 4691:         $target.'>'.$text.'</a>';
 4692: }
 4693: ##############################################
 4694: 
 4695: =pod
 4696: 
 4697: =item * &pgrdlink()
 4698: 
 4699: Inputs: $text $uname $udom $symb $target
 4700: 
 4701: Returns: A link to grades.pm such as to see the PGRD view of a student
 4702: 
 4703: =cut
 4704: 
 4705: ###############################################
 4706: sub pgrdlink {
 4707:     my $link=&submlink(@_);
 4708:     $link=~s/(&command=submission)/$1&showgrading=yes/;
 4709:     return $link;
 4710: }
 4711: ##############################################
 4712: 
 4713: =pod
 4714: 
 4715: =item * &pprmlink()
 4716: 
 4717: Inputs: $text $uname $udom $symb $target
 4718: 
 4719: Returns: A link to parmset.pm such as to see the PPRM view of a
 4720: student and a specific resource
 4721: 
 4722: =cut
 4723: 
 4724: ###############################################
 4725: sub pprmlink {
 4726:     my ($text,$uname,$udom,$symb,$target)=@_;
 4727:     if (!($uname && $udom)) {
 4728: 	(my $cursymb, my $courseid,$udom,$uname)=
 4729: 	    &Apache::lonnet::whichuser($symb);
 4730: 	if (!$symb) { $symb=$cursymb; }
 4731:     }
 4732:     if (!$symb) { $symb=&Apache::lonnet::symbread(); }
 4733:     $symb=&escape($symb);
 4734:     if ($target) { $target="target=\"$target\""; }
 4735:     return '<a href="/adm/parmset?command=set&amp;'.
 4736: 	'symb='.$symb.'&amp;uname='.$uname.
 4737: 	'&amp;udom='.$udom.'" '.$target.'>'.$text.'</a>';
 4738: }
 4739: ##############################################
 4740: 
 4741: =pod
 4742: 
 4743: =back
 4744: 
 4745: =cut
 4746: 
 4747: ###############################################
 4748: 
 4749: 
 4750: sub timehash {
 4751:     my ($thistime) = @_;
 4752:     my $timezone = &Apache::lonlocal::gettimezone();
 4753:     my $dt = DateTime->from_epoch(epoch => $thistime)
 4754:                      ->set_time_zone($timezone);
 4755:     my $wday = $dt->day_of_week();
 4756:     if ($wday == 7) { $wday = 0; }
 4757:     return ( 'second' => $dt->second(),
 4758:              'minute' => $dt->minute(),
 4759:              'hour'   => $dt->hour(),
 4760:              'day'     => $dt->day_of_month(),
 4761:              'month'   => $dt->month(),
 4762:              'year'    => $dt->year(),
 4763:              'weekday' => $wday,
 4764:              'dayyear' => $dt->day_of_year(),
 4765:              'dlsav'   => $dt->is_dst() );
 4766: }
 4767: 
 4768: sub utc_string {
 4769:     my ($date)=@_;
 4770:     return strftime("%Y%m%dT%H%M%SZ",gmtime($date));
 4771: }
 4772: 
 4773: sub maketime {
 4774:     my %th=@_;
 4775:     my ($epoch_time,$timezone,$dt);
 4776:     $timezone = &Apache::lonlocal::gettimezone();
 4777:     eval {
 4778:         $dt = DateTime->new( year   => $th{'year'},
 4779:                              month  => $th{'month'},
 4780:                              day    => $th{'day'},
 4781:                              hour   => $th{'hour'},
 4782:                              minute => $th{'minute'},
 4783:                              second => $th{'second'},
 4784:                              time_zone => $timezone,
 4785:                          );
 4786:     };
 4787:     if (!$@) {
 4788:         $epoch_time = $dt->epoch;
 4789:         if ($epoch_time) {
 4790:             return $epoch_time;
 4791:         }
 4792:     }
 4793:     return POSIX::mktime(
 4794:         ($th{'seconds'},$th{'minutes'},$th{'hours'},
 4795:          $th{'day'},$th{'month'}-1,$th{'year'}-1900,0,0,-1));
 4796: }
 4797: 
 4798: #########################################
 4799: 
 4800: sub findallcourses {
 4801:     my ($roles,$uname,$udom) = @_;
 4802:     my %roles;
 4803:     if (ref($roles)) { %roles = map { $_ => 1 } @{$roles}; }
 4804:     my %courses;
 4805:     my $now=time;
 4806:     if (!defined($uname)) {
 4807:         $uname = $env{'user.name'};
 4808:     }
 4809:     if (!defined($udom)) {
 4810:         $udom = $env{'user.domain'};
 4811:     }
 4812:     if (($uname ne $env{'user.name'}) || ($udom ne $env{'user.domain'})) {
 4813:         my %roleshash = &Apache::lonnet::dump('roles',$udom,$uname);
 4814:         if (!%roles) {
 4815:             %roles = (
 4816:                        cc => 1,
 4817:                        co => 1,
 4818:                        in => 1,
 4819:                        ep => 1,
 4820:                        ta => 1,
 4821:                        cr => 1,
 4822:                        st => 1,
 4823:              );
 4824:         }
 4825:         foreach my $entry (keys(%roleshash)) {
 4826:             my ($trole,$tend,$tstart) = split(/_/,$roleshash{$entry});
 4827:             if ($trole =~ /^cr/) { 
 4828:                 next if (!exists($roles{$trole}) && !exists($roles{'cr'}));
 4829:             } else {
 4830:                 next if (!exists($roles{$trole}));
 4831:             }
 4832:             if ($tend) {
 4833:                 next if ($tend < $now);
 4834:             }
 4835:             if ($tstart) {
 4836:                 next if ($tstart > $now);
 4837:             }
 4838:             my ($cdom,$cnum,$sec,$cnumpart,$secpart,$role);
 4839:             (undef,$cdom,$cnumpart,$secpart) = split(/\//,$entry);
 4840:             my $value = $trole.'/'.$cdom.'/';
 4841:             if ($secpart eq '') {
 4842:                 ($cnum,$role) = split(/_/,$cnumpart); 
 4843:                 $sec = 'none';
 4844:                 $value .= $cnum.'/';
 4845:             } else {
 4846:                 $cnum = $cnumpart;
 4847:                 ($sec,$role) = split(/_/,$secpart);
 4848:                 $value .= $cnum.'/'.$sec;
 4849:             }
 4850:             if (ref($courses{$cdom.'_'.$cnum}{$sec}) eq 'ARRAY') {
 4851:                 unless (grep(/^\Q$value\E$/,@{$courses{$cdom.'_'.$cnum}{$sec}})) {
 4852:                     push(@{$courses{$cdom.'_'.$cnum}{$sec}},$value);
 4853:                 }
 4854:             } else {
 4855:                 @{$courses{$cdom.'_'.$cnum}{$sec}} = ($value);
 4856:             }
 4857:         }
 4858:     } else {
 4859:         foreach my $key (keys(%env)) {
 4860: 	    if ( $key=~m{^user\.role\.(\w+)\./($match_domain)/($match_courseid)/?(\w*)$} ||
 4861:                  $key=~m{^user\.role\.(cr/$match_domain/$match_username/\w+)\./($match_domain)/($match_courseid)/?(\w*)$}) {
 4862: 	        my ($role,$cdom,$cnum,$sec) = ($1,$2,$3,$4);
 4863: 	        next if ($role eq 'ca' || $role eq 'aa');
 4864: 	        next if (%roles && !exists($roles{$role}));
 4865: 	        my ($starttime,$endtime)=split(/\./,$env{$key});
 4866:                 my $active=1;
 4867:                 if ($starttime) {
 4868: 		    if ($now<$starttime) { $active=0; }
 4869:                 }
 4870:                 if ($endtime) {
 4871:                     if ($now>$endtime) { $active=0; }
 4872:                 }
 4873:                 if ($active) {
 4874:                     my $value = $role.'/'.$cdom.'/'.$cnum.'/';
 4875:                     if ($sec eq '') {
 4876:                         $sec = 'none';
 4877:                     } else {
 4878:                         $value .= $sec;
 4879:                     }
 4880:                     if (ref($courses{$cdom.'_'.$cnum}{$sec}) eq 'ARRAY') {
 4881:                         unless (grep(/^\Q$value\E$/,@{$courses{$cdom.'_'.$cnum}{$sec}})) {
 4882:                             push(@{$courses{$cdom.'_'.$cnum}{$sec}},$value);
 4883:                         }
 4884:                     } else {
 4885:                         @{$courses{$cdom.'_'.$cnum}{$sec}} = ($value);
 4886:                     }
 4887:                 }
 4888:             }
 4889:         }
 4890:     }
 4891:     return %courses;
 4892: }
 4893: 
 4894: ###############################################
 4895: 
 4896: sub blockcheck {
 4897:     my ($setters,$activity,$clientip,$uname,$udom,$url,$is_course,$symb,$caller) = @_;
 4898: 
 4899:     unless (($activity eq 'docs') || ($activity eq 'reinit') || ($activity eq 'alert')) {
 4900:         my ($has_evb,$check_ipaccess);
 4901:         my $dom = $env{'user.domain'};
 4902:         if ($env{'request.course.id'}) {
 4903:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 4904:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 4905:             my $checkrole = "cm./$cdom/$cnum";
 4906:             my $sec = $env{'request.course.sec'};
 4907:             if ($sec ne '') {
 4908:                 $checkrole .= "/$sec";
 4909:             }
 4910:             if ((&Apache::lonnet::allowed('evb',undef,undef,$checkrole)) &&
 4911:                 ($env{'request.role'} !~ /^st/)) {
 4912:                 $has_evb = 1;
 4913:             }
 4914:             unless ($has_evb) {
 4915:                 if (($activity eq 'printout') || ($activity eq 'grades') || ($activity eq 'search') ||
 4916:                     ($activity eq 'boards') || ($activity eq 'groups') || ($activity eq 'chat')) {
 4917:                     if ($udom eq $cdom) {
 4918:                         $check_ipaccess = 1;
 4919:                     }
 4920:                 }
 4921:             }
 4922:         } elsif (($activity eq 'com') || ($activity eq 'port') || ($activity eq 'blogs') ||
 4923:                 ($activity eq 'about') || ($activity eq 'wishlist') || ($activity eq 'passwd')) {
 4924:             my $checkrole;
 4925:             if ($env{'request.role.domain'} eq '') {
 4926:                 $checkrole = "cm./$env{'user.domain'}/";
 4927:             } else {
 4928:                 $checkrole = "cm./$env{'request.role.domain'}/";
 4929:             }
 4930:             if (($checkrole) && (&Apache::lonnet::allowed('evb',undef,undef,$checkrole))) {
 4931:                 $has_evb = 1;
 4932:             }
 4933:         }
 4934:         unless ($has_evb || $check_ipaccess) {
 4935:             my @machinedoms = &Apache::lonnet::current_machine_domains();
 4936:             if (($dom eq 'public') && ($activity eq 'port')) {
 4937:                 $dom = $udom;
 4938:             }
 4939:             if (($dom ne '') && (grep(/^\Q$dom\E$/,@machinedoms))) {
 4940:                 $check_ipaccess = 1;
 4941:             } else {
 4942:                 my $lonhost = $Apache::lonnet::perlvar{'lonHostID'};
 4943:                 my $internet_names = &Apache::lonnet::get_internet_names($lonhost);
 4944:                 my $prim = &Apache::lonnet::domain($dom,'primary');
 4945:                 my $intdom = &Apache::lonnet::internet_dom($prim);
 4946:                 if (($intdom ne '') && (ref($internet_names) eq 'ARRAY')) {
 4947:                     if (grep(/^\Q$intdom\E$/,@{$internet_names})) {
 4948:                         $check_ipaccess = 1;
 4949:                     }
 4950:                 }
 4951:             }
 4952:         }
 4953:         if ($check_ipaccess) {
 4954:             my ($ipaccessref,$cached)=&Apache::lonnet::is_cached_new('ipaccess',$dom);
 4955:             unless (defined($cached)) {
 4956:                 my %domconfig =
 4957:                     &Apache::lonnet::get_dom('configuration',['ipaccess'],$dom);
 4958:                 $ipaccessref = &Apache::lonnet::do_cache_new('ipaccess',$dom,$domconfig{'ipaccess'},1800);
 4959:             }
 4960:             if ((ref($ipaccessref) eq 'HASH') && ($clientip)) {
 4961:                 foreach my $id (keys(%{$ipaccessref})) {
 4962:                     if (ref($ipaccessref->{$id}) eq 'HASH') {
 4963:                         my $range = $ipaccessref->{$id}->{'ip'};
 4964:                         if ($range) {
 4965:                             if (&Apache::lonnet::ip_match($clientip,$range)) {
 4966:                                 if (ref($ipaccessref->{$id}->{'commblocks'}) eq 'HASH') {
 4967:                                     if ($ipaccessref->{$id}->{'commblocks'}->{$activity} eq 'on') {
 4968:                                         return ('','','',$id,$dom);
 4969:                                         last;
 4970:                                     }
 4971:                                 }
 4972:                             }
 4973:                         }
 4974:                     }
 4975:                 }
 4976:             }
 4977:         }
 4978:         if (($activity eq 'wishlist') || ($activity eq 'annotate')) {
 4979:             return ();
 4980:         }
 4981:     }
 4982:     if (defined($udom) && defined($uname)) {
 4983:         # If uname and udom are for a course, check for blocks in the course.
 4984:         if (($is_course) || (&Apache::lonnet::is_course($udom,$uname))) {
 4985:             my ($startblock,$endblock,$triggerblock) =
 4986:                 &get_blocks($setters,$activity,$udom,$uname,$url,$symb,$caller);
 4987:             return ($startblock,$endblock,$triggerblock);
 4988:         }
 4989:     } else {
 4990:         $udom = $env{'user.domain'};
 4991:         $uname = $env{'user.name'};
 4992:     }
 4993: 
 4994:     my $startblock = 0;
 4995:     my $endblock = 0;
 4996:     my $triggerblock = '';
 4997:     my %live_courses;
 4998:     unless (($activity eq 'wishlist') || ($activity eq 'annotate')) {
 4999:         %live_courses = &findallcourses(undef,$uname,$udom);
 5000:     }
 5001: 
 5002:     # If uname is for a user, and activity is course-specific, i.e.,
 5003:     # boards, chat or groups, check for blocking in current course only.
 5004: 
 5005:     if (($activity eq 'boards' || $activity eq 'chat' ||
 5006:          $activity eq 'groups' || $activity eq 'printout' ||
 5007:          $activity eq 'search' || $activity eq 'reinit' ||
 5008:          $activity eq 'alert') && ($env{'request.course.id'})) {
 5009:         foreach my $key (keys(%live_courses)) {
 5010:             if ($key ne $env{'request.course.id'}) {
 5011:                 delete($live_courses{$key});
 5012:             }
 5013:         }
 5014:     }
 5015: 
 5016:     my $otheruser = 0;
 5017:     my %own_courses;
 5018:     if ((($uname ne $env{'user.name'})) || ($udom ne $env{'user.domain'})) {
 5019:         # Resource belongs to user other than current user.
 5020:         $otheruser = 1;
 5021:         # Gather courses for current user
 5022:         %own_courses = 
 5023:             &findallcourses(undef,$env{'user.name'},$env{'user.domain'});
 5024:     }
 5025: 
 5026:     # Gather active course roles - course coordinator, instructor, 
 5027:     # exam proctor, ta, student, or custom role.
 5028: 
 5029:     foreach my $course (keys(%live_courses)) {
 5030:         my ($cdom,$cnum);
 5031:         if ((defined($env{'course.'.$course.'.domain'})) && (defined($env{'course.'.$course.'.num'}))) {
 5032:             $cdom = $env{'course.'.$course.'.domain'};
 5033:             $cnum = $env{'course.'.$course.'.num'};
 5034:         } else {
 5035:             ($cdom,$cnum) = split(/_/,$course); 
 5036:         }
 5037:         my $no_ownblock = 0;
 5038:         my $no_userblock = 0;
 5039:         if ($otheruser && $activity ne 'com') {
 5040:             # Check if current user has 'evb' priv for this
 5041:             if (defined($own_courses{$course})) {
 5042:                 foreach my $sec (keys(%{$own_courses{$course}})) {
 5043:                     my $checkrole = 'cm./'.$cdom.'/'.$cnum;
 5044:                     if ($sec ne 'none') {
 5045:                         $checkrole .= '/'.$sec;
 5046:                     }
 5047:                     if (&Apache::lonnet::allowed('evb',undef,undef,$checkrole)) {
 5048:                         $no_ownblock = 1;
 5049:                         last;
 5050:                     }
 5051:                 }
 5052:             }
 5053:             # if they have 'evb' priv and are currently not playing student
 5054:             next if (($no_ownblock) &&
 5055:                  ($env{'request.role'} !~ m{^st\./$cdom/$cnum}));
 5056:         }
 5057:         foreach my $sec (keys(%{$live_courses{$course}})) {
 5058:             my $checkrole = 'cm./'.$cdom.'/'.$cnum;
 5059:             if ($sec ne 'none') {
 5060:                 $checkrole .= '/'.$sec;
 5061:             }
 5062:             if ($otheruser) {
 5063:                 # Resource belongs to user other than current user.
 5064:                 # Assemble privs for that user, and check for 'evb' priv.
 5065:                 my (%allroles,%userroles);
 5066:                 if (ref($live_courses{$course}{$sec}) eq 'ARRAY') {
 5067:                     foreach my $entry (@{$live_courses{$course}{$sec}}) { 
 5068:                         my ($trole,$tdom,$tnum,$tsec);
 5069:                         if ($entry =~ /^cr/) {
 5070:                             ($trole,$tdom,$tnum,$tsec) = 
 5071:                                 ($entry =~ m|^(cr/$match_domain/$match_username/\w+)\./($match_domain)/($match_username)/?(\w*)$|);
 5072:                         } else {
 5073:                            ($trole,$tdom,$tnum,$tsec) = split(/\//,$entry);
 5074:                         }
 5075:                         my ($spec,$area,$trest);
 5076:                         $area = '/'.$tdom.'/'.$tnum;
 5077:                         $trest = $tnum;
 5078:                         if ($tsec ne '') {
 5079:                             $area .= '/'.$tsec;
 5080:                             $trest .= '/'.$tsec;
 5081:                         }
 5082:                         $spec = $trole.'.'.$area;
 5083:                         if ($trole =~ /^cr/) {
 5084:                             &Apache::lonnet::custom_roleprivs(\%allroles,$trole,
 5085:                                                               $tdom,$spec,$trest,$area);
 5086:                         } else {
 5087:                             &Apache::lonnet::standard_roleprivs(\%allroles,$trole,
 5088:                                                                 $tdom,$spec,$trest,$area);
 5089:                         }
 5090:                     }
 5091:                     my ($author,$adv,$rar) = &Apache::lonnet::set_userprivs(\%userroles,\%allroles);
 5092:                     if ($userroles{'user.priv.'.$checkrole} =~ /evb\&([^\:]*)/) {
 5093:                         if ($1) {
 5094:                             $no_userblock = 1;
 5095:                             last;
 5096:                         }
 5097:                     }
 5098:                 }
 5099:             } else {
 5100:                 # Resource belongs to current user
 5101:                 # Check for 'evb' priv via lonnet::allowed().
 5102:                 if (&Apache::lonnet::allowed('evb',undef,undef,$checkrole)) {
 5103:                     $no_ownblock = 1;
 5104:                     last;
 5105:                 }
 5106:             }
 5107:         }
 5108:         # if they have the evb priv and are currently not playing student
 5109:         next if (($no_ownblock) &&
 5110:                  ($env{'request.role'} !~ m{^st\./\Q$cdom\E/\Q$cnum\E}));
 5111:         next if ($no_userblock);
 5112: 
 5113:         # Retrieve blocking times and identity of blocker for course
 5114:         # of specified user, unless user has 'evb' privilege.
 5115:         
 5116:         my ($start,$end,$trigger) = 
 5117:             &get_blocks($setters,$activity,$cdom,$cnum,$url,$symb,$caller);
 5118:         if (($start != 0) && 
 5119:             (($startblock == 0) || ($startblock > $start))) {
 5120:             $startblock = $start;
 5121:             if ($trigger ne '') {
 5122:                 $triggerblock = $trigger;
 5123:             }
 5124:         }
 5125:         if (($end != 0)  &&
 5126:             (($endblock == 0) || ($endblock < $end))) {
 5127:             $endblock = $end;
 5128:             if ($trigger ne '') {
 5129:                 $triggerblock = $trigger;
 5130:             }
 5131:         }
 5132:     }
 5133:     return ($startblock,$endblock,$triggerblock);
 5134: }
 5135: 
 5136: sub get_blocks {
 5137:     my ($setters,$activity,$cdom,$cnum,$url,$symb,$caller) = @_;
 5138:     my $startblock = 0;
 5139:     my $endblock = 0;
 5140:     my $triggerblock = '';
 5141:     my $course = $cdom.'_'.$cnum;
 5142:     $setters->{$course} = {};
 5143:     $setters->{$course}{'staff'} = [];
 5144:     $setters->{$course}{'times'} = [];
 5145:     $setters->{$course}{'triggers'} = [];
 5146:     my (@blockers,%triggered);
 5147:     my $now = time;
 5148:     my %commblocks = &Apache::lonnet::get_comm_blocks($cdom,$cnum);
 5149:     if ($activity eq 'docs') {
 5150:         my ($blocked,$nosymbcache,$noenccheck);
 5151:         if (($caller eq 'blockedaccess') || ($caller eq 'blockingstatus')) {
 5152:             $blocked = 1;
 5153:             $nosymbcache = 1;
 5154:             $noenccheck = 1;
 5155:         }
 5156:         @blockers = &Apache::lonnet::has_comm_blocking('bre',$symb,$url,$nosymbcache,$noenccheck,$blocked,\%commblocks);
 5157:         foreach my $block (@blockers) {
 5158:             if ($block =~ /^firstaccess____(.+)$/) {
 5159:                 my $item = $1;
 5160:                 my $type = 'map';
 5161:                 my $timersymb = $item;
 5162:                 if ($item eq 'course') {
 5163:                     $type = 'course';
 5164:                 } elsif ($item =~ /___\d+___/) {
 5165:                     $type = 'resource';
 5166:                 } else {
 5167:                     $timersymb = &Apache::lonnet::symbread($item);
 5168:                 }
 5169:                 my $start = $env{'course.'.$cdom.'_'.$cnum.'.firstaccess.'.$timersymb};
 5170:                 my $end = $start + $env{'course.'.$cdom.'_'.$cnum.'.timerinterval.'.$timersymb};
 5171:                 $triggered{$block} = {
 5172:                                        start => $start,
 5173:                                        end   => $end,
 5174:                                        type  => $type,
 5175:                                      };
 5176:             }
 5177:         }
 5178:     } else {
 5179:         foreach my $block (keys(%commblocks)) {
 5180:             if ($block =~ m/^(\d+)____(\d+)$/) { 
 5181:                 my ($start,$end) = ($1,$2);
 5182:                 if ($start <= time && $end >= time) {
 5183:                     if (ref($commblocks{$block}) eq 'HASH') {
 5184:                         if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
 5185:                             if ($commblocks{$block}{'blocks'}{$activity} eq 'on') {
 5186:                                 unless(grep(/^\Q$block\E$/,@blockers)) {
 5187:                                     push(@blockers,$block);
 5188:                                 }
 5189:                             }
 5190:                         }
 5191:                     }
 5192:                 }
 5193:             } elsif ($block =~ /^firstaccess____(.+)$/) {
 5194:                 my $item = $1;
 5195:                 my $timersymb = $item; 
 5196:                 my $type = 'map';
 5197:                 if ($item eq 'course') {
 5198:                     $type = 'course';
 5199:                 } elsif ($item =~ /___\d+___/) {
 5200:                     $type = 'resource';
 5201:                 } else {
 5202:                     $timersymb = &Apache::lonnet::symbread($item);
 5203:                 }
 5204:                 my $start = $env{'course.'.$cdom.'_'.$cnum.'.firstaccess.'.$timersymb};
 5205:                 my $end = $start + $env{'course.'.$cdom.'_'.$cnum.'.timerinterval.'.$timersymb}; 
 5206:                 if ($start && $end) {
 5207:                     if (($start <= time) && ($end >= time)) {
 5208:                         if (ref($commblocks{$block}) eq 'HASH') {
 5209:                             if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
 5210:                                 if ($commblocks{$block}{'blocks'}{$activity} eq 'on') {
 5211:                                     unless(grep(/^\Q$block\E$/,@blockers)) {
 5212:                                         push(@blockers,$block);
 5213:                                         $triggered{$block} = {
 5214:                                                                start => $start,
 5215:                                                                end   => $end,
 5216:                                                                type  => $type,
 5217:                                                              };
 5218:                                     }
 5219:                                 }
 5220:                             }
 5221:                         }
 5222:                     }
 5223:                 }
 5224:             }
 5225:         }
 5226:     }
 5227:     foreach my $blocker (@blockers) {
 5228:         my ($staff_name,$staff_dom,$title,$blocks) =
 5229:             &parse_block_record($commblocks{$blocker});
 5230:         push(@{$$setters{$course}{'staff'}},[$staff_name,$staff_dom]);
 5231:         my ($start,$end,$triggertype);
 5232:         if ($blocker =~ m/^(\d+)____(\d+)$/) {
 5233:             ($start,$end) = ($1,$2);
 5234:         } elsif (ref($triggered{$blocker}) eq 'HASH') {
 5235:             $start = $triggered{$blocker}{'start'};
 5236:             $end = $triggered{$blocker}{'end'};
 5237:             $triggertype = $triggered{$blocker}{'type'};
 5238:         }
 5239:         if ($start) {
 5240:             push(@{$$setters{$course}{'times'}}, [$start,$end]);
 5241:             if ($triggertype) {
 5242:                 push(@{$$setters{$course}{'triggers'}},$triggertype);
 5243:             } else {
 5244:                 push(@{$$setters{$course}{'triggers'}},0);
 5245:             }
 5246:             if ( ($startblock == 0) || ($startblock > $start) ) {
 5247:                 $startblock = $start;
 5248:                 if ($triggertype) {
 5249:                     $triggerblock = $blocker;
 5250:                 }
 5251:             }
 5252:             if ( ($endblock == 0) || ($endblock < $end) ) {
 5253:                $endblock = $end;
 5254:                if ($triggertype) {
 5255:                    $triggerblock = $blocker;
 5256:                }
 5257:             }
 5258:         }
 5259:     }
 5260:     return ($startblock,$endblock,$triggerblock);
 5261: }
 5262: 
 5263: sub parse_block_record {
 5264:     my ($record) = @_;
 5265:     my ($setuname,$setudom,$title,$blocks);
 5266:     if (ref($record) eq 'HASH') {
 5267:         ($setuname,$setudom) = split(/:/,$record->{'setter'});
 5268:         $title = &unescape($record->{'event'});
 5269:         $blocks = $record->{'blocks'};
 5270:     } else {
 5271:         my @data = split(/:/,$record,3);
 5272:         if (scalar(@data) eq 2) {
 5273:             $title = $data[1];
 5274:             ($setuname,$setudom) = split(/@/,$data[0]);
 5275:         } else {
 5276:             ($setuname,$setudom,$title) = @data;
 5277:         }
 5278:         $blocks = { 'com' => 'on' };
 5279:     }
 5280:     return ($setuname,$setudom,$title,$blocks);
 5281: }
 5282: 
 5283: sub blocking_status {
 5284:     my ($activity,$clientip,$uname,$udom,$url,$is_course,$symb,$caller) = @_;
 5285:     my %setters;
 5286: 
 5287: # check for active blocking
 5288:     if ($clientip eq '') {
 5289:         $clientip = &Apache::lonnet::get_requestor_ip();
 5290:     }
 5291:     my ($startblock,$endblock,$triggerblock,$by_ip,$blockdom) = 
 5292:         &blockcheck(\%setters,$activity,$clientip,$uname,$udom,$url,$is_course,$symb,$caller);
 5293:     my $blocked = 0;
 5294:     if (($startblock && $endblock) || ($by_ip)) {
 5295:         $blocked = 1;
 5296:     }
 5297: 
 5298: # caller just wants to know whether a block is active
 5299:     if (!wantarray) { return $blocked; }
 5300: 
 5301: # build a link to a popup window containing the details
 5302:     my $querystring  = "?activity=$activity";
 5303: # $uname and $udom decide whose portfolio (or information page) the user is trying to look at
 5304:     if (($activity eq 'port') || ($activity eq 'about') || ($activity eq 'passwd')) {
 5305:         $querystring .= "&amp;udom=$udom"      if ($udom =~ /^$match_domain$/);
 5306:         $querystring .= "&amp;uname=$uname"    if ($uname =~ /^$match_username$/);
 5307:     } elsif ($activity eq 'docs') {
 5308:         my $showurl = &Apache::lonenc::check_encrypt($url);
 5309:         $querystring .= '&amp;url='.&HTML::Entities::encode($showurl,'\'&"<>');
 5310:         if ($symb) {
 5311:             my $showsymb = &Apache::lonenc::check_encrypt($symb);
 5312:             $querystring .= '&amp;symb='.&HTML::Entities::encode($showsymb,'\'&"<>');
 5313:         }
 5314:     }
 5315: 
 5316:     my $output .= <<'END_MYBLOCK';
 5317: function openWindow(url, wdwName, w, h, toolbar,scrollbar) {
 5318:     var options = "width=" + w + ",height=" + h + ",";
 5319:     options += "resizable=yes,scrollbars="+scrollbar+",status=no,";
 5320:     options += "menubar=no,toolbar="+toolbar+",location=no,directories=no";
 5321:     var newWin = window.open(url, wdwName, options);
 5322:     newWin.focus();
 5323: }
 5324: END_MYBLOCK
 5325: 
 5326:     $output = Apache::lonhtmlcommon::scripttag($output);
 5327:   
 5328:     my $popupUrl = "/adm/blockingstatus/$querystring";
 5329:     my $text = &mt('Communication Blocked');
 5330:     my $class = 'LC_comblock';
 5331:     if ($activity eq 'docs') {
 5332:         $text = &mt('Content Access Blocked');
 5333:         $class = '';
 5334:     } elsif ($activity eq 'printout') {
 5335:         $text = &mt('Printing Blocked');
 5336:     } elsif ($activity eq 'passwd') {
 5337:         $text = &mt('Password Changing Blocked');
 5338:     } elsif ($activity eq 'grades') {
 5339:         $text = &mt('Gradebook Blocked');
 5340:     } elsif ($activity eq 'search') {
 5341:         $text = &mt('Search Blocked');
 5342:     } elsif ($activity eq 'alert') {
 5343:         $text = &mt('Checking Critical Messages Blocked');
 5344:     } elsif ($activity eq 'reinit') {
 5345:         $text = &mt('Checking Course Update Blocked');
 5346:     } elsif ($activity eq 'about') {
 5347:         $text = &mt('Access to User Information Pages Blocked');
 5348:     } elsif ($activity eq 'wishlist') {
 5349:         $text = &mt('Access to Stored Links Blocked');
 5350:     } elsif ($activity eq 'annotate') {
 5351:         $text = &mt('Access to Annotations Blocked');
 5352:     }
 5353:     $output .= <<"END_BLOCK";
 5354: <div class='$class'>
 5355:   <a onclick='openWindow("$popupUrl","Blocking Table",600,300,"no","no");return false;' href='/adm/blockingstatus/$querystring'
 5356:   title='$text'>
 5357:   <img class='LC_noBorder LC_middle' title='$text' src='/res/adm/pages/comblock.png' alt='$text'/></a>
 5358:   <a onclick='openWindow("$popupUrl","Blocking Table",600,300,"no","no");return false;' href='/adm/blockingstatus/$querystring' 
 5359:   title='$text'>$text</a>
 5360: </div>
 5361: 
 5362: END_BLOCK
 5363: 
 5364:     return ($blocked, $output);
 5365: }
 5366: 
 5367: ###############################################
 5368: 
 5369: sub check_ip_acc {
 5370:     my ($acc,$clientip)=@_;
 5371:     &Apache::lonxml::debug("acc is $acc");
 5372:     if (!defined($acc) || $acc =~ /^\s*$/ || $acc =~/^\s*no\s*$/i) {
 5373:         return 1;
 5374:     }
 5375:     my $allowed=0;
 5376:     my $ip;
 5377:     if (($ENV{'REMOTE_ADDR'} eq '127.0.0.1') ||
 5378:         ($ENV{'REMOTE_ADDR'} eq &Apache::lonnet::get_host_ip($Apache::lonnet::perlvar{'lonHostID'}))) {
 5379:         $ip = $env{'request.host'} || $ENV{'REMOTE_ADDR'} || $clientip;
 5380:     } else {
 5381:         my $remote_ip = &Apache::lonnet::get_requestor_ip();
 5382:         $ip = $remote_ip || $env{'request.host'} || $clientip;
 5383:     }
 5384: 
 5385:     my $name;
 5386:     my %access = (
 5387:                      allowfrom => 1,
 5388:                      denyfrom  => 0,
 5389:                  );
 5390:     my @allows;
 5391:     my @denies;
 5392:     foreach my $item (split(',',$acc)) {
 5393:         $item =~ s/^\s*//;
 5394:         $item =~ s/\s*$//;
 5395:         if ($item =~ /^\!(.+)$/) {
 5396:             push(@denies,$1);
 5397:         } else {
 5398:             push(@allows,$item);
 5399:         }
 5400:     }
 5401:     my $numdenies = scalar(@denies);
 5402:     my $numallows = scalar(@allows);
 5403:     my $count = 0;
 5404:     foreach my $pattern (@denies,@allows) {
 5405:         $count ++;
 5406:         my $acctype = 'allowfrom';
 5407:         if ($count <= $numdenies) {
 5408:             $acctype = 'denyfrom';
 5409:         }
 5410:         if ($pattern =~ /\*$/) {
 5411:             #35.8.*
 5412:             $pattern=~s/\*//;
 5413:             if ($ip =~ /^\Q$pattern\E/) { $allowed=$access{$acctype}; }
 5414:         } elsif ($pattern =~ /(\d+\.\d+\.\d+)\.\[(\d+)-(\d+)\]$/) {
 5415:             #35.8.3.[34-56]
 5416:             my $low=$2;
 5417:             my $high=$3;
 5418:             $pattern=$1;
 5419:             if ($ip =~ /^\Q$pattern\E/) {
 5420:                 my $last=(split(/\./,$ip))[3];
 5421:                 if ($last <=$high && $last >=$low) { $allowed=$access{$acctype}; }
 5422:             }
 5423:         } elsif ($pattern =~ /^\*/) {
 5424:             #*.msu.edu
 5425:             $pattern=~s/\*//;
 5426:             if (!defined($name)) {
 5427:                 use Socket;
 5428:                 my $netaddr=inet_aton($ip);
 5429:                 ($name)=gethostbyaddr($netaddr,AF_INET);
 5430:             }
 5431:             if ($name =~ /\Q$pattern\E$/i) { $allowed=$access{$acctype}; }
 5432:         } elsif ($pattern =~ /\d+\.\d+\.\d+\.\d+/) {
 5433:             #127.0.0.1
 5434:             if ($ip =~ /^\Q$pattern\E/) { $allowed=$access{$acctype}; }
 5435:         } else {
 5436:             #some.name.com
 5437:             if (!defined($name)) {
 5438:                 use Socket;
 5439:                 my $netaddr=inet_aton($ip);
 5440:                 ($name)=gethostbyaddr($netaddr,AF_INET);
 5441:             }
 5442:             if ($name =~ /\Q$pattern\E$/i) { $allowed=$access{$acctype}; }
 5443:         }
 5444:         if ($allowed =~ /^(0|1)$/) { last; }
 5445:     }
 5446:     if ($allowed eq '') {
 5447:         if ($numdenies && !$numallows) {
 5448:             $allowed = 1;
 5449:         } else {
 5450:             $allowed = 0;
 5451:         }
 5452:     }
 5453:     return $allowed;
 5454: }
 5455: 
 5456: ###############################################
 5457: 
 5458: =pod
 5459: 
 5460: =head1 Domain Template Functions
 5461: 
 5462: =over 4
 5463: 
 5464: =item * &determinedomain()
 5465: 
 5466: Inputs: $domain (usually will be undef)
 5467: 
 5468: Returns: Determines which domain should be used for designs
 5469: 
 5470: =cut
 5471: 
 5472: ###############################################
 5473: sub determinedomain {
 5474:     my $domain=shift;
 5475:     if (! $domain) {
 5476:         # Determine domain if we have not been given one
 5477:         $domain = &Apache::lonnet::default_login_domain();
 5478:         if ($env{'user.domain'}) { $domain=$env{'user.domain'}; }
 5479:         if ($env{'request.role.domain'}) { 
 5480:             $domain=$env{'request.role.domain'}; 
 5481:         }
 5482:     }
 5483:     return $domain;
 5484: }
 5485: ###############################################
 5486: 
 5487: sub devalidate_domconfig_cache {
 5488:     my ($udom)=@_;
 5489:     &Apache::lonnet::devalidate_cache_new('domainconfig',$udom);
 5490: }
 5491: 
 5492: # ---------------------- Get domain configuration for a domain
 5493: sub get_domainconf {
 5494:     my ($udom) = @_;
 5495:     my $cachetime=1800;
 5496:     my ($result,$cached)=&Apache::lonnet::is_cached_new('domainconfig',$udom);
 5497:     if (defined($cached)) { return %{$result}; }
 5498: 
 5499:     my %domconfig = &Apache::lonnet::get_dom('configuration',
 5500: 					     ['login','rolecolors','autoenroll'],$udom);
 5501:     my (%designhash,%legacy);
 5502:     if (keys(%domconfig) > 0) {
 5503:         if (ref($domconfig{'login'}) eq 'HASH') {
 5504:             if (keys(%{$domconfig{'login'}})) {
 5505:                 foreach my $key (keys(%{$domconfig{'login'}})) {
 5506:                     if (ref($domconfig{'login'}{$key}) eq 'HASH') {
 5507:                         if (($key eq 'loginvia') || ($key eq 'headtag')) {
 5508:                             if (ref($domconfig{'login'}{$key}) eq 'HASH') {
 5509:                                 foreach my $hostname (keys(%{$domconfig{'login'}{$key}})) {
 5510:                                     if (ref($domconfig{'login'}{$key}{$hostname}) eq 'HASH') {
 5511:                                         if ($key eq 'loginvia') {
 5512:                                             if ($domconfig{'login'}{'loginvia'}{$hostname}{'server'}) {
 5513:                                                 my $server = $domconfig{'login'}{'loginvia'}{$hostname}{'server'};
 5514:                                                 $designhash{$udom.'.login.loginvia'} = $server;
 5515:                                                 if ($domconfig{'login'}{'loginvia'}{$hostname}{'serverpath'} eq 'custom') {
 5516:                                                     $designhash{$udom.'.login.loginvia_'.$hostname} = $server.':'.$domconfig{'login'}{'loginvia'}{$hostname}{'custompath'};
 5517:                                                 } else {
 5518:                                                     $designhash{$udom.'.login.loginvia_'.$hostname} = $server.':'.$domconfig{'login'}{'loginvia'}{$hostname}{'serverpath'};
 5519:                                                 }
 5520:                                             }
 5521:                                         } elsif ($key eq 'headtag') {
 5522:                                             if ($domconfig{'login'}{'headtag'}{$hostname}{'url'}) {
 5523:                                                 $designhash{$udom.'.login.headtag_'.$hostname} = $domconfig{'login'}{'headtag'}{$hostname}{'url'};
 5524:                                             }
 5525:                                         }
 5526:                                         if ($domconfig{'login'}{$key}{$hostname}{'exempt'}) {
 5527:                                             $designhash{$udom.'.login.'.$key.'_exempt_'.$hostname} = $domconfig{'login'}{$key}{$hostname}{'exempt'};
 5528:                                         }
 5529:                                     }
 5530:                                 }
 5531:                             }
 5532:                         } elsif ($key eq 'saml') {
 5533:                             if (ref($domconfig{'login'}{$key}) eq 'HASH') {
 5534:                                 foreach my $host (keys(%{$domconfig{'login'}{$key}})) {
 5535:                                     if (ref($domconfig{'login'}{$key}{$host}) eq 'HASH') {
 5536:                                         $designhash{$udom.'.login.'.$key.'_'.$host} = 1;
 5537:                                         foreach my $item ('text','img','alt','url','title','window','notsso') {
 5538:                                             $designhash{$udom.'.login.'.$key.'_'.$item.'_'.$host} = $domconfig{'login'}{$key}{$host}{$item};
 5539:                                         }
 5540:                                     }
 5541:                                 }
 5542:                             }
 5543:                         } else {
 5544:                             foreach my $img (keys(%{$domconfig{'login'}{$key}})) {
 5545:                                 $designhash{$udom.'.login.'.$key.'_'.$img} = 
 5546:                                     $domconfig{'login'}{$key}{$img};
 5547:                             }
 5548:                         }
 5549:                     } else {
 5550:                         $designhash{$udom.'.login.'.$key}=$domconfig{'login'}{$key};
 5551:                     }
 5552:                 }
 5553:             } else {
 5554:                 $legacy{'login'} = 1;
 5555:             }
 5556:         } else {
 5557:             $legacy{'login'} = 1;
 5558:         }
 5559:         if (ref($domconfig{'rolecolors'}) eq 'HASH') {
 5560:             if (keys(%{$domconfig{'rolecolors'}})) {
 5561:                 foreach my $role (keys(%{$domconfig{'rolecolors'}})) {
 5562:                     if (ref($domconfig{'rolecolors'}{$role}) eq 'HASH') {
 5563:                         foreach my $item (keys(%{$domconfig{'rolecolors'}{$role}})) {
 5564:                             $designhash{$udom.'.'.$role.'.'.$item}=$domconfig{'rolecolors'}{$role}{$item};
 5565:                         }
 5566:                     }
 5567:                 }
 5568:             } else {
 5569:                 $legacy{'rolecolors'} = 1;
 5570:             }
 5571:         } else {
 5572:             $legacy{'rolecolors'} = 1;
 5573:         }
 5574:         if (ref($domconfig{'autoenroll'}) eq 'HASH') {
 5575:             if ($domconfig{'autoenroll'}{'co-owners'}) {
 5576:                 $designhash{$udom.'.autoassign.co-owners'}=$domconfig{'autoenroll'}{'co-owners'};
 5577:             }
 5578:         }
 5579:         if (keys(%legacy) > 0) {
 5580:             my %legacyhash = &get_legacy_domconf($udom);
 5581:             foreach my $item (keys(%legacyhash)) {
 5582:                 if ($item =~ /^\Q$udom\E\.login/) {
 5583:                     if ($legacy{'login'}) { 
 5584:                         $designhash{$item} = $legacyhash{$item};
 5585:                     }
 5586:                 } else {
 5587:                     if ($legacy{'rolecolors'}) {
 5588:                         $designhash{$item} = $legacyhash{$item};
 5589:                     }
 5590:                 }
 5591:             }
 5592:         }
 5593:     } else {
 5594:         %designhash = &get_legacy_domconf($udom); 
 5595:     }
 5596:     &Apache::lonnet::do_cache_new('domainconfig',$udom,\%designhash,
 5597: 				  $cachetime);
 5598:     return %designhash;
 5599: }
 5600: 
 5601: sub get_legacy_domconf {
 5602:     my ($udom) = @_;
 5603:     my %legacyhash;
 5604:     my $designdir=$Apache::lonnet::perlvar{'lonTabDir'}.'/lonDomColors';
 5605:     my $designfile =  $designdir.'/'.$udom.'.tab';
 5606:     if (-e $designfile) {
 5607:         if ( open (my $fh,'<',$designfile) ) {
 5608:             while (my $line = <$fh>) {
 5609:                 next if ($line =~ /^\#/);
 5610:                 chomp($line);
 5611:                 my ($key,$val)=(split(/\=/,$line));
 5612:                 if ($val) { $legacyhash{$udom.'.'.$key}=$val; }
 5613:             }
 5614:             close($fh);
 5615:         }
 5616:     }
 5617:     if (-e $Apache::lonnet::perlvar{'lonDocRoot'}.'/adm/lonDomLogos/'.$udom.'.gif') {
 5618:         $legacyhash{$udom.'.login.domlogo'} = "/adm/lonDomLogos/$udom.gif";
 5619:     }
 5620:     return %legacyhash;
 5621: }
 5622: 
 5623: =pod
 5624: 
 5625: =item * &domainlogo()
 5626: 
 5627: Inputs: $domain (usually will be undef)
 5628: 
 5629: Returns: A link to a domain logo, if the domain logo exists.
 5630: If the domain logo does not exist, a description of the domain.
 5631: 
 5632: =cut
 5633: 
 5634: ###############################################
 5635: sub domainlogo {
 5636:     my $domain = &determinedomain(shift);
 5637:     my %designhash = &get_domainconf($domain);    
 5638:     # See if there is a logo
 5639:     if ($designhash{$domain.'.login.domlogo'} ne '') {
 5640:         my $imgsrc = $designhash{$domain.'.login.domlogo'};
 5641:         if ($imgsrc =~ m{^/(adm|res)/}) {
 5642: 	    if ($imgsrc =~ m{^/res/}) {
 5643: 		my $local_name = &Apache::lonnet::filelocation('',$imgsrc);
 5644: 		&Apache::lonnet::repcopy($local_name);
 5645: 	    }
 5646: 	   $imgsrc = &lonhttpdurl($imgsrc);
 5647:         }
 5648:         my $alttext = $domain;
 5649:         if ($designhash{$domain.'.login.alttext_domlogo'} ne '') {
 5650:             $alttext = $designhash{$domain.'.login.alttext_domlogo'};
 5651:         }
 5652:         return '<img src="'.$imgsrc.'" alt="'.$alttext.'" id="lclogindomlogo" />';
 5653:     } elsif (defined(&Apache::lonnet::domain($domain,'description'))) {
 5654:         return &Apache::lonnet::domain($domain,'description');
 5655:     } else {
 5656:         return '';
 5657:     }
 5658: }
 5659: ##############################################
 5660: 
 5661: =pod
 5662: 
 5663: =item * &designparm()
 5664: 
 5665: Inputs: $which parameter; $domain (usually will be undef)
 5666: 
 5667: Returns: value of designparamter $which
 5668: 
 5669: =cut
 5670: 
 5671: 
 5672: ##############################################
 5673: sub designparm {
 5674:     my ($which,$domain)=@_;
 5675:     if (exists($env{'environment.color.'.$which})) {
 5676:         return $env{'environment.color.'.$which};
 5677:     }
 5678:     $domain=&determinedomain($domain);
 5679:     my %domdesign;
 5680:     unless ($domain eq 'public') {
 5681:         %domdesign = &get_domainconf($domain);
 5682:     }
 5683:     my $output;
 5684:     if ($domdesign{$domain.'.'.$which} ne '') {
 5685:         $output = $domdesign{$domain.'.'.$which};
 5686:     } else {
 5687:         $output = $defaultdesign{$which};
 5688:     }
 5689:     if (($which =~ /^(student|coordinator|author|admin)\.img$/) ||
 5690:         ($which =~ /login\.(img|logo|domlogo|login)/)) {
 5691:         if ($output =~ m{^/(adm|res)/}) {
 5692:             if ($output =~ m{^/res/}) {
 5693:                 my $local_name = &Apache::lonnet::filelocation('',$output);
 5694:                 &Apache::lonnet::repcopy($local_name);
 5695:             }
 5696:             $output = &lonhttpdurl($output);
 5697:         }
 5698:     }
 5699:     return $output;
 5700: }
 5701: 
 5702: ##############################################
 5703: =pod
 5704: 
 5705: =item * &authorspace()
 5706: 
 5707: Inputs: $url (usually will be undef).
 5708: 
 5709: Returns: Path to Authoring Space containing the resource or 
 5710:          directory being viewed (or for which action is being taken). 
 5711:          If $url is provided, and begins /priv/<domain>/<uname>
 5712:          the path will be that portion of the $context argument.
 5713:          Otherwise the path will be for the author space of the current
 5714:          user when the current role is author, or for that of the 
 5715:          co-author/assistant co-author space when the current role 
 5716:          is co-author or assistant co-author.
 5717: 
 5718: =cut
 5719: 
 5720: sub authorspace {
 5721:     my ($url) = @_;
 5722:     if ($url ne '') {
 5723:         if ($url =~ m{^(/priv/$match_domain/$match_username/)}) {
 5724:            return $1;
 5725:         }
 5726:     }
 5727:     my $caname = '';
 5728:     my $cadom = '';
 5729:     if ($env{'request.role'} =~ /^(?:ca|aa)/) {
 5730:         ($cadom,$caname) =
 5731:             ($env{'request.role'}=~/($match_domain)\/($match_username)$/);
 5732:     } elsif ($env{'request.role'} =~ m{^au\./($match_domain)/}) {
 5733:         $caname = $env{'user.name'};
 5734:         $cadom = $env{'user.domain'};
 5735:     }
 5736:     if (($caname ne '') && ($cadom ne '')) {
 5737:         return "/priv/$cadom/$caname/";
 5738:     }
 5739:     return;
 5740: }
 5741: 
 5742: ##############################################
 5743: =pod
 5744: 
 5745: =item * &head_subbox()
 5746: 
 5747: Inputs: $content (contains HTML code with page functions, etc.)
 5748: 
 5749: Returns: HTML div with $content
 5750:          To be included in page header
 5751: 
 5752: =cut
 5753: 
 5754: sub head_subbox {
 5755:     my ($content)=@_;
 5756:     my $output =
 5757:         '<div class="LC_head_subbox">'
 5758:        .$content
 5759:        .'</div>'
 5760: }
 5761: 
 5762: ##############################################
 5763: =pod
 5764: 
 5765: =item * &CSTR_pageheader()
 5766: 
 5767: Input: (optional) filename from which breadcrumb trail is built.
 5768:        In most cases no input as needed, as $env{'request.filename'}
 5769:        is appropriate for use in building the breadcrumb trail.
 5770:        frameset flag
 5771:        If page header is being requested for use in a frameset, then
 5772:        the second (option) argument -- frameset will be true, and
 5773:        the target attribute set for links should be target="_parent".
 5774: 
 5775: Returns: HTML div with CSTR path and recent box
 5776:          To be included on Authoring Space pages
 5777: 
 5778: =cut
 5779: 
 5780: sub CSTR_pageheader {
 5781:     my ($trailfile,$frameset) = @_;
 5782:     if ($trailfile eq '') {
 5783:         $trailfile = $env{'request.filename'};
 5784:     }
 5785: 
 5786: # this is for resources; directories have customtitle, and crumbs
 5787: # and select recent are created in lonpubdir.pm
 5788: 
 5789:     my $londocroot = $Apache::lonnet::perlvar{'lonDocRoot'};
 5790:     my ($udom,$uname,$thisdisfn)=
 5791:         ($trailfile =~ m{^\Q$londocroot\E/priv/([^/]+)/([^/]+)(?:|/(.*))$});
 5792:     my $formaction = "/priv/$udom/$uname/$thisdisfn";
 5793:     $formaction =~ s{/+}{/}g;
 5794: 
 5795:     my $parentpath = '';
 5796:     my $lastitem = '';
 5797:     if ($thisdisfn =~ m-(.+/)([^/]*)$-) {
 5798:         $parentpath = $1;
 5799:         $lastitem = $2;
 5800:     } else {
 5801:         $lastitem = $thisdisfn;
 5802:     }
 5803: 
 5804:     my ($target,$crumbtarget) = (' target="_top"','_top');
 5805:     if ($frameset) {
 5806:         $target = ' target="_parent"';
 5807:         $crumbtarget = '_parent';
 5808:     } elsif (($env{'request.deeplink.login'}) && ($env{'request.deeplink.target'})) {
 5809:         $target = ' target="'.$env{'request.deeplink.target'}.'"';
 5810:         $crumbtarget = $env{'request.deeplink.target'};
 5811:     }
 5812: 
 5813:     my $output =
 5814:          '<div>'
 5815:         .&Apache::loncommon::help_open_menu('','',3,'Authoring') #FIXME: Broken? Where is it?
 5816:         .'<b>'.&mt('Authoring Space:').'</b> '
 5817:         .'<form name="dirs" method="post" action="'.$formaction.'"'.$target.'>'
 5818:         .&Apache::lonhtmlcommon::crumbs($uname.'/'.$parentpath,$crumbtarget,'/priv/'.$udom,undef,undef);
 5819: 
 5820:     if ($lastitem) {
 5821:         $output .=
 5822:              '<span class="LC_filename">'
 5823:             .$lastitem
 5824:             .'</span>';
 5825:     }
 5826:     $output .=
 5827:          '<br />'
 5828:         #FIXME lonpubdir: &Apache::lonhtmlcommon::crumbs($uname.$thisdisfn.'/',$crumbtarget,'/priv','','+1',1)."</b></tt><br />"
 5829:         .&Apache::lonhtmlcommon::select_recent('construct','recent','this.form.action=this.form.recent.value;this.form.submit()')
 5830:         .'</form>'
 5831:         .&Apache::lonmenu::constspaceform($frameset)
 5832:         .'</div>';
 5833: 
 5834:     return $output;
 5835: }
 5836: 
 5837: ###############################################
 5838: ###############################################
 5839: 
 5840: =pod
 5841: 
 5842: =back
 5843: 
 5844: =head1 HTML Helpers
 5845: 
 5846: =over 4
 5847: 
 5848: =item * &bodytag()
 5849: 
 5850: Returns a uniform header for LON-CAPA web pages.
 5851: 
 5852: Inputs: 
 5853: 
 5854: =over 4
 5855: 
 5856: =item * $title, A title to be displayed on the page.
 5857: 
 5858: =item * $function, the current role (can be undef).
 5859: 
 5860: =item * $addentries, extra parameters for the <body> tag.
 5861: 
 5862: =item * $bodyonly, if defined, only return the <body> tag.
 5863: 
 5864: =item * $domain, if defined, force a given domain.
 5865: 
 5866: =item * $forcereg, if page should register as content page (relevant for 
 5867:             text interface only)
 5868: 
 5869: =item * $no_nav_bar, if true, keep the 'what is this' info but remove the
 5870:                      navigational links
 5871: 
 5872: =item * $bgcolor, used to override the bgcolor on a webpage to a specific value
 5873: 
 5874: =item * $no_inline_link, if true and in remote mode, don't show the
 5875:          'Switch To Inline Menu' link
 5876: 
 5877: =item * $args, optional argument valid values are
 5878:             no_auto_mt_title -> prevents &mt()ing the title arg
 5879:             use_absolute     -> for external resource or syllabus, this will
 5880:                                 contain https://<hostname> if server uses
 5881:                                 https (as per hosts.tab), but request is for http
 5882:             hostname         -> hostname, from $r->hostname().
 5883: 
 5884: =item * $advtoolsref, optional argument, ref to an array containing
 5885:             inlineremote items to be added in "Functions" menu below
 5886:             breadcrumbs.
 5887: 
 5888: =item * $ltiscope, optional argument, will be one of: resource, map or
 5889:             course, if LON-CAPA is in LTI Provider context. Value is
 5890:             the scope of use, i.e., launch was for access to a single, a map
 5891:             or the entire course.
 5892: 
 5893: =item * $ltiuri, optional argument, if LON-CAPA is in LTI Provider
 5894:             context, this will contain the URL for the landing item in
 5895:             the course, after launch from an LTI Consumer
 5896: 
 5897: =item * $ltimenu, optional argument, if LON-CAPA is in LTI Provider
 5898:             context, this will contain a reference to hash of items
 5899:             to be included in the page header and/or inline menu.
 5900: 
 5901: =item * $menucoll, optional argument, if specific menu collection is in
 5902:             effect, either set as the default for the course, or set for
 5903:             the deeplink paramater for $env{'request.deeplink.login'}
 5904:             then $menucoll will be the number of that collection.
 5905: 
 5906: =item * $menuref, optional argument, reference to a hash, containing the
 5907:             menu options included for the menu in effect, based on the
 5908:             configuration for the numbered menu collection in use.
 5909: 
 5910: =item * $showncrumbsref, reference to a scalar. Calls to lonmenu::innerregister
 5911:             within &bodytag() can result in calls to lonhtmlcommon::breadcrumbs(),
 5912:             if so, $showncrumbsref is set there to 1, and will propagate back
 5913:             via &bodytag() to &start_page(), to prevent lonhtmlcommon::breadcrumbs()
 5914:             being called a second time.
 5915: 
 5916: =back
 5917: 
 5918: Returns: A uniform header for LON-CAPA web pages.  
 5919: If $bodyonly is nonzero, a string containing a <body> tag will be returned.
 5920: If $bodyonly is undef or zero, an html string containing a <body> tag and 
 5921: other decorations will be returned.
 5922: 
 5923: =cut
 5924: 
 5925: sub bodytag {
 5926:     my ($title,$function,$addentries,$bodyonly,$domain,$forcereg,
 5927:         $no_nav_bar,$bgcolor,$no_inline_link,$args,$advtoolsref,
 5928:         $ltiscope,$ltiuri,$ltimenu,$menucoll,$menuref,$showncrumbsref)=@_;
 5929: 
 5930:     my $public;
 5931:     if ((($env{'user.name'} eq 'public') && ($env{'user.domain'} eq 'public'))
 5932:         || ($env{'user.name'} eq '') && ($env{'user.domain'} eq '')) {
 5933:         $public = 1;
 5934:     }
 5935:     if (!$args->{'no_auto_mt_title'}) { $title = &mt($title); }
 5936:     my $httphost = $args->{'use_absolute'};
 5937:     my $hostname = $args->{'hostname'};
 5938: 
 5939:     $function = &get_users_function() if (!$function);
 5940:     my $img =    &designparm($function.'.img',$domain);
 5941:     my $font =   &designparm($function.'.font',$domain);
 5942:     my $pgbg   = $bgcolor || &designparm($function.'.pgbg',$domain);
 5943: 
 5944:     my %design = ( 'style'   => 'margin-top: 0',
 5945: 		   'bgcolor' => $pgbg,
 5946: 		   'text'    => $font,
 5947:                    'alink'   => &designparm($function.'.alink',$domain),
 5948: 		   'vlink'   => &designparm($function.'.vlink',$domain),
 5949: 		   'link'    => &designparm($function.'.link',$domain),);
 5950:     @design{keys(%$addentries)} = @$addentries{keys(%$addentries)}; 
 5951: 
 5952:  # role and realm
 5953:     my ($role,$realm) = split(m{\./},$env{'request.role'},2);
 5954:     if ($realm) {
 5955:         $realm = '/'.$realm;
 5956:     }
 5957:     if ($role eq 'ca') {
 5958:         my ($rdom,$rname) = ($realm =~ m{^/($match_domain)/($match_username)$});
 5959:         $realm = &plainname($rname,$rdom);
 5960:     } 
 5961: # realm
 5962:     my ($cid,$sec);
 5963:     if ($env{'request.course.id'}) {
 5964:         $cid = $env{'request.course.id'};
 5965:         if ($env{'request.course.sec'}) {
 5966:             $sec = $env{'request.course.sec'};
 5967:         }
 5968:     } elsif ($realm =~ m{^/($match_domain)/($match_courseid)(?:|/(\w+))$}) {
 5969:         if (&Apache::lonnet::is_course($1,$2)) {
 5970:             $cid = $1.'_'.$2;
 5971:             $sec = $3;
 5972:         }
 5973:     }
 5974:     if ($cid) {
 5975:         if ($env{'request.role'} !~ /^cr/) {
 5976:             $role = &Apache::lonnet::plaintext($role,&course_type());
 5977:         } elsif ($role =~ m{^cr/($match_domain)/\1-domainconfig/(\w+)$}) {
 5978:             if ($env{'request.role.desc'}) {
 5979:                 $role = $env{'request.role.desc'};
 5980:             } else {
 5981:                 $role = &mt('Helpdesk[_1]','&nbsp;'.$2);
 5982:             }
 5983:         } else {
 5984:             $role = (split(/\//,$role,4))[-1];
 5985:         }
 5986:         if ($sec) {
 5987:             $role .= ('&nbsp;'x2).'-&nbsp;'.&mt('section:').'&nbsp;'.$sec;
 5988:         }   
 5989: 	$realm = $env{'course.'.$cid.'.description'};
 5990:     } else {
 5991:         $role = &Apache::lonnet::plaintext($role);
 5992:     }
 5993: 
 5994:     if (!$realm) { $realm='&nbsp;'; }
 5995: 
 5996:     my $extra_body_attr = &make_attr_string($forcereg,\%design);
 5997: 
 5998: # construct main body tag
 5999:     my $bodytag = "<body $extra_body_attr>".
 6000: 	&Apache::lontexconvert::init_math_support();
 6001: 
 6002:     &get_unprocessed_cgi($ENV{'QUERY_STRING'}, ['inhibitmenu']);
 6003: 
 6004:     if (($bodyonly) || ($no_nav_bar) || ($env{'form.inhibitmenu'} eq 'yes')) {
 6005:         return $bodytag;
 6006:     }
 6007: 
 6008:     if ($public) {
 6009: 	undef($role);
 6010:     }
 6011: 
 6012:     my $showcrstitle = 1;
 6013:     if (($cid) && ($env{'request.lti.login'})) {
 6014:         if (ref($ltimenu) eq 'HASH') {
 6015:             unless ($ltimenu->{'role'}) {
 6016:                 undef($role);
 6017:             }
 6018:             unless ($ltimenu->{'coursetitle'}) {
 6019:                 $realm='&nbsp;';
 6020:                 $showcrstitle = 0;
 6021:             }
 6022:         }
 6023:     } elsif (($cid) && ($menucoll)) {
 6024:         if (ref($menuref) eq 'HASH') {
 6025:             unless ($menuref->{'role'}) {
 6026:                 undef($role);
 6027:             }
 6028:             unless ($menuref->{'crs'}) {
 6029:                 $realm='&nbsp;';
 6030:                 $showcrstitle = 0;
 6031:             }
 6032:         }
 6033:     }
 6034: 
 6035:     my $titleinfo = '<h1>'.$title.'</h1>';
 6036:     #
 6037:     # Extra info if you are the DC
 6038:     my $dc_info = '';
 6039:     if (($env{'user.adv'}) && ($env{'request.course.id'}) && $showcrstitle &&
 6040:         (exists($env{'user.role.dc./'.$env{'course.'.$cid.'.domain'}.'/'}))) {
 6041:         $dc_info = $cid.' '.$env{'course.'.$cid.'.internal.coursecode'};
 6042:         $dc_info =~ s/\s+$//;
 6043:     }
 6044: 
 6045:     my $crstype;
 6046:     if ($cid) {
 6047:         $crstype = $env{'course.'.$cid.'.type'};
 6048:     } elsif ($args->{'crstype'}) {
 6049:         $crstype = $args->{'crstype'};
 6050:     }
 6051: 
 6052:     $role = '<span class="LC_nobreak">('.$role.')</span>' if ($role && !$env{'browser.mobile'});
 6053: 
 6054:     if ($env{'request.state'} eq 'construct') { $forcereg=1; }
 6055: 
 6056: 
 6057: 
 6058:     my $funclist;
 6059:     if (($env{'environment.remote'} eq 'on') && ($env{'request.state'} ne 'construct')) {
 6060:         $bodytag .= Apache::lonhtmlcommon::scripttag(Apache::lonmenu::utilityfunctions($httphost), 'start')."\n".
 6061:                     Apache::lonmenu::serverform();
 6062:         my $forbodytag;
 6063:         &Apache::lonmenu::prepare_functions($env{'request.noversionuri'},
 6064:                                             $forcereg,$args->{'group'},
 6065:                                             $args->{'bread_crumbs'},
 6066:                                             $advtoolsref,'','',\$forbodytag);
 6067:         unless (ref($args->{'bread_crumbs'}) eq 'ARRAY') {
 6068:             $funclist = $forbodytag;
 6069:         }
 6070:     } else {
 6071: 
 6072:         #    if ($env{'request.state'} eq 'construct') {
 6073:         #        $titleinfo = &CSTR_pageheader(); #FIXME: Will be removed once all scripts have their own calls
 6074:         #    }
 6075: 
 6076:         $bodytag .= Apache::lonhtmlcommon::scripttag(
 6077:             Apache::lonmenu::utilityfunctions($httphost), 'start');
 6078: 
 6079:         unless ($args->{'no_primary_menu'}) {
 6080:             my ($left,$right) = Apache::lonmenu::primary_menu($crstype,$ltimenu,$menucoll,$menuref,
 6081:                                                               $args->{'links_disabled'},
 6082:                                                               $args->{'links_target'});
 6083:             if ($env{'request.noversionuri'} =~ m{^/res/adm/pages/}) {
 6084:                 if ($dc_info) {
 6085:                     $dc_info = qq|<span class="LC_cusr_subheading">$dc_info</span>|;
 6086:                 }
 6087:                 $bodytag .= qq|<div id="LC_nav_bar">$left $role<br />
 6088:                                <em>$realm</em> $dc_info</div>|;
 6089:                 return $bodytag;
 6090:             }
 6091: 
 6092:             unless ($env{'request.symb'} =~ m/\.page___\d+___/) {
 6093:                 $bodytag .= qq|<div id="LC_nav_bar">$left $role</div>|;
 6094:             }
 6095: 
 6096:             $bodytag .= $right;
 6097: 
 6098:             if ($dc_info) {
 6099:                 $dc_info = &dc_courseid_toggle($dc_info);
 6100:             }
 6101:             $bodytag .= qq|<div id="LC_realm">$realm $dc_info</div>|;
 6102:         }
 6103: 
 6104:         #if directed to not display the secondary menu, don't.
 6105:         if ($args->{'no_secondary_menu'}) {
 6106:             return $bodytag;
 6107:         }
 6108:         #don't show menus for public users
 6109:         if (!$public){
 6110:             unless ($args->{'no_inline_menu'}) {
 6111:                 $bodytag .= Apache::lonmenu::secondary_menu($httphost,$ltiscope,$ltimenu,
 6112:                                                             $args->{'no_primary_menu'},
 6113:                                                             $menucoll,$menuref,
 6114:                                                             $args->{'links_disabled'},
 6115:                                                             $args->{'links_target'});
 6116:             }
 6117:             $bodytag .= Apache::lonmenu::serverform();
 6118:             $bodytag .= Apache::lonhtmlcommon::scripttag('', 'end');
 6119:             if ($env{'request.state'} eq 'construct') {
 6120:                 $bodytag .= &Apache::lonmenu::innerregister($forcereg,
 6121:                                 $args->{'bread_crumbs'},'','',$hostname,
 6122:                                 $ltiscope,$ltiuri,$showncrumbsref);
 6123:             } elsif ($forcereg) {
 6124:                 $bodytag .= &Apache::lonmenu::innerregister($forcereg,undef,
 6125:                                 $args->{'group'},$args->{'hide_buttons'},
 6126:                                 $hostname,$ltiscope,$ltiuri,$showncrumbsref);
 6127:             } else {
 6128:                 my $forbodytag;
 6129:                 &Apache::lonmenu::prepare_functions($env{'request.noversionuri'},
 6130:                                                     $forcereg,$args->{'group'},
 6131:                                                     $args->{'bread_crumbs'},
 6132:                                                     $advtoolsref,'',$hostname,
 6133:                                                     \$forbodytag);
 6134:                 unless (ref($args->{'bread_crumbs'}) eq 'ARRAY') {
 6135:                     $bodytag .= $forbodytag;
 6136:                 }
 6137:             }
 6138:         }else{
 6139:             # this is to seperate menu from content when there's no secondary
 6140:             # menu. Especially needed for public accessible ressources.
 6141:             $bodytag .= '<hr style="clear:both" />';
 6142:             $bodytag .= Apache::lonhtmlcommon::scripttag('', 'end'); 
 6143:         }
 6144: 
 6145:         return $bodytag;
 6146:     }
 6147: 
 6148: #
 6149: # Top frame rendering, Remote is up
 6150: #
 6151: 
 6152:     my $imgsrc = $img;
 6153:     if ($img =~ /^\/adm/) {
 6154:         $imgsrc = &lonhttpdurl($img);
 6155:     }
 6156:     my $upperleft='<img src="'.$imgsrc.'" alt="'.$function.'" />';
 6157: 
 6158:     my $help=($no_inline_link?''
 6159:               :&Apache::loncommon::top_nav_help('Help'));
 6160: 
 6161:     # Explicit link to get inline menu
 6162:     my $menu= ($no_inline_link?''
 6163:                :'<a href="/adm/remote?action=collapse" target="_top">'.&mt('Switch to Inline Menu Mode').'</a>');
 6164: 
 6165:     if ($dc_info) {
 6166:         $dc_info = qq|<span class="LC_cusr_subheading">($dc_info)</span>|;
 6167:     }
 6168: 
 6169:     my $name = &plainname($env{'user.name'},$env{'user.domain'});
 6170:     unless ($public) {
 6171:         $name = &aboutmewrapper($name,$env{'user.name'},$env{'user.domain'},
 6172:                                 undef,'LC_menubuttons_link');
 6173:     }
 6174: 
 6175:     unless ($env{'form.inhibitmenu'}) {
 6176:         $bodytag .= qq|<div id="LC_nav_bar">$name $role</div>
 6177:                        <ol class="LC_primary_menu LC_floatright LC_right">
 6178:                        <li>$help</li>
 6179:                        <li>$menu</li>
 6180:                        </ol><div id="LC_realm"> $realm $dc_info</div>|;
 6181:     }
 6182:     if ($env{'request.state'} eq 'construct') {
 6183:         if (!$public){
 6184:             if ($env{'request.state'} eq 'construct') {
 6185:                 $funclist = &Apache::lonhtmlcommon::scripttag(
 6186:                                 &Apache::lonmenu::utilityfunctions($httphost), 'start').
 6187:                             &Apache::lonhtmlcommon::scripttag('','end').
 6188:                             &Apache::lonmenu::innerregister($forcereg,
 6189:                                                             $args->{'bread_crumbs'});
 6190:             }
 6191:         }
 6192:     }
 6193:     return $bodytag."\n".$funclist;
 6194: }
 6195: 
 6196: sub dc_courseid_toggle {
 6197:     my ($dc_info) = @_;
 6198:     return ' <span id="dccidtext" class="LC_cusr_subheading LC_nobreak">'.
 6199:            '<a href="javascript:showCourseID();" class="LC_menubuttons_link">'.
 6200:            &mt('(More ...)').'</a></span>'.
 6201:            '<div id="dccid" class="LC_dccid">'.$dc_info.'</div>';
 6202: }
 6203: 
 6204: sub make_attr_string {
 6205:     my ($register,$attr_ref) = @_;
 6206: 
 6207:     if ($attr_ref && !ref($attr_ref)) {
 6208: 	die("addentries Must be a hash ref ".
 6209: 	    join(':',caller(1))." ".
 6210: 	    join(':',caller(0))." ");
 6211:     }
 6212: 
 6213:     if ($register) {
 6214: 	my ($on_load,$on_unload);
 6215: 	foreach my $key (keys(%{$attr_ref})) {
 6216: 	    if      (lc($key) eq 'onload') {
 6217: 		$on_load.=$attr_ref->{$key}.';';
 6218: 		delete($attr_ref->{$key});
 6219: 
 6220: 	    } elsif (lc($key) eq 'onunload') {
 6221: 		$on_unload.=$attr_ref->{$key}.';';
 6222: 		delete($attr_ref->{$key});
 6223: 	    }
 6224: 	}
 6225:         if ($env{'environment.remote'} eq 'on') {
 6226:             $attr_ref->{'onload'}  =
 6227:                 &Apache::lonmenu::loadevents().  $on_load;
 6228:             $attr_ref->{'onunload'}=
 6229:                 &Apache::lonmenu::unloadevents().$on_unload;
 6230:         } else {  
 6231: 	    $attr_ref->{'onload'}  = $on_load;
 6232: 	    $attr_ref->{'onunload'}= $on_unload;
 6233:         }
 6234:     }
 6235: 
 6236:     my $attr_string;
 6237:     foreach my $attr (sort(keys(%$attr_ref))) {
 6238: 	$attr_string .= " $attr=\"".$attr_ref->{$attr}.'" ';
 6239:     }
 6240:     return $attr_string;
 6241: }
 6242: 
 6243: 
 6244: ###############################################
 6245: ###############################################
 6246: 
 6247: =pod
 6248: 
 6249: =item * &endbodytag()
 6250: 
 6251: Returns a uniform footer for LON-CAPA web pages.
 6252: 
 6253: Inputs: 1 - optional reference to an args hash
 6254: If in the hash, key for noredirectlink has a value which evaluates to true,
 6255: a 'Continue' link is not displayed if the page contains an
 6256: internal redirect in the <head></head> section,
 6257: i.e., $env{'internal.head.redirect'} exists   
 6258: 
 6259: =cut
 6260: 
 6261: sub endbodytag {
 6262:     my ($args) = @_;
 6263:     my $endbodytag;
 6264:     unless ((ref($args) eq 'HASH') && ($args->{'notbody'})) {
 6265:         $endbodytag='</body>';
 6266:     }
 6267:     if ( exists( $env{'internal.head.redirect'} ) ) {
 6268:         if (!(ref($args) eq 'HASH' && $args->{'noredirectlink'})) {
 6269:             my ($endbodyjs,$idattr);
 6270:             if ($env{'internal.head.to_opener'}) {
 6271:                 my $linkid = 'LC_continue_link';
 6272:                 $idattr = ' id="'.$linkid.'"';
 6273:                 my $redirect_for_js = &js_escape($env{'internal.head.redirect'});
 6274:                 $endbodyjs=<<ENDJS;
 6275: <script type="text/javascript">
 6276: // <![CDATA[
 6277: function ebFunction(evt) {
 6278:     evt.preventDefault();
 6279:     var dest = '$redirect_for_js';
 6280:     if (window.opener != null && !window.opener.closed) {
 6281:         window.opener.location.href=dest;
 6282:         window.close();
 6283:     } else {
 6284:         window.location.href=dest;
 6285:     }
 6286:     return false;
 6287: }
 6288: 
 6289: \$(document).ready(function () {
 6290:   if (document.getElementById('$linkid')) {
 6291:     var clickelem = document.getElementById('$linkid');
 6292:     clickelem.addEventListener('click',ebFunction,false);
 6293:   }
 6294: });
 6295: // ]]>
 6296: </script>
 6297: ENDJS
 6298:             }
 6299: 	    $endbodytag=
 6300: 	        "$endbodyjs<br /><a href=\"$env{'internal.head.redirect'}\"$idattr>".
 6301: 	        &mt('Continue').'</a>'.
 6302: 	        $endbodytag;
 6303:         }
 6304:     }
 6305:     return $endbodytag;
 6306: }
 6307: 
 6308: =pod
 6309: 
 6310: =item * &standard_css()
 6311: 
 6312: Returns a style sheet
 6313: 
 6314: Inputs: (all optional)
 6315:             domain         -> force to color decorate a page for a specific
 6316:                                domain
 6317:             function       -> force usage of a specific rolish color scheme
 6318:             bgcolor        -> override the default page bgcolor
 6319: 
 6320: =cut
 6321: 
 6322: sub standard_css {
 6323:     my ($function,$domain,$bgcolor) = @_;
 6324:     $function  = &get_users_function() if (!$function);
 6325:     my $img    = &designparm($function.'.img',   $domain);
 6326:     my $tabbg  = &designparm($function.'.tabbg', $domain);
 6327:     my $font   = &designparm($function.'.font',  $domain);
 6328:     my $fontmenu = &designparm($function.'.fontmenu', $domain);
 6329: #second colour for later usage
 6330:     my $sidebg = &designparm($function.'.sidebg',$domain);
 6331:     my $pgbg_or_bgcolor =
 6332: 	         $bgcolor ||
 6333: 	         &designparm($function.'.pgbg',  $domain);
 6334:     my $pgbg   = &designparm($function.'.pgbg',  $domain);
 6335:     my $alink  = &designparm($function.'.alink', $domain);
 6336:     my $vlink  = &designparm($function.'.vlink', $domain);
 6337:     my $link   = &designparm($function.'.link',  $domain);
 6338: 
 6339:     my $sans                 = 'Verdana,Arial,Helvetica,sans-serif';
 6340:     my $mono                 = 'monospace';
 6341:     my $data_table_head      = $sidebg;
 6342:     my $data_table_light     = '#FAFAFA';
 6343:     my $data_table_dark      = '#E0E0E0';
 6344:     my $data_table_darker    = '#CCCCCC';
 6345:     my $data_table_highlight = '#FFFF00';
 6346:     my $mail_new             = '#FFBB77';
 6347:     my $mail_new_hover       = '#DD9955';
 6348:     my $mail_read            = '#BBBB77';
 6349:     my $mail_read_hover      = '#999944';
 6350:     my $mail_replied         = '#AAAA88';
 6351:     my $mail_replied_hover   = '#888855';
 6352:     my $mail_other           = '#99BBBB';
 6353:     my $mail_other_hover     = '#669999';
 6354:     my $table_header         = '#DDDDDD';
 6355:     my $feedback_link_bg     = '#BBBBBB';
 6356:     my $lg_border_color      = '#C8C8C8';
 6357:     my $button_hover         = '#BF2317';
 6358: 
 6359:     my $border = ($env{'browser.type'} eq 'explorer' ||
 6360:       $env{'browser.type'} eq 'safari'     ) ? '0 2px 0 2px'
 6361:                                              : '0 3px 0 4px';
 6362: 
 6363: 
 6364:     return <<END;
 6365: 
 6366: /* needed for iframe to allow 100% height in FF */
 6367: body, html { 
 6368:     margin: 0;
 6369:     padding: 0 0.5%;
 6370:     height: 99%; /* to avoid scrollbars */
 6371: }
 6372: 
 6373: body {
 6374:   font-family: $sans;
 6375:   line-height:130%;
 6376:   font-size:0.83em;
 6377:   color:$font;
 6378: }
 6379: 
 6380: a:focus,
 6381: a:focus img {
 6382:   color: red;
 6383: }
 6384: 
 6385: form, .inline {
 6386:   display: inline;
 6387: }
 6388: 
 6389: .LC_right {
 6390:   text-align:right;
 6391: }
 6392: 
 6393: .LC_middle {
 6394:   vertical-align:middle;
 6395: }
 6396: 
 6397: .LC_floatleft {
 6398:   float: left;
 6399: }
 6400: 
 6401: .LC_floatright {
 6402:   float: right;
 6403: }
 6404: 
 6405: .LC_400Box {
 6406:   width:400px;
 6407: }
 6408: 
 6409: .LC_iframecontainer {
 6410:     width: 98%;
 6411:     margin: 0;
 6412:     position: fixed;
 6413:     top: 8.5em;
 6414:     bottom: 0;
 6415: }
 6416: 
 6417: .LC_iframecontainer iframe{
 6418:     border: none;
 6419:     width: 100%;
 6420:     height: 100%;
 6421: }
 6422: 
 6423: .LC_filename {
 6424:   font-family: $mono;
 6425:   white-space:pre;
 6426:   font-size: 120%;
 6427: }
 6428: 
 6429: .LC_fileicon {
 6430:   border: none;
 6431:   height: 1.3em;
 6432:   vertical-align: text-bottom;
 6433:   margin-right: 0.3em;
 6434:   text-decoration:none;
 6435: }
 6436: 
 6437: .LC_setting {
 6438:   text-decoration:underline;
 6439: }
 6440: 
 6441: .LC_error {
 6442:   color: red;
 6443: }
 6444: 
 6445: .LC_warning {
 6446:   color: darkorange;
 6447: }
 6448: 
 6449: .LC_diff_removed {
 6450:   color: red;
 6451: }
 6452: 
 6453: .LC_info,
 6454: .LC_success,
 6455: .LC_diff_added {
 6456:   color: green;
 6457: }
 6458: 
 6459: div.LC_confirm_box {
 6460:   background-color: #FAFAFA;
 6461:   border: 1px solid $lg_border_color;
 6462:   margin-right: 0;
 6463:   padding: 5px;
 6464: }
 6465: 
 6466: div.LC_confirm_box .LC_error img,
 6467: div.LC_confirm_box .LC_success img {
 6468:   vertical-align: middle;
 6469: }
 6470: 
 6471: .LC_maxwidth {
 6472:   max-width: 100%;
 6473:   height: auto;
 6474: }
 6475: 
 6476: .LC_textsize_mobile {
 6477:   \@media only screen and (max-device-width: 480px) {
 6478:       -webkit-text-size-adjust:100%; -moz-text-size-adjust:100%; -ms-text-size-adjust:100%;
 6479:   }
 6480: }
 6481: 
 6482: .LC_icon {
 6483:   border: none;
 6484:   vertical-align: middle;
 6485: }
 6486: 
 6487: .LC_docs_spacer {
 6488:   width: 25px;
 6489:   height: 1px;
 6490:   border: none;
 6491: }
 6492: 
 6493: .LC_internal_info {
 6494:   color: #999999;
 6495: }
 6496: 
 6497: .LC_discussion {
 6498:   background: $data_table_dark;
 6499:   border: 1px solid black;
 6500:   margin: 2px;
 6501: }
 6502: 
 6503: .LC_disc_action_left {
 6504:   background: $sidebg;
 6505:   text-align: left;
 6506:   padding: 4px;
 6507:   margin: 2px;
 6508: }
 6509: 
 6510: .LC_disc_action_right {
 6511:   background: $sidebg;
 6512:   text-align: right;
 6513:   padding: 4px;
 6514:   margin: 2px;
 6515: }
 6516: 
 6517: .LC_disc_new_item {
 6518:   background: white;
 6519:   border: 2px solid red;
 6520:   margin: 4px;
 6521:   padding: 4px;
 6522: }
 6523: 
 6524: .LC_disc_old_item {
 6525:   background: white;
 6526:   margin: 4px;
 6527:   padding: 4px;
 6528: }
 6529: 
 6530: table.LC_pastsubmission {
 6531:   border: 1px solid black;
 6532:   margin: 2px;
 6533: }
 6534: 
 6535: table#LC_menubuttons {
 6536:   width: 100%;
 6537:   background: $pgbg;
 6538:   border: 2px;
 6539:   border-collapse: separate;
 6540:   padding: 0;
 6541: }
 6542: 
 6543: table#LC_title_bar a {
 6544:   color: $fontmenu;
 6545: }
 6546: 
 6547: table#LC_title_bar {
 6548:   clear: both;
 6549:   display: none;
 6550: }
 6551: 
 6552: table#LC_title_bar,
 6553: table.LC_breadcrumbs, /* obsolete? */
 6554: table#LC_title_bar.LC_with_remote {
 6555:   width: 100%;
 6556:   border-color: $pgbg;
 6557:   border-style: solid;
 6558:   border-width: $border;
 6559:   background: $pgbg;
 6560:   color: $fontmenu;
 6561:   border-collapse: collapse;
 6562:   padding: 0;
 6563:   margin: 0;
 6564: }
 6565: 
 6566: ul.LC_breadcrumb_tools_outerlist {
 6567:     margin: 0;
 6568:     padding: 0;
 6569:     position: relative;
 6570:     list-style: none;
 6571: }
 6572: ul.LC_breadcrumb_tools_outerlist li {
 6573:     display: inline;
 6574: }
 6575: 
 6576: .LC_breadcrumb_tools_navigation {
 6577:     padding: 0;
 6578:     margin: 0;
 6579:     float: left;
 6580: }
 6581: .LC_breadcrumb_tools_tools {
 6582:     padding: 0;
 6583:     margin: 0;
 6584:     float: right;
 6585: }
 6586: 
 6587: table#LC_title_bar td {
 6588:   background: $tabbg;
 6589: }
 6590: 
 6591: table#LC_menubuttons img {
 6592:   border: none;
 6593: }
 6594: 
 6595: .LC_breadcrumbs_component {
 6596:   float: right;
 6597:   margin: 0 1em;
 6598: }
 6599: .LC_breadcrumbs_component img {
 6600:   vertical-align: middle;
 6601: }
 6602: 
 6603: .LC_breadcrumbs_hoverable {
 6604:   background: $sidebg;
 6605: }
 6606: 
 6607: td.LC_table_cell_checkbox {
 6608:   text-align: center;
 6609: }
 6610: 
 6611: .LC_fontsize_small {
 6612:   font-size: 70%;
 6613: }
 6614: 
 6615: #LC_breadcrumbs {
 6616:   clear:both;
 6617:   background: $sidebg;
 6618:   border-bottom: 1px solid $lg_border_color;
 6619:   line-height: 2.5em;
 6620:   overflow: hidden;
 6621:   margin: 0;
 6622:   padding: 0;
 6623:   text-align: left;
 6624: }
 6625: 
 6626: .LC_head_subbox, .LC_actionbox {
 6627:   clear:both;
 6628:   background: #F8F8F8; /* $sidebg; */
 6629:   border: 1px solid $sidebg;
 6630:   margin: 0 0 10px 0;
 6631:   padding: 3px;
 6632:   text-align: left;
 6633: }
 6634: 
 6635: .LC_fontsize_medium {
 6636:   font-size: 85%;
 6637: }
 6638: 
 6639: .LC_fontsize_large {
 6640:   font-size: 120%;
 6641: }
 6642: 
 6643: .LC_menubuttons_inline_text {
 6644:   color: $font;
 6645:   font-size: 90%;
 6646:   padding-left:3px;
 6647: }
 6648: 
 6649: .LC_menubuttons_inline_text img{
 6650:   vertical-align: middle;
 6651: }
 6652: 
 6653: li.LC_menubuttons_inline_text img {
 6654:   cursor:pointer;
 6655:   text-decoration: none;
 6656: }
 6657: 
 6658: .LC_menubuttons_link {
 6659:   text-decoration: none;
 6660: }
 6661: 
 6662: .LC_menubuttons_category {
 6663:   color: $font;
 6664:   background: $pgbg;
 6665:   font-size: larger;
 6666:   font-weight: bold;
 6667: }
 6668: 
 6669: td.LC_menubuttons_text {
 6670:   color: $font;
 6671: }
 6672: 
 6673: .LC_current_location {
 6674:   background: $tabbg;
 6675: }
 6676: 
 6677: td.LC_zero_height {
 6678:   line-height: 0;
 6679:   cellpadding: 0;
 6680: }
 6681: 
 6682: table.LC_data_table {
 6683:   border: 1px solid #000000;
 6684:   border-collapse: separate;
 6685:   border-spacing: 1px;
 6686:   background: $pgbg;
 6687: }
 6688: 
 6689: .LC_data_table_dense {
 6690:   font-size: small;
 6691: }
 6692: 
 6693: table.LC_nested_outer {
 6694:   border: 1px solid #000000;
 6695:   border-collapse: collapse;
 6696:   border-spacing: 0;
 6697:   width: 100%;
 6698: }
 6699: 
 6700: table.LC_innerpickbox,
 6701: table.LC_nested {
 6702:   border: none;
 6703:   border-collapse: collapse;
 6704:   border-spacing: 0;
 6705:   width: 100%;
 6706: }
 6707: 
 6708: table.LC_data_table tr th,
 6709: table.LC_calendar tr th,
 6710: table.LC_prior_tries tr th,
 6711: table.LC_innerpickbox tr th {
 6712:   font-weight: bold;
 6713:   background-color: $data_table_head;
 6714:   color:$fontmenu;
 6715:   font-size:90%;
 6716: }
 6717: 
 6718: table.LC_innerpickbox tr th,
 6719: table.LC_innerpickbox tr td {
 6720:   vertical-align: top;
 6721: }
 6722: 
 6723: table.LC_data_table tr.LC_info_row > td {
 6724:   background-color: #CCCCCC;
 6725:   font-weight: bold;
 6726:   text-align: left;
 6727: }
 6728: 
 6729: table.LC_data_table tr.LC_odd_row > td {
 6730:   background-color: $data_table_light;
 6731:   padding: 2px;
 6732:   vertical-align: top;
 6733: }
 6734: 
 6735: table.LC_pick_box tr > td.LC_odd_row {
 6736:   background-color: $data_table_light;
 6737:   vertical-align: top;
 6738: }
 6739: 
 6740: table.LC_data_table tr.LC_even_row > td {
 6741:   background-color: $data_table_dark;
 6742:   padding: 2px;
 6743:   vertical-align: top;
 6744: }
 6745: 
 6746: table.LC_pick_box tr > td.LC_even_row {
 6747:   background-color: $data_table_dark;
 6748:   vertical-align: top;
 6749: }
 6750: 
 6751: table.LC_data_table tr.LC_data_table_highlight td {
 6752:   background-color: $data_table_darker;
 6753: }
 6754: 
 6755: table.LC_data_table tr td.LC_leftcol_header {
 6756:   background-color: $data_table_head;
 6757:   font-weight: bold;
 6758: }
 6759: 
 6760: table.LC_data_table tr.LC_empty_row td,
 6761: table.LC_nested tr.LC_empty_row td {
 6762:   font-weight: bold;
 6763:   font-style: italic;
 6764:   text-align: center;
 6765:   padding: 8px;
 6766: }
 6767: 
 6768: table.LC_data_table tr.LC_empty_row td,
 6769: table.LC_data_table tr.LC_footer_row td {
 6770:   background-color: $sidebg;
 6771: }
 6772: 
 6773: table.LC_nested tr.LC_empty_row td {
 6774:   background-color: #FFFFFF;
 6775: }
 6776: 
 6777: table.LC_caption {
 6778: }
 6779: 
 6780: table.LC_nested tr.LC_empty_row td {
 6781:   padding: 4ex
 6782: }
 6783: 
 6784: table.LC_nested_outer tr th {
 6785:   font-weight: bold;
 6786:   color:$fontmenu;
 6787:   background-color: $data_table_head;
 6788:   font-size: small;
 6789:   border-bottom: 1px solid #000000;
 6790: }
 6791: 
 6792: table.LC_nested_outer tr td.LC_subheader {
 6793:   background-color: $data_table_head;
 6794:   font-weight: bold;
 6795:   font-size: small;
 6796:   border-bottom: 1px solid #000000;
 6797:   text-align: right;
 6798: }
 6799: 
 6800: table.LC_nested tr.LC_info_row td {
 6801:   background-color: #CCCCCC;
 6802:   font-weight: bold;
 6803:   font-size: small;
 6804:   text-align: center;
 6805: }
 6806: 
 6807: table.LC_nested tr.LC_info_row td.LC_left_item,
 6808: table.LC_nested_outer tr th.LC_left_item {
 6809:   text-align: left;
 6810: }
 6811: 
 6812: table.LC_nested td {
 6813:   background-color: #FFFFFF;
 6814:   font-size: small;
 6815: }
 6816: 
 6817: table.LC_nested_outer tr th.LC_right_item,
 6818: table.LC_nested tr.LC_info_row td.LC_right_item,
 6819: table.LC_nested tr.LC_odd_row td.LC_right_item,
 6820: table.LC_nested tr td.LC_right_item {
 6821:   text-align: right;
 6822: }
 6823: 
 6824: table.LC_nested tr.LC_odd_row td {
 6825:   background-color: #EEEEEE;
 6826: }
 6827: 
 6828: table.LC_createuser {
 6829: }
 6830: 
 6831: table.LC_createuser tr.LC_section_row td {
 6832:   font-size: small;
 6833: }
 6834: 
 6835: table.LC_createuser tr.LC_info_row td  {
 6836:   background-color: #CCCCCC;
 6837:   font-weight: bold;
 6838:   text-align: center;
 6839: }
 6840: 
 6841: table.LC_calendar {
 6842:   border: 1px solid #000000;
 6843:   border-collapse: collapse;
 6844:   width: 98%;
 6845: }
 6846: 
 6847: table.LC_calendar_pickdate {
 6848:   font-size: xx-small;
 6849: }
 6850: 
 6851: table.LC_calendar tr td {
 6852:   border: 1px solid #000000;
 6853:   vertical-align: top;
 6854:   width: 14%;
 6855: }
 6856: 
 6857: table.LC_calendar tr td.LC_calendar_day_empty {
 6858:   background-color: $data_table_dark;
 6859: }
 6860: 
 6861: table.LC_calendar tr td.LC_calendar_day_current {
 6862:   background-color: $data_table_highlight;
 6863: }
 6864: 
 6865: table.LC_data_table tr td.LC_mail_new {
 6866:   background-color: $mail_new;
 6867: }
 6868: 
 6869: table.LC_data_table tr.LC_mail_new:hover {
 6870:   background-color: $mail_new_hover;
 6871: }
 6872: 
 6873: table.LC_data_table tr td.LC_mail_read {
 6874:   background-color: $mail_read;
 6875: }
 6876: 
 6877: /*
 6878: table.LC_data_table tr.LC_mail_read:hover {
 6879:   background-color: $mail_read_hover;
 6880: }
 6881: */
 6882: 
 6883: table.LC_data_table tr td.LC_mail_replied {
 6884:   background-color: $mail_replied;
 6885: }
 6886: 
 6887: /*
 6888: table.LC_data_table tr.LC_mail_replied:hover {
 6889:   background-color: $mail_replied_hover;
 6890: }
 6891: */
 6892: 
 6893: table.LC_data_table tr td.LC_mail_other {
 6894:   background-color: $mail_other;
 6895: }
 6896: 
 6897: /*
 6898: table.LC_data_table tr.LC_mail_other:hover {
 6899:   background-color: $mail_other_hover;
 6900: }
 6901: */
 6902: 
 6903: table.LC_data_table tr > td.LC_browser_file,
 6904: table.LC_data_table tr > td.LC_browser_file_published {
 6905:   background: #AAEE77;
 6906: }
 6907: 
 6908: table.LC_data_table tr > td.LC_browser_file_locked,
 6909: table.LC_data_table tr > td.LC_browser_file_unpublished {
 6910:   background: #FFAA99;
 6911: }
 6912: 
 6913: table.LC_data_table tr > td.LC_browser_file_obsolete {
 6914:   background: #888888;
 6915: }
 6916: 
 6917: table.LC_data_table tr > td.LC_browser_file_modified,
 6918: table.LC_data_table tr > td.LC_browser_file_metamodified {
 6919:   background: #F8F866;
 6920: }
 6921: 
 6922: table.LC_data_table tr.LC_browser_folder > td {
 6923:   background: #E0E8FF;
 6924: }
 6925: 
 6926: table.LC_data_table tr > td.LC_roles_is {
 6927:   /* background: #77FF77; */
 6928: }
 6929: 
 6930: table.LC_data_table tr > td.LC_roles_future {
 6931:   border-right: 8px solid #FFFF77;
 6932: }
 6933: 
 6934: table.LC_data_table tr > td.LC_roles_will {
 6935:   border-right: 8px solid #FFAA77;
 6936: }
 6937: 
 6938: table.LC_data_table tr > td.LC_roles_expired {
 6939:   border-right: 8px solid #FF7777;
 6940: }
 6941: 
 6942: table.LC_data_table tr > td.LC_roles_will_not {
 6943:   border-right: 8px solid #AAFF77;
 6944: }
 6945: 
 6946: table.LC_data_table tr > td.LC_roles_selected {
 6947:   border-right: 8px solid #11CC55;
 6948: }
 6949: 
 6950: span.LC_current_location {
 6951:   font-size:larger;
 6952:   background: $pgbg;
 6953: }
 6954: 
 6955: span.LC_current_nav_location {
 6956:   font-weight:bold;
 6957:   background: $sidebg;
 6958: }
 6959: 
 6960: span.LC_parm_menu_item {
 6961:   font-size: larger;
 6962: }
 6963: 
 6964: span.LC_parm_scope_all {
 6965:   color: red;
 6966: }
 6967: 
 6968: span.LC_parm_scope_folder {
 6969:   color: green;
 6970: }
 6971: 
 6972: span.LC_parm_scope_resource {
 6973:   color: orange;
 6974: }
 6975: 
 6976: span.LC_parm_part {
 6977:   color: blue;
 6978: }
 6979: 
 6980: span.LC_parm_folder,
 6981: span.LC_parm_symb {
 6982:   font-size: x-small;
 6983:   font-family: $mono;
 6984:   color: #AAAAAA;
 6985: }
 6986: 
 6987: ul.LC_parm_parmlist li {
 6988:   display: inline-block;
 6989:   padding: 0.3em 0.8em;
 6990:   vertical-align: top;
 6991:   width: 150px;
 6992:   border-top:1px solid $lg_border_color;
 6993: }
 6994: 
 6995: td.LC_parm_overview_level_menu,
 6996: td.LC_parm_overview_map_menu,
 6997: td.LC_parm_overview_parm_selectors,
 6998: td.LC_parm_overview_restrictions  {
 6999:   border: 1px solid black;
 7000:   border-collapse: collapse;
 7001: }
 7002: 
 7003: table.LC_parm_overview_restrictions td {
 7004:   border-width: 1px 4px 1px 4px;
 7005:   border-style: solid;
 7006:   border-color: $pgbg;
 7007:   text-align: center;
 7008: }
 7009: 
 7010: table.LC_parm_overview_restrictions th {
 7011:   background: $tabbg;
 7012:   border-width: 1px 4px 1px 4px;
 7013:   border-style: solid;
 7014:   border-color: $pgbg;
 7015: }
 7016: 
 7017: table#LC_helpmenu {
 7018:   border: none;
 7019:   height: 55px;
 7020:   border-spacing: 0;
 7021: }
 7022: 
 7023: table#LC_helpmenu fieldset legend {
 7024:   font-size: larger;
 7025: }
 7026: 
 7027: table#LC_helpmenu_links {
 7028:   width: 100%;
 7029:   border: 1px solid black;
 7030:   background: $pgbg;
 7031:   padding: 0;
 7032:   border-spacing: 1px;
 7033: }
 7034: 
 7035: table#LC_helpmenu_links tr td {
 7036:   padding: 1px;
 7037:   background: $tabbg;
 7038:   text-align: center;
 7039:   font-weight: bold;
 7040: }
 7041: 
 7042: table#LC_helpmenu_links a:link,
 7043: table#LC_helpmenu_links a:visited,
 7044: table#LC_helpmenu_links a:active {
 7045:   text-decoration: none;
 7046:   color: $font;
 7047: }
 7048: 
 7049: table#LC_helpmenu_links a:hover {
 7050:   text-decoration: underline;
 7051:   color: $vlink;
 7052: }
 7053: 
 7054: .LC_chrt_popup_exists {
 7055:   border: 1px solid #339933;
 7056:   margin: -1px;
 7057: }
 7058: 
 7059: .LC_chrt_popup_up {
 7060:   border: 1px solid yellow;
 7061:   margin: -1px;
 7062: }
 7063: 
 7064: .LC_chrt_popup {
 7065:   border: 1px solid #8888FF;
 7066:   background: #CCCCFF;
 7067: }
 7068: 
 7069: table.LC_pick_box {
 7070:   border-collapse: separate;
 7071:   background: white;
 7072:   border: 1px solid black;
 7073:   border-spacing: 1px;
 7074: }
 7075: 
 7076: table.LC_pick_box td.LC_pick_box_title {
 7077:   background: $sidebg;
 7078:   font-weight: bold;
 7079:   text-align: left;
 7080:   vertical-align: top;
 7081:   width: 184px;
 7082:   padding: 8px;
 7083: }
 7084: 
 7085: table.LC_pick_box td.LC_pick_box_value {
 7086:   text-align: left;
 7087:   padding: 8px;
 7088: }
 7089: 
 7090: table.LC_pick_box td.LC_pick_box_select {
 7091:   text-align: left;
 7092:   padding: 8px;
 7093: }
 7094: 
 7095: table.LC_pick_box td.LC_pick_box_separator {
 7096:   padding: 0;
 7097:   height: 1px;
 7098:   background: black;
 7099: }
 7100: 
 7101: table.LC_pick_box td.LC_pick_box_submit {
 7102:   text-align: right;
 7103: }
 7104: 
 7105: table.LC_pick_box td.LC_evenrow_value {
 7106:   text-align: left;
 7107:   padding: 8px;
 7108:   background-color: $data_table_light;
 7109: }
 7110: 
 7111: table.LC_pick_box td.LC_oddrow_value {
 7112:   text-align: left;
 7113:   padding: 8px;
 7114:   background-color: $data_table_light;
 7115: }
 7116: 
 7117: span.LC_helpform_receipt_cat {
 7118:   font-weight: bold;
 7119: }
 7120: 
 7121: table.LC_group_priv_box {
 7122:   background: white;
 7123:   border: 1px solid black;
 7124:   border-spacing: 1px;
 7125: }
 7126: 
 7127: table.LC_group_priv_box td.LC_pick_box_title {
 7128:   background: $tabbg;
 7129:   font-weight: bold;
 7130:   text-align: right;
 7131:   width: 184px;
 7132: }
 7133: 
 7134: table.LC_group_priv_box td.LC_groups_fixed {
 7135:   background: $data_table_light;
 7136:   text-align: center;
 7137: }
 7138: 
 7139: table.LC_group_priv_box td.LC_groups_optional {
 7140:   background: $data_table_dark;
 7141:   text-align: center;
 7142: }
 7143: 
 7144: table.LC_group_priv_box td.LC_groups_functionality {
 7145:   background: $data_table_darker;
 7146:   text-align: center;
 7147:   font-weight: bold;
 7148: }
 7149: 
 7150: table.LC_group_priv td {
 7151:   text-align: left;
 7152:   padding: 0;
 7153: }
 7154: 
 7155: .LC_navbuttons {
 7156:   margin: 2ex 0ex 2ex 0ex;
 7157: }
 7158: 
 7159: .LC_topic_bar {
 7160:   font-weight: bold;
 7161:   background: $tabbg;
 7162:   margin: 1em 0em 1em 2em;
 7163:   padding: 3px;
 7164:   font-size: 1.2em;
 7165: }
 7166: 
 7167: .LC_topic_bar span {
 7168:   left: 0.5em;
 7169:   position: absolute;
 7170:   vertical-align: middle;
 7171:   font-size: 1.2em;
 7172: }
 7173: 
 7174: table.LC_course_group_status {
 7175:   margin: 20px;
 7176: }
 7177: 
 7178: table.LC_status_selector td {
 7179:   vertical-align: top;
 7180:   text-align: center;
 7181:   padding: 4px;
 7182: }
 7183: 
 7184: div.LC_feedback_link {
 7185:   clear: both;
 7186:   background: $sidebg;
 7187:   width: 100%;
 7188:   padding-bottom: 10px;
 7189:   border: 1px $tabbg solid;
 7190:   height: 22px;
 7191:   line-height: 22px;
 7192:   padding-top: 5px;
 7193: }
 7194: 
 7195: div.LC_feedback_link img {
 7196:   height: 22px;
 7197:   vertical-align:middle;
 7198: }
 7199: 
 7200: div.LC_feedback_link a {
 7201:   text-decoration: none;
 7202: }
 7203: 
 7204: div.LC_comblock {
 7205:   display:inline;
 7206:   color:$font;
 7207:   font-size:90%;
 7208: }
 7209: 
 7210: div.LC_feedback_link div.LC_comblock {
 7211:   padding-left:5px;
 7212: }
 7213: 
 7214: div.LC_feedback_link div.LC_comblock a {
 7215:   color:$font;
 7216: }
 7217: 
 7218: span.LC_feedback_link {
 7219:   /* background: $feedback_link_bg; */
 7220:   font-size: larger;
 7221: }
 7222: 
 7223: span.LC_message_link {
 7224:   /* background: $feedback_link_bg; */
 7225:   font-size: larger;
 7226:   position: absolute;
 7227:   right: 1em;
 7228: }
 7229: 
 7230: table.LC_prior_tries {
 7231:   border: 1px solid #000000;
 7232:   border-collapse: separate;
 7233:   border-spacing: 1px;
 7234: }
 7235: 
 7236: table.LC_prior_tries td {
 7237:   padding: 2px;
 7238: }
 7239: 
 7240: .LC_answer_correct {
 7241:   background: lightgreen;
 7242:   color: darkgreen;
 7243:   padding: 6px;
 7244: }
 7245: 
 7246: .LC_answer_charged_try {
 7247:   background: #FFAAAA;
 7248:   color: darkred;
 7249:   padding: 6px;
 7250: }
 7251: 
 7252: .LC_answer_not_charged_try,
 7253: .LC_answer_no_grade,
 7254: .LC_answer_late {
 7255:   background: lightyellow;
 7256:   color: black;
 7257:   padding: 6px;
 7258: }
 7259: 
 7260: .LC_answer_previous {
 7261:   background: lightblue;
 7262:   color: darkblue;
 7263:   padding: 6px;
 7264: }
 7265: 
 7266: .LC_answer_no_message {
 7267:   background: #FFFFFF;
 7268:   color: black;
 7269:   padding: 6px;
 7270: }
 7271: 
 7272: .LC_answer_unknown,
 7273: .LC_answer_warning {
 7274:   background: orange;
 7275:   color: black;
 7276:   padding: 6px;
 7277: }
 7278: 
 7279: span.LC_prior_numerical,
 7280: span.LC_prior_string,
 7281: span.LC_prior_custom,
 7282: span.LC_prior_reaction,
 7283: span.LC_prior_math {
 7284:   font-family: $mono;
 7285:   white-space: pre;
 7286: }
 7287: 
 7288: span.LC_prior_string {
 7289:   font-family: $mono;
 7290:   white-space: pre;
 7291: }
 7292: 
 7293: table.LC_prior_option {
 7294:   width: 100%;
 7295:   border-collapse: collapse;
 7296: }
 7297: 
 7298: table.LC_prior_rank,
 7299: table.LC_prior_match {
 7300:   border-collapse: collapse;
 7301: }
 7302: 
 7303: table.LC_prior_option tr td,
 7304: table.LC_prior_rank tr td,
 7305: table.LC_prior_match tr td {
 7306:   border: 1px solid #000000;
 7307: }
 7308: 
 7309: .LC_nobreak {
 7310:   white-space: nowrap;
 7311: }
 7312: 
 7313: span.LC_cusr_emph {
 7314:   font-style: italic;
 7315: }
 7316: 
 7317: span.LC_cusr_subheading {
 7318:   font-weight: normal;
 7319:   font-size: 85%;
 7320: }
 7321: 
 7322: div.LC_docs_entry_move {
 7323:   border: 1px solid #BBBBBB;
 7324:   background: #DDDDDD;
 7325:   width: 22px;
 7326:   padding: 1px;
 7327:   margin: 0;
 7328: }
 7329: 
 7330: table.LC_data_table tr > td.LC_docs_entry_commands,
 7331: table.LC_data_table tr > td.LC_docs_entry_parameter {
 7332:   font-size: x-small;
 7333: }
 7334: 
 7335: .LC_docs_entry_parameter {
 7336:   white-space: nowrap;
 7337: }
 7338: 
 7339: .LC_docs_copy {
 7340:   color: #000099;
 7341: }
 7342: 
 7343: .LC_docs_cut {
 7344:   color: #550044;
 7345: }
 7346: 
 7347: .LC_docs_rename {
 7348:   color: #009900;
 7349: }
 7350: 
 7351: .LC_docs_remove {
 7352:   color: #990000;
 7353: }
 7354: 
 7355: .LC_domprefs_email,
 7356: .LC_docs_reinit_warn,
 7357: .LC_docs_ext_edit {
 7358:   font-size: x-small;
 7359: }
 7360: 
 7361: table.LC_docs_adddocs td,
 7362: table.LC_docs_adddocs th {
 7363:   border: 1px solid #BBBBBB;
 7364:   padding: 4px;
 7365:   background: #DDDDDD;
 7366: }
 7367: 
 7368: table.LC_sty_begin {
 7369:   background: #BBFFBB;
 7370: }
 7371: 
 7372: table.LC_sty_end {
 7373:   background: #FFBBBB;
 7374: }
 7375: 
 7376: table.LC_double_column {
 7377:   border-width: 0;
 7378:   border-collapse: collapse;
 7379:   width: 100%;
 7380:   padding: 2px;
 7381: }
 7382: 
 7383: table.LC_double_column tr td.LC_left_col {
 7384:   top: 2px;
 7385:   left: 2px;
 7386:   width: 47%;
 7387:   vertical-align: top;
 7388: }
 7389: 
 7390: table.LC_double_column tr td.LC_right_col {
 7391:   top: 2px;
 7392:   right: 2px;
 7393:   width: 47%;
 7394:   vertical-align: top;
 7395: }
 7396: 
 7397: div.LC_left_float {
 7398:   float: left;
 7399:   padding-right: 5%;
 7400:   padding-bottom: 4px;
 7401: }
 7402: 
 7403: div.LC_clear_float_header {
 7404:   padding-bottom: 2px;
 7405: }
 7406: 
 7407: div.LC_clear_float_footer {
 7408:   padding-top: 10px;
 7409:   clear: both;
 7410: }
 7411: 
 7412: div.LC_grade_show_user {
 7413: /*  border-left: 5px solid $sidebg; */
 7414:   border-top: 5px solid #000000;
 7415:   margin: 50px 0 0 0;
 7416:   padding: 15px 0 5px 10px;
 7417: }
 7418: 
 7419: div.LC_grade_show_user_odd_row {
 7420: /*  border-left: 5px solid #000000; */
 7421: }
 7422: 
 7423: div.LC_grade_show_user div.LC_Box {
 7424:   margin-right: 50px;
 7425: }
 7426: 
 7427: div.LC_grade_submissions,
 7428: div.LC_grade_message_center,
 7429: div.LC_grade_info_links {
 7430:   margin: 5px;
 7431:   width: 99%;
 7432:   background: #FFFFFF;
 7433: }
 7434: 
 7435: div.LC_grade_submissions_header,
 7436: div.LC_grade_message_center_header {
 7437:   font-weight: bold;
 7438:   font-size: large;
 7439: }
 7440: 
 7441: div.LC_grade_submissions_body,
 7442: div.LC_grade_message_center_body {
 7443:   border: 1px solid black;
 7444:   width: 99%;
 7445:   background: #FFFFFF;
 7446: }
 7447: 
 7448: table.LC_scantron_action {
 7449:   width: 100%;
 7450: }
 7451: 
 7452: table.LC_scantron_action tr th {
 7453:   font-weight:bold;
 7454:   font-style:normal;
 7455: }
 7456: 
 7457: .LC_edit_problem_header,
 7458: div.LC_edit_problem_footer {
 7459:   font-weight: normal;
 7460:   font-size:  medium;
 7461:   margin: 2px;
 7462:   background-color: $sidebg;
 7463: }
 7464: 
 7465: div.LC_edit_problem_header,
 7466: div.LC_edit_problem_header div,
 7467: div.LC_edit_problem_footer,
 7468: div.LC_edit_problem_footer div,
 7469: div.LC_edit_problem_editxml_header,
 7470: div.LC_edit_problem_editxml_header div {
 7471:   z-index: 100;
 7472: }
 7473: 
 7474: div.LC_edit_problem_header_title {
 7475:   font-weight: bold;
 7476:   font-size: larger;
 7477:   background: $tabbg;
 7478:   padding: 3px;
 7479:   margin: 0 0 5px 0;
 7480: }
 7481: 
 7482: table.LC_edit_problem_header_title {
 7483:   width: 100%;
 7484:   background: $tabbg;
 7485: }
 7486: 
 7487: div.LC_edit_actionbar {
 7488:     background-color: $sidebg;
 7489:     margin: 0;
 7490:     padding: 0;
 7491:     line-height: 200%;
 7492: }
 7493: 
 7494: div.LC_edit_actionbar div{
 7495:     padding: 0;
 7496:     margin: 0;
 7497:     display: inline-block;
 7498: }
 7499: 
 7500: .LC_edit_opt {
 7501:   padding-left: 1em;
 7502:   white-space: nowrap;
 7503: }
 7504: 
 7505: .LC_edit_problem_latexhelper{
 7506:     text-align: right;
 7507: }
 7508: 
 7509: #LC_edit_problem_colorful div{
 7510:     margin-left: 40px;
 7511: }
 7512: 
 7513: #LC_edit_problem_codemirror div{
 7514:     margin-left: 0px;
 7515: }
 7516: 
 7517: img.stift {
 7518:   border-width: 0;
 7519:   vertical-align: middle;
 7520: }
 7521: 
 7522: table td.LC_mainmenu_col_fieldset {
 7523:   vertical-align: top;
 7524: }
 7525: 
 7526: div.LC_createcourse {
 7527:   margin: 10px 10px 10px 10px;
 7528: }
 7529: 
 7530: .LC_dccid {
 7531:   float: right;
 7532:   margin: 0.2em 0 0 0;
 7533:   padding: 0;
 7534:   font-size: 90%;
 7535:   display:none;
 7536: }
 7537: 
 7538: ol.LC_primary_menu a:hover,
 7539: ol#LC_MenuBreadcrumbs a:hover,
 7540: ol#LC_PathBreadcrumbs a:hover,
 7541: ul#LC_secondary_menu a:hover,
 7542: .LC_FormSectionClearButton input:hover
 7543: ul.LC_TabContent   li:hover a {
 7544:   color:$button_hover;
 7545:   text-decoration:none;
 7546: }
 7547: 
 7548: h1 {
 7549:   padding: 0;
 7550:   line-height:130%;
 7551: }
 7552: 
 7553: h2,
 7554: h3,
 7555: h4,
 7556: h5,
 7557: h6 {
 7558:   margin: 5px 0 5px 0;
 7559:   padding: 0;
 7560:   line-height:130%;
 7561: }
 7562: 
 7563: .LC_hcell {
 7564:   padding:3px 15px 3px 15px;
 7565:   margin: 0;
 7566:   background-color:$tabbg;
 7567:   color:$fontmenu;
 7568:   border-bottom:solid 1px $lg_border_color;
 7569: }
 7570: 
 7571: .LC_Box > .LC_hcell {
 7572:   margin: 0 -10px 10px -10px;
 7573: }
 7574: 
 7575: .LC_noBorder {
 7576:   border: 0;
 7577: }
 7578: 
 7579: .LC_FormSectionClearButton input {
 7580:   background-color:transparent;
 7581:   border: none;
 7582:   cursor:pointer;
 7583:   text-decoration:underline;
 7584: }
 7585: 
 7586: .LC_help_open_topic {
 7587:   color: #FFFFFF;
 7588:   background-color: #EEEEFF;
 7589:   margin: 1px;
 7590:   padding: 4px;
 7591:   border: 1px solid #000033;
 7592:   white-space: nowrap;
 7593:   /* vertical-align: middle; */
 7594: }
 7595: 
 7596: dl,
 7597: ul,
 7598: div,
 7599: fieldset {
 7600:   margin: 10px 10px 10px 0;
 7601:   /* overflow: hidden; */
 7602: }
 7603: 
 7604: article.geogebraweb div {
 7605:     margin: 0;
 7606: }
 7607: 
 7608: fieldset > legend {
 7609:   font-weight: bold;
 7610:   padding: 0 5px 0 5px;
 7611: }
 7612: 
 7613: #LC_nav_bar {
 7614:   float: left;
 7615:   background-color: $pgbg_or_bgcolor;
 7616:   margin: 0 0 2px 0;
 7617: }
 7618: 
 7619: #LC_realm {
 7620:   margin: 0.2em 0 0 0;
 7621:   padding: 0;
 7622:   font-weight: bold;
 7623:   text-align: center;
 7624:   background-color: $pgbg_or_bgcolor;
 7625: }
 7626: 
 7627: #LC_nav_bar em {
 7628:   font-weight: bold;
 7629:   font-style: normal;
 7630: }
 7631: 
 7632: ol.LC_primary_menu {
 7633:   margin: 0;
 7634:   padding: 0;
 7635: }
 7636: 
 7637: ol#LC_PathBreadcrumbs {
 7638:   margin: 0;
 7639: }
 7640: 
 7641: ol.LC_primary_menu li {
 7642:   color: RGB(80, 80, 80);
 7643:   vertical-align: middle;
 7644:   text-align: left;
 7645:   list-style: none;
 7646:   position: relative;
 7647:   float: left;
 7648:   z-index: 100; /* will be displayed above codemirror and underneath the help-layer */
 7649:   line-height: 1.5em;
 7650: }
 7651: 
 7652: ol.LC_primary_menu li a, 
 7653: ol.LC_primary_menu li p {
 7654:   display: block;
 7655:   margin: 0;
 7656:   padding: 0 5px 0 10px;
 7657:   text-decoration: none;
 7658: }
 7659: 
 7660: ol.LC_primary_menu li p span.LC_primary_menu_innertitle {
 7661:   display: inline-block;
 7662:   width: 95%;
 7663:   text-align: left;
 7664: }
 7665: 
 7666: ol.LC_primary_menu li p span.LC_primary_menu_innerarrow {
 7667:   display: inline-block;
 7668:   width: 5%;
 7669:   float: right;
 7670:   text-align: right;
 7671:   font-size: 70%;
 7672: }
 7673: 
 7674: ol.LC_primary_menu ul {
 7675:   display: none;
 7676:   width: 15em;
 7677:   background-color: $data_table_light;
 7678:   position: absolute;
 7679:   top: 100%;
 7680: }
 7681: 
 7682: ol.LC_primary_menu ul ul {
 7683:   left: 100%;
 7684:   top: 0;
 7685: }
 7686: 
 7687: ol.LC_primary_menu li:hover > ul, ol.LC_primary_menu li.hover > ul {
 7688:   display: block;
 7689:   position: absolute;
 7690:   margin: 0;
 7691:   padding: 0;
 7692:   z-index: 2;
 7693: }
 7694: 
 7695: ol.LC_primary_menu li:hover li, ol.LC_primary_menu li.hover li {
 7696: /* First Submenu -> size should be smaller than the menu title of the whole menu */
 7697:   font-size: 90%;
 7698:   vertical-align: top;
 7699:   float: none;
 7700:   border-left: 1px solid black;
 7701:   border-right: 1px solid black;
 7702: /* A dark bottom border to visualize different menu options;
 7703: overwritten in the create_submenu routine for the last border-bottom of the menu */
 7704:   border-bottom: 1px solid $data_table_dark;
 7705: }
 7706: 
 7707: ol.LC_primary_menu li li p:hover {
 7708:   color:$button_hover;
 7709:   text-decoration:none;
 7710:   background-color:$data_table_dark;
 7711: }
 7712: 
 7713: ol.LC_primary_menu li li a:hover {
 7714:    color:$button_hover;
 7715:    background-color:$data_table_dark;
 7716: }
 7717: 
 7718: /* Font-size equal to the size of the predecessors*/
 7719: ol.LC_primary_menu li:hover li li {
 7720:   font-size: 100%;
 7721: }
 7722: 
 7723: ol.LC_primary_menu li img {
 7724:   vertical-align: bottom;
 7725:   height: 1.1em;
 7726:   margin: 0.2em 0 0 0;
 7727: }
 7728: 
 7729: ol.LC_primary_menu a {
 7730:   color: RGB(80, 80, 80);
 7731:   text-decoration: none;
 7732: }
 7733: 
 7734: ol.LC_primary_menu a.LC_new_message {
 7735:   font-weight:bold;
 7736:   color: darkred;
 7737: }
 7738: 
 7739: ol.LC_docs_parameters {
 7740:   margin-left: 0;
 7741:   padding: 0;
 7742:   list-style: none;
 7743: }
 7744: 
 7745: ol.LC_docs_parameters li {
 7746:   margin: 0;
 7747:   padding-right: 20px;
 7748:   display: inline;
 7749: }
 7750: 
 7751: ol.LC_docs_parameters li:before {
 7752:   content: "\\002022 \\0020";
 7753: }
 7754: 
 7755: li.LC_docs_parameters_title {
 7756:   font-weight: bold;
 7757: }
 7758: 
 7759: ol.LC_docs_parameters li.LC_docs_parameters_title:before {
 7760:   content: "";
 7761: }
 7762: 
 7763: ul#LC_secondary_menu {
 7764:   clear: right;
 7765:   color: $fontmenu;
 7766:   background: $tabbg;
 7767:   list-style: none;
 7768:   padding: 0;
 7769:   margin: 0;
 7770:   width: 100%;
 7771:   text-align: left;
 7772:   float: left;
 7773: }
 7774: 
 7775: ul#LC_secondary_menu li {
 7776:   font-weight: bold;
 7777:   line-height: 1.8em;
 7778:   border-right: 1px solid black;
 7779:   float: left;
 7780: }
 7781: 
 7782: ul#LC_secondary_menu li.LC_hoverable:hover, ul#LC_secondary_menu li.hover {
 7783:   background-color: $data_table_light;
 7784: }
 7785: 
 7786: ul#LC_secondary_menu li a {
 7787:   padding: 0 0.8em;
 7788: }
 7789: 
 7790: ul#LC_secondary_menu li ul {
 7791:   display: none;
 7792: }
 7793: 
 7794: ul#LC_secondary_menu li:hover ul, ul#LC_secondary_menu li.hover ul {
 7795:   display: block;
 7796:   position: absolute;
 7797:   margin: 0;
 7798:   padding: 0;
 7799:   list-style:none;
 7800:   float: none;
 7801:   background-color: $data_table_light;
 7802:   z-index: 2;
 7803:   margin-left: -1px;
 7804: }
 7805: 
 7806: ul#LC_secondary_menu li ul li {
 7807:   font-size: 90%;
 7808:   vertical-align: top;
 7809:   border-left: 1px solid black;
 7810:   border-right: 1px solid black;
 7811:   background-color: $data_table_light;
 7812:   list-style:none;
 7813:   float: none;
 7814: }
 7815: 
 7816: ul#LC_secondary_menu li ul li:hover, ul#LC_secondary_menu li ul li.hover {
 7817:   background-color: $data_table_dark;
 7818: }
 7819: 
 7820: ul.LC_TabContent {
 7821:   display:block;
 7822:   background: $sidebg;
 7823:   border-bottom: solid 1px $lg_border_color;
 7824:   list-style:none;
 7825:   margin: -1px -10px 0 -10px;
 7826:   padding: 0;
 7827: }
 7828: 
 7829: ul.LC_TabContent li,
 7830: ul.LC_TabContentBigger li {
 7831:   float:left;
 7832: }
 7833: 
 7834: ul#LC_secondary_menu li a {
 7835:   color: $fontmenu;
 7836:   text-decoration: none;
 7837: }
 7838: 
 7839: ul.LC_TabContent {
 7840:   min-height:20px;
 7841: }
 7842: 
 7843: ul.LC_TabContent li {
 7844:   vertical-align:middle;
 7845:   padding: 0 16px 0 10px;
 7846:   background-color:$tabbg;
 7847:   border-bottom:solid 1px $lg_border_color;
 7848:   border-left: solid 1px $font;
 7849: }
 7850: 
 7851: ul.LC_TabContent .right {
 7852:   float:right;
 7853: }
 7854: 
 7855: ul.LC_TabContent li a,
 7856: ul.LC_TabContent li {
 7857:   color:rgb(47,47,47);
 7858:   text-decoration:none;
 7859:   font-size:95%;
 7860:   font-weight:bold;
 7861:   min-height:20px;
 7862: }
 7863: 
 7864: ul.LC_TabContent li a:hover,
 7865: ul.LC_TabContent li a:focus {
 7866:   color: $button_hover;
 7867:   background:none;
 7868:   outline:none;
 7869: }
 7870: 
 7871: ul.LC_TabContent li:hover {
 7872:   color: $button_hover;
 7873:   cursor:pointer;
 7874: }
 7875: 
 7876: ul.LC_TabContent li.active {
 7877:   color: $font;
 7878:   background:#FFFFFF url(/adm/lonIcons/open.gif) no-repeat scroll right center;
 7879:   border-bottom:solid 1px #FFFFFF;
 7880:   cursor: default;
 7881: }
 7882: 
 7883: ul.LC_TabContent li.active a {
 7884:   color:$font;
 7885:   background:#FFFFFF;
 7886:   outline: none;
 7887: }
 7888: 
 7889: ul.LC_TabContent li.goback {
 7890:   float: left;
 7891:   border-left: none;
 7892: }
 7893: 
 7894: #maincoursedoc {
 7895:   clear:both;
 7896: }
 7897: 
 7898: ul.LC_TabContentBigger {
 7899:   display:block;
 7900:   list-style:none;
 7901:   padding: 0;
 7902: }
 7903: 
 7904: ul.LC_TabContentBigger li {
 7905:   vertical-align:bottom;
 7906:   height: 30px;
 7907:   font-size:110%;
 7908:   font-weight:bold;
 7909:   color: #737373;
 7910: }
 7911: 
 7912: ul.LC_TabContentBigger li.active {
 7913:   position: relative;
 7914:   top: 1px;
 7915: }
 7916: 
 7917: ul.LC_TabContentBigger li a {
 7918:   background:url('/adm/lonIcons/tabbgleft.gif') left bottom no-repeat;
 7919:   height: 30px;
 7920:   line-height: 30px;
 7921:   text-align: center;
 7922:   display: block;
 7923:   text-decoration: none;
 7924:   outline: none;  
 7925: }
 7926: 
 7927: ul.LC_TabContentBigger li.active a {
 7928:   background:url('/adm/lonIcons/tabbgleft.gif') left top no-repeat;
 7929:   color:$font;
 7930: }
 7931: 
 7932: ul.LC_TabContentBigger li b {
 7933:   background: url('/adm/lonIcons/tabbgright.gif') no-repeat right bottom;
 7934:   display: block;
 7935:   float: left;
 7936:   padding: 0 30px;
 7937:   border-bottom: 1px solid $lg_border_color;
 7938: }
 7939: 
 7940: ul.LC_TabContentBigger li:hover b {
 7941:   color:$button_hover;
 7942: }
 7943: 
 7944: ul.LC_TabContentBigger li.active b {
 7945:   background:url('/adm/lonIcons/tabbgright.gif') right top no-repeat;
 7946:   color:$font;
 7947:   border: 0;
 7948: }
 7949: 
 7950: 
 7951: ul.LC_CourseBreadcrumbs {
 7952:   background: $sidebg;
 7953:   height: 2em;
 7954:   padding-left: 10px;
 7955:   margin: 0;
 7956:   list-style-position: inside;
 7957: }
 7958: 
 7959: ol#LC_MenuBreadcrumbs,
 7960: ol#LC_PathBreadcrumbs {
 7961:   padding-left: 10px;
 7962:   margin: 0;
 7963:   height: 2.5em;  /* equal to #LC_breadcrumbs line-height */
 7964: }
 7965: 
 7966: ol#LC_MenuBreadcrumbs li,
 7967: ol#LC_PathBreadcrumbs li,
 7968: ul.LC_CourseBreadcrumbs li {
 7969:   display: inline;
 7970:   white-space: normal;  
 7971: }
 7972: 
 7973: ol#LC_MenuBreadcrumbs li a,
 7974: ul.LC_CourseBreadcrumbs li a {
 7975:   text-decoration: none;
 7976:   font-size:90%;
 7977: }
 7978: 
 7979: ol#LC_MenuBreadcrumbs h1 {
 7980:   display: inline;
 7981:   font-size: 90%;
 7982:   line-height: 2.5em;
 7983:   margin: 0;
 7984:   padding: 0;
 7985: }
 7986: 
 7987: ol#LC_PathBreadcrumbs li a {
 7988:   text-decoration:none;
 7989:   font-size:100%;
 7990:   font-weight:bold;
 7991: }
 7992: 
 7993: .LC_Box {
 7994:   border: solid 1px $lg_border_color;
 7995:   padding: 0 10px 10px 10px;
 7996: }
 7997: 
 7998: .LC_DocsBox {
 7999:   border: solid 1px $lg_border_color;
 8000:   padding: 0 0 10px 10px;
 8001: }
 8002: 
 8003: .LC_AboutMe_Image {
 8004:   float:left;
 8005:   margin-right:10px;
 8006: }
 8007: 
 8008: .LC_Clear_AboutMe_Image {
 8009:   clear:left;
 8010: }
 8011: 
 8012: dl.LC_ListStyleClean dt {
 8013:   padding-right: 5px;
 8014:   display: table-header-group;
 8015: }
 8016: 
 8017: dl.LC_ListStyleClean dd {
 8018:   display: table-row;
 8019: }
 8020: 
 8021: .LC_ListStyleClean,
 8022: .LC_ListStyleSimple,
 8023: .LC_ListStyleNormal,
 8024: .LC_ListStyleSpecial {
 8025:   /* display:block; */
 8026:   list-style-position: inside;
 8027:   list-style-type: none;
 8028:   overflow: hidden;
 8029:   padding: 0;
 8030: }
 8031: 
 8032: .LC_ListStyleSimple li,
 8033: .LC_ListStyleSimple dd,
 8034: .LC_ListStyleNormal li,
 8035: .LC_ListStyleNormal dd,
 8036: .LC_ListStyleSpecial li,
 8037: .LC_ListStyleSpecial dd {
 8038:   margin: 0;
 8039:   padding: 5px 5px 5px 10px;
 8040:   clear: both;
 8041: }
 8042: 
 8043: .LC_ListStyleClean li,
 8044: .LC_ListStyleClean dd {
 8045:   padding-top: 0;
 8046:   padding-bottom: 0;
 8047: }
 8048: 
 8049: .LC_ListStyleSimple dd,
 8050: .LC_ListStyleSimple li {
 8051:   border-bottom: solid 1px $lg_border_color;
 8052: }
 8053: 
 8054: .LC_ListStyleSpecial li,
 8055: .LC_ListStyleSpecial dd {
 8056:   list-style-type: none;
 8057:   background-color: RGB(220, 220, 220);
 8058:   margin-bottom: 4px;
 8059: }
 8060: 
 8061: table.LC_SimpleTable {
 8062:   margin:5px;
 8063:   border:solid 1px $lg_border_color;
 8064: }
 8065: 
 8066: table.LC_SimpleTable tr {
 8067:   padding: 0;
 8068:   border:solid 1px $lg_border_color;
 8069: }
 8070: 
 8071: table.LC_SimpleTable thead {
 8072:   background:rgb(220,220,220);
 8073: }
 8074: 
 8075: div.LC_columnSection {
 8076:   display: block;
 8077:   clear: both;
 8078:   overflow: hidden;
 8079:   margin: 0;
 8080: }
 8081: 
 8082: div.LC_columnSection>* {
 8083:   float: left;
 8084:   margin: 10px 20px 10px 0;
 8085:   overflow:hidden;
 8086: }
 8087: 
 8088: table em {
 8089:   font-weight: bold;
 8090:   font-style: normal;
 8091: }
 8092: 
 8093: table.LC_tableBrowseRes,
 8094: table.LC_tableOfContent {
 8095:   border:none;
 8096:   border-spacing: 1px;
 8097:   padding: 3px;
 8098:   background-color: #FFFFFF;
 8099:   font-size: 90%;
 8100: }
 8101: 
 8102: table.LC_tableOfContent {
 8103:   border-collapse: collapse;
 8104: }
 8105: 
 8106: table.LC_tableBrowseRes a,
 8107: table.LC_tableOfContent a {
 8108:   background-color: transparent;
 8109:   text-decoration: none;
 8110: }
 8111: 
 8112: table.LC_tableOfContent img {
 8113:   border: none;
 8114:   height: 1.3em;
 8115:   vertical-align: text-bottom;
 8116:   margin-right: 0.3em;
 8117: }
 8118: 
 8119: a#LC_content_toolbar_firsthomework {
 8120:   background-image:url(/res/adm/pages/open-first-problem.gif);
 8121: }
 8122: 
 8123: a#LC_content_toolbar_everything {
 8124:   background-image:url(/res/adm/pages/show-all.gif);
 8125: }
 8126: 
 8127: a#LC_content_toolbar_uncompleted {
 8128:   background-image:url(/res/adm/pages/show-incomplete-problems.gif);
 8129: }
 8130: 
 8131: #LC_content_toolbar_clearbubbles {
 8132:   background-image:url(/res/adm/pages/mark-discussionentries-read.gif);
 8133: }
 8134: 
 8135: a#LC_content_toolbar_changefolder {
 8136:   background : url(/res/adm/pages/close-all-folders.gif) top center ;
 8137: }
 8138: 
 8139: a#LC_content_toolbar_changefolder_toggled {
 8140:   background-image:url(/res/adm/pages/open-all-folders.gif);
 8141: }
 8142: 
 8143: a#LC_content_toolbar_edittoplevel {
 8144:   background-image:url(/res/adm/pages/edittoplevel.gif);
 8145: }
 8146: 
 8147: ul#LC_toolbar li a:hover {
 8148:   background-position: bottom center;
 8149: }
 8150: 
 8151: ul#LC_toolbar {
 8152:   padding: 0;
 8153:   margin: 2px;
 8154:   list-style:none;
 8155:   position:relative;
 8156:   background-color:white;
 8157:   overflow: auto;
 8158: }
 8159: 
 8160: ul#LC_toolbar li {
 8161:   border:1px solid white;
 8162:   padding: 0;
 8163:   margin: 0;
 8164:   float: left;
 8165:   display:inline;
 8166:   vertical-align:middle;
 8167:   white-space: nowrap;
 8168: }
 8169: 
 8170: 
 8171: a.LC_toolbarItem {
 8172:   display:block;
 8173:   padding: 0;
 8174:   margin: 0;
 8175:   height: 32px;
 8176:   width: 32px;
 8177:   color:white;
 8178:   border: none;
 8179:   background-repeat:no-repeat;
 8180:   background-color:transparent;
 8181: }
 8182: 
 8183: ul.LC_funclist {
 8184:     margin: 0;
 8185:     padding: 0.5em 1em 0.5em 0;
 8186: }
 8187: 
 8188: ul.LC_funclist > li:first-child {
 8189:     font-weight:bold; 
 8190:     margin-left:0.8em;
 8191: }
 8192: 
 8193: ul.LC_funclist + ul.LC_funclist {
 8194:     /* 
 8195:        left border as a seperator if we have more than
 8196:        one list 
 8197:     */
 8198:     border-left: 1px solid $sidebg;
 8199:     /* 
 8200:        this hides the left border behind the border of the 
 8201:        outer box if element is wrapped to the next 'line' 
 8202:     */
 8203:     margin-left: -1px;
 8204: }
 8205: 
 8206: ul.LC_funclist li {
 8207:   display: inline;
 8208:   white-space: nowrap;
 8209:   margin: 0 0 0 25px;
 8210:   line-height: 150%;
 8211: }
 8212: 
 8213: .LC_hidden {
 8214:   display: none;
 8215: }
 8216: 
 8217: .LCmodal-overlay {
 8218: 		position:fixed;
 8219: 		top:0;
 8220: 		right:0;
 8221: 		bottom:0;
 8222: 		left:0;
 8223: 		height:100%;
 8224: 		width:100%;
 8225: 		margin:0;
 8226: 		padding:0;
 8227: 		background:#999;
 8228: 		opacity:.75;
 8229: 		filter: alpha(opacity=75);
 8230: 		-moz-opacity: 0.75;
 8231: 		z-index:101;
 8232: }
 8233: 
 8234: * html .LCmodal-overlay {   
 8235: 		position: absolute;
 8236: 		height: expression(document.body.scrollHeight > document.body.offsetHeight ? document.body.scrollHeight : document.body.offsetHeight + 'px');
 8237: }
 8238: 
 8239: .LCmodal-window {
 8240: 		position:fixed;
 8241: 		top:50%;
 8242: 		left:50%;
 8243: 		margin:0;
 8244: 		padding:0;
 8245: 		z-index:102;
 8246: 	}
 8247: 
 8248: * html .LCmodal-window {
 8249: 		position:absolute;
 8250: }
 8251: 
 8252: .LCclose-window {
 8253: 		position:absolute;
 8254: 		width:32px;
 8255: 		height:32px;
 8256: 		right:8px;
 8257: 		top:8px;
 8258: 		background:transparent url('/res/adm/pages/process-stop.png') no-repeat scroll right top;
 8259: 		text-indent:-99999px;
 8260: 		overflow:hidden;
 8261: 		cursor:pointer;
 8262: }
 8263: 
 8264: .LCisDisabled {
 8265:   cursor: not-allowed;
 8266:   opacity: 0.5;
 8267: }
 8268: 
 8269: a[aria-disabled="true"] {
 8270:   color: currentColor;
 8271:   display: inline-block;  /* For IE11/ MS Edge bug */
 8272:   pointer-events: none;
 8273:   text-decoration: none;
 8274: }
 8275: 
 8276: pre.LC_wordwrap {
 8277:   white-space: pre-wrap;
 8278:   white-space: -moz-pre-wrap;
 8279:   white-space: -pre-wrap;
 8280:   white-space: -o-pre-wrap;
 8281:   word-wrap: break-word;
 8282: }
 8283: 
 8284: /*
 8285:   styles used by TTH when "Default set of options to pass to tth/m
 8286:   when converting TeX" in course settings has been set
 8287: 
 8288:   option passed: -t
 8289: 
 8290: */
 8291: 
 8292: td div.comp { margin-top: -0.6ex; margin-bottom: -1ex;}
 8293: td div.comb { margin-top: -0.6ex; margin-bottom: -.6ex;}
 8294: td div.hrcomp { line-height: 0.9; margin-top: -0.8ex; margin-bottom: -1ex;}
 8295: td div.norm {line-height:normal;}
 8296: 
 8297: /*
 8298:   option passed -y3
 8299: */
 8300: 
 8301: span.roman {font-family: serif; font-style: normal; font-weight: normal;}
 8302: span.overacc2 {position: relative;  left: .8em; top: -1.2ex;}
 8303: span.overacc1 {position: relative;  left: .6em; top: -1.2ex;}
 8304: 
 8305: #LC_minitab_header {
 8306:   float:left;
 8307:   width:100%;
 8308:   background:#DAE0D2 url("/res/adm/pages/minitabmenu_bg.gif") repeat-x bottom;
 8309:   font-size:93%;
 8310:   line-height:normal;
 8311:   margin: 0.5em 0 0.5em 0;
 8312: }
 8313: #LC_minitab_header ul {
 8314:   margin:0;
 8315:   padding:10px 10px 0;
 8316:   list-style:none;
 8317: }
 8318: #LC_minitab_header li {
 8319:   float:left;
 8320:   background:url("/res/adm/pages/minitabmenu_left.gif") no-repeat left top;
 8321:   margin:0;
 8322:   padding:0 0 0 9px;
 8323: }
 8324: #LC_minitab_header a {
 8325:   display:block;
 8326:   background:url("/res/adm/pages/minitabmenu_right.gif") no-repeat right top;
 8327:   padding:5px 15px 4px 6px;
 8328: }
 8329: #LC_minitab_header #LC_current_minitab {
 8330:   background-image:url("/res/adm/pages/minitabmenu_left_on.gif");
 8331: }
 8332: #LC_minitab_header #LC_current_minitab a {
 8333:   background-image:url("/res/adm/pages/minitabmenu_right_on.gif");
 8334:   padding-bottom:5px;
 8335: }
 8336: 
 8337: 
 8338: END
 8339: }
 8340: 
 8341: =pod
 8342: 
 8343: =item * &headtag()
 8344: 
 8345: Returns a uniform footer for LON-CAPA web pages.
 8346: 
 8347: Inputs: $title - optional title for the head
 8348:         $head_extra - optional extra HTML to put inside the <head>
 8349:         $args - optional arguments
 8350:             force_register - if is true call registerurl so the remote is 
 8351:                              informed
 8352:             redirect       -> array ref of
 8353:                                    1- seconds before redirect occurs
 8354:                                    2- url to redirect to
 8355:                                    3- whether the side effect should occur
 8356:                            (side effect of setting 
 8357:                                $env{'internal.head.redirect'} to the url 
 8358:                                redirected to)
 8359:                                    4- whether the redirect target should be
 8360:                                       the opener of the current (pop-up)
 8361:                                       window (side effect of setting
 8362:                                       $env{'internal.head.to_opener'} to
 8363:                                       1, if true.
 8364:                                    5- whether encrypt check should be skipped
 8365:             domain         -> force to color decorate a page for a specific
 8366:                                domain
 8367:             function       -> force usage of a specific rolish color scheme
 8368:             bgcolor        -> override the default page bgcolor
 8369:             no_auto_mt_title
 8370:                            -> prevent &mt()ing the title arg
 8371: 
 8372: =cut
 8373: 
 8374: sub headtag {
 8375:     my ($title,$head_extra,$args) = @_;
 8376:     
 8377:     my $function = $args->{'function'} || &get_users_function();
 8378:     my $domain   = $args->{'domain'}   || &determinedomain();
 8379:     my $bgcolor  = $args->{'bgcolor'}  || &designparm($function.'.pgbg',$domain);
 8380:     my $httphost = $args->{'use_absolute'};
 8381:     my $url = join(':',$env{'user.name'},$env{'user.domain'},
 8382: 		   $Apache::lonnet::perlvar{'lonVersion'},
 8383: 		   #time(),
 8384: 		   $env{'environment.color.timestamp'},
 8385: 		   $function,$domain,$bgcolor);
 8386: 
 8387:     $url = '/adm/css/'.&escape($url).'.css';
 8388: 
 8389:     my $result =
 8390: 	'<head>'.
 8391: 	&font_settings($args);
 8392: 
 8393:     my $inhibitprint;
 8394:     if ($args->{'print_suppress'}) {
 8395:         $inhibitprint = &print_suppression();
 8396:     }
 8397: 
 8398:     if (!$args->{'frameset'}) {
 8399: 	$result .= &Apache::lonhtmlcommon::htmlareaheaders();
 8400:     }
 8401:     if ($args->{'force_register'}) {
 8402:         $result .= &Apache::lonmenu::registerurl(1);
 8403:     }
 8404:     if (!$args->{'no_nav_bar'} 
 8405: 	&& !$args->{'only_body'}
 8406: 	&& !$args->{'frameset'}) {
 8407: 	$result .= &help_menu_js($httphost);
 8408:         $result.=&modal_window();
 8409:         $result.=&togglebox_script();
 8410:         $result.=&wishlist_window();
 8411:         $result.=&LCprogressbarUpdate_script();
 8412:     } else {
 8413:         if ($args->{'add_modal'}) {
 8414:            $result.=&modal_window();
 8415:         }
 8416:         if ($args->{'add_wishlist'}) {
 8417:            $result.=&wishlist_window();
 8418:         }
 8419:         if ($args->{'add_togglebox'}) {
 8420:            $result.=&togglebox_script();
 8421:         }
 8422:         if ($args->{'add_progressbar'}) {
 8423:            $result.=&LCprogressbarUpdate_script();
 8424:         }
 8425:     }
 8426:     if (ref($args->{'redirect'})) {
 8427: 	my ($time,$url,$inhibit_continue,$to_opener,$skip_enc_check) = @{$args->{'redirect'}};
 8428:         if (!$skip_enc_check) {
 8429: 	    $url = &Apache::lonenc::check_encrypt($url);
 8430:         }
 8431: 	if (!$inhibit_continue) {
 8432: 	    $env{'internal.head.redirect'} = $url;
 8433: 	}
 8434:         $result.=<<"ADDMETA";
 8435: <meta http-equiv="pragma" content="no-cache" />
 8436: ADDMETA
 8437:         if ($to_opener) {
 8438:             $env{'internal.head.to_opener'} = 1;
 8439:             my $dest = &js_escape($url);
 8440:             my $timeout = int($time * 1000);
 8441:             $result .=<<"ENDJS";
 8442: <script type="text/javascript">
 8443: // <![CDATA[
 8444: function LC_To_Opener() {
 8445:     var dest = '$dest';
 8446:     if (dest != '') {
 8447:         if (window.opener != null && !window.opener.closed) {
 8448:             window.opener.location.href=dest;
 8449:             window.close();
 8450:         } else {
 8451:             window.location.href=dest;
 8452:         }
 8453:     }
 8454: }
 8455: \$(document).ready(function () {
 8456:     setTimeout('LC_To_Opener()',$timeout);
 8457: });
 8458: // ]]>
 8459: </script>
 8460: ENDJS
 8461:         } else {
 8462:             $result.=<<"ADDMETA";
 8463: <meta http-equiv="Refresh" content="$time; url=$url" />
 8464: ADDMETA
 8465:         }
 8466:     } else {
 8467:         unless (($args->{'frameset'}) || ($args->{'js_ready'}) || ($args->{'only_body'}) || ($args->{'no_nav_bar'})) {
 8468:             my $requrl = $env{'request.uri'};
 8469:             if ($requrl eq '') {
 8470:                 $requrl = $ENV{'REQUEST_URI'};
 8471:                 $requrl =~ s/\?.+$//;
 8472:             }
 8473:             unless (($requrl =~ m{^/adm/(?:switchserver|login|authenticate|logout|groupsort|cleanup|helper|slotrequest|grades)(\?|$)}) ||
 8474:                     (($requrl =~ m{^/res/}) && (($env{'form.submitted'} eq 'scantron') ||
 8475:                      ($env{'form.grade_symb'}) || ($Apache::lonhomework::scantronmode)))) {
 8476:                 my $dom_in_use = $Apache::lonnet::perlvar{'lonDefDomain'};
 8477:                 unless (&Apache::lonnet::allowed('mau',$dom_in_use)) {
 8478:                     my %domdefs = &Apache::lonnet::get_domain_defaults($dom_in_use);
 8479:                     my $lonhost = $Apache::lonnet::perlvar{'lonHostID'};
 8480:                     my ($offload,$offloadoth);
 8481:                     if (ref($domdefs{'offloadnow'}) eq 'HASH') {
 8482:                         if ($domdefs{'offloadnow'}{$lonhost}) {
 8483:                             $offload = 1;
 8484:                             if (($env{'user.domain'} ne '') && ($env{'user.domain'} ne $dom_in_use) &&
 8485:                                 (!(($env{'user.name'} eq 'public') && ($env{'user.domain'} eq 'public')))) {
 8486:                                 unless (&Apache::lonnet::shared_institution($env{'user.domain'})) {
 8487:                                     $offloadoth = 1;
 8488:                                     $dom_in_use = $env{'user.domain'};
 8489:                                 }
 8490:                             }
 8491:                         }
 8492:                     }
 8493:                     unless ($offload) {
 8494:                         if (ref($domdefs{'offloadoth'}) eq 'HASH') {
 8495:                             if ($domdefs{'offloadoth'}{$lonhost}) {
 8496:                                 if (($env{'user.domain'} ne '') && ($env{'user.domain'} ne $dom_in_use) &&
 8497:                                     (!(($env{'user.name'} eq 'public') && ($env{'user.domain'} eq 'public')))) {
 8498:                                     unless (&Apache::lonnet::shared_institution($env{'user.domain'})) {
 8499:                                         $offload = 1;
 8500:                                         $offloadoth = 1;
 8501:                                         $dom_in_use = $env{'user.domain'};
 8502:                                     }
 8503:                                 }
 8504:                             }
 8505:                         }
 8506:                     }
 8507:                     if ($offload) {
 8508:                         my $newserver = &Apache::lonnet::spareserver(undef,30000,undef,1,$dom_in_use);
 8509:                         if (($newserver eq '') && ($offloadoth)) {
 8510:                             my @domains = &Apache::lonnet::current_machine_domains();
 8511:                             if (($dom_in_use ne '') && (!grep(/^\Q$dom_in_use\E$/,@domains))) {
 8512:                                 ($newserver) = &Apache::lonnet::choose_server($dom_in_use);
 8513:                             }
 8514:                         }
 8515:                         if (($newserver) && ($newserver ne $lonhost)) {
 8516:                             my $numsec = 5;
 8517:                             my $timeout = $numsec * 1000;
 8518:                             my ($newurl,$locknum,%locks,$msg);
 8519:                             if ($env{'request.role.adv'}) {
 8520:                                 ($locknum,%locks) = &Apache::lonnet::get_locks();
 8521:                             }
 8522:                             my $disable_submit = 0;
 8523:                             if ($requrl =~ /$LONCAPA::assess_re/) {
 8524:                                 $disable_submit = 1;
 8525:                             }
 8526:                             if ($locknum) {
 8527:                                 my @lockinfo = sort(values(%locks));
 8528:                                 $msg = &mt('Once the following tasks are complete:')." \n".
 8529:                                        join(", ",sort(values(%locks)))."\n";
 8530:                                 if (&show_course()) {
 8531:                                     $msg .= &mt('your session will be transferred to a different server, after you click "Courses".');
 8532:                                 } else {
 8533:                                     $msg .= &mt('your session will be transferred to a different server, after you click "Roles".');
 8534:                                 }
 8535:                             } else {
 8536:                                 if (($requrl =~ m{^/res/}) && ($env{'form.submitted'} =~ /^part_/)) {
 8537:                                     $msg = &mt('Your LON-CAPA submission has been recorded')."\n";
 8538:                                 }
 8539:                                 $msg .= &mt('Your current LON-CAPA session will be transferred to a different server in [quant,_1,second].',$numsec);
 8540:                                 $newurl = '/adm/switchserver?otherserver='.$newserver;
 8541:                                 if (($env{'request.role'}) && ($env{'request.role'} ne 'cm')) {
 8542:                                     $newurl .= '&role='.$env{'request.role'};
 8543:                                 }
 8544:                                 if ($env{'request.symb'}) {
 8545:                                     my $shownsymb = &Apache::lonenc::check_encrypt($env{'request.symb'});
 8546:                                     if ($shownsymb =~ m{^/enc/}) {
 8547:                                         my $reqdmajor = 2;
 8548:                                         my $reqdminor = 11;
 8549:                                         my $reqdsubminor = 3;
 8550:                                         my $newserverrev = &Apache::lonnet::get_server_loncaparev('',$newserver);
 8551:                                         my $remoterev = &Apache::lonnet::get_server_loncaparev(undef,$newserver);
 8552:                                         my ($major,$minor,$subminor) = ($remoterev =~ /^\'?(\d+)\.(\d+)\.(\d+|)[\w.\-]+\'?$/);
 8553:                                         if (($major eq '' && $minor eq '') ||
 8554:                                             (($reqdmajor > $major) || (($reqdmajor == $major) && ($reqdminor > $minor)) ||
 8555:                                             (($reqdmajor == $major) && ($reqdminor == $minor) && (($subminor eq '') ||
 8556:                                              ($reqdsubminor > $subminor))))) {
 8557:                                             undef($shownsymb);
 8558:                                         }
 8559:                                     }
 8560:                                     if ($shownsymb) {
 8561:                                         &js_escape(\$shownsymb);
 8562:                                         $newurl .= '&symb='.$shownsymb;
 8563:                                     }
 8564:                                 } else {
 8565:                                     my $shownurl = &Apache::lonenc::check_encrypt($requrl);
 8566:                                     &js_escape(\$shownurl);
 8567:                                     $newurl .= '&origurl='.$shownurl;
 8568:                                 }
 8569:                             }
 8570:                             &js_escape(\$msg);
 8571:                             $result.=<<OFFLOAD
 8572: <meta http-equiv="pragma" content="no-cache" />
 8573: <script type="text/javascript">
 8574: // <![CDATA[
 8575: function LC_Offload_Now() {
 8576:     var dest = "$newurl";
 8577:     if (dest != '') {
 8578:         window.location.href="$newurl";
 8579:     }
 8580: }
 8581: \$(document).ready(function () {
 8582:     window.alert('$msg');
 8583:     if ($disable_submit) {
 8584:         \$(".LC_hwk_submit").prop("disabled", true);
 8585:         \$( ".LC_textline" ).prop( "readonly", "readonly");
 8586:     }
 8587:     setTimeout('LC_Offload_Now()', $timeout);
 8588: });
 8589: // ]]>
 8590: </script>
 8591: OFFLOAD
 8592:                         }
 8593:                     }
 8594:                 }
 8595:             }
 8596:         }
 8597:     }
 8598:     if (!defined($title)) {
 8599: 	$title = 'The LearningOnline Network with CAPA';
 8600:     }
 8601:     if (!$args->{'no_auto_mt_title'}) { $title = &mt($title); }
 8602:     $result .= '<title> LON-CAPA '.$title.'</title>'
 8603: 	.'<link rel="stylesheet" type="text/css" href="'.$url.'"';
 8604:     if (!$args->{'frameset'}) {
 8605:         $result .= ' /';
 8606:     }
 8607:     $result .= '>'
 8608:         .$inhibitprint
 8609: 	.$head_extra;
 8610:     my $clientmobile;
 8611:     if (($env{'user.name'} eq '') && ($env{'user.domain'} eq '')) {
 8612:         (undef,undef,undef,undef,undef,undef,$clientmobile) = &decode_user_agent();
 8613:     } else {
 8614:         $clientmobile = $env{'browser.mobile'};
 8615:     }
 8616:     if ($clientmobile) {
 8617:         $result .= '
 8618: <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=0, minimum-scale=1.0, maximum-scale=1.0">
 8619: <meta name="apple-mobile-web-app-capable" content="yes" />';
 8620:     }
 8621:     $result .= '<meta name="google" content="notranslate" />'."\n";
 8622:     return $result.'</head>';
 8623: }
 8624: 
 8625: =pod
 8626: 
 8627: =item * &font_settings()
 8628: 
 8629: Returns neccessary <meta> to set the proper encoding
 8630: 
 8631: Inputs: optional reference to HASH -- $args passed to &headtag()
 8632: 
 8633: =cut
 8634: 
 8635: sub font_settings {
 8636:     my ($args) = @_;
 8637:     my $headerstring='';
 8638:     if ((!$env{'browser.mathml'} && $env{'browser.unicode'}) ||
 8639:         ((ref($args) eq 'HASH') && ($args->{'browser.unicode'}))) {
 8640: 	$headerstring.=
 8641: 	    '<meta http-equiv="Content-Type" content="text/html; charset=utf-8"';
 8642:         if (!$args->{'frameset'}) {
 8643:             $headerstring.= ' /';
 8644:         }
 8645:         $headerstring .= '>'."\n";
 8646:     }
 8647:     return $headerstring;
 8648: }
 8649: 
 8650: =pod
 8651: 
 8652: =item * &print_suppression()
 8653: 
 8654: In course context returns css which causes the body to be blank when media="print",
 8655: if printout generation is unavailable for the current resource.
 8656: 
 8657: This could be because:
 8658: 
 8659: (a) printstartdate is in the future
 8660: 
 8661: (b) printenddate is in the past
 8662: 
 8663: (c) there is an active exam block with "printout"
 8664: functionality blocked
 8665: 
 8666: Users with pav, pfo or evb privileges are exempt.
 8667: 
 8668: Inputs: none
 8669: 
 8670: =cut
 8671: 
 8672: 
 8673: sub print_suppression {
 8674:     my $noprint;
 8675:     if ($env{'request.course.id'}) {
 8676:         my $scope = $env{'request.course.id'};
 8677:         if ((&Apache::lonnet::allowed('pav',$scope)) ||
 8678:             (&Apache::lonnet::allowed('pfo',$scope))) {
 8679:             return;
 8680:         }
 8681:         if ($env{'request.course.sec'} ne '') {
 8682:             $scope .= "/$env{'request.course.sec'}";
 8683:             if ((&Apache::lonnet::allowed('pav',$scope)) ||
 8684:                 (&Apache::lonnet::allowed('pfo',$scope))) {
 8685:                 return;
 8686:             }
 8687:         }
 8688:         my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 8689:         my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 8690:         my $clientip = &Apache::lonnet::get_requestor_ip();
 8691:         my $blocked = &blocking_status('printout',$clientip,$cnum,$cdom,undef,1);
 8692:         if ($blocked) {
 8693:             my $checkrole = "cm./$cdom/$cnum";
 8694:             if ($env{'request.course.sec'} ne '') {
 8695:                 $checkrole .= "/$env{'request.course.sec'}";
 8696:             }
 8697:             unless ((&Apache::lonnet::allowed('evb',undef,undef,$checkrole)) &&
 8698:                     ($env{'request.role'} !~ m{^st\./$cdom/$cnum})) {
 8699:                 $noprint = 1;
 8700:             }
 8701:         }
 8702:         unless ($noprint) {
 8703:             my $symb = &Apache::lonnet::symbread();
 8704:             if ($symb ne '') {
 8705:                 my $navmap = Apache::lonnavmaps::navmap->new();
 8706:                 if (ref($navmap)) {
 8707:                     my $res = $navmap->getBySymb($symb);
 8708:                     if (ref($res)) {
 8709:                         if (!$res->resprintable()) {
 8710:                             $noprint = 1;
 8711:                         }
 8712:                     }
 8713:                 }
 8714:             }
 8715:         }
 8716:         if ($noprint) {
 8717:             return <<"ENDSTYLE";
 8718: <style type="text/css" media="print">
 8719:     body { display:none }
 8720: </style>
 8721: ENDSTYLE
 8722:         }
 8723:     }
 8724:     return;
 8725: }
 8726: 
 8727: =pod
 8728: 
 8729: =item * &xml_begin()
 8730: 
 8731: Returns the needed doctype and <html>
 8732: 
 8733: Inputs: none
 8734: 
 8735: =cut
 8736: 
 8737: sub xml_begin {
 8738:     my ($is_frameset) = @_;
 8739:     my $output='';
 8740: 
 8741:     if ($env{'browser.mathml'}) {
 8742: 	$output='<?xml version="1.0"?>'
 8743:             #.'<?xml-stylesheet type="text/css" href="/adm/MathML/mathml.css"?>'."\n"
 8744: #            .'<!DOCTYPE html SYSTEM "/adm/MathML/mathml.dtd" '
 8745:             
 8746: #	    .'<!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">] >'
 8747: 	    .'<!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">'
 8748:             .'<html xmlns:math="http://www.w3.org/1998/Math/MathML" ' 
 8749: 	    .'xmlns="http://www.w3.org/1999/xhtml">';
 8750:     } elsif ($is_frameset) {
 8751:         $output='<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Frameset//EN" "http://www.w3.org/TR/html4/frameset.dtd">'."\n".
 8752:                 '<html>'."\n";
 8753:     } else {
 8754: 	$output='<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">'."\n".
 8755:                 '<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">'."\n";
 8756:     }
 8757:     return $output;
 8758: }
 8759: 
 8760: =pod
 8761: 
 8762: =item * &start_page()
 8763: 
 8764: Returns a complete <html> .. <body> section for LON-CAPA web pages.
 8765: 
 8766: Inputs:
 8767: 
 8768: =over 4
 8769: 
 8770: $title - optional title for the page
 8771: 
 8772: $head_extra - optional extra HTML to incude inside the <head>
 8773: 
 8774: $args - additional optional args supported are:
 8775: 
 8776: =over 8
 8777: 
 8778:              only_body      -> is true will set &bodytag() onlybodytag
 8779:                                     arg on
 8780:              no_nav_bar     -> is true will set &bodytag() no_nav_bar arg on
 8781:              add_entries    -> additional attributes to add to the  <body>
 8782:              domain         -> force to color decorate a page for a 
 8783:                                     specific domain
 8784:              function       -> force usage of a specific rolish color
 8785:                                     scheme
 8786:              redirect       -> see &headtag()
 8787:              bgcolor        -> override the default page bg color
 8788:              js_ready       -> return a string ready for being used in 
 8789:                                     a javascript writeln
 8790:              html_encode    -> return a string ready for being used in 
 8791:                                     a html attribute
 8792:              force_register -> if is true will turn on the &bodytag()
 8793:                                     $forcereg arg
 8794:              frameset       -> if true will start with a <frameset>
 8795:                                     rather than <body>
 8796:              skip_phases    -> hash ref of 
 8797:                                     head -> skip the <html><head> generation
 8798:                                     body -> skip all <body> generation
 8799:              no_inline_link -> if true and in remote mode, don't show the
 8800:                                     'Switch To Inline Menu' link
 8801:              no_auto_mt_title -> prevent &mt()ing the title arg
 8802:              bread_crumbs ->             Array containing breadcrumbs
 8803:              bread_crumbs_component ->  if exists show it as headline else show only the breadcrumbs
 8804:              bread_crumbs_nomenu -> if true will pass false as the value of $menulink
 8805:                                     to lonhtmlcommon::breadcrumbs
 8806:              group          -> includes the current group, if page is for a
 8807:                                specific group
 8808:              use_absolute   -> for request for external resource or syllabus, this
 8809:                                will contain https://<hostname> if server uses
 8810:                                https (as per hosts.tab), but request is for http
 8811:              hostname       -> hostname, originally from $r->hostname(), (optional).
 8812:              links_disabled -> Links in primary and secondary menus are disabled
 8813:                                (Can enable them once page has loaded - see lonroles.pm
 8814:                                for an example).
 8815:              links_target   -> Target for links, e.g., _parent (optional).
 8816: 
 8817: =back
 8818: 
 8819: =back
 8820: 
 8821: =cut
 8822: 
 8823: sub start_page {
 8824:     my ($title,$head_extra,$args) = @_;
 8825:     #&Apache::lonnet::logthis("start_page ".join(':',caller(0)));
 8826: 
 8827:     $env{'internal.start_page'}++;
 8828:     my ($result,@advtools,$ltiscope,$ltiuri,%ltimenu,$menucoll,%menu);
 8829: 
 8830:     if (! exists($args->{'skip_phases'}{'head'}) ) {
 8831:         $result .= &xml_begin($args->{'frameset'}) . &headtag($title, $head_extra, $args);
 8832:     }
 8833: 
 8834:     if (($env{'request.course.id'}) && ($env{'request.lti.login'})) {
 8835:         if ($env{'course.'.$env{'request.course.id'}.'.lti.override'}) {
 8836:             unless ($env{'course.'.$env{'request.course.id'}.'.lti.topmenu'}) {
 8837:                 $args->{'no_primary_menu'} = 1;
 8838:             }
 8839:             unless ($env{'course.'.$env{'request.course.id'}.'.lti.inlinemenu'}) {
 8840:                 $args->{'no_inline_menu'} = 1;
 8841:             }
 8842:             if ($env{'course.'.$env{'request.course.id'}.'.lti.lcmenu'}) {
 8843:                 map { $ltimenu{$_} = 1; } split(/,/,$env{'course.'.$env{'request.course.id'}.'.lti.lcmenu'});
 8844:             }
 8845:         } else {
 8846:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 8847:             my %lti = &Apache::lonnet::get_domain_lti($cdom,'provider');
 8848:             if (ref($lti{$env{'request.lti.login'}}) eq 'HASH') {
 8849:                 unless ($lti{$env{'request.lti.login'}}{'topmenu'}) {
 8850:                     $args->{'no_primary_menu'} = 1;
 8851:                 }
 8852:                 unless ($lti{$env{'request.lti.login'}}{'inlinemenu'}) {
 8853:                     $args->{'no_inline_menu'} = 1;
 8854:                 }
 8855:                 if (ref($lti{$env{'request.lti.login'}}{'lcmenu'}) eq 'ARRAY') {
 8856:                     map { $ltimenu{$_} = 1; } @{$lti{$env{'request.lti.login'}}{'lcmenu'}};
 8857:                 }
 8858:             }
 8859:         }
 8860:         ($ltiscope,$ltiuri) = &LONCAPA::ltiutils::lti_provider_scope($env{'request.lti.uri'},
 8861:                                   $env{'course.'.$env{'request.course.id'}.'.domain'},
 8862:                                   $env{'course.'.$env{'request.course.id'}.'.num'});
 8863:     } elsif ($env{'request.course.id'}) {
 8864:         my $expiretime=600;
 8865:         if ((time-$env{'course.'.$env{'request.course.id'}.'.last_cache'}) > $expiretime) {
 8866:             &Apache::lonnet::coursedescription($env{'request.course.id'},{'freshen_cache' => 1});
 8867:         }
 8868:         my ($deeplinkmenu,$menuref);
 8869:         ($menucoll,$deeplinkmenu,$menuref) = &menucoll_in_effect();
 8870:         if ($menucoll) {
 8871:             if (ref($menuref) eq 'HASH') {
 8872:                 %menu = %{$menuref};
 8873:             }
 8874:             if ($menu{'top'} eq 'n') {
 8875:                 $args->{'no_primary_menu'} = 1;
 8876:             }
 8877:             if ($menu{'inline'} eq 'n') {
 8878:                 unless (&Apache::lonnet::allowed('opa')) {
 8879:                     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 8880:                     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 8881:                     my $crstype = &course_type();
 8882:                     my $now = time;
 8883:                     my $ccrole;
 8884:                     if ($crstype eq 'Community') {
 8885:                         $ccrole = 'co';
 8886:                     } else {
 8887:                         $ccrole = 'cc';
 8888:                     }
 8889:                     if ($env{'user.role.'.$ccrole.'./'.$cdom.'/'.$cnum}) {
 8890:                         my ($start,$end) = split(/\./,$env{'user.role.'.$ccrole.'./'.$cdom.'/'.$cnum});
 8891:                         if ((($start) && ($start<0)) ||
 8892:                             (($end) && ($end<$now))  ||
 8893:                             (($start) && ($now<$start))) {
 8894:                             $args->{'no_inline_menu'} = 1;
 8895:                         }
 8896:                     } else {
 8897:                         $args->{'no_inline_menu'} = 1;
 8898:                     }
 8899:                 }
 8900:             }
 8901:         }
 8902:     }
 8903: 
 8904:     my $showncrumbs;
 8905:     if (! exists($args->{'skip_phases'}{'body'}) ) {
 8906: 	if ($args->{'frameset'}) {
 8907: 	    my $attr_string = &make_attr_string($args->{'force_register'},
 8908: 						$args->{'add_entries'});
 8909: 	    $result .= "\n<frameset $attr_string>\n";
 8910:         } else {
 8911:             $result .=
 8912:                 &bodytag($title, 
 8913:                          $args->{'function'},       $args->{'add_entries'},
 8914:                          $args->{'only_body'},      $args->{'domain'},
 8915:                          $args->{'force_register'}, $args->{'no_nav_bar'},
 8916:                          $args->{'bgcolor'},        $args->{'no_inline_link'},
 8917:                          $args,                     \@advtools,
 8918:                          $ltiscope,$ltiuri,\%ltimenu,$menucoll,\%menu,\$showncrumbs);
 8919:         }
 8920:     }
 8921: 
 8922:     if ($args->{'js_ready'}) {
 8923: 		$result = &js_ready($result);
 8924:     }
 8925:     if ($args->{'html_encode'}) {
 8926: 		$result = &html_encode($result);
 8927:     }
 8928: 
 8929:     # Preparation for new and consistent functionlist at top of screen
 8930:     # if ($args->{'functionlist'}) {
 8931:     #            $result .= &build_functionlist();
 8932:     #}
 8933: 
 8934:     # Don't add anything more if only_body wanted or in const space
 8935:     return $result if    $args->{'only_body'} 
 8936:                       || $env{'request.state'} eq 'construct';
 8937: 
 8938:     #Breadcrumbs
 8939:     if (exists($args->{'bread_crumbs'}) or exists($args->{'bread_crumbs_component'})) {
 8940:         unless ($showncrumbs) {
 8941: 		&Apache::lonhtmlcommon::clear_breadcrumbs();
 8942: 		#if any br links exists, add them to the breadcrumbs
 8943: 		if (exists($args->{'bread_crumbs'}) and ref($args->{'bread_crumbs'}) eq 'ARRAY') {         
 8944: 			foreach my $crumb (@{$args->{'bread_crumbs'}}){
 8945: 				&Apache::lonhtmlcommon::add_breadcrumb($crumb);
 8946: 			}
 8947: 		}
 8948:                 # if @advtools array contains items add then to the breadcrumbs
 8949:                 if (@advtools > 0) {
 8950:                     &Apache::lonmenu::advtools_crumbs(@advtools);
 8951:                 }
 8952:                 my $menulink;
 8953:                 # if arg: bread_crumbs_nomenu is true pass 0 as $menulink item.
 8954:                 if ((exists($args->{'bread_crumbs_nomenu'})) ||
 8955:                     ($ltiscope eq 'map') || ($ltiscope eq 'resource')) {
 8956:                     $menulink = 0;
 8957:                 } else {
 8958:                     undef($menulink);
 8959:                 }
 8960:                 my $linkprotout;
 8961:                 if ($env{'request.deeplink.login'}) {
 8962:                     my $linkprotout = &Apache::lonmenu::linkprot_exit();
 8963:                     if ($linkprotout) {
 8964:                         &Apache::lonhtmlcommon::add_breadcrumb_tool('tools',$linkprotout);
 8965:                     }
 8966:                 }
 8967: 		#if bread_crumbs_component exists show it as headline else show only the breadcrumbs
 8968: 		if(exists($args->{'bread_crumbs_component'})){
 8969: 			$result .= &Apache::lonhtmlcommon::breadcrumbs($args->{'bread_crumbs_component'},'',$menulink);
 8970: 		} else {
 8971: 			$result .= &Apache::lonhtmlcommon::breadcrumbs('','',$menulink);
 8972: 		}
 8973:         }
 8974:     } elsif (($env{'environment.remote'} eq 'on') &&
 8975:              ($env{'form.inhibitmenu'} ne 'yes') &&
 8976:              ($env{'request.noversionuri'} =~ m{^/res/}) &&
 8977:              ($env{'request.noversionuri'} !~ m{^/res/adm/pages/})) {
 8978:         $result .= '<div style="padding:0;margin:0;clear:both"><hr /></div>';
 8979:     }
 8980:     return $result;
 8981: }
 8982: 
 8983: sub end_page {
 8984:     my ($args) = @_;
 8985:     $env{'internal.end_page'}++;
 8986:     my $result;
 8987:     if ($args->{'discussion'}) {
 8988: 	my ($target,$parser);
 8989: 	if (ref($args->{'discussion'})) {
 8990: 	    ($target,$parser) =($args->{'discussion'}{'target'},
 8991: 				$args->{'discussion'}{'parser'});
 8992: 	}
 8993: 	$result .= &Apache::lonxml::xmlend($target,$parser);
 8994:     }
 8995:     if ($args->{'frameset'}) {
 8996: 	$result .= '</frameset>';
 8997:     } else {
 8998: 	$result .= &endbodytag($args);
 8999:     }
 9000:     unless ($args->{'notbody'}) {
 9001:         $result .= "\n</html>";
 9002:     }
 9003: 
 9004:     if ($args->{'js_ready'}) {
 9005: 	$result = &js_ready($result);
 9006:     }
 9007: 
 9008:     if ($args->{'html_encode'}) {
 9009: 	$result = &html_encode($result);
 9010:     }
 9011: 
 9012:     return $result;
 9013: }
 9014: 
 9015: sub menucoll_in_effect {
 9016:     my ($menucoll,$deeplinkmenu,%menu);
 9017:     if ($env{'request.course.id'}) {
 9018:         $menucoll = $env{'course.'.$env{'request.course.id'}.'.menudefault'};
 9019:         if ($env{'request.deeplink.login'}) {
 9020:             my ($deeplink_symb,$deeplink,$check_login_symb);
 9021:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 9022:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 9023:             if ($env{'request.noversionuri'} =~ m{^/(res|uploaded)/}) {
 9024:                 if ($env{'request.noversionuri'} =~ /\.(page|sequence)$/) {
 9025:                     my $navmap = Apache::lonnavmaps::navmap->new();
 9026:                     if (ref($navmap)) {
 9027:                         $deeplink = $navmap->get_mapparam(undef,
 9028:                                                           &Apache::lonnet::declutter($env{'request.noversionuri'}),
 9029:                                                           '0.deeplink');
 9030:                     } else {
 9031:                         $check_login_symb = 1;
 9032:                     }
 9033:                 } else {
 9034:                     my $symb=&Apache::lonnet::symbread();
 9035:                     if ($symb) {
 9036:                         $deeplink = &Apache::lonnet::EXT('resource.0.deeplink',$symb);
 9037:                     } else {
 9038:                         $check_login_symb = 1;
 9039:                     }
 9040:                 }
 9041:             } else {
 9042:                 $check_login_symb = 1;
 9043:             }
 9044:             if ($check_login_symb) {
 9045:                 $deeplink_symb = &deeplink_login_symb($cnum,$cdom);
 9046:                 if ($deeplink_symb =~ /\.(page|sequence)$/) {
 9047:                     my $mapname = &Apache::lonnet::deversion((&Apache::lonnet::decode_symb($deeplink_symb))[2]);
 9048:                     my $navmap = Apache::lonnavmaps::navmap->new();
 9049:                     if (ref($navmap)) {
 9050:                         $deeplink = $navmap->get_mapparam(undef,$mapname,'0.deeplink');
 9051:                     }
 9052:                 } else {
 9053:                     $deeplink = &Apache::lonnet::EXT('resource.0.deeplink',$deeplink_symb);
 9054:                 }
 9055:             }
 9056:             if ($deeplink ne '') {
 9057:                 my ($state,$others,$listed,$scope,$protect,$display,$target) = split(/,/,$deeplink);
 9058:                 if ($display =~ /^\d+$/) {
 9059:                     $deeplinkmenu = 1;
 9060:                     $menucoll = $display;
 9061:                 }
 9062:             }
 9063:         }
 9064:         if ($menucoll) {
 9065:             %menu = &page_menu($env{'course.'.$env{'request.course.id'}.'.menucollections'},$menucoll);
 9066:         }
 9067:     }
 9068:     return ($menucoll,$deeplinkmenu,\%menu);
 9069: }
 9070: 
 9071: sub deeplink_login_symb {
 9072:     my ($cnum,$cdom) = @_;
 9073:     my $login_symb;
 9074:     if ($env{'request.deeplink.login'}) {
 9075:         $login_symb = &symb_from_tinyurl($env{'request.deeplink.login'},$cnum,$cdom);
 9076:     }
 9077:     return $login_symb;
 9078: }
 9079: 
 9080: sub symb_from_tinyurl {
 9081:     my ($url,$cnum,$cdom) = @_;
 9082:     if ($url =~ m{^\Q/tiny/$cdom/\E(\w+)$}) {
 9083:         my $key = $1;
 9084:         my ($tinyurl,$login);
 9085:         my ($result,$cached)=&Apache::lonnet::is_cached_new('tiny',$cdom."\0".$key);
 9086:         if (defined($cached)) {
 9087:             $tinyurl = $result;
 9088:         } else {
 9089:             my $configuname = &Apache::lonnet::get_domainconfiguser($cdom);
 9090:             my %currtiny = &Apache::lonnet::get('tiny',[$key],$cdom,$configuname);
 9091:             if ($currtiny{$key} ne '') {
 9092:                 $tinyurl = $currtiny{$key};
 9093:                 &Apache::lonnet::do_cache_new('tiny',$cdom."\0".$key,$currtiny{$key},600);
 9094:             }
 9095:         }
 9096:         if ($tinyurl ne '') {
 9097:             my ($cnumreq,$symb) = split(/\&/,$tinyurl);
 9098:             if (wantarray) {
 9099:                 return ($cnumreq,$symb);
 9100:             } elsif ($cnumreq eq $cnum) {
 9101:                 return $symb;
 9102:             }
 9103:         }
 9104:     }
 9105:     if (wantarray) {
 9106:         return ();
 9107:     } else {
 9108:         return;
 9109:     }
 9110: }
 9111: 
 9112: sub wishlist_window {
 9113:     return(<<'ENDWISHLIST');
 9114: <script type="text/javascript">
 9115: // <![CDATA[
 9116: // <!-- BEGIN LON-CAPA Internal
 9117: function set_wishlistlink(title, path) {
 9118:     if (!title) {
 9119:         title = document.title;
 9120:         title = title.replace(/^LON-CAPA /,'');
 9121:     }
 9122:     title = encodeURIComponent(title);
 9123:     title = title.replace("'","\\\'");
 9124:     if (!path) {
 9125:         path = location.pathname;
 9126:     }
 9127:     path = encodeURIComponent(path);
 9128:     path = path.replace("'","\\\'");
 9129:     Win = window.open('/adm/wishlist?mode=newLink&setTitle='+title+'&setPath='+path,
 9130:                       'wishlistNewLink','width=560,height=350,scrollbars=0');
 9131: }
 9132: // END LON-CAPA Internal -->
 9133: // ]]>
 9134: </script>
 9135: ENDWISHLIST
 9136: }
 9137: 
 9138: sub modal_window {
 9139:     return(<<'ENDMODAL');
 9140: <script type="text/javascript">
 9141: // <![CDATA[
 9142: // <!-- BEGIN LON-CAPA Internal
 9143: var modalWindow = {
 9144: 	parent:"body",
 9145: 	windowId:null,
 9146: 	content:null,
 9147: 	width:null,
 9148: 	height:null,
 9149: 	close:function()
 9150: 	{
 9151: 	        $(".LCmodal-window").remove();
 9152: 	        $(".LCmodal-overlay").remove();
 9153: 	},
 9154: 	open:function()
 9155: 	{
 9156: 		var modal = "";
 9157: 		modal += "<div class=\"LCmodal-overlay\"></div>";
 9158: 		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;\">";
 9159: 		modal += this.content;
 9160: 		modal += "</div>";	
 9161: 
 9162: 		$(this.parent).append(modal);
 9163: 
 9164: 		$(".LCmodal-window").append("<a class=\"LCclose-window\"></a>");
 9165: 		$(".LCclose-window").click(function(){modalWindow.close();});
 9166: 		$(".LCmodal-overlay").click(function(){modalWindow.close();});
 9167: 	}
 9168: };
 9169: 	var openMyModal = function(source,width,height,scrolling,transparency,style)
 9170: 	{
 9171:                 source = source.replace(/'/g,"&#39;");
 9172: 		modalWindow.windowId = "myModal";
 9173: 		modalWindow.width = width;
 9174: 		modalWindow.height = height;
 9175: 		modalWindow.content = "<iframe width='"+width+"' height='"+height+"' frameborder='0' scrolling='"+scrolling+"' allowtransparency='"+transparency+"' src='" + source + "' style='"+style+"'></iframe>";
 9176: 		modalWindow.open();
 9177: 	};
 9178: // END LON-CAPA Internal -->
 9179: // ]]>
 9180: </script>
 9181: ENDMODAL
 9182: }
 9183: 
 9184: sub modal_link {
 9185:     my ($link,$linktext,$width,$height,$target,$scrolling,$title,$transparency,$style)=@_;
 9186:     unless ($width) { $width=480; }
 9187:     unless ($height) { $height=400; }
 9188:     unless ($scrolling) { $scrolling='yes'; }
 9189:     unless ($transparency) { $transparency='true'; }
 9190: 
 9191:     my $target_attr;
 9192:     if (defined($target)) {
 9193:         $target_attr = 'target="'.$target.'"';
 9194:     }
 9195:     return <<"ENDLINK";
 9196: <a href="$link" $target_attr title="$title" onclick="javascript:openMyModal('$link',$width,$height,'$scrolling','$transparency','$style'); return false;">$linktext</a>
 9197: ENDLINK
 9198: }
 9199: 
 9200: sub modal_adhoc_script {
 9201:     my ($funcname,$width,$height,$content,$possmathjax)=@_;
 9202:     my $mathjax;
 9203:     if ($possmathjax) {
 9204:         $mathjax = <<'ENDJAX';
 9205:                if (typeof MathJax == 'object') {
 9206:                    MathJax.Hub.Queue(["Typeset",MathJax.Hub]);
 9207:                }
 9208: ENDJAX
 9209:     }
 9210:     return (<<ENDADHOC);
 9211: <script type="text/javascript">
 9212: // <![CDATA[
 9213:         var $funcname = function()
 9214:         {
 9215:                 modalWindow.windowId = "myModal";
 9216:                 modalWindow.width = $width;
 9217:                 modalWindow.height = $height;
 9218:                 modalWindow.content = '$content';
 9219:                 modalWindow.open();
 9220:                 $mathjax
 9221:         };  
 9222: // ]]>
 9223: </script>
 9224: ENDADHOC
 9225: }
 9226: 
 9227: sub modal_adhoc_inner {
 9228:     my ($funcname,$width,$height,$content,$possmathjax)=@_;
 9229:     my $innerwidth=$width-20;
 9230:     $content=&js_ready(
 9231:                &start_page('Dialog',undef,{'only_body'=>1,'bgcolor'=>'#FFFFFF'}).
 9232:                  &start_scrollbox($width.'px',$innerwidth.'px',$height.'px','myModal','#FFFFFF',undef,1).
 9233:                  $content.
 9234:                  &end_scrollbox().
 9235:                  &end_page()
 9236:              );
 9237:     return &modal_adhoc_script($funcname,$width,$height,$content,$possmathjax);
 9238: }
 9239: 
 9240: sub modal_adhoc_window {
 9241:     my ($funcname,$width,$height,$content,$linktext,$possmathjax)=@_;
 9242:     return &modal_adhoc_inner($funcname,$width,$height,$content,$possmathjax).
 9243:            "<a href=\"javascript:$funcname();void(0);\">".$linktext."</a>";
 9244: }
 9245: 
 9246: sub modal_adhoc_launch {
 9247:     my ($funcname,$width,$height,$content)=@_;
 9248:     return &modal_adhoc_inner($funcname,$width,$height,$content).(<<ENDLAUNCH);
 9249: <script type="text/javascript">
 9250: // <![CDATA[
 9251: $funcname();
 9252: // ]]>
 9253: </script>
 9254: ENDLAUNCH
 9255: }
 9256: 
 9257: sub modal_adhoc_close {
 9258:     return (<<ENDCLOSE);
 9259: <script type="text/javascript">
 9260: // <![CDATA[
 9261: modalWindow.close();
 9262: // ]]>
 9263: </script>
 9264: ENDCLOSE
 9265: }
 9266: 
 9267: sub togglebox_script {
 9268:    return(<<ENDTOGGLE);
 9269: <script type="text/javascript"> 
 9270: // <![CDATA[
 9271: function LCtoggleDisplay(id,hidetext,showtext) {
 9272:    link = document.getElementById(id + "link").childNodes[0];
 9273:    with (document.getElementById(id).style) {
 9274:       if (display == "none" ) {
 9275:           display = "inline";
 9276:           link.nodeValue = hidetext;
 9277:         } else {
 9278:           display = "none";
 9279:           link.nodeValue = showtext;
 9280:        }
 9281:    }
 9282: }
 9283: // ]]>
 9284: </script>
 9285: ENDTOGGLE
 9286: }
 9287: 
 9288: sub start_togglebox {
 9289:     my ($id,$heading,$headerbg,$hidetext,$showtext)=@_;
 9290:     unless ($heading) { $heading=''; } else { $heading.=' '; }
 9291:     unless ($showtext) { $showtext=&mt('show'); }
 9292:     unless ($hidetext) { $hidetext=&mt('hide'); }
 9293:     unless ($headerbg) { $headerbg='#FFFFFF'; }
 9294:     return &start_data_table().
 9295:            &start_data_table_header_row().
 9296:            '<td bgcolor="'.$headerbg.'">'.$heading.
 9297:            '[<a id="'.$id.'link" href="javascript:LCtoggleDisplay(\''.$id.'\',\''.$hidetext.'\',\''.
 9298:            $showtext.'\')">'.$showtext.'</a>]</td>'.
 9299:            &end_data_table_header_row().
 9300:            '<tr id="'.$id.'" style="display:none""><td>';
 9301: }
 9302: 
 9303: sub end_togglebox {
 9304:     return '</td></tr>'.&end_data_table();
 9305: }
 9306: 
 9307: sub LCprogressbar_script {
 9308:    my ($id,$number_to_do)=@_;
 9309:    if ($number_to_do) {
 9310:        return(<<ENDPROGRESS);
 9311: <script type="text/javascript">
 9312: // <![CDATA[
 9313: \$('#progressbar$id').progressbar({
 9314:   value: 0,
 9315:   change: function(event, ui) {
 9316:     var newVal = \$(this).progressbar('option', 'value');
 9317:     \$('.pblabel', this).text(LCprogressTxt);
 9318:   }
 9319: });
 9320: // ]]>
 9321: </script>
 9322: ENDPROGRESS
 9323:    } else {
 9324:        return(<<ENDPROGRESS);
 9325: <script type="text/javascript">
 9326: // <![CDATA[
 9327: \$('#progressbar$id').progressbar({
 9328:   value: false,
 9329:   create: function(event, ui) {
 9330:     \$('.ui-widget-header', this).css({'background':'#F0F0F0'});
 9331:     \$('.ui-progressbar-overlay', this).css({'margin':'0'});
 9332:   }
 9333: });
 9334: // ]]>
 9335: </script>
 9336: ENDPROGRESS
 9337:    }
 9338: }
 9339: 
 9340: sub LCprogressbarUpdate_script {
 9341:    return(<<ENDPROGRESSUPDATE);
 9342: <style type="text/css">
 9343: .ui-progressbar { position:relative; }
 9344: .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%; }
 9345: .pblabel { position: absolute; width: 100%; text-align: center; line-height: 1.9em; }
 9346: </style>
 9347: <script type="text/javascript">
 9348: // <![CDATA[
 9349: var LCprogressTxt='---';
 9350: 
 9351: function LCupdateProgress(percent,progresstext,id,maxnum) {
 9352:    LCprogressTxt=progresstext;
 9353:    if ((maxnum == '') || (maxnum == undefined) || (maxnum == null)) {
 9354:        \$('#progressbar'+id).find('.progress-label').text(LCprogressTxt);
 9355:    } else if (percent === \$('#progressbar'+id).progressbar( "value" )) {
 9356:        \$('#progressbar'+id).find('.pblabel').text(LCprogressTxt);
 9357:    } else {
 9358:        \$('#progressbar'+id).progressbar('value',percent);
 9359:    }
 9360: }
 9361: // ]]>
 9362: </script>
 9363: ENDPROGRESSUPDATE
 9364: }
 9365: 
 9366: my $LClastpercent;
 9367: my $LCidcnt;
 9368: my $LCcurrentid;
 9369: 
 9370: sub LCprogressbar {
 9371:     my ($r,$number_to_do,$preamble)=@_;
 9372:     $LClastpercent=0;
 9373:     $LCidcnt++;
 9374:     $LCcurrentid=$$.'_'.$LCidcnt;
 9375:     my ($starting,$content);
 9376:     if ($number_to_do) {
 9377:         $starting=&mt('Starting');
 9378:         $content=(<<ENDPROGBAR);
 9379: $preamble
 9380:   <div id="progressbar$LCcurrentid">
 9381:     <span class="pblabel">$starting</span>
 9382:   </div>
 9383: ENDPROGBAR
 9384:     } else {
 9385:         $starting=&mt('Loading...');
 9386:         $LClastpercent='false';
 9387:         $content=(<<ENDPROGBAR);
 9388: $preamble
 9389:   <div id="progressbar$LCcurrentid">
 9390:       <div class="progress-label">$starting</div>
 9391:   </div>
 9392: ENDPROGBAR
 9393:     }
 9394:     &r_print($r,$content.&LCprogressbar_script($LCcurrentid,$number_to_do));
 9395: }
 9396: 
 9397: sub LCprogressbarUpdate {
 9398:     my ($r,$val,$text,$number_to_do)=@_;
 9399:     if ($number_to_do) {
 9400:         unless ($val) { 
 9401:             if ($LClastpercent) {
 9402:                 $val=$LClastpercent;
 9403:             } else {
 9404:                 $val=0;
 9405:             }
 9406:         }
 9407:         if ($val<0) { $val=0; }
 9408:         if ($val>100) { $val=0; }
 9409:         $LClastpercent=$val;
 9410:         unless ($text) { $text=$val.'%'; }
 9411:     } else {
 9412:         $val = 'false';
 9413:     }
 9414:     $text=&js_ready($text);
 9415:     &r_print($r,<<ENDUPDATE);
 9416: <script type="text/javascript">
 9417: // <![CDATA[
 9418: LCupdateProgress($val,'$text','$LCcurrentid','$number_to_do');
 9419: // ]]>
 9420: </script>
 9421: ENDUPDATE
 9422: }
 9423: 
 9424: sub LCprogressbarClose {
 9425:     my ($r)=@_;
 9426:     $LClastpercent=0;
 9427:     &r_print($r,<<ENDCLOSE);
 9428: <script type="text/javascript">
 9429: // <![CDATA[
 9430: \$("#progressbar$LCcurrentid").hide('slow'); 
 9431: // ]]>
 9432: </script>
 9433: ENDCLOSE
 9434: }
 9435: 
 9436: sub r_print {
 9437:     my ($r,$to_print)=@_;
 9438:     if ($r) {
 9439:       $r->print($to_print);
 9440:       $r->rflush();
 9441:     } else {
 9442:       print($to_print);
 9443:     }
 9444: }
 9445: 
 9446: sub html_encode {
 9447:     my ($result) = @_;
 9448: 
 9449:     $result = &HTML::Entities::encode($result,'<>&"');
 9450:     
 9451:     return $result;
 9452: }
 9453: 
 9454: sub js_ready {
 9455:     my ($result) = @_;
 9456: 
 9457:     $result =~ s/[\n\r]/ /xmsg;
 9458:     $result =~ s/\\/\\\\/xmsg;
 9459:     $result =~ s/'/\\'/xmsg;
 9460:     $result =~ s{</}{<\\/}xmsg;
 9461:     
 9462:     return $result;
 9463: }
 9464: 
 9465: sub validate_page {
 9466:     if (  exists($env{'internal.start_page'})
 9467: 	  &&     $env{'internal.start_page'} > 1) {
 9468: 	&Apache::lonnet::logthis('start_page called multiple times '.
 9469: 				 $env{'internal.start_page'}.' '.
 9470: 				 $ENV{'request.filename'});
 9471:     }
 9472:     if (  exists($env{'internal.end_page'})
 9473: 	  &&     $env{'internal.end_page'} > 1) {
 9474: 	&Apache::lonnet::logthis('end_page called multiple times '.
 9475: 				 $env{'internal.end_page'}.' '.
 9476: 				 $env{'request.filename'});
 9477:     }
 9478:     if (     exists($env{'internal.start_page'})
 9479: 	&& ! exists($env{'internal.end_page'})) {
 9480: 	&Apache::lonnet::logthis('start_page called without end_page '.
 9481: 				 $env{'request.filename'});
 9482:     }
 9483:     if (   ! exists($env{'internal.start_page'})
 9484: 	&&   exists($env{'internal.end_page'})) {
 9485: 	&Apache::lonnet::logthis('end_page called without start_page'.
 9486: 				 $env{'request.filename'});
 9487:     }
 9488: }
 9489: 
 9490: 
 9491: sub start_scrollbox {
 9492:     my ($outerwidth,$width,$height,$id,$bgcolor,$cursor,$needjsready) = @_;
 9493:     unless ($outerwidth) { $outerwidth='520px'; }
 9494:     unless ($width) { $width='500px'; }
 9495:     unless ($height) { $height='200px'; }
 9496:     my ($table_id,$div_id,$tdcol);
 9497:     if ($id ne '') {
 9498:         $table_id = ' id="table_'.$id.'"';
 9499:         $div_id = ' id="div_'.$id.'"';
 9500:     }
 9501:     if ($bgcolor ne '') {
 9502:         $tdcol = "background-color: $bgcolor;";
 9503:     }
 9504:     my $nicescroll_js;
 9505:     if ($env{'browser.mobile'}) {
 9506:         $nicescroll_js = &nicescroll_javascript('div_'.$id,$cursor,$needjsready);
 9507:     }
 9508:     return <<"END";
 9509: $nicescroll_js
 9510: 
 9511: <table style="width: $outerwidth; border: 1px solid none;"$table_id><tr><td style="width: $width;$tdcol">
 9512: <div style="overflow:auto; width:$width; height:$height;"$div_id>
 9513: END
 9514: }
 9515: 
 9516: sub end_scrollbox {
 9517:     return '</div></td></tr></table>';
 9518: }
 9519: 
 9520: sub nicescroll_javascript {
 9521:     my ($id,$cursor,$needjsready,$framecheck,$location) = @_;
 9522:     my %options;
 9523:     if (ref($cursor) eq 'HASH') {
 9524:         %options = %{$cursor};
 9525:     }
 9526:     unless ($options{'railalign'} =~ /^left|right$/) {
 9527:         $options{'railalign'} = 'left';
 9528:     }
 9529:     unless ($options{'cursorcolor'} =~ /^\#\w+$/) {
 9530:         my $function  = &get_users_function();
 9531:         $options{'cursorcolor'} = &designparm($function.'.sidebg',$env{'request.role.domain'});
 9532:         unless ($options{'cursorcolor'} =~ /^\#\w+$/) {
 9533:             $options{'cursorcolor'} = '#00F';
 9534:         }
 9535:     }
 9536:     if ($options{'cursoropacity'} =~ /^[\d.]+$/) {
 9537:         unless ($options{'cursoropacity'} >= 0.0 && $options{'cursoropacity'} <=1.0) {
 9538:             $options{'cursoropacity'}='1.0';
 9539:         }
 9540:     } else {
 9541:         $options{'cursoropacity'}='1.0';
 9542:     }
 9543:     if ($options{'cursorfixedheight'} eq 'none') {
 9544:         delete($options{'cursorfixedheight'});
 9545:     } else {
 9546:         unless ($options{'cursorfixedheight'} =~ /^\d+$/) { $options{'cursorfixedheight'}='50'; }
 9547:     }
 9548:     unless ($options{'railoffset'} =~ /^{[\w\:\d\-,]+}$/) {
 9549:         delete($options{'railoffset'});
 9550:     }
 9551:     my @niceoptions;
 9552:     while (my($key,$value) = each(%options)) {
 9553:         if ($value =~ /^\{.+\}$/) {
 9554:             push(@niceoptions,$key.':'.$value);
 9555:         } else {
 9556:             push(@niceoptions,$key.':"'.$value.'"');
 9557:         }
 9558:     }
 9559:     my $nicescroll_js = '
 9560: $(document).ready(
 9561:       function() {
 9562:           $("#'.$id.'").niceScroll({'.join(',',@niceoptions).'});
 9563:       }
 9564: );
 9565: ';
 9566:     if ($framecheck) {
 9567:         $nicescroll_js .= '
 9568: function expand_div(caller) {
 9569:     if (top === self) {
 9570:         document.getElementById("'.$id.'").style.width = "auto";
 9571:         document.getElementById("'.$id.'").style.height = "auto";
 9572:     } else {
 9573:         try {
 9574:             if (parent.frames) {
 9575:                 if (parent.frames.length > 1) {
 9576:                     var framesrc = parent.frames[1].location.href;
 9577:                     var currsrc = framesrc.replace(/\#.*$/,"");
 9578:                     if ((caller == "search") || (currsrc == "'.$location.'")) {
 9579:                         document.getElementById("'.$id.'").style.width = "auto";
 9580:                         document.getElementById("'.$id.'").style.height = "auto";
 9581:                     }
 9582:                 }
 9583:             }
 9584:         } catch (e) {
 9585:             return;
 9586:         }
 9587:     }
 9588:     return;
 9589: }
 9590: ';
 9591:     }
 9592:     if ($needjsready) {
 9593:         $nicescroll_js = '
 9594: <script type="text/javascript">'."\n".$nicescroll_js."\n</script>\n";
 9595:     } else {
 9596:         $nicescroll_js = &Apache::lonhtmlcommon::scripttag($nicescroll_js);
 9597:     }
 9598:     return $nicescroll_js;
 9599: }
 9600: 
 9601: sub simple_error_page {
 9602:     my ($r,$title,$msg,$args) = @_;
 9603:     my %displayargs;
 9604:     if (ref($args) eq 'HASH') {
 9605:         if (!$args->{'no_auto_mt_msg'}) { $msg = &mt($msg); }
 9606:         if ($args->{'only_body'}) {
 9607:             $displayargs{'only_body'} = 1;
 9608:         }
 9609:         if ($args->{'no_nav_bar'}) {
 9610:             $displayargs{'no_nav_bar'} = 1;
 9611:         }
 9612:     } else {
 9613:         $msg = &mt($msg);
 9614:     }
 9615: 
 9616:     my $page =
 9617: 	&Apache::loncommon::start_page($title,'',\%displayargs).
 9618: 	'<p class="LC_error">'.$msg.'</p>'.
 9619: 	&Apache::loncommon::end_page();
 9620:     if (ref($r)) {
 9621: 	$r->print($page);
 9622: 	return;
 9623:     }
 9624:     return $page;
 9625: }
 9626: 
 9627: {
 9628:     my @row_count;
 9629: 
 9630:     sub start_data_table_count {
 9631:         unshift(@row_count, 0);
 9632:         return;
 9633:     }
 9634: 
 9635:     sub end_data_table_count {
 9636:         shift(@row_count);
 9637:         return;
 9638:     }
 9639: 
 9640:     sub start_data_table {
 9641: 	my ($add_class,$id) = @_;
 9642: 	my $css_class = (join(' ','LC_data_table',$add_class));
 9643:         my $table_id;
 9644:         if (defined($id)) {
 9645:             $table_id = ' id="'.$id.'"';
 9646:         }
 9647: 	&start_data_table_count();
 9648: 	return '<table class="'.$css_class.'"'.$table_id.'>'."\n";
 9649:     }
 9650: 
 9651:     sub end_data_table {
 9652: 	&end_data_table_count();
 9653: 	return '</table>'."\n";;
 9654:     }
 9655: 
 9656:     sub start_data_table_row {
 9657: 	my ($add_class, $id) = @_;
 9658: 	$row_count[0]++;
 9659: 	my $css_class = ($row_count[0] % 2)?'LC_odd_row':'LC_even_row';
 9660: 	$css_class = (join(' ',$css_class,$add_class)) unless ($add_class eq '');
 9661:         $id = (' id="'.$id.'"') unless ($id eq '');
 9662:         return  '<tr class="'.$css_class.'"'.$id.'>'."\n";
 9663:     }
 9664:     
 9665:     sub continue_data_table_row {
 9666: 	my ($add_class, $id) = @_;
 9667: 	my $css_class = ($row_count[0] % 2)?'LC_odd_row':'LC_even_row';
 9668: 	$css_class = (join(' ',$css_class,$add_class)) unless ($add_class eq '');
 9669:         $id = (' id="'.$id.'"') unless ($id eq '');
 9670:         return  '<tr class="'.$css_class.'"'.$id.'>'."\n";
 9671:     }
 9672: 
 9673:     sub end_data_table_row {
 9674: 	return '</tr>'."\n";;
 9675:     }
 9676: 
 9677:     sub start_data_table_empty_row {
 9678: #	$row_count[0]++;
 9679: 	return  '<tr class="LC_empty_row" >'."\n";;
 9680:     }
 9681: 
 9682:     sub end_data_table_empty_row {
 9683: 	return '</tr>'."\n";;
 9684:     }
 9685: 
 9686:     sub start_data_table_header_row {
 9687: 	return  '<tr class="LC_header_row">'."\n";;
 9688:     }
 9689: 
 9690:     sub end_data_table_header_row {
 9691: 	return '</tr>'."\n";;
 9692:     }
 9693: 
 9694:     sub data_table_caption {
 9695:         my $caption = shift;
 9696:         return "<caption class=\"LC_caption\">$caption</caption>";
 9697:     }
 9698: }
 9699: 
 9700: =pod
 9701: 
 9702: =item * &inhibit_menu_check($arg)
 9703: 
 9704: Checks for a inhibitmenu state and generates output to preserve it
 9705: 
 9706: Inputs:         $arg - can be any of
 9707:                      - undef - in which case the return value is a string 
 9708:                                to add  into arguments list of a uri
 9709:                      - 'input' - in which case the return value is a HTML
 9710:                                  <form> <input> field of type hidden to
 9711:                                  preserve the value
 9712:                      - a url - in which case the return value is the url with
 9713:                                the neccesary cgi args added to preserve the
 9714:                                inhibitmenu state
 9715:                      - a ref to a url - no return value, but the string is
 9716:                                         updated to include the neccessary cgi
 9717:                                         args to preserve the inhibitmenu state
 9718: 
 9719: =cut
 9720: 
 9721: sub inhibit_menu_check {
 9722:     my ($arg) = @_;
 9723:     &get_unprocessed_cgi($ENV{'QUERY_STRING'}, ['inhibitmenu']);
 9724:     if ($arg eq 'input') {
 9725: 	if ($env{'form.inhibitmenu'}) {
 9726: 	    return '<input type="hidden" name="inhibitmenu" value="'.$env{'form.inhibitmenu'}.'" />';
 9727: 	} else {
 9728: 	    return
 9729: 	}
 9730:     }
 9731:     if ($env{'form.inhibitmenu'}) {
 9732: 	if (ref($arg)) {
 9733: 	    $$arg .= '?inhibitmenu='.$env{'form.inhibitmenu'};
 9734: 	} elsif ($arg eq '') {
 9735: 	    $arg .= 'inhibitmenu='.$env{'form.inhibitmenu'};
 9736: 	} else {
 9737: 	    $arg .= '?inhibitmenu='.$env{'form.inhibitmenu'};
 9738: 	}
 9739:     }
 9740:     if (!ref($arg)) {
 9741: 	return $arg;
 9742:     }
 9743: }
 9744: 
 9745: ###############################################
 9746: 
 9747: =pod
 9748: 
 9749: =back
 9750: 
 9751: =head1 User Information Routines
 9752: 
 9753: =over 4
 9754: 
 9755: =item * &get_users_function()
 9756: 
 9757: Used by &bodytag to determine the current users primary role.
 9758: Returns either 'student','coordinator','admin', or 'author'.
 9759: 
 9760: =cut
 9761: 
 9762: ###############################################
 9763: sub get_users_function {
 9764:     my $function = 'norole';
 9765:     if ($env{'request.role'}=~/^(st)/) {
 9766:         $function='student';
 9767:     }
 9768:     if ($env{'request.role'}=~/^(cc|co|in|ta|ep)/) {
 9769:         $function='coordinator';
 9770:     }
 9771:     if ($env{'request.role'}=~/^(su|dc|ad|li)/) {
 9772:         $function='admin';
 9773:     }
 9774:     if (($env{'request.role'}=~/^(au|ca|aa)/) ||
 9775:         ($ENV{'REQUEST_URI'}=~ m{/^(/priv)})) {
 9776:         $function='author';
 9777:     }
 9778:     return $function;
 9779: }
 9780: 
 9781: ###############################################
 9782: 
 9783: =pod
 9784: 
 9785: =item * &show_course()
 9786: 
 9787: Used by lonmenu.pm and lonroles.pm to determine whether to use the word
 9788: 'Courses' or 'Roles' in inline navigation and on screen displaying user's roles.
 9789: 
 9790: Inputs:
 9791: None
 9792: 
 9793: Outputs:
 9794: Scalar: 1 if 'Course' to be used, 0 otherwise.
 9795: 
 9796: =cut
 9797: 
 9798: ###############################################
 9799: sub show_course {
 9800:     my $course = !$env{'user.adv'};
 9801:     if (!$env{'user.adv'}) {
 9802:         foreach my $env (keys(%env)) {
 9803:             next if ($env !~ m/^user\.priv\./);
 9804:             if ($env !~ m/^user\.priv\.(?:st|cm)/) {
 9805:                 $course = 0;
 9806:                 last;
 9807:             }
 9808:         }
 9809:     }
 9810:     return $course;
 9811: }
 9812: 
 9813: ###############################################
 9814: 
 9815: =pod
 9816: 
 9817: =item * &check_user_status()
 9818: 
 9819: Determines current status of supplied role for a
 9820: specific user. Roles can be active, previous or future.
 9821: 
 9822: Inputs: 
 9823: user's domain, user's username, course's domain,
 9824: course's number, optional section ID.
 9825: 
 9826: Outputs:
 9827: role status: active, previous or future. 
 9828: 
 9829: =cut
 9830: 
 9831: sub check_user_status {
 9832:     my ($udom,$uname,$cdom,$crs,$role,$sec) = @_;
 9833:     my %userinfo = &Apache::lonnet::dump('roles',$udom,$uname);
 9834:     my @uroles = keys(%userinfo);
 9835:     my $srchstr;
 9836:     my $active_chk = 'none';
 9837:     my $now = time;
 9838:     if (@uroles > 0) {
 9839:         if (($role eq 'cc') || ($role eq 'co') || ($sec eq '') || (!defined($sec))) {
 9840:             $srchstr = '/'.$cdom.'/'.$crs.'_'.$role;
 9841:         } else {
 9842:             $srchstr = '/'.$cdom.'/'.$crs.'/'.$sec.'_'.$role;
 9843:         }
 9844:         if (grep/^\Q$srchstr\E$/,@uroles) {
 9845:             my $role_end = 0;
 9846:             my $role_start = 0;
 9847:             $active_chk = 'active';
 9848:             if ($userinfo{$srchstr} =~ m/^\Q$role\E_(\d+)/) {
 9849:                 $role_end = $1;
 9850:                 if ($userinfo{$srchstr} =~ m/^\Q$role\E_\Q$role_end\E_(\d+)$/) {
 9851:                     $role_start = $1;
 9852:                 }
 9853:             }
 9854:             if ($role_start > 0) {
 9855:                 if ($now < $role_start) {
 9856:                     $active_chk = 'future';
 9857:                 }
 9858:             }
 9859:             if ($role_end > 0) {
 9860:                 if ($now > $role_end) {
 9861:                     $active_chk = 'previous';
 9862:                 }
 9863:             }
 9864:         }
 9865:     }
 9866:     return $active_chk;
 9867: }
 9868: 
 9869: ###############################################
 9870: 
 9871: =pod
 9872: 
 9873: =item * &get_sections()
 9874: 
 9875: Determines all the sections for a course including
 9876: sections with students and sections containing other roles.
 9877: Incoming parameters: 
 9878: 
 9879: 1. domain
 9880: 2. course number 
 9881: 3. reference to array containing roles for which sections should 
 9882: be gathered (optional).
 9883: 4. reference to array containing status types for which sections 
 9884: should be gathered (optional).
 9885: 
 9886: If the third argument is undefined, sections are gathered for any role. 
 9887: If the fourth argument is undefined, sections are gathered for any status.
 9888: Permissible values are 'active' or 'future' or 'previous'.
 9889:  
 9890: Returns section hash (keys are section IDs, values are
 9891: number of users in each section), subject to the
 9892: optional roles filter, optional status filter 
 9893: 
 9894: =cut
 9895: 
 9896: ###############################################
 9897: sub get_sections {
 9898:     my ($cdom,$cnum,$possible_roles,$possible_status) = @_;
 9899:     if (!defined($cdom) || !defined($cnum)) {
 9900:         my $cid =  $env{'request.course.id'};
 9901: 
 9902: 	return if (!defined($cid));
 9903: 
 9904:         $cdom = $env{'course.'.$cid.'.domain'};
 9905:         $cnum = $env{'course.'.$cid.'.num'};
 9906:     }
 9907: 
 9908:     my %sectioncount;
 9909:     my $now = time;
 9910: 
 9911:     my $check_students = 1;
 9912:     my $only_students = 0;
 9913:     if (ref($possible_roles) eq 'ARRAY') {
 9914:         if (grep(/^st$/,@{$possible_roles})) {
 9915:             if (@{$possible_roles} == 1) {
 9916:                 $only_students = 1;
 9917:             }
 9918:         } else {
 9919:             $check_students = 0;
 9920:         }
 9921:     }
 9922: 
 9923:     if ($check_students) {
 9924: 	my ($classlist) = &Apache::loncoursedata::get_classlist($cdom,$cnum);
 9925: 	my $sec_index = &Apache::loncoursedata::CL_SECTION();
 9926: 	my $status_index = &Apache::loncoursedata::CL_STATUS();
 9927:         my $start_index = &Apache::loncoursedata::CL_START();
 9928:         my $end_index = &Apache::loncoursedata::CL_END();
 9929:         my $status;
 9930: 	while (my ($student,$data) = each(%$classlist)) {
 9931: 	    my ($section,$stu_status,$start,$end) = ($data->[$sec_index],
 9932: 				                     $data->[$status_index],
 9933:                                                      $data->[$start_index],
 9934:                                                      $data->[$end_index]);
 9935:             if ($stu_status eq 'Active') {
 9936:                 $status = 'active';
 9937:             } elsif ($end < $now) {
 9938:                 $status = 'previous';
 9939:             } elsif ($start > $now) {
 9940:                 $status = 'future';
 9941:             } 
 9942: 	    if ($section ne '-1' && $section !~ /^\s*$/) {
 9943:                 if ((!defined($possible_status)) || (($status ne '') && 
 9944:                     (grep/^\Q$status\E$/,@{$possible_status}))) { 
 9945: 		    $sectioncount{$section}++;
 9946:                 }
 9947: 	    }
 9948: 	}
 9949:     }
 9950:     if ($only_students) {
 9951:         return %sectioncount;
 9952:     }
 9953:     my %courseroles = &Apache::lonnet::dump('nohist_userroles',$cdom,$cnum);
 9954:     foreach my $user (sort(keys(%courseroles))) {
 9955: 	if ($user !~ /^(\w{2})/) { next; }
 9956: 	my ($role) = ($user =~ /^(\w{2})/);
 9957: 	if ($possible_roles && !(grep(/^$role$/,@$possible_roles))) { next; }
 9958: 	my ($section,$status);
 9959: 	if ($role eq 'cr' &&
 9960: 	    $user =~ m-^$role/[^/]*/[^/]*/[^/]*:[^:]*:[^:]*:(\w+)-) {
 9961: 	    $section=$1;
 9962: 	}
 9963: 	if ($user =~ /^$role:[^:]*:[^:]*:(\w+)/) { $section=$1; }
 9964: 	if (!defined($section) || $section eq '-1') { next; }
 9965:         my ($end,$start) = ($courseroles{$user} =~ /^([^:]*):([^:]*)$/);
 9966:         if ($end == -1 && $start == -1) {
 9967:             next; #deleted role
 9968:         }
 9969:         if (!defined($possible_status)) { 
 9970:             $sectioncount{$section}++;
 9971:         } else {
 9972:             if ((!$end || $end >= $now) && (!$start || $start <= $now)) {
 9973:                 $status = 'active';
 9974:             } elsif ($end < $now) {
 9975:                 $status = 'future';
 9976:             } elsif ($start > $now) {
 9977:                 $status = 'previous';
 9978:             }
 9979:             if (($status ne '') && (grep/^\Q$status\E$/,@{$possible_status})) {
 9980:                 $sectioncount{$section}++;
 9981:             }
 9982:         }
 9983:     }
 9984:     return %sectioncount;
 9985: }
 9986: 
 9987: ###############################################
 9988: 
 9989: =pod
 9990: 
 9991: =item * &get_course_users()
 9992: 
 9993: Retrieves usernames:domains for users in the specified course
 9994: with specific role(s), and access status. 
 9995: 
 9996: Incoming parameters:
 9997: 1. course domain
 9998: 2. course number
 9999: 3. access status: users must have - either active, 
10000: previous, future, or all.
10001: 4. reference to array of permissible roles
10002: 5. reference to array of section restrictions (optional)
10003: 6. reference to results object (hash of hashes).
10004: 7. reference to optional userdata hash
10005: 8. reference to optional statushash
10006: 9. flag if privileged users (except those set to unhide in
10007:    course settings) should be excluded    
10008: Keys of top level results hash are roles.
10009: Keys of inner hashes are username:domain, with 
10010: values set to access type.
10011: Optional userdata hash returns an array with arguments in the 
10012: same order as loncoursedata::get_classlist() for student data.
10013: 
10014: Optional statushash returns
10015: 
10016: Entries for end, start, section and status are blank because
10017: of the possibility of multiple values for non-student roles.
10018: 
10019: =cut
10020: 
10021: ###############################################
10022: 
10023: sub get_course_users {
10024:     my ($cdom,$cnum,$types,$roles,$sections,$users,$userdata,$statushash,$hidepriv) = @_;
10025:     my %idx = ();
10026:     my %seclists;
10027: 
10028:     $idx{udom} = &Apache::loncoursedata::CL_SDOM();
10029:     $idx{uname} =  &Apache::loncoursedata::CL_SNAME();
10030:     $idx{end} = &Apache::loncoursedata::CL_END();
10031:     $idx{start} = &Apache::loncoursedata::CL_START();
10032:     $idx{id} = &Apache::loncoursedata::CL_ID();
10033:     $idx{section} = &Apache::loncoursedata::CL_SECTION();
10034:     $idx{fullname} = &Apache::loncoursedata::CL_FULLNAME();
10035:     $idx{status} = &Apache::loncoursedata::CL_STATUS();
10036: 
10037:     if (grep(/^st$/,@{$roles})) {
10038:         my ($classlist,$keylist)=&Apache::loncoursedata::get_classlist($cdom,$cnum);
10039:         my $now = time;
10040:         foreach my $student (keys(%{$classlist})) {
10041:             my $match = 0;
10042:             my $secmatch = 0;
10043:             my $section = $$classlist{$student}[$idx{section}];
10044:             my $status = $$classlist{$student}[$idx{status}];
10045:             if ($section eq '') {
10046:                 $section = 'none';
10047:             }
10048:             if ((ref($sections) eq 'ARRAY') && (@{$sections} > 0)) {
10049:                 if (grep(/^all$/,@{$sections})) {
10050:                     $secmatch = 1;
10051:                 } elsif ($$classlist{$student}[$idx{section}] eq '') {
10052:                     if (grep(/^none$/,@{$sections})) {
10053:                         $secmatch = 1;
10054:                     }
10055:                 } else {  
10056: 		    if (grep(/^\Q$section\E$/,@{$sections})) {
10057: 		        $secmatch = 1;
10058:                     }
10059: 		}
10060:                 if (!$secmatch) {
10061:                     next;
10062:                 }
10063:             }
10064:             if (defined($$types{'active'})) {
10065:                 if ($$classlist{$student}[$idx{status}] eq 'Active') {
10066:                     push(@{$$users{st}{$student}},'active');
10067:                     $match = 1;
10068:                 }
10069:             }
10070:             if (defined($$types{'previous'})) {
10071:                 if ($$classlist{$student}[$idx{status}] eq 'Expired') {
10072:                     push(@{$$users{st}{$student}},'previous');
10073:                     $match = 1;
10074:                 }
10075:             }
10076:             if (defined($$types{'future'})) {
10077:                 if ($$classlist{$student}[$idx{status}] eq 'Future') {
10078:                     push(@{$$users{st}{$student}},'future');
10079:                     $match = 1;
10080:                 }
10081:             }
10082:             if ($match) {
10083:                 push(@{$seclists{$student}},$section);
10084:                 if (ref($userdata) eq 'HASH') {
10085:                     $$userdata{$student} = $$classlist{$student};
10086:                 }
10087:                 if (ref($statushash) eq 'HASH') {
10088:                     $statushash->{$student}{'st'}{$section} = $status;
10089:                 }
10090:             }
10091:         }
10092:     }
10093:     if ((@{$roles} > 1) || ((@{$roles} == 1) && ($$roles[0] ne "st"))) {
10094:         my %coursepersonnel = &Apache::lonnet::dump('nohist_userroles',$cdom,$cnum);
10095:         my $now = time;
10096:         my %displaystatus = ( previous => 'Expired',
10097:                               active   => 'Active',
10098:                               future   => 'Future',
10099:                             );
10100:         my (%nothide,@possdoms);
10101:         if ($hidepriv) {
10102:             my %coursehash=&Apache::lonnet::coursedescription($cdom.'_'.$cnum);
10103:             foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
10104:                 if ($user !~ /:/) {
10105:                     $nothide{join(':',split(/[\@]/,$user))}=1;
10106:                 } else {
10107:                     $nothide{$user} = 1;
10108:                 }
10109:             }
10110:             my @possdoms = ($cdom);
10111:             if ($coursehash{'checkforpriv'}) {
10112:                 push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
10113:             }
10114:         }
10115:         foreach my $person (sort(keys(%coursepersonnel))) {
10116:             my $match = 0;
10117:             my $secmatch = 0;
10118:             my $status;
10119:             my ($role,$user,$usec) = ($person =~ /^([^:]*):([^:]+:[^:]+):([^:]*)/);
10120:             $user =~ s/:$//;
10121:             my ($end,$start) = split(/:/,$coursepersonnel{$person});
10122:             if ($end == -1 || $start == -1) {
10123:                 next;
10124:             }
10125:             if (($role) && ((grep(/^\Q$role\E$/,@{$roles})) ||
10126:                 (grep(/^cr$/,@{$roles}) && $role =~ /^cr\//))) {
10127:                 my ($uname,$udom) = split(/:/,$user);
10128:                 if ((ref($sections) eq 'ARRAY') && (@{$sections} > 0)) {
10129:                     if (grep(/^all$/,@{$sections})) {
10130:                         $secmatch = 1;
10131:                     } elsif ($usec eq '') {
10132:                         if (grep(/^none$/,@{$sections})) {
10133:                             $secmatch = 1;
10134:                         }
10135:                     } else {
10136:                         if (grep(/^\Q$usec\E$/,@{$sections})) {
10137:                             $secmatch = 1;
10138:                         }
10139:                     }
10140:                     if (!$secmatch) {
10141:                         next;
10142:                     }
10143:                 }
10144:                 if ($usec eq '') {
10145:                     $usec = 'none';
10146:                 }
10147:                 if ($uname ne '' && $udom ne '') {
10148:                     if ($hidepriv) {
10149:                         if ((&Apache::lonnet::privileged($uname,$udom,\@possdoms)) &&
10150:                             (!$nothide{$uname.':'.$udom})) {
10151:                             next;
10152:                         }
10153:                     }
10154:                     if ($end > 0 && $end < $now) {
10155:                         $status = 'previous';
10156:                     } elsif ($start > $now) {
10157:                         $status = 'future';
10158:                     } else {
10159:                         $status = 'active';
10160:                     }
10161:                     foreach my $type (keys(%{$types})) { 
10162:                         if ($status eq $type) {
10163:                             if (!grep(/^\Q$type\E$/,@{$$users{$role}{$user}})) {
10164:                                 push(@{$$users{$role}{$user}},$type);
10165:                             }
10166:                             $match = 1;
10167:                         }
10168:                     }
10169:                     if (($match) && (ref($userdata) eq 'HASH')) {
10170:                         if (!exists($$userdata{$uname.':'.$udom})) {
10171: 			    &get_user_info($udom,$uname,\%idx,$userdata);
10172:                         }
10173:                         if (!grep(/^\Q$usec\E$/,@{$seclists{$uname.':'.$udom}})) {
10174:                             push(@{$seclists{$uname.':'.$udom}},$usec);
10175:                         }
10176:                         if (ref($statushash) eq 'HASH') {
10177:                             $statushash->{$uname.':'.$udom}{$role}{$usec} = $displaystatus{$status};
10178:                         }
10179:                     }
10180:                 }
10181:             }
10182:         }
10183:         if (grep(/^ow$/,@{$roles})) {
10184:             if ((defined($cdom)) && (defined($cnum))) {
10185:                 my %csettings = &Apache::lonnet::get('environment',['internal.courseowner'],$cdom,$cnum);
10186:                 if ( defined($csettings{'internal.courseowner'}) ) {
10187:                     my $owner = $csettings{'internal.courseowner'};
10188:                     next if ($owner eq '');
10189:                     my ($ownername,$ownerdom);
10190:                     if ($owner =~ /^([^:]+):([^:]+)$/) {
10191:                         $ownername = $1;
10192:                         $ownerdom = $2;
10193:                     } else {
10194:                         $ownername = $owner;
10195:                         $ownerdom = $cdom;
10196:                         $owner = $ownername.':'.$ownerdom;
10197:                     }
10198:                     @{$$users{'ow'}{$owner}} = 'any';
10199:                     if (defined($userdata) && 
10200: 			!exists($$userdata{$owner})) {
10201: 			&get_user_info($ownerdom,$ownername,\%idx,$userdata);
10202:                         if (!grep(/^none$/,@{$seclists{$owner}})) {
10203:                             push(@{$seclists{$owner}},'none');
10204:                         }
10205:                         if (ref($statushash) eq 'HASH') {
10206:                             $statushash->{$owner}{'ow'}{'none'} = 'Any';
10207:                         }
10208: 		    }
10209:                 }
10210:             }
10211:         }
10212:         foreach my $user (keys(%seclists)) {
10213:             @{$seclists{$user}} = (sort {$a <=> $b} @{$seclists{$user}});
10214:             $$userdata{$user}[$idx{section}] = join(',',@{$seclists{$user}});
10215:         }
10216:     }
10217:     return;
10218: }
10219: 
10220: sub get_user_info {
10221:     my ($udom,$uname,$idx,$userdata) = @_;
10222:     $$userdata{$uname.':'.$udom}[$$idx{fullname}] = 
10223: 	&plainname($uname,$udom,'lastname');
10224:     $$userdata{$uname.':'.$udom}[$$idx{uname}] = $uname;
10225:     $$userdata{$uname.':'.$udom}[$$idx{udom}] = $udom;
10226:     my %idhash =  &Apache::lonnet::idrget($udom,($uname));
10227:     $$userdata{$uname.':'.$udom}[$$idx{id}] = $idhash{$uname}; 
10228:     return;
10229: }
10230: 
10231: ###############################################
10232: 
10233: =pod
10234: 
10235: =item * &get_user_quota()
10236: 
10237: Retrieves quota assigned for storage of user files.
10238: Default is to report quota for portfolio files.
10239: 
10240: Incoming parameters:
10241: 1. user's username
10242: 2. user's domain
10243: 3. quota name - portfolio, author, or course
10244:    (if no quota name provided, defaults to portfolio).
10245: 4. crstype - official, unofficial, textbook or community, if quota name is
10246:    course
10247: 
10248: Returns:
10249: 1. Disk quota (in MB) assigned to student.
10250: 2. (Optional) Type of setting: custom or default
10251:    (individually assigned or default for user's 
10252:    institutional status).
10253: 3. (Optional) - User's institutional status (e.g., faculty, staff
10254:    or student - types as defined in localenroll::inst_usertypes 
10255:    for user's domain, which determines default quota for user.
10256: 4. (Optional) - Default quota which would apply to the user.
10257: 
10258: If a value has been stored in the user's environment, 
10259: it will return that, otherwise it returns the maximal default
10260: defined for the user's institutional status(es) in the domain.
10261: 
10262: =cut
10263: 
10264: ###############################################
10265: 
10266: 
10267: sub get_user_quota {
10268:     my ($uname,$udom,$quotaname,$crstype) = @_;
10269:     my ($quota,$quotatype,$settingstatus,$defquota);
10270:     if (!defined($udom)) {
10271:         $udom = $env{'user.domain'};
10272:     }
10273:     if (!defined($uname)) {
10274:         $uname = $env{'user.name'};
10275:     }
10276:     if (($udom eq '' || $uname eq '') ||
10277:         ($udom eq 'public') && ($uname eq 'public')) {
10278:         $quota = 0;
10279:         $quotatype = 'default';
10280:         $defquota = 0; 
10281:     } else {
10282:         my $inststatus;
10283:         if ($quotaname eq 'course') {
10284:             if (($env{'course.'.$udom.'_'.$uname.'.num'} eq $uname) &&
10285:                 ($env{'course.'.$udom.'_'.$uname.'.domain'} eq $udom)) {
10286:                 $quota = $env{'course.'.$udom.'_'.$uname.'.internal.uploadquota'};
10287:             } else {
10288:                 my %cenv = &Apache::lonnet::coursedescription("$udom/$uname");
10289:                 $quota = $cenv{'internal.uploadquota'};
10290:             }
10291:         } else {
10292:             if ($udom eq $env{'user.domain'} && $uname eq $env{'user.name'}) {
10293:                 if ($quotaname eq 'author') {
10294:                     $quota = $env{'environment.authorquota'};
10295:                 } else {
10296:                     $quota = $env{'environment.portfolioquota'};
10297:                 }
10298:                 $inststatus = $env{'environment.inststatus'};
10299:             } else {
10300:                 my %userenv = 
10301:                     &Apache::lonnet::get('environment',['portfolioquota',
10302:                                          'authorquota','inststatus'],$udom,$uname);
10303:                 my ($tmp) = keys(%userenv);
10304:                 if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
10305:                     if ($quotaname eq 'author') {
10306:                         $quota = $userenv{'authorquota'};
10307:                     } else {
10308:                         $quota = $userenv{'portfolioquota'};
10309:                     }
10310:                     $inststatus = $userenv{'inststatus'};
10311:                 } else {
10312:                     undef(%userenv);
10313:                 }
10314:             }
10315:         }
10316:         if ($quota eq '' || wantarray) {
10317:             if ($quotaname eq 'course') {
10318:                 my %domdefs = &Apache::lonnet::get_domain_defaults($udom);
10319:                 if (($crstype eq 'official') || ($crstype eq 'unofficial') ||
10320:                     ($crstype eq 'community') || ($crstype eq 'textbook')) {
10321:                     $defquota = $domdefs{$crstype.'quota'};
10322:                 }
10323:                 if ($defquota eq '') {
10324:                     $defquota = 500;
10325:                 }
10326:             } else {
10327:                 ($defquota,$settingstatus) = &default_quota($udom,$inststatus,$quotaname);
10328:             }
10329:             if ($quota eq '') {
10330:                 $quota = $defquota;
10331:                 $quotatype = 'default';
10332:             } else {
10333:                 $quotatype = 'custom';
10334:             }
10335:         }
10336:     }
10337:     if (wantarray) {
10338:         return ($quota,$quotatype,$settingstatus,$defquota);
10339:     } else {
10340:         return $quota;
10341:     }
10342: }
10343: 
10344: ###############################################
10345: 
10346: =pod
10347: 
10348: =item * &default_quota()
10349: 
10350: Retrieves default quota assigned for storage of user portfolio files,
10351: given an (optional) user's institutional status.
10352: 
10353: Incoming parameters:
10354: 
10355: 1. domain
10356: 2. (Optional) institutional status(es).  This is a : separated list of 
10357:    status types (e.g., faculty, staff, student etc.)
10358:    which apply to the user for whom the default is being retrieved.
10359:    If the institutional status string in undefined, the domain
10360:    default quota will be returned.
10361: 3.  quota name - portfolio, author, or course
10362:    (if no quota name provided, defaults to portfolio).
10363: 
10364: Returns:
10365: 
10366: 1. Default disk quota (in MB) for user portfolios in the domain.
10367: 2. (Optional) institutional type which determined the value of the
10368:    default quota.
10369: 
10370: If a value has been stored in the domain's configuration db,
10371: it will return that, otherwise it returns 20 (for backwards 
10372: compatibility with domains which have not set up a configuration
10373: db file; the original statically defined portfolio quota was 20 MB). 
10374: 
10375: If the user's status includes multiple types (e.g., staff and student),
10376: the largest default quota which applies to the user determines the
10377: default quota returned.
10378: 
10379: =cut
10380: 
10381: ###############################################
10382: 
10383: 
10384: sub default_quota {
10385:     my ($udom,$inststatus,$quotaname) = @_;
10386:     my ($defquota,$settingstatus);
10387:     my %quotahash = &Apache::lonnet::get_dom('configuration',
10388:                                             ['quotas'],$udom);
10389:     my $key = 'defaultquota';
10390:     if ($quotaname eq 'author') {
10391:         $key = 'authorquota';
10392:     }
10393:     if (ref($quotahash{'quotas'}) eq 'HASH') {
10394:         if ($inststatus ne '') {
10395:             my @statuses = map { &unescape($_); } split(/:/,$inststatus);
10396:             foreach my $item (@statuses) {
10397:                 if (ref($quotahash{'quotas'}{$key}) eq 'HASH') {
10398:                     if ($quotahash{'quotas'}{$key}{$item} ne '') {
10399:                         if ($defquota eq '') {
10400:                             $defquota = $quotahash{'quotas'}{$key}{$item};
10401:                             $settingstatus = $item;
10402:                         } elsif ($quotahash{'quotas'}{$key}{$item} > $defquota) {
10403:                             $defquota = $quotahash{'quotas'}{$key}{$item};
10404:                             $settingstatus = $item;
10405:                         }
10406:                     }
10407:                 } elsif ($key eq 'defaultquota') {
10408:                     if ($quotahash{'quotas'}{$item} ne '') {
10409:                         if ($defquota eq '') {
10410:                             $defquota = $quotahash{'quotas'}{$item};
10411:                             $settingstatus = $item;
10412:                         } elsif ($quotahash{'quotas'}{$item} > $defquota) {
10413:                             $defquota = $quotahash{'quotas'}{$item};
10414:                             $settingstatus = $item;
10415:                         }
10416:                     }
10417:                 }
10418:             }
10419:         }
10420:         if ($defquota eq '') {
10421:             if (ref($quotahash{'quotas'}{$key}) eq 'HASH') {
10422:                 $defquota = $quotahash{'quotas'}{$key}{'default'};
10423:             } elsif ($key eq 'defaultquota') {
10424:                 $defquota = $quotahash{'quotas'}{'default'};
10425:             }
10426:             $settingstatus = 'default';
10427:             if ($defquota eq '') {
10428:                 if ($quotaname eq 'author') {
10429:                     $defquota = 500;
10430:                 }
10431:             }
10432:         }
10433:     } else {
10434:         $settingstatus = 'default';
10435:         if ($quotaname eq 'author') {
10436:             $defquota = 500;
10437:         } else {
10438:             $defquota = 20;
10439:         }
10440:     }
10441:     if (wantarray) {
10442:         return ($defquota,$settingstatus);
10443:     } else {
10444:         return $defquota;
10445:     }
10446: }
10447: 
10448: ###############################################
10449: 
10450: =pod
10451: 
10452: =item * &excess_filesize_warning()
10453: 
10454: Returns warning message if upload of file to authoring space, or copying
10455: of existing file within authoring space will cause quota for the authoring
10456: space to be exceeded.
10457: 
10458: Same, if upload of a file directly to a course/community via Course Editor
10459: will cause quota for uploaded content for the course to be exceeded.
10460: 
10461: Inputs: 7 
10462: 1. username or coursenum
10463: 2. domain
10464: 3. context ('author' or 'course')
10465: 4. filename of file for which action is being requested
10466: 5. filesize (kB) of file
10467: 6. action being taken: copy or upload.
10468: 7. quotatype (in course context -- official, unofficial, community or textbook).
10469: 
10470: Returns: 1 scalar: HTML to display containing warning if quota would be exceeded,
10471:          otherwise return null.
10472: 
10473: =back
10474: 
10475: =cut
10476: 
10477: sub excess_filesize_warning {
10478:     my ($uname,$udom,$context,$filename,$filesize,$action,$quotatype) = @_;
10479:     my $current_disk_usage = 0;
10480:     my $disk_quota = &get_user_quota($uname,$udom,$context,$quotatype); #expressed in MB
10481:     if ($context eq 'author') {
10482:         my $authorspace = $Apache::lonnet::perlvar{'lonDocRoot'}."/priv/$udom/$uname";
10483:         $current_disk_usage = &Apache::lonnet::diskusage($udom,$uname,$authorspace);
10484:     } else {
10485:         foreach my $subdir ('docs','supplemental') {
10486:             $current_disk_usage += &Apache::lonnet::diskusage($udom,$uname,"userfiles/$subdir",1);
10487:         }
10488:     }
10489:     $disk_quota = int($disk_quota * 1000);
10490:     if (($current_disk_usage + $filesize) > $disk_quota) {
10491:         return '<p class="LC_warning">'.
10492:                 &mt("Unable to $action [_1]. (size = [_2] kilobytes). Disk quota will be exceeded.",
10493:                     '<span class="LC_filename">'.$filename.'</span>',$filesize).'</p>'.
10494:                '<p>'.&mt('Disk quota is [_1] kilobytes. Your current disk usage is [_2] kilobytes.',
10495:                             $disk_quota,$current_disk_usage).
10496:                '</p>';
10497:     }
10498:     return;
10499: }
10500: 
10501: ###############################################
10502: 
10503: 
10504: sub get_secgrprole_info {
10505:     my ($cdom,$cnum,$needroles,$type)  = @_;
10506:     my %sections_count = &get_sections($cdom,$cnum);
10507:     my @sections =  (sort {$a <=> $b} keys(%sections_count));
10508:     my %curr_groups = &Apache::longroup::coursegroups($cdom,$cnum);
10509:     my @groups = sort(keys(%curr_groups));
10510:     my $allroles = [];
10511:     my $rolehash;
10512:     my $accesshash = {
10513:                      active => 'Currently has access',
10514:                      future => 'Will have future access',
10515:                      previous => 'Previously had access',
10516:                   };
10517:     if ($needroles) {
10518:         $rolehash = {'all' => 'all'};
10519:         my %user_roles = &Apache::lonnet::dump('nohist_userroles',$cdom,$cnum);
10520: 	if (&Apache::lonnet::error(%user_roles)) {
10521: 	    undef(%user_roles);
10522: 	}
10523:         foreach my $item (keys(%user_roles)) {
10524:             my ($role)=split(/\:/,$item,2);
10525:             if ($role eq 'cr') { next; }
10526:             if ($role =~ /^cr/) {
10527:                 $$rolehash{$role} = (split('/',$role))[3];
10528:             } else {
10529:                 $$rolehash{$role} = &Apache::lonnet::plaintext($role,$type);
10530:             }
10531:         }
10532:         foreach my $key (sort(keys(%{$rolehash}))) {
10533:             push(@{$allroles},$key);
10534:         }
10535:         push (@{$allroles},'st');
10536:         $$rolehash{'st'} = &Apache::lonnet::plaintext('st',$type);
10537:     }
10538:     return (\@sections,\@groups,$allroles,$rolehash,$accesshash);
10539: }
10540: 
10541: sub user_picker {
10542:     my ($dom,$srch,$forcenewuser,$caller,$cancreate,$usertype,$context,$fixeddom,$noinstd) = @_;
10543:     my $currdom = $dom;
10544:     my @alldoms = &Apache::lonnet::all_domains();
10545:     if (@alldoms == 1) {
10546:         my %domsrch = &Apache::lonnet::get_dom('configuration',
10547:                                                ['directorysrch'],$alldoms[0]);
10548:         my $domdesc = &Apache::lonnet::domain($alldoms[0],'description');
10549:         my $showdom = $domdesc;
10550:         if ($showdom eq '') {
10551:             $showdom = $dom;
10552:         }
10553:         if (ref($domsrch{'directorysrch'}) eq 'HASH') {
10554:             if ((!$domsrch{'directorysrch'}{'available'}) &&
10555:                 ($domsrch{'directorysrch'}{'lcavailable'} eq '0')) {
10556:                 return (&mt('LON-CAPA directory search is not available in domain: [_1]',$showdom),0);
10557:             }
10558:         }
10559:     }
10560:     my %curr_selected = (
10561:                         srchin => 'dom',
10562:                         srchby => 'lastname',
10563:                       );
10564:     my $srchterm;
10565:     if ((ref($srch) eq 'HASH') && ($env{'form.origform'} ne 'crtusername')) {
10566:         if ($srch->{'srchby'} ne '') {
10567:             $curr_selected{'srchby'} = $srch->{'srchby'};
10568:         }
10569:         if ($srch->{'srchin'} ne '') {
10570:             $curr_selected{'srchin'} = $srch->{'srchin'};
10571:         }
10572:         if ($srch->{'srchtype'} ne '') {
10573:             $curr_selected{'srchtype'} = $srch->{'srchtype'};
10574:         }
10575:         if ($srch->{'srchdomain'} ne '') {
10576:             $currdom = $srch->{'srchdomain'};
10577:         }
10578:         $srchterm = $srch->{'srchterm'};
10579:     }
10580:     my %html_lt=&Apache::lonlocal::texthash(
10581:                     'usr'       => 'Search criteria',
10582:                     'doma'      => 'Domain/institution to search',
10583:                     'uname'     => 'username',
10584:                     'lastname'  => 'last name',
10585:                     'lastfirst' => 'last name, first name',
10586:                     'crs'       => 'in this course',
10587:                     'dom'       => 'in selected LON-CAPA domain', 
10588:                     'alc'       => 'all LON-CAPA',
10589:                     'instd'     => 'in institutional directory for selected domain',
10590:                     'exact'     => 'is',
10591:                     'contains'  => 'contains',
10592:                     'begins'    => 'begins with',
10593:                                        );
10594:     my %js_lt=&Apache::lonlocal::texthash(
10595:                     'youm'      => "You must include some text to search for.",
10596:                     'thte'      => "The text you are searching for must contain at least two characters when using a 'begins' type search.",
10597:                     'thet'      => "The text you are searching for must contain at least three characters when using a 'contains' type search.",
10598:                     'yomc'      => "You must choose a domain when using an institutional directory search.",
10599:                     'ymcd'      => "You must choose a domain when using a domain search.",
10600:                     'whus'      => "When using searching by last,first you must include a comma as separator between last name and first name.",
10601:                     'whse'      => "When searching by last,first you must include at least one character in the first name.",
10602:                      'thfo'     => "The following need to be corrected before the search can be run:",
10603:                                        );
10604:     &html_escape(\%html_lt);
10605:     &js_escape(\%js_lt);
10606:     my $domform;
10607:     my $allow_blank = 1;
10608:     if ($fixeddom) {
10609:         $allow_blank = 0;
10610:         $domform = &select_dom_form($currdom,'srchdomain',$allow_blank,1,undef,[$currdom]);
10611:     } else {
10612:         $domform = &select_dom_form($currdom,'srchdomain',$allow_blank,1);
10613:     }
10614:     my $srchinsel = ' <select name="srchin">';
10615: 
10616:     my @srchins = ('crs','dom','alc','instd');
10617: 
10618:     foreach my $option (@srchins) {
10619:         # FIXME 'alc' option unavailable until 
10620:         #       loncreateuser::print_user_query_page()
10621:         #       has been completed.
10622:         next if ($option eq 'alc');
10623:         next if (($option eq 'crs') && ($env{'form.form'} eq 'requestcrs'));  
10624:         next if ($option eq 'crs' && !$env{'request.course.id'});
10625:         next if (($option eq 'instd') && ($noinstd));
10626:         if ($curr_selected{'srchin'} eq $option) {
10627:             $srchinsel .= ' 
10628:    <option value="'.$option.'" selected="selected">'.$html_lt{$option}.'</option>';
10629:         } else {
10630:             $srchinsel .= '
10631:    <option value="'.$option.'">'.$html_lt{$option}.'</option>';
10632:         }
10633:     }
10634:     $srchinsel .= "\n  </select>\n";
10635: 
10636:     my $srchbysel =  ' <select name="srchby">';
10637:     foreach my $option ('lastname','lastfirst','uname') {
10638:         if ($curr_selected{'srchby'} eq $option) {
10639:             $srchbysel .= '
10640:    <option value="'.$option.'" selected="selected">'.$html_lt{$option}.'</option>';
10641:         } else {
10642:             $srchbysel .= '
10643:    <option value="'.$option.'">'.$html_lt{$option}.'</option>';
10644:          }
10645:     }
10646:     $srchbysel .= "\n  </select>\n";
10647: 
10648:     my $srchtypesel = ' <select name="srchtype">';
10649:     foreach my $option ('begins','contains','exact') {
10650:         if ($curr_selected{'srchtype'} eq $option) {
10651:             $srchtypesel .= '
10652:    <option value="'.$option.'" selected="selected">'.$html_lt{$option}.'</option>';
10653:         } else {
10654:             $srchtypesel .= '
10655:    <option value="'.$option.'">'.$html_lt{$option}.'</option>';
10656:         }
10657:     }
10658:     $srchtypesel .= "\n  </select>\n";
10659: 
10660:     my ($newuserscript,$new_user_create);
10661:     my $context_dom = $env{'request.role.domain'};
10662:     if ($context eq 'requestcrs') {
10663:         if ($env{'form.coursedom'} ne '') { 
10664:             $context_dom = $env{'form.coursedom'};
10665:         }
10666:     }
10667:     if ($forcenewuser) {
10668:         if (ref($srch) eq 'HASH') {
10669:             if ($srch->{'srchby'} eq 'uname' && $srch->{'srchtype'} eq 'exact' && $srch->{'srchin'} eq 'dom' && $srch->{'srchdomain'} eq $context_dom) {
10670:                 if ($cancreate) {
10671:                     $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>';
10672:                 } else {
10673:                     my $helplink = 'javascript:helpMenu('."'display'".')';
10674:                     my %usertypetext = (
10675:                         official   => 'institutional',
10676:                         unofficial => 'non-institutional',
10677:                     );
10678:                     $new_user_create = '<p class="LC_warning">'
10679:                                       .&mt("You are not authorized to create new $usertypetext{$usertype} users in this domain.")
10680:                                       .' '
10681:                                       .&mt('Please contact the [_1]helpdesk[_2] for assistance.'
10682:                                           ,'<a href="'.$helplink.'">','</a>')
10683:                                       .'</p><br />';
10684:                 }
10685:             }
10686:         }
10687: 
10688:         $newuserscript = <<"ENDSCRIPT";
10689: 
10690: function setSearch(createnew,callingForm) {
10691:     if (createnew == 1) {
10692:         for (var i=0; i<callingForm.srchby.length; i++) {
10693:             if (callingForm.srchby.options[i].value == 'uname') {
10694:                 callingForm.srchby.selectedIndex = i;
10695:             }
10696:         }
10697:         for (var i=0; i<callingForm.srchin.length; i++) {
10698:             if ( callingForm.srchin.options[i].value == 'dom') {
10699: 		callingForm.srchin.selectedIndex = i;
10700:             }
10701:         }
10702:         for (var i=0; i<callingForm.srchtype.length; i++) {
10703:             if (callingForm.srchtype.options[i].value == 'exact') {
10704:                 callingForm.srchtype.selectedIndex = i;
10705:             }
10706:         }
10707:         for (var i=0; i<callingForm.srchdomain.length; i++) {
10708:             if (callingForm.srchdomain.options[i].value == '$context_dom') {
10709:                 callingForm.srchdomain.selectedIndex = i;
10710:             }
10711:         }
10712:     }
10713: }
10714: ENDSCRIPT
10715: 
10716:     }
10717: 
10718:     my $output = <<"END_BLOCK";
10719: <script type="text/javascript">
10720: // <![CDATA[
10721: function validateEntry(callingForm) {
10722: 
10723:     var checkok = 1;
10724:     var srchin;
10725:     for (var i=0; i<callingForm.srchin.length; i++) {
10726: 	if ( callingForm.srchin[i].checked ) {
10727: 	    srchin = callingForm.srchin[i].value;
10728: 	}
10729:     }
10730: 
10731:     var srchtype = callingForm.srchtype.options[callingForm.srchtype.selectedIndex].value;
10732:     var srchby = callingForm.srchby.options[callingForm.srchby.selectedIndex].value;
10733:     var srchdomain = callingForm.srchdomain.options[callingForm.srchdomain.selectedIndex].value;
10734:     var srchterm =  callingForm.srchterm.value;
10735:     var srchin = callingForm.srchin.options[callingForm.srchin.selectedIndex].value;
10736:     var msg = "";
10737: 
10738:     if (srchterm == "") {
10739:         checkok = 0;
10740:         msg += "$js_lt{'youm'}\\n";
10741:     }
10742: 
10743:     if (srchtype== 'begins') {
10744:         if (srchterm.length < 2) {
10745:             checkok = 0;
10746:             msg += "$js_lt{'thte'}\\n";
10747:         }
10748:     }
10749: 
10750:     if (srchtype== 'contains') {
10751:         if (srchterm.length < 3) {
10752:             checkok = 0;
10753:             msg += "$js_lt{'thet'}\\n";
10754:         }
10755:     }
10756:     if (srchin == 'instd') {
10757:         if (srchdomain == '') {
10758:             checkok = 0;
10759:             msg += "$js_lt{'yomc'}\\n";
10760:         }
10761:     }
10762:     if (srchin == 'dom') {
10763:         if (srchdomain == '') {
10764:             checkok = 0;
10765:             msg += "$js_lt{'ymcd'}\\n";
10766:         }
10767:     }
10768:     if (srchby == 'lastfirst') {
10769:         if (srchterm.indexOf(",") == -1) {
10770:             checkok = 0;
10771:             msg += "$js_lt{'whus'}\\n";
10772:         }
10773:         if (srchterm.indexOf(",") == srchterm.length -1) {
10774:             checkok = 0;
10775:             msg += "$js_lt{'whse'}\\n";
10776:         }
10777:     }
10778:     if (checkok == 0) {
10779:         alert("$js_lt{'thfo'}\\n"+msg);
10780:         return;
10781:     }
10782:     if (checkok == 1) {
10783:         callingForm.submit();
10784:     }
10785: }
10786: 
10787: $newuserscript
10788: 
10789: // ]]>
10790: </script>
10791: 
10792: $new_user_create
10793: 
10794: END_BLOCK
10795: 
10796:     $output .= &Apache::lonhtmlcommon::start_pick_box().
10797:                &Apache::lonhtmlcommon::row_title($html_lt{'doma'}).
10798:                $domform.
10799:                &Apache::lonhtmlcommon::row_closure().
10800:                &Apache::lonhtmlcommon::row_title($html_lt{'usr'}).
10801:                $srchbysel.
10802:                $srchtypesel. 
10803:                '<input type="text" size="15" name="srchterm" value="'.$srchterm.'" />'.
10804:                $srchinsel.
10805:                &Apache::lonhtmlcommon::row_closure(1). 
10806:                &Apache::lonhtmlcommon::end_pick_box().
10807:                '<br />';
10808:     return ($output,1);
10809: }
10810: 
10811: sub user_rule_check {
10812:     my ($usershash,$checks,$alerts,$rulematch,$inst_results,$curr_rules,$got_rules) = @_;
10813:     my ($response,%inst_response);
10814:     if (ref($usershash) eq 'HASH') {
10815:         if (keys(%{$usershash}) > 1) {
10816:             my (%by_username,%by_id,%userdoms);
10817:             my $checkid;
10818:             if (ref($checks) eq 'HASH') {
10819:                 if ((!defined($checks->{'username'})) && (defined($checks->{'id'}))) {
10820:                     $checkid = 1;
10821:                 }
10822:             }
10823:             foreach my $user (keys(%{$usershash})) {
10824:                 my ($uname,$udom) = split(/:/,$user);
10825:                 if ($checkid) {
10826:                     if (ref($usershash->{$user}) eq 'HASH') {
10827:                         if ($usershash->{$user}->{'id'} ne '') {
10828:                             $by_id{$udom}{$usershash->{$user}->{'id'}} = $uname;
10829:                             $userdoms{$udom} = 1;
10830:                             if (ref($inst_results) eq 'HASH') {
10831:                                 $inst_results->{$uname.':'.$udom} = {};
10832:                             }
10833:                         }
10834:                     }
10835:                 } else {
10836:                     $by_username{$udom}{$uname} = 1;
10837:                     $userdoms{$udom} = 1;
10838:                     if (ref($inst_results) eq 'HASH') {
10839:                         $inst_results->{$uname.':'.$udom} = {};
10840:                     }
10841:                 }
10842:             }
10843:             foreach my $udom (keys(%userdoms)) {
10844:                 if (!$got_rules->{$udom}) {
10845:                     my %domconfig = &Apache::lonnet::get_dom('configuration',
10846:                                                              ['usercreation'],$udom);
10847:                     if (ref($domconfig{'usercreation'}) eq 'HASH') {
10848:                         foreach my $item ('username','id') {
10849:                             if (ref($domconfig{'usercreation'}{$item.'_rule'}) eq 'ARRAY') {
10850:                                 $$curr_rules{$udom}{$item} =
10851:                                     $domconfig{'usercreation'}{$item.'_rule'};
10852:                             }
10853:                         }
10854:                     }
10855:                     $got_rules->{$udom} = 1;
10856:                 }
10857:             }
10858:             if ($checkid) {
10859:                 foreach my $udom (keys(%by_id)) {
10860:                     my ($outcome,$results) = &Apache::lonnet::get_multiple_instusers($udom,$by_id{$udom},'id');
10861:                     if ($outcome eq 'ok') {
10862:                         foreach my $id (keys(%{$by_id{$udom}})) {
10863:                             my $uname = $by_id{$udom}{$id};
10864:                             $inst_response{$uname.':'.$udom} = $outcome;
10865:                         }
10866:                         if (ref($results) eq 'HASH') {
10867:                             foreach my $uname (keys(%{$results})) {
10868:                                 if (exists($inst_response{$uname.':'.$udom})) {
10869:                                     $inst_response{$uname.':'.$udom} = $outcome;
10870:                                     $inst_results->{$uname.':'.$udom} = $results->{$uname};
10871:                                 }
10872:                             }
10873:                         }
10874:                     }
10875:                 }
10876:             } else {
10877:                 foreach my $udom (keys(%by_username)) {
10878:                     my ($outcome,$results) = &Apache::lonnet::get_multiple_instusers($udom,$by_username{$udom});
10879:                     if ($outcome eq 'ok') {
10880:                         foreach my $uname (keys(%{$by_username{$udom}})) {
10881:                             $inst_response{$uname.':'.$udom} = $outcome;
10882:                         }
10883:                         if (ref($results) eq 'HASH') {
10884:                             foreach my $uname (keys(%{$results})) {
10885:                                 $inst_results->{$uname.':'.$udom} = $results->{$uname};
10886:                             }
10887:                         }
10888:                     }
10889:                 }
10890:             }
10891:         } elsif (keys(%{$usershash}) == 1) {
10892:             my $user = (keys(%{$usershash}))[0];
10893:             my ($uname,$udom) = split(/:/,$user);
10894:             if (($udom ne '') && ($uname ne '')) {
10895:                 if (ref($usershash->{$user}) eq 'HASH') {
10896:                     if (ref($checks) eq 'HASH') {
10897:                         if (defined($checks->{'username'})) {
10898:                             ($inst_response{$user},%{$inst_results->{$user}}) =
10899:                                 &Apache::lonnet::get_instuser($udom,$uname);
10900:                         } elsif (defined($checks->{'id'})) {
10901:                             if ($usershash->{$user}->{'id'} ne '') {
10902:                                 ($inst_response{$user},%{$inst_results->{$user}}) =
10903:                                     &Apache::lonnet::get_instuser($udom,undef,
10904:                                                                   $usershash->{$user}->{'id'});
10905:                             } else {
10906:                                 ($inst_response{$user},%{$inst_results->{$user}}) =
10907:                                     &Apache::lonnet::get_instuser($udom,$uname);
10908:                             }
10909:                         }
10910:                     } else {
10911:                        ($inst_response{$user},%{$inst_results->{$user}}) =
10912:                             &Apache::lonnet::get_instuser($udom,$uname);
10913:                        return;
10914:                     }
10915:                     if (!$got_rules->{$udom}) {
10916:                         my %domconfig = &Apache::lonnet::get_dom('configuration',
10917:                                                                  ['usercreation'],$udom);
10918:                         if (ref($domconfig{'usercreation'}) eq 'HASH') {
10919:                             foreach my $item ('username','id') {
10920:                                 if (ref($domconfig{'usercreation'}{$item.'_rule'}) eq 'ARRAY') {
10921:                                    $$curr_rules{$udom}{$item} =
10922:                                        $domconfig{'usercreation'}{$item.'_rule'};
10923:                                 }
10924:                             }
10925:                         }
10926:                         $got_rules->{$udom} = 1;
10927:                     }
10928:                 }
10929:             } else {
10930:                 return;
10931:             }
10932:         } else {
10933:             return;
10934:         }
10935:         foreach my $user (keys(%{$usershash})) {
10936:             my ($uname,$udom) = split(/:/,$user);
10937:             next if (($udom eq '') || ($uname eq ''));
10938:             my $id;
10939:             if (ref($inst_results) eq 'HASH') {
10940:                 if (ref($inst_results->{$user}) eq 'HASH') {
10941:                     $id = $inst_results->{$user}->{'id'};
10942:                 }
10943:             }
10944:             if ($id eq '') {
10945:                 if (ref($usershash->{$user})) {
10946:                     $id = $usershash->{$user}->{'id'};
10947:                 }
10948:             }
10949:             foreach my $item (keys(%{$checks})) {
10950:                 if (ref($$curr_rules{$udom}) eq 'HASH') {
10951:                     if (ref($$curr_rules{$udom}{$item}) eq 'ARRAY') {
10952:                         if (@{$$curr_rules{$udom}{$item}} > 0) {
10953:                             my %rule_check = &Apache::lonnet::inst_rulecheck($udom,$uname,$id,$item,
10954:                                                                              $$curr_rules{$udom}{$item});
10955:                             foreach my $rule (@{$$curr_rules{$udom}{$item}}) {
10956:                                 if ($rule_check{$rule}) {
10957:                                     $$rulematch{$user}{$item} = $rule;
10958:                                     if ($inst_response{$user} eq 'ok') {
10959:                                         if (ref($inst_results) eq 'HASH') {
10960:                                             if (ref($inst_results->{$user}) eq 'HASH') {
10961:                                                 if (keys(%{$inst_results->{$user}}) == 0) {
10962:                                                     $$alerts{$item}{$udom}{$uname} = 1;
10963:                                                 } elsif ($item eq 'id') {
10964:                                                     if ($inst_results->{$user}->{'id'} eq '') {
10965:                                                         $$alerts{$item}{$udom}{$uname} = 1;
10966:                                                     }
10967:                                                 }
10968:                                             }
10969:                                         }
10970:                                     }
10971:                                     last;
10972:                                 }
10973:                             }
10974:                         }
10975:                     }
10976:                 }
10977:             }
10978:         }
10979:     }
10980:     return;
10981: }
10982: 
10983: sub user_rule_formats {
10984:     my ($domain,$domdesc,$curr_rules,$check) = @_;
10985:     my %text = ( 
10986:                  'username' => 'Usernames',
10987:                  'id'       => 'IDs',
10988:                );
10989:     my $output;
10990:     my ($rules,$ruleorder) = &Apache::lonnet::inst_userrules($domain,$check);
10991:     if ((ref($rules) eq 'HASH') && (ref($ruleorder) eq 'ARRAY')) {
10992:         if (@{$ruleorder} > 0) {
10993:             $output = '<br />'.
10994:                       &mt($text{$check}.' with the following format(s) may [_1]only[_2] be used for verified users at [_3]:',
10995:                           '<span class="LC_cusr_emph">','</span>',$domdesc).
10996:                       ' <ul>';
10997:             foreach my $rule (@{$ruleorder}) {
10998:                 if (ref($curr_rules) eq 'ARRAY') {
10999:                     if (grep(/^\Q$rule\E$/,@{$curr_rules})) {
11000:                         if (ref($rules->{$rule}) eq 'HASH') {
11001:                             $output .= '<li>'.$rules->{$rule}{'name'}.': '.
11002:                                         $rules->{$rule}{'desc'}.'</li>';
11003:                         }
11004:                     }
11005:                 }
11006:             }
11007:             $output .= '</ul>';
11008:         }
11009:     }
11010:     return $output;
11011: }
11012: 
11013: sub instrule_disallow_msg {
11014:     my ($checkitem,$domdesc,$count,$mode) = @_;
11015:     my $response;
11016:     my %text = (
11017:                   item   => 'username',
11018:                   items  => 'usernames',
11019:                   match  => 'matches',
11020:                   do     => 'does',
11021:                   action => 'a username',
11022:                   one    => 'one',
11023:                );
11024:     if ($count > 1) {
11025:         $text{'item'} = 'usernames';
11026:         $text{'match'} ='match';
11027:         $text{'do'} = 'do';
11028:         $text{'action'} = 'usernames',
11029:         $text{'one'} = 'ones';
11030:     }
11031:     if ($checkitem eq 'id') {
11032:         $text{'items'} = 'IDs';
11033:         $text{'item'} = 'ID';
11034:         $text{'action'} = 'an ID';
11035:         if ($count > 1) {
11036:             $text{'item'} = 'IDs';
11037:             $text{'action'} = 'IDs';
11038:         }
11039:     }
11040:     $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 />';
11041:     if ($mode eq 'upload') {
11042:         if ($checkitem eq 'username') {
11043:             $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'}.");
11044:         } elsif ($checkitem eq 'id') {
11045:             $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.");
11046:         }
11047:     } elsif ($mode eq 'selfcreate') {
11048:         if ($checkitem eq 'id') {
11049:             $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.");
11050:         }
11051:     } else {
11052:         if ($checkitem eq 'username') {
11053:             $response .= &mt("You must choose $text{'action'} with a different format --  $text{'one'} that will not conflict with 'official' institutional $text{'items'}.");
11054:         } elsif ($checkitem eq 'id') {
11055:             $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.");
11056:         }
11057:     }
11058:     return $response;
11059: }
11060: 
11061: sub personal_data_fieldtitles {
11062:     my %fieldtitles = &Apache::lonlocal::texthash (
11063:                         id => 'Student/Employee ID',
11064:                         permanentemail => 'E-mail address',
11065:                         lastname => 'Last Name',
11066:                         firstname => 'First Name',
11067:                         middlename => 'Middle Name',
11068:                         generation => 'Generation',
11069:                         gen => 'Generation',
11070:                         inststatus => 'Affiliation',
11071:                    );
11072:     return %fieldtitles;
11073: }
11074: 
11075: sub sorted_inst_types {
11076:     my ($dom) = @_;
11077:     my ($usertypes,$order);
11078:     my %domdefaults = &Apache::lonnet::get_domain_defaults($dom);
11079:     if (ref($domdefaults{'inststatus'}) eq 'HASH') {
11080:         $usertypes = $domdefaults{'inststatus'}{'inststatustypes'};
11081:         $order = $domdefaults{'inststatus'}{'inststatusorder'};
11082:     } else {
11083:         ($usertypes,$order) = &Apache::lonnet::retrieve_inst_usertypes($dom);
11084:     }
11085:     my $othertitle = &mt('All users');
11086:     if ($env{'request.course.id'}) {
11087:         $othertitle  = &mt('Any users');
11088:     }
11089:     my @types;
11090:     if (ref($order) eq 'ARRAY') {
11091:         @types = @{$order};
11092:     }
11093:     if (@types == 0) {
11094:         if (ref($usertypes) eq 'HASH') {
11095:             @types = sort(keys(%{$usertypes}));
11096:         }
11097:     }
11098:     if (keys(%{$usertypes}) > 0) {
11099:         $othertitle = &mt('Other users');
11100:     }
11101:     return ($othertitle,$usertypes,\@types);
11102: }
11103: 
11104: sub get_institutional_codes {
11105:     my ($cdom,$crs,$settings,$allcourses,$LC_code) = @_;
11106: # Get complete list of course sections to update
11107:     my @currsections = ();
11108:     my @currxlists = ();
11109:     my (%unclutteredsec,%unclutteredlcsec);
11110:     my $coursecode = $$settings{'internal.coursecode'};
11111:     my $crskey = $crs.':'.$coursecode;
11112:     @{$unclutteredsec{$crskey}} = ();
11113:     @{$unclutteredlcsec{$crskey}} = ();
11114: 
11115:     if ($$settings{'internal.sectionnums'} ne '') {
11116:         @currsections = split(/,/,$$settings{'internal.sectionnums'});
11117:     }
11118: 
11119:     if ($$settings{'internal.crosslistings'} ne '') {
11120:         @currxlists = split(/,/,$$settings{'internal.crosslistings'});
11121:     }
11122: 
11123:     if (@currxlists > 0) {
11124:         foreach my $xl (@currxlists) {
11125:             if ($xl =~ /^([^:]+):(\w*)$/) {
11126:                 unless (grep/^$1$/,@{$allcourses}) {
11127:                     push(@{$allcourses},$1);
11128:                     $$LC_code{$1} = $2;
11129:                 }
11130:             }
11131:         }
11132:     }
11133: 
11134:     if (@currsections > 0) {
11135:         foreach my $sec (@currsections) {
11136:             if ($sec =~ m/^(\w+):(\w*)$/ ) {
11137:                 my $instsec = $1;
11138:                 my $lc_sec = $2;
11139:                 unless (grep/^\Q$instsec\E$/,@{$unclutteredsec{$crskey}}) {
11140:                     push(@{$unclutteredsec{$crskey}},$instsec);
11141:                     push(@{$unclutteredlcsec{$crskey}},$lc_sec);
11142:                 }
11143:             }
11144:         }
11145:     }
11146: 
11147:     if (@{$unclutteredsec{$crskey}} > 0) {
11148:         my %formattedsec = &Apache::lonnet::auto_instsec_reformat($cdom,'clutter',\%unclutteredsec);
11149:         if ((ref($formattedsec{$crskey}) eq 'ARRAY') && (ref($unclutteredlcsec{$crskey}) eq 'ARRAY')) {
11150:             for (my $i=0; $i<@{$formattedsec{$crskey}}; $i++) {
11151:                 my $sec = $coursecode.$formattedsec{$crskey}[$i];
11152:                 unless (grep/^\Q$sec\E$/,@{$allcourses}) {
11153:                     push(@{$allcourses},$sec);
11154:                     $$LC_code{$sec} = $unclutteredlcsec{$crskey}[$i];
11155:                 }
11156:             }
11157:         }
11158:     }
11159:     return;
11160: }
11161: 
11162: sub get_standard_codeitems {
11163:     return ('Year','Semester','Department','Number','Section');
11164: }
11165: 
11166: =pod
11167: 
11168: =head1 Slot Helpers
11169: 
11170: =over 4
11171: 
11172: =item * sorted_slots()
11173: 
11174: Sorts an array of slot names in order of an optional sort key,
11175: default sort is by slot start time (earliest first). 
11176: 
11177: Inputs:
11178: 
11179: =over 4
11180: 
11181: slotsarr  - Reference to array of unsorted slot names.
11182: 
11183: slots     - Reference to hash of hash, where outer hash keys are slot names.
11184: 
11185: sortkey   - Name of key in inner hash to be sorted on (e.g., starttime).
11186: 
11187: =back
11188: 
11189: Returns:
11190: 
11191: =over 4
11192: 
11193: sorted   - An array of slot names sorted by a specified sort key 
11194:            (default sort key is start time of the slot).
11195: 
11196: =back
11197: 
11198: =cut
11199: 
11200: 
11201: sub sorted_slots {
11202:     my ($slotsarr,$slots,$sortkey) = @_;
11203:     if ($sortkey eq '') {
11204:         $sortkey = 'starttime';
11205:     }
11206:     my @sorted;
11207:     if ((ref($slotsarr) eq 'ARRAY') && (ref($slots) eq 'HASH')) {
11208:         @sorted =
11209:             sort {
11210:                      if (ref($slots->{$a}) && ref($slots->{$b})) {
11211:                          return $slots->{$a}{$sortkey} <=> $slots->{$b}{$sortkey}
11212:                      }
11213:                      if (ref($slots->{$a})) { return -1;}
11214:                      if (ref($slots->{$b})) { return 1;}
11215:                      return 0;
11216:                  } @{$slotsarr};
11217:     }
11218:     return @sorted;
11219: }
11220: 
11221: =pod
11222: 
11223: =item * get_future_slots()
11224: 
11225: Inputs:
11226: 
11227: =over 4
11228: 
11229: cnum - course number
11230: 
11231: cdom - course domain
11232: 
11233: now - current UNIX time
11234: 
11235: symb - optional symb
11236: 
11237: =back
11238: 
11239: Returns:
11240: 
11241: =over 4
11242: 
11243: sorted_reservable - ref to array of student_schedulable slots currently 
11244:                     reservable, ordered by end date of reservation period.
11245: 
11246: reservable_now - ref to hash of student_schedulable slots currently
11247:                  reservable.
11248: 
11249:     Keys in inner hash are:
11250:     (a) symb: either blank or symb to which slot use is restricted.
11251:     (b) endreserve: end date of reservation period.
11252:     (c) uniqueperiod: start,end dates when slot is to be uniquely
11253:         selected.
11254: 
11255: sorted_future - ref to array of student_schedulable slots reservable in
11256:                 the future, ordered by start date of reservation period.
11257: 
11258: future_reservable - ref to hash of student_schedulable slots reservable
11259:                     in the future.
11260: 
11261:     Keys in inner hash are:
11262:     (a) symb: either blank or symb to which slot use is restricted.
11263:     (b) startreserve:  start date of reservation period.
11264:     (c) uniqueperiod: start,end dates when slot is to be uniquely
11265:         selected.
11266: 
11267: =back
11268: 
11269: =cut
11270: 
11271: sub get_future_slots {
11272:     my ($cnum,$cdom,$now,$symb) = @_;
11273:     my (%reservable_now,%future_reservable,@sorted_reservable,@sorted_future);
11274:     my %slots = &Apache::lonnet::get_course_slots($cnum,$cdom);
11275:     foreach my $slot (keys(%slots)) {
11276:         next unless($slots{$slot}->{'type'} eq 'schedulable_student');
11277:         if ($symb) {
11278:             next if (($slots{$slot}->{'symb'} ne '') && 
11279:                      ($slots{$slot}->{'symb'} ne $symb));
11280:         }
11281:         if (($slots{$slot}->{'starttime'} > $now) &&
11282:             ($slots{$slot}->{'endtime'} > $now)) {
11283:             if (($slots{$slot}->{'allowedsections'}) || ($slots{$slot}->{'allowedusers'})) {
11284:                 my $userallowed = 0;
11285:                 if ($slots{$slot}->{'allowedsections'}) {
11286:                     my @allowed_sec = split(',',$slots{$slot}->{'allowedsections'});
11287:                     if (!defined($env{'request.role.sec'})
11288:                         && grep(/^No section assigned$/,@allowed_sec)) {
11289:                         $userallowed=1;
11290:                     } else {
11291:                         if (grep(/^\Q$env{'request.role.sec'}\E$/,@allowed_sec)) {
11292:                             $userallowed=1;
11293:                         }
11294:                     }
11295:                     unless ($userallowed) {
11296:                         if (defined($env{'request.course.groups'})) {
11297:                             my @groups = split(/:/,$env{'request.course.groups'});
11298:                             foreach my $group (@groups) {
11299:                                 if (grep(/^\Q$group\E$/,@allowed_sec)) {
11300:                                     $userallowed=1;
11301:                                     last;
11302:                                 }
11303:                             }
11304:                         }
11305:                     }
11306:                 }
11307:                 if ($slots{$slot}->{'allowedusers'}) {
11308:                     my @allowed_users = split(',',$slots{$slot}->{'allowedusers'});
11309:                     my $user = $env{'user.name'}.':'.$env{'user.domain'};
11310:                     if (grep(/^\Q$user\E$/,@allowed_users)) {
11311:                         $userallowed = 1;
11312:                     }
11313:                 }
11314:                 next unless($userallowed);
11315:             }
11316:             my $startreserve = $slots{$slot}->{'startreserve'};
11317:             my $endreserve = $slots{$slot}->{'endreserve'};
11318:             my $symb = $slots{$slot}->{'symb'};
11319:             my $uniqueperiod;
11320:             if (ref($slots{$slot}->{'uniqueperiod'}) eq 'ARRAY') {
11321:                 $uniqueperiod = join(',',@{$slots{$slot}->{'uniqueperiod'}});
11322:             }
11323:             if (($startreserve < $now) &&
11324:                 (!$endreserve || $endreserve > $now)) {
11325:                 my $lastres = $endreserve;
11326:                 if (!$lastres) {
11327:                     $lastres = $slots{$slot}->{'starttime'};
11328:                 }
11329:                 $reservable_now{$slot} = {
11330:                                            symb       => $symb,
11331:                                            endreserve => $lastres,
11332:                                            uniqueperiod => $uniqueperiod,   
11333:                                          };
11334:             } elsif (($startreserve > $now) &&
11335:                      (!$endreserve || $endreserve > $startreserve)) {
11336:                 $future_reservable{$slot} = {
11337:                                               symb         => $symb,
11338:                                               startreserve => $startreserve,
11339:                                               uniqueperiod => $uniqueperiod,
11340:                                             };
11341:             }
11342:         }
11343:     }
11344:     my @unsorted_reservable = keys(%reservable_now);
11345:     if (@unsorted_reservable > 0) {
11346:         @sorted_reservable = 
11347:             &sorted_slots(\@unsorted_reservable,\%reservable_now,'endreserve');
11348:     }
11349:     my @unsorted_future = keys(%future_reservable);
11350:     if (@unsorted_future > 0) {
11351:         @sorted_future =
11352:             &sorted_slots(\@unsorted_future,\%future_reservable,'startreserve');
11353:     }
11354:     return (\@sorted_reservable,\%reservable_now,\@sorted_future,\%future_reservable);
11355: }
11356: 
11357: =pod
11358: 
11359: =back
11360: 
11361: =head1 HTTP Helpers
11362: 
11363: =over 4
11364: 
11365: =item * &get_unprocessed_cgi($query,$possible_names)
11366: 
11367: Modify the %env hash to contain unprocessed CGI form parameters held in
11368: $query.  The parameters listed in $possible_names (an array reference),
11369: will be set in $env{'form.name'} if they do not already exist.
11370: 
11371: Typically called with $ENV{'QUERY_STRING'} as the first parameter.  
11372: $possible_names is an ref to an array of form element names.  As an example:
11373: get_unprocessed_cgi($ENV{'QUERY_STRING'},['uname','udom']);
11374: will result in $env{'form.uname'} and $env{'form.udom'} being set.
11375: 
11376: =cut
11377: 
11378: sub get_unprocessed_cgi {
11379:   my ($query,$possible_names)= @_;
11380:   # $Apache::lonxml::debug=1;
11381:   foreach my $pair (split(/&/,$query)) {
11382:     my ($name, $value) = split(/=/,$pair);
11383:     $name = &unescape($name);
11384:     if (!defined($possible_names) || (grep {$_ eq $name} @$possible_names)) {
11385:       $value =~ tr/+/ /;
11386:       $value =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack("C",hex($1))/eg;
11387:       unless (defined($env{'form.'.$name})) { &add_to_env('form.'.$name,$value) };
11388:     }
11389:   }
11390: }
11391: 
11392: =pod
11393: 
11394: =item * &cacheheader() 
11395: 
11396: returns cache-controlling header code
11397: 
11398: =cut
11399: 
11400: sub cacheheader {
11401:     unless ($env{'request.method'} eq 'GET') { return ''; }
11402:     my $date=strftime("%a, %d %b %Y %H:%M:%S GMT",gmtime);
11403:     my $output .='<meta HTTP-EQUIV="Expires" CONTENT="'.$date.'" />
11404:                 <meta HTTP-EQUIV="Cache-control" CONTENT="no-cache" />
11405:                 <meta HTTP-EQUIV="Pragma" CONTENT="no-cache" />';
11406:     return $output;
11407: }
11408: 
11409: =pod
11410: 
11411: =item * &no_cache($r) 
11412: 
11413: specifies header code to not have cache
11414: 
11415: =cut
11416: 
11417: sub no_cache {
11418:     my ($r) = @_;
11419:     if ($ENV{'REQUEST_METHOD'} ne 'GET' &&
11420: 	$env{'request.method'} ne 'GET') { return ''; }
11421:     my $date=strftime("%a, %d %b %Y %H:%M:%S GMT",gmtime(time));
11422:     $r->no_cache(1);
11423:     $r->header_out("Expires" => $date);
11424:     $r->header_out("Pragma" => "no-cache");
11425: }
11426: 
11427: sub content_type {
11428:     my ($r,$type,$charset) = @_;
11429:     if ($r) {
11430: 	#  Note that printout.pl calls this with undef for $r.
11431: 	&no_cache($r);
11432:     }
11433:     if ($env{'browser.mathml'} && $type eq 'text/html') { $type='text/xml'; }
11434:     unless ($charset) {
11435: 	$charset=&Apache::lonlocal::current_encoding;
11436:     }
11437:     if ($charset) { $type.='; charset='.$charset; }
11438:     if ($r) {
11439: 	$r->content_type($type);
11440:     } else {
11441: 	print("Content-type: $type\n\n");
11442:     }
11443: }
11444: 
11445: =pod
11446: 
11447: =item * &add_to_env($name,$value) 
11448: 
11449: adds $name to the %env hash with value
11450: $value, if $name already exists, the entry is converted to an array
11451: reference and $value is added to the array.
11452: 
11453: =cut
11454: 
11455: sub add_to_env {
11456:   my ($name,$value)=@_;
11457:   if (defined($env{$name})) {
11458:     if (ref($env{$name})) {
11459:       #already have multiple values
11460:       push(@{ $env{$name} },$value);
11461:     } else {
11462:       #first time seeing multiple values, convert hash entry to an arrayref
11463:       my $first=$env{$name};
11464:       undef($env{$name});
11465:       push(@{ $env{$name} },$first,$value);
11466:     }
11467:   } else {
11468:     $env{$name}=$value;
11469:   }
11470: }
11471: 
11472: =pod
11473: 
11474: =item * &get_env_multiple($name) 
11475: 
11476: gets $name from the %env hash, it seemlessly handles the cases where multiple
11477: values may be defined and end up as an array ref.
11478: 
11479: returns an array of values
11480: 
11481: =cut
11482: 
11483: sub get_env_multiple {
11484:     my ($name) = @_;
11485:     my @values;
11486:     if (defined($env{$name})) {
11487:         # exists is it an array
11488:         if (ref($env{$name})) {
11489:             @values=@{ $env{$name} };
11490:         } else {
11491:             $values[0]=$env{$name};
11492:         }
11493:     }
11494:     return(@values);
11495: }
11496: 
11497: sub ask_for_embedded_content {
11498:     my ($actionurl,$state,$allfiles,$codebase,$args)=@_;
11499:     my (%subdependencies,%dependencies,%mapping,%existing,%newfiles,%pathchanges,
11500:         %currsubfile,%unused,$rem);
11501:     my $counter = 0;
11502:     my $numnew = 0;
11503:     my $numremref = 0;
11504:     my $numinvalid = 0;
11505:     my $numpathchg = 0;
11506:     my $numexisting = 0;
11507:     my $numunused = 0;
11508:     my ($output,$upload_output,$toplevel,$url,$udom,$uname,$getpropath,$cdom,$cnum,
11509:         $fileloc,$filename,$delete_output,$modify_output,$title,$symb,$path,$navmap);
11510:     my $heading = &mt('Upload embedded files');
11511:     my $buttontext = &mt('Upload');
11512: 
11513:     if ($env{'request.course.id'}) {
11514:         if ($actionurl eq '/adm/dependencies') {
11515:             $navmap = Apache::lonnavmaps::navmap->new();
11516:         }
11517:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
11518:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
11519:     }
11520:     if (($actionurl eq '/adm/portfolio') ||
11521:         ($actionurl eq '/adm/coursegrp_portfolio')) {
11522:         my $current_path='/';
11523:         if ($env{'form.currentpath'}) {
11524:             $current_path = $env{'form.currentpath'};
11525:         }
11526:         if ($actionurl eq '/adm/coursegrp_portfolio') {
11527:             $udom = $cdom;
11528:             $uname = $cnum;
11529:             $url = '/userfiles/groups/'.$env{'form.group'}.'/portfolio';
11530:         } else {
11531:             $udom = $env{'user.domain'};
11532:             $uname = $env{'user.name'};
11533:             $url = '/userfiles/portfolio';
11534:         }
11535:         $toplevel = $url.'/';
11536:         $url .= $current_path;
11537:         $getpropath = 1;
11538:     } elsif (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank') ||
11539:              ($actionurl eq '/adm/imsimport')) { 
11540:         my ($udom,$uname,$rest) = ($args->{'current_path'} =~ m{/priv/($match_domain)/($match_username)/?(.*)$});
11541:         $url = $Apache::lonnet::perlvar{'lonDocRoot'}."/priv/$udom/$uname/";
11542:         $toplevel = $url;
11543:         if ($rest ne '') {
11544:             $url .= $rest;
11545:         }
11546:     } elsif ($actionurl eq '/adm/coursedocs') {
11547:         if (ref($args) eq 'HASH') {
11548:             $url = $args->{'docs_url'};
11549:             $toplevel = $url;
11550:             if ($args->{'context'} eq 'paste') {
11551:                 ($cdom,$cnum) = ($url =~ m{^\Q/uploaded/\E($match_domain)/($match_courseid)/});
11552:                 ($path) =
11553:                     ($toplevel =~ m{^(\Q/uploaded/$cdom/$cnum/\E(?:docs|supplemental)/(?:default|\d+)/\d+)/});
11554:                 $fileloc = &Apache::lonnet::filelocation('',$toplevel);
11555:                 $fileloc =~ s{^/}{};
11556:             }
11557:         }
11558:     } elsif ($actionurl eq '/adm/dependencies') {
11559:         if ($env{'request.course.id'} ne '') {
11560:             if (ref($args) eq 'HASH') {
11561:                 $url = $args->{'docs_url'};
11562:                 $title = $args->{'docs_title'};
11563:                 $toplevel = $url;
11564:                 unless ($toplevel =~ m{^/}) {
11565:                     $toplevel = "/$url";
11566:                 }
11567:                 ($rem) = ($toplevel =~ m{^(.+/)[^/]+$});
11568:                 if ($toplevel =~ m{^(\Q/uploaded/$cdom/$cnum/portfolio/syllabus\E)}) {
11569:                     $path = $1;
11570:                 } else {
11571:                     ($path) =
11572:                         ($toplevel =~ m{^(\Q/uploaded/$cdom/$cnum/\E(?:docs|supplemental)/(?:default|\d+)/\d+)/});
11573:                 }
11574:                 if ($toplevel=~/^\/*(uploaded|editupload)/) {
11575:                     $fileloc = $toplevel;
11576:                     $fileloc=~ s/^\s*(\S+)\s*$/$1/;
11577:                     my ($udom,$uname,$fname) =
11578:                         ($fileloc=~ m{^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$});
11579:                     $fileloc = propath($udom,$uname).'/userfiles/'.$fname;
11580:                 } else {
11581:                     $fileloc = &Apache::lonnet::filelocation('',$toplevel);
11582:                 }
11583:                 $fileloc =~ s{^/}{};
11584:                 ($filename) = ($fileloc =~ m{.+/([^/]+)$});
11585:                 $heading = &mt('Status of dependencies in [_1]',"$title ($filename)");
11586:             }
11587:         }
11588:     } elsif ($actionurl eq "/public/$cdom/$cnum/syllabus") {
11589:         $udom = $cdom;
11590:         $uname = $cnum;
11591:         $url = "/uploaded/$cdom/$cnum/portfolio/syllabus";
11592:         $toplevel = $url;
11593:         $path = $url;
11594:         $fileloc = &Apache::lonnet::filelocation('',$toplevel).'/';
11595:         $fileloc =~ s{^/}{};
11596:     }
11597:     foreach my $file (keys(%{$allfiles})) {
11598:         my $embed_file;
11599:         if (($path eq "/uploaded/$cdom/$cnum/portfolio/syllabus") && ($file =~ m{^\Q$path/\E(.+)$})) {
11600:             $embed_file = $1;
11601:         } else {
11602:             $embed_file = $file;
11603:         }
11604:         my ($absolutepath,$cleaned_file);
11605:         if ($embed_file =~ m{^\w+://}) {
11606:             $cleaned_file = $embed_file;
11607:             $newfiles{$cleaned_file} = 1;
11608:             $mapping{$cleaned_file} = $embed_file;
11609:         } else {
11610:             $cleaned_file = &clean_path($embed_file);
11611:             if ($embed_file =~ m{^/}) {
11612:                 $absolutepath = $embed_file;
11613:             }
11614:             if ($cleaned_file =~ m{/}) {
11615:                 my ($path,$fname) = ($cleaned_file =~ m{^(.+)/([^/]*)$});
11616:                 $path = &check_for_traversal($path,$url,$toplevel);
11617:                 my $item = $fname;
11618:                 if ($path ne '') {
11619:                     $item = $path.'/'.$fname;
11620:                     $subdependencies{$path}{$fname} = 1;
11621:                 } else {
11622:                     $dependencies{$item} = 1;
11623:                 }
11624:                 if ($absolutepath) {
11625:                     $mapping{$item} = $absolutepath;
11626:                 } else {
11627:                     $mapping{$item} = $embed_file;
11628:                 }
11629:             } else {
11630:                 $dependencies{$embed_file} = 1;
11631:                 if ($absolutepath) {
11632:                     $mapping{$cleaned_file} = $absolutepath;
11633:                 } else {
11634:                     $mapping{$cleaned_file} = $embed_file;
11635:                 }
11636:             }
11637:         }
11638:     }
11639:     my $dirptr = 16384;
11640:     foreach my $path (keys(%subdependencies)) {
11641:         $currsubfile{$path} = {};
11642:         if (($actionurl eq '/adm/portfolio') ||
11643:             ($actionurl eq '/adm/coursegrp_portfolio')) { 
11644:             my ($sublistref,$listerror) =
11645:                 &Apache::lonnet::dirlist($url.$path,$udom,$uname,$getpropath);
11646:             if (ref($sublistref) eq 'ARRAY') {
11647:                 foreach my $line (@{$sublistref}) {
11648:                     my ($file_name,$rest) = split(/\&/,$line,2);
11649:                     $currsubfile{$path}{$file_name} = 1;
11650:                 }
11651:             }
11652:         } elsif (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank')) {
11653:             if (opendir(my $dir,$url.'/'.$path)) {
11654:                 my @subdir_list = grep(!/^\./,readdir($dir));
11655:                 map {$currsubfile{$path}{$_} = 1;} @subdir_list;
11656:             }
11657:         } elsif (($actionurl eq '/adm/dependencies') ||
11658:                  (($actionurl eq '/adm/coursedocs') && (ref($args) eq 'HASH') &&
11659:                   ($args->{'context'} eq 'paste')) ||
11660:                  ($actionurl eq "/public/$cdom/$cnum/syllabus")) {
11661:             if ($env{'request.course.id'} ne '') {
11662:                 my $dir;
11663:                 if ($actionurl eq "/public/$cdom/$cnum/syllabus") {
11664:                     $dir = $fileloc;
11665:                 } else {
11666:                     ($dir) = ($fileloc =~ m{^(.+/)[^/]+$});
11667:                 }
11668:                 if ($dir ne '') {
11669:                     my ($sublistref,$listerror) =
11670:                         &Apache::lonnet::dirlist($dir.$path,$cdom,$cnum,$getpropath,undef,'/');
11671:                     if (ref($sublistref) eq 'ARRAY') {
11672:                         foreach my $line (@{$sublistref}) {
11673:                             my ($file_name,$dom,undef,$testdir,undef,undef,undef,undef,$size,
11674:                                 undef,$mtime)=split(/\&/,$line,12);
11675:                             unless (($testdir&$dirptr) ||
11676:                                     ($file_name =~ /^\.\.?$/)) {
11677:                                 $currsubfile{$path}{$file_name} = [$size,$mtime];
11678:                             }
11679:                         }
11680:                     }
11681:                 }
11682:             }
11683:         }
11684:         foreach my $file (keys(%{$subdependencies{$path}})) {
11685:             if (exists($currsubfile{$path}{$file})) {
11686:                 my $item = $path.'/'.$file;
11687:                 unless ($mapping{$item} eq $item) {
11688:                     $pathchanges{$item} = 1;
11689:                 }
11690:                 $existing{$item} = 1;
11691:                 $numexisting ++;
11692:             } else {
11693:                 $newfiles{$path.'/'.$file} = 1;
11694:             }
11695:         }
11696:         if ($actionurl eq '/adm/dependencies') {
11697:             foreach my $path (keys(%currsubfile)) {
11698:                 if (ref($currsubfile{$path}) eq 'HASH') {
11699:                     foreach my $file (keys(%{$currsubfile{$path}})) {
11700:                          unless ($subdependencies{$path}{$file}) {
11701:                              next if (($rem ne '') &&
11702:                                       (($env{"httpref.$rem"."$path/$file"} ne '') ||
11703:                                        (ref($navmap) &&
11704:                                        (($navmap->getResourceByUrl($rem."$path/$file") ne '') ||
11705:                                         (($file =~ /^(.*\.s?html?)\.bak$/i) &&
11706:                                          ($navmap->getResourceByUrl($rem."$path/$1")))))));
11707:                              $unused{$path.'/'.$file} = 1; 
11708:                          }
11709:                     }
11710:                 }
11711:             }
11712:         }
11713:     }
11714:     my %currfile;
11715:     if (($actionurl eq '/adm/portfolio') ||
11716:         ($actionurl eq '/adm/coursegrp_portfolio')) {
11717:         my ($dirlistref,$listerror) =
11718:             &Apache::lonnet::dirlist($url,$udom,$uname,$getpropath);
11719:         if (ref($dirlistref) eq 'ARRAY') {
11720:             foreach my $line (@{$dirlistref}) {
11721:                 my ($file_name,$rest) = split(/\&/,$line,2);
11722:                 $currfile{$file_name} = 1;
11723:             }
11724:         }
11725:     } elsif (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank')) {
11726:         if (opendir(my $dir,$url)) {
11727:             my @dir_list = grep(!/^\./,readdir($dir));
11728:             map {$currfile{$_} = 1;} @dir_list;
11729:         }
11730:     } elsif (($actionurl eq '/adm/dependencies') ||
11731:              (($actionurl eq '/adm/coursedocs') && (ref($args) eq 'HASH') &&
11732:               ($args->{'context'} eq 'paste')) ||
11733:              ($actionurl eq "/public/$cdom/$cnum/syllabus")) {
11734:         if ($env{'request.course.id'} ne '') {
11735:             my ($dir) = ($fileloc =~ m{^(.+/)[^/]+$});
11736:             if ($dir ne '') {
11737:                 my ($dirlistref,$listerror) =
11738:                     &Apache::lonnet::dirlist($dir,$cdom,$cnum,$getpropath,undef,'/');
11739:                 if (ref($dirlistref) eq 'ARRAY') {
11740:                     foreach my $line (@{$dirlistref}) {
11741:                         my ($file_name,$dom,undef,$testdir,undef,undef,undef,undef,
11742:                             $size,undef,$mtime)=split(/\&/,$line,12);
11743:                         unless (($testdir&$dirptr) ||
11744:                                 ($file_name =~ /^\.\.?$/)) {
11745:                             $currfile{$file_name} = [$size,$mtime];
11746:                         }
11747:                     }
11748:                 }
11749:             }
11750:         }
11751:     }
11752:     foreach my $file (keys(%dependencies)) {
11753:         if (exists($currfile{$file})) {
11754:             unless ($mapping{$file} eq $file) {
11755:                 $pathchanges{$file} = 1;
11756:             }
11757:             $existing{$file} = 1;
11758:             $numexisting ++;
11759:         } else {
11760:             $newfiles{$file} = 1;
11761:         }
11762:     }
11763:     foreach my $file (keys(%currfile)) {
11764:         unless (($file eq $filename) ||
11765:                 ($file eq $filename.'.bak') ||
11766:                 ($dependencies{$file})) {
11767:             if ($actionurl eq '/adm/dependencies') {
11768:                 unless ($toplevel =~ m{^\Q/uploaded/$cdom/$cnum/portfolio/syllabus\E}) {
11769:                     next if (($rem ne '') &&
11770:                              (($env{"httpref.$rem".$file} ne '') ||
11771:                               (ref($navmap) &&
11772:                               (($navmap->getResourceByUrl($rem.$file) ne '') ||
11773:                                (($file =~ /^(.*\.s?html?)\.bak$/i) &&
11774:                                 ($navmap->getResourceByUrl($rem.$1)))))));
11775:                 }
11776:             }
11777:             $unused{$file} = 1;
11778:         }
11779:     }
11780:     if (($actionurl eq '/adm/coursedocs') && (ref($args) eq 'HASH') &&
11781:         ($args->{'context'} eq 'paste')) {
11782:         $counter = scalar(keys(%existing));
11783:         $numpathchg = scalar(keys(%pathchanges));
11784:         return ($output,$counter,$numpathchg,\%existing);
11785:     } elsif (($actionurl eq "/public/$cdom/$cnum/syllabus") &&
11786:              (ref($args) eq 'HASH') && ($args->{'context'} eq 'rewrites')) {
11787:         $counter = scalar(keys(%existing));
11788:         $numpathchg = scalar(keys(%pathchanges));
11789:         return ($output,$counter,$numpathchg,\%existing,\%mapping);
11790:     }
11791:     foreach my $embed_file (sort {lc($a) cmp lc($b)} keys(%newfiles)) {
11792:         if ($actionurl eq '/adm/dependencies') {
11793:             next if ($embed_file =~ m{^\w+://});
11794:         }
11795:         $upload_output .= &start_data_table_row().
11796:                           '<td valign="top"><img src="'.&icon($embed_file).'" />&nbsp;'.
11797:                           '<span class="LC_filename">'.$embed_file.'</span>';
11798:         unless ($mapping{$embed_file} eq $embed_file) {
11799:             $upload_output .= '<br /><span class="LC_info" style="font-size:smaller;">'.
11800:                               &mt('changed from: [_1]',$mapping{$embed_file}).'</span>';
11801:         }
11802:         $upload_output .= '</td>';
11803:         if ($args->{'ignore_remote_references'} && $embed_file =~ m{^\w+://}) { 
11804:             $upload_output.='<td align="right">'.
11805:                             '<span class="LC_info LC_fontsize_medium">'.
11806:                             &mt("URL points to web address").'</span>';
11807:             $numremref++;
11808:         } elsif ($args->{'error_on_invalid_names'}
11809:             && $embed_file ne &Apache::lonnet::clean_filename($embed_file,{'keep_path' => 1,})) {
11810:             $upload_output.='<td align="right"><span class="LC_warning">'.
11811:                             &mt('Invalid characters').'</span>';
11812:             $numinvalid++;
11813:         } else {
11814:             $upload_output .= '<td>'.
11815:                               &embedded_file_element('upload_embedded',$counter,
11816:                                                      $embed_file,\%mapping,
11817:                                                      $allfiles,$codebase,'upload');
11818:             $counter ++;
11819:             $numnew ++;
11820:         }
11821:         $upload_output .= '</td>'.&Apache::loncommon::end_data_table_row()."\n";
11822:     }
11823:     foreach my $embed_file (sort {lc($a) cmp lc($b)} keys(%existing)) {
11824:         if ($actionurl eq '/adm/dependencies') {
11825:             my ($size,$mtime) = &get_dependency_details(\%currfile,\%currsubfile,$embed_file);
11826:             $modify_output .= &start_data_table_row().
11827:                               '<td><a href="'.$path.'/'.$embed_file.'" style="text-decoration:none;">'.
11828:                               '<img src="'.&icon($embed_file).'" border="0" />'.
11829:                               '&nbsp;<span class="LC_filename">'.$embed_file.'</span></a></td>'.
11830:                               '<td>'.$size.'</td>'.
11831:                               '<td>'.$mtime.'</td>'.
11832:                               '<td><label><input type="checkbox" name="mod_upload_dep" '.
11833:                               'onclick="toggleBrowse('."'$counter'".')" id="mod_upload_dep_'.
11834:                               $counter.'" value="'.$counter.'" />'.&mt('Yes').'</label>'.
11835:                               '<div id="moduploaddep_'.$counter.'" style="display:none;">'.
11836:                               &embedded_file_element('upload_embedded',$counter,
11837:                                                      $embed_file,\%mapping,
11838:                                                      $allfiles,$codebase,'modify').
11839:                               '</div></td>'.
11840:                               &end_data_table_row()."\n";
11841:             $counter ++;
11842:         } else {
11843:             $upload_output .= &start_data_table_row().
11844:                               '<td valign="top"><img src="'.&icon($embed_file).'" />&nbsp;'.
11845:                               '<span class="LC_filename">'.$embed_file.'</span></td>'.
11846:                               '<td align="right"><span class="LC_info LC_fontsize_medium">'.&mt('Already exists').'</span></td>'.
11847:                               &Apache::loncommon::end_data_table_row()."\n";
11848:         }
11849:     }
11850:     my $delidx = $counter;
11851:     foreach my $oldfile (sort {lc($a) cmp lc($b)} keys(%unused)) {
11852:         my ($size,$mtime) = &get_dependency_details(\%currfile,\%currsubfile,$oldfile);
11853:         $delete_output .= &start_data_table_row().
11854:                           '<td><img src="'.&icon($oldfile).'" />'.
11855:                           '&nbsp;<span class="LC_filename">'.$oldfile.'</span></td>'.
11856:                           '<td>'.$size.'</td>'.
11857:                           '<td>'.$mtime.'</td>'.
11858:                           '<td><label><input type="checkbox" name="del_upload_dep" '.
11859:                           ' value="'.$delidx.'" />'.&mt('Yes').'</label>'.
11860:                           &embedded_file_element('upload_embedded',$delidx,
11861:                                                  $oldfile,\%mapping,$allfiles,
11862:                                                  $codebase,'delete').'</td>'.
11863:                           &end_data_table_row()."\n"; 
11864:         $numunused ++;
11865:         $delidx ++;
11866:     }
11867:     if ($upload_output) {
11868:         $upload_output = &start_data_table().
11869:                          $upload_output.
11870:                          &end_data_table()."\n";
11871:     }
11872:     if ($modify_output) {
11873:         $modify_output = &start_data_table().
11874:                          &start_data_table_header_row().
11875:                          '<th>'.&mt('File').'</th>'.
11876:                          '<th>'.&mt('Size (KB)').'</th>'.
11877:                          '<th>'.&mt('Modified').'</th>'.
11878:                          '<th>'.&mt('Upload replacement?').'</th>'.
11879:                          &end_data_table_header_row().
11880:                          $modify_output.
11881:                          &end_data_table()."\n";
11882:     }
11883:     if ($delete_output) {
11884:         $delete_output = &start_data_table().
11885:                          &start_data_table_header_row().
11886:                          '<th>'.&mt('File').'</th>'.
11887:                          '<th>'.&mt('Size (KB)').'</th>'.
11888:                          '<th>'.&mt('Modified').'</th>'.
11889:                          '<th>'.&mt('Delete?').'</th>'.
11890:                          &end_data_table_header_row().
11891:                          $delete_output.
11892:                          &end_data_table()."\n";
11893:     }
11894:     my $applies = 0;
11895:     if ($numremref) {
11896:         $applies ++;
11897:     }
11898:     if ($numinvalid) {
11899:         $applies ++;
11900:     }
11901:     if ($numexisting) {
11902:         $applies ++;
11903:     }
11904:     if ($counter || $numunused) {
11905:         $output = '<form name="upload_embedded" action="'.$actionurl.'"'.
11906:                   ' method="post" enctype="multipart/form-data">'."\n".
11907:                   $state.'<h3>'.$heading.'</h3>'; 
11908:         if ($actionurl eq '/adm/dependencies') {
11909:             if ($numnew) {
11910:                 $output .= '<h4>'.&mt('Missing dependencies').'</h4>'.
11911:                            '<p>'.&mt('The following files need to be uploaded.').'</p>'."\n".
11912:                            $upload_output.'<br />'."\n";
11913:             }
11914:             if ($numexisting) {
11915:                 $output .= '<h4>'.&mt('Uploaded dependencies (in use)').'</h4>'.
11916:                            '<p>'.&mt('Upload a new file to replace the one currently in use.').'</p>'."\n".
11917:                            $modify_output.'<br />'."\n";
11918:                            $buttontext = &mt('Save changes');
11919:             }
11920:             if ($numunused) {
11921:                 $output .= '<h4>'.&mt('Unused files').'</h4>'.
11922:                            '<p>'.&mt('The following uploaded files are no longer used.').'</p>'."\n".
11923:                            $delete_output.'<br />'."\n";
11924:                            $buttontext = &mt('Save changes');
11925:             }
11926:         } else {
11927:             $output .= $upload_output.'<br />'."\n";
11928:         }
11929:         $output .= '<input type ="hidden" name="number_embedded_items" value="'.
11930:                    $counter.'" />'."\n";
11931:         if ($actionurl eq '/adm/dependencies') { 
11932:             $output .= '<input type ="hidden" name="number_newemb_items" value="'.
11933:                        $numnew.'" />'."\n";
11934:         } elsif ($actionurl eq '') {
11935:             $output .=  '<input type="hidden" name="phase" value="three" />';
11936:         }
11937:     } elsif ($applies) {
11938:         $output = '<b>'.&mt('Referenced files').'</b>:<br />';
11939:         if ($applies > 1) {
11940:             $output .=  
11941:                 &mt('No dependencies need to be uploaded, as one of the following applies to each reference:').'<ul>';
11942:             if ($numremref) {
11943:                 $output .= '<li>'.&mt('reference is to a URL which points to another server').'</li>'."\n";
11944:             }
11945:             if ($numinvalid) {
11946:                 $output .= '<li>'.&mt('reference is to file with a name containing invalid characters').'</li>'."\n";
11947:             }
11948:             if ($numexisting) {
11949:                 $output .= '<li>'.&mt('reference is to an existing file at the specified location').'</li>'."\n";
11950:             }
11951:             $output .= '</ul><br />';
11952:         } elsif ($numremref) {
11953:             $output .= '<p>'.&mt('None to upload, as all references are to URLs pointing to another server.').'</p>';
11954:         } elsif ($numinvalid) {
11955:             $output .= '<p>'.&mt('None to upload, as all references are to files with names containing invalid characters.').'</p>';
11956:         } elsif ($numexisting) {
11957:             $output .= '<p>'.&mt('None to upload, as all references are to existing files.').'</p>';
11958:         }
11959:         $output .= $upload_output.'<br />';
11960:     }
11961:     my ($pathchange_output,$chgcount);
11962:     $chgcount = $counter;
11963:     if (keys(%pathchanges) > 0) {
11964:         foreach my $embed_file (sort {lc($a) cmp lc($b)} keys(%pathchanges)) {
11965:             if ($counter) {
11966:                 $output .= &embedded_file_element('pathchange',$chgcount,
11967:                                                   $embed_file,\%mapping,
11968:                                                   $allfiles,$codebase,'change');
11969:             } else {
11970:                 $pathchange_output .= 
11971:                     &start_data_table_row().
11972:                     '<td><input type ="checkbox" name="namechange" value="'.
11973:                     $chgcount.'" checked="checked" /></td>'.
11974:                     '<td>'.$mapping{$embed_file}.'</td>'.
11975:                     '<td>'.$embed_file.
11976:                     &embedded_file_element('pathchange',$numpathchg,$embed_file,
11977:                                            \%mapping,$allfiles,$codebase,'change').
11978:                     '</td>'.&end_data_table_row();
11979:             }
11980:             $numpathchg ++;
11981:             $chgcount ++;
11982:         }
11983:     }
11984:     if (($counter) || ($numunused)) {
11985:         if ($numpathchg) {
11986:             $output .= '<input type ="hidden" name="number_pathchange_items" value="'.
11987:                        $numpathchg.'" />'."\n";
11988:         }
11989:         if (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank') || 
11990:             ($actionurl eq '/adm/imsimport')) {
11991:             $output .= '<input type="hidden" name="phase" value="three" />'."\n";
11992:         } elsif ($actionurl eq '/adm/portfolio' || $actionurl eq '/adm/coursegrp_portfolio') {
11993:             $output .= '<input type="hidden" name="action" value="upload_embedded" />';
11994:         } elsif ($actionurl eq '/adm/dependencies') {
11995:             $output .= '<input type="hidden" name="action" value="process_changes" />';
11996:         }
11997:         $output .= '<input type ="submit" value="'.$buttontext.'" />'."\n".'</form>'."\n";
11998:     } elsif ($numpathchg) {
11999:         my %pathchange = ();
12000:         $output .= &modify_html_form('pathchange',$actionurl,$state,\%pathchange,$pathchange_output);
12001:         if (($actionurl eq '/adm/portfolio') || ($actionurl eq '/adm/coursegrp_portfolio')) {
12002:             $output .= '<p>'.&mt('or').'</p>'; 
12003:         }
12004:     }
12005:     return ($output,$counter,$numpathchg);
12006: }
12007: 
12008: =pod
12009: 
12010: =item * clean_path($name)
12011: 
12012: Performs clean-up of directories, subdirectories and filename in an
12013: embedded object, referenced in an HTML file which is being uploaded
12014: to a course or portfolio, where
12015: "Upload embedded images/multimedia files if HTML file" checkbox was
12016: checked.
12017: 
12018: Clean-up is similar to replacements in lonnet::clean_filename()
12019: except each / between sub-directory and next level is preserved.
12020: 
12021: =cut
12022: 
12023: sub clean_path {
12024:     my ($embed_file) = @_;
12025:     $embed_file =~s{^/+}{};
12026:     my @contents;
12027:     if ($embed_file =~ m{/}) {
12028:         @contents = split(/\//,$embed_file);
12029:     } else {
12030:         @contents = ($embed_file);
12031:     }
12032:     my $lastidx = scalar(@contents)-1;
12033:     for (my $i=0; $i<=$lastidx; $i++) {
12034:         $contents[$i]=~s{\\}{/}g;
12035:         $contents[$i]=~s/\s+/\_/g;
12036:         $contents[$i]=~s{[^/\w\.\-]}{}g;
12037:         if ($i == $lastidx) {
12038:             $contents[$i]=~s/\.(\d+)(?=\.)/_$1/g;
12039:         }
12040:     }
12041:     if ($lastidx > 0) {
12042:         return join('/',@contents);
12043:     } else {
12044:         return $contents[0];
12045:     }
12046: }
12047: 
12048: sub embedded_file_element {
12049:     my ($context,$num,$embed_file,$mapping,$allfiles,$codebase,$type) = @_;
12050:     return unless ((ref($mapping) eq 'HASH') && (ref($allfiles) eq 'HASH') &&
12051:                    (ref($codebase) eq 'HASH'));
12052:     my $output;
12053:     if (($context eq 'upload_embedded') && ($type ne 'delete')) {
12054:        $output = '<input name="embedded_item_'.$num.'" type="file" value="" />'."\n";
12055:     }
12056:     $output .= '<input name="embedded_orig_'.$num.'" type="hidden" value="'.
12057:                &escape($embed_file).'" />';
12058:     unless (($context eq 'upload_embedded') && 
12059:             ($mapping->{$embed_file} eq $embed_file)) {
12060:         $output .='
12061:         <input name="embedded_ref_'.$num.'" type="hidden" value="'.&escape($mapping->{$embed_file}).'" />';
12062:     }
12063:     my $attrib;
12064:     if (ref($allfiles->{$mapping->{$embed_file}}) eq 'ARRAY') {
12065:         $attrib = &escape(join(':',@{$allfiles->{$mapping->{$embed_file}}}));
12066:     }
12067:     $output .=
12068:         "\n\t\t".
12069:         '<input name="embedded_attrib_'.$num.'" type="hidden" value="'.
12070:         $attrib.'" />';
12071:     if (exists($codebase->{$mapping->{$embed_file}})) {
12072:         $output .=
12073:             "\n\t\t".
12074:             '<input name="codebase_'.$num.'" type="hidden" value="'.
12075:             &escape($codebase->{$mapping->{$embed_file}}).'" />';
12076:     }
12077:     return $output;
12078: }
12079: 
12080: sub get_dependency_details {
12081:     my ($currfile,$currsubfile,$embed_file) = @_;
12082:     my ($size,$mtime,$showsize,$showmtime);
12083:     if ((ref($currfile) eq 'HASH') && (ref($currsubfile))) {
12084:         if ($embed_file =~ m{/}) {
12085:             my ($path,$fname) = split(/\//,$embed_file);
12086:             if (ref($currsubfile->{$path}{$fname}) eq 'ARRAY') {
12087:                 ($size,$mtime) = @{$currsubfile->{$path}{$fname}};
12088:             }
12089:         } else {
12090:             if (ref($currfile->{$embed_file}) eq 'ARRAY') {
12091:                 ($size,$mtime) = @{$currfile->{$embed_file}};
12092:             }
12093:         }
12094:         $showsize = $size/1024.0;
12095:         $showsize = sprintf("%.1f",$showsize);
12096:         if ($mtime > 0) {
12097:             $showmtime = &Apache::lonlocal::locallocaltime($mtime);
12098:         }
12099:     }
12100:     return ($showsize,$showmtime);
12101: }
12102: 
12103: sub ask_embedded_js {
12104:     return <<"END";
12105: <script type="text/javascript"">
12106: // <![CDATA[
12107: function toggleBrowse(counter) {
12108:     var chkboxid = document.getElementById('mod_upload_dep_'+counter);
12109:     var fileid = document.getElementById('embedded_item_'+counter);
12110:     var uploaddivid = document.getElementById('moduploaddep_'+counter);
12111:     if (chkboxid.checked == true) {
12112:         uploaddivid.style.display='block';
12113:     } else {
12114:         uploaddivid.style.display='none';
12115:         fileid.value = '';
12116:     }
12117: }
12118: // ]]>
12119: </script>
12120: 
12121: END
12122: }
12123: 
12124: sub upload_embedded {
12125:     my ($context,$dirpath,$uname,$udom,$dir_root,$url_root,$group,$disk_quota,
12126:         $current_disk_usage,$hiddenstate,$actionurl) = @_;
12127:     my (%pathchange,$output,$modifyform,$footer,$returnflag);
12128:     for (my $i=0; $i<$env{'form.number_embedded_items'}; $i++) {
12129:         next if (!exists($env{'form.embedded_item_'.$i.'.filename'}));
12130:         my $orig_uploaded_filename =
12131:             $env{'form.embedded_item_'.$i.'.filename'};
12132:         foreach my $type ('orig','ref','attrib','codebase') {
12133:             if ($env{'form.embedded_'.$type.'_'.$i} ne '') {
12134:                 $env{'form.embedded_'.$type.'_'.$i} =
12135:                     &unescape($env{'form.embedded_'.$type.'_'.$i});
12136:             }
12137:         }
12138:         my ($path,$fname) =
12139:             ($env{'form.embedded_orig_'.$i} =~ m{(.*/)([^/]*)});
12140:         # no path, whole string is fname
12141:         if (!$fname) { $fname = $env{'form.embedded_orig_'.$i} };
12142:         $fname = &Apache::lonnet::clean_filename($fname);
12143:         # See if there is anything left
12144:         next if ($fname eq '');
12145: 
12146:         # Check if file already exists as a file or directory.
12147:         my ($state,$msg);
12148:         if ($context eq 'portfolio') {
12149:             my $port_path = $dirpath;
12150:             if ($group ne '') {
12151:                 $port_path = "groups/$group/$port_path";
12152:             }
12153:             ($state,$msg) = &check_for_upload($env{'form.currentpath'}.$path,
12154:                                               $fname,$group,'embedded_item_'.$i,
12155:                                               $dir_root,$port_path,$disk_quota,
12156:                                               $current_disk_usage,$uname,$udom);
12157:             if ($state eq 'will_exceed_quota'
12158:                 || $state eq 'file_locked') {
12159:                 $output .= $msg;
12160:                 next;
12161:             }
12162:         } elsif (($context eq 'author') || ($context eq 'testbank')) {
12163:             ($state,$msg) = &check_for_existing($path,$fname,'embedded_item_'.$i);
12164:             if ($state eq 'exists') {
12165:                 $output .= $msg;
12166:                 next;
12167:             }
12168:         }
12169:         # Check if extension is valid
12170:         if (($fname =~ /\.(\w+)$/) &&
12171:             (&Apache::loncommon::fileembstyle($1) eq 'hdn')) {
12172:             $output .= &mt('Invalid file extension ([_1]) - reserved for internal use.',$1)
12173:                       .' '.&mt('Rename the file with a different extension and re-upload.').'<br />';
12174:             next;
12175:         } elsif (($fname =~ /\.(\w+)$/) &&
12176:                  (!defined(&Apache::loncommon::fileembstyle($1)))) {
12177:             $output .= &mt('Unrecognized file extension ([_1]) - rename the file with a proper extension and re-upload.',$1).'<br />';
12178:             next;
12179:         } elsif ($fname=~/\.(\d+)\.(\w+)$/) {
12180:             $output .= &mt('Filename not allowed - rename the file to remove the number immediately before the file extension([_1]) and re-upload.',$2).'<br />';
12181:             next;
12182:         }
12183:         $env{'form.embedded_item_'.$i.'.filename'}=$fname;
12184:         my $subdir = $path;
12185:         $subdir =~ s{/+$}{};
12186:         if ($context eq 'portfolio') {
12187:             my $result;
12188:             if ($state eq 'existingfile') {
12189:                 $result=
12190:                     &Apache::lonnet::userfileupload('embedded_item_'.$i,'existingfile',
12191:                                                     $dirpath.$env{'form.currentpath'}.$subdir);
12192:             } else {
12193:                 $result=
12194:                     &Apache::lonnet::userfileupload('embedded_item_'.$i,'',
12195:                                                     $dirpath.
12196:                                                     $env{'form.currentpath'}.$subdir);
12197:                 if ($result !~ m|^/uploaded/|) {
12198:                     $output .= '<span class="LC_error">'
12199:                                .&mt('An error occurred ([_1]) while trying to upload [_2] for embedded element [_3].'
12200:                                ,$result,$orig_uploaded_filename,$env{'form.embedded_orig_'.$i})
12201:                                .'</span><br />';
12202:                     next;
12203:                 } else {
12204:                     $output .= &mt('Uploaded [_1]','<span class="LC_filename">'.
12205:                                $path.$fname.'</span>').'<br />';     
12206:                 }
12207:             }
12208:         } elsif (($context eq 'coursedoc') || ($context eq 'syllabus')) {
12209:             my $extendedsubdir = $dirpath.'/'.$subdir;
12210:             $extendedsubdir =~ s{/+$}{};
12211:             my $result =
12212:                 &Apache::lonnet::userfileupload('embedded_item_'.$i,$context,$extendedsubdir);
12213:             if ($result !~ m|^/uploaded/|) {
12214:                 $output .= '<span class="LC_error">'
12215:                            .&mt('An error occurred ([_1]) while trying to upload [_2] for embedded element [_3].'
12216:                            ,$result,$orig_uploaded_filename,$env{'form.embedded_orig_'.$i})
12217:                            .'</span><br />';
12218:                     next;
12219:             } else {
12220:                 $output .= &mt('Uploaded [_1]','<span class="LC_filename">'.
12221:                            $path.$fname.'</span>').'<br />';
12222:                 if ($context eq 'syllabus') {
12223:                     &Apache::lonnet::make_public_indefinitely($result);
12224:                 }
12225:             }
12226:         } else {
12227: # Save the file
12228:             my $target = $env{'form.embedded_item_'.$i};
12229:             my $fullpath = $dir_root.$dirpath.'/'.$path;
12230:             my $dest = $fullpath.$fname;
12231:             my $url = $url_root.$dirpath.'/'.$path.$fname;
12232:             my @parts=split(/\//,"$dirpath/$path");
12233:             my $count;
12234:             my $filepath = $dir_root;
12235:             foreach my $subdir (@parts) {
12236:                 $filepath .= "/$subdir";
12237:                 if (!-e $filepath) {
12238:                     mkdir($filepath,0770);
12239:                 }
12240:             }
12241:             my $fh;
12242:             if (!open($fh,'>'.$dest)) {
12243:                 &Apache::lonnet::logthis('Failed to create '.$dest);
12244:                 $output .= '<span class="LC_error">'.
12245:                            &mt('An error occurred while trying to upload [_1] for embedded element [_2].',
12246:                                $orig_uploaded_filename,$env{'form.embedded_orig_'.$i}).
12247:                            '</span><br />';
12248:             } else {
12249:                 if (!print $fh $env{'form.embedded_item_'.$i}) {
12250:                     &Apache::lonnet::logthis('Failed to write to '.$dest);
12251:                     $output .= '<span class="LC_error">'.
12252:                               &mt('An error occurred while writing the file [_1] for embedded element [_2].',
12253:                                   $orig_uploaded_filename,$env{'form.embedded_orig_'.$i}).
12254:                               '</span><br />';
12255:                 } else {
12256:                     $output .= &mt('Uploaded [_1]','<span class="LC_filename">'.
12257:                                $url.'</span>').'<br />';
12258:                     unless ($context eq 'testbank') {
12259:                         $footer .= &mt('View embedded file: [_1]',
12260:                                        '<a href="'.$url.'">'.$fname.'</a>').'<br />';
12261:                     }
12262:                 }
12263:                 close($fh);
12264:             }
12265:         }
12266:         if ($env{'form.embedded_ref_'.$i}) {
12267:             $pathchange{$i} = 1;
12268:         }
12269:     }
12270:     if ($output) {
12271:         $output = '<p>'.$output.'</p>';
12272:     }
12273:     $output .= &modify_html_form('upload_embedded',$actionurl,$hiddenstate,\%pathchange);
12274:     $returnflag = 'ok';
12275:     my $numpathchgs = scalar(keys(%pathchange));
12276:     if ($numpathchgs > 0) {
12277:         if ($context eq 'portfolio') {
12278:             $output .= '<p>'.&mt('or').'</p>';
12279:         } elsif ($context eq 'testbank') {
12280:             $output .=  '<p>'.&mt('Or [_1]continue[_2] the testbank import without modifying the reference(s).',
12281:                                   '<a href="javascript:document.testbankForm.submit();">','</a>').'</p>';
12282:             $returnflag = 'modify_orightml';
12283:         }
12284:     }
12285:     return ($output.$footer,$returnflag,$numpathchgs);
12286: }
12287: 
12288: sub modify_html_form {
12289:     my ($context,$actionurl,$hiddenstate,$pathchange,$pathchgtable) = @_;
12290:     my $end = 0;
12291:     my $modifyform;
12292:     if ($context eq 'upload_embedded') {
12293:         return unless (ref($pathchange) eq 'HASH');
12294:         if ($env{'form.number_embedded_items'}) {
12295:             $end += $env{'form.number_embedded_items'};
12296:         }
12297:         if ($env{'form.number_pathchange_items'}) {
12298:             $end += $env{'form.number_pathchange_items'};
12299:         }
12300:         if ($end) {
12301:             for (my $i=0; $i<$end; $i++) {
12302:                 if ($i < $env{'form.number_embedded_items'}) {
12303:                     next unless($pathchange->{$i});
12304:                 }
12305:                 $modifyform .=
12306:                     &start_data_table_row().
12307:                     '<td><input type ="checkbox" name="namechange" value="'.$i.'" '.
12308:                     'checked="checked" /></td>'.
12309:                     '<td>'.$env{'form.embedded_ref_'.$i}.
12310:                     '<input type="hidden" name="embedded_ref_'.$i.'" value="'.
12311:                     &escape($env{'form.embedded_ref_'.$i}).'" />'.
12312:                     '<input type="hidden" name="embedded_codebase_'.$i.'" value="'.
12313:                     &escape($env{'form.embedded_codebase_'.$i}).'" />'.
12314:                     '<input type="hidden" name="embedded_attrib_'.$i.'" value="'.
12315:                     &escape($env{'form.embedded_attrib_'.$i}).'" /></td>'.
12316:                     '<td>'.$env{'form.embedded_orig_'.$i}.
12317:                     '<input type="hidden" name="embedded_orig_'.$i.'" value="'.
12318:                     &escape($env{'form.embedded_orig_'.$i}).'" /></td>'.
12319:                     &end_data_table_row();
12320:             }
12321:         }
12322:     } else {
12323:         $modifyform = $pathchgtable;
12324:         if (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank')) {
12325:             $hiddenstate .= '<input type="hidden" name="phase" value="four" />';
12326:         } elsif (($actionurl eq '/adm/portfolio') || ($actionurl eq '/adm/coursegrp_portfolio')) {
12327:             $hiddenstate .= '<input type="hidden" name="action" value="modify_orightml" />';
12328:         }
12329:     }
12330:     if ($modifyform) {
12331:         if ($actionurl eq '/adm/dependencies') {
12332:             $hiddenstate .= '<input type="hidden" name="action" value="modifyhrefs" />';
12333:         }
12334:         return '<h3>'.&mt('Changes in content of HTML file required').'</h3>'."\n".
12335:                '<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".
12336:                '<li>'.&mt('For consistency between the reference(s) and the location of the corresponding stored file within LON-CAPA.').'</li>'."\n".
12337:                '<li>'.&mt('To change absolute paths to relative paths, or replace directory traversal via "../" within the original reference.').'</li>'."\n".
12338:                '</ol></p>'."\n".'<p>'.
12339:                &mt('LON-CAPA can make the required changes to your HTML file.').'</p>'."\n".
12340:                '<form method="post" name="refchanger" action="'.$actionurl.'">'.
12341:                &start_data_table()."\n".
12342:                &start_data_table_header_row().
12343:                '<th>'.&mt('Change?').'</th>'.
12344:                '<th>'.&mt('Current reference').'</th>'.
12345:                '<th>'.&mt('Required reference').'</th>'.
12346:                &end_data_table_header_row()."\n".
12347:                $modifyform.
12348:                &end_data_table().'<br />'."\n".$hiddenstate.
12349:                '<input type="submit" name="pathchanges" value="'.&mt('Modify HTML file').'" />'.
12350:                '</form>'."\n";
12351:     }
12352:     return;
12353: }
12354: 
12355: sub modify_html_refs {
12356:     my ($context,$dirpath,$uname,$udom,$dir_root,$url) = @_;
12357:     my $container;
12358:     if ($context eq 'portfolio') {
12359:         $container = $env{'form.container'};
12360:     } elsif ($context eq 'coursedoc') {
12361:         $container = $env{'form.primaryurl'};
12362:     } elsif ($context eq 'manage_dependencies') {
12363:         (undef,undef,$container) = &Apache::lonnet::decode_symb($env{'form.symb'});
12364:         $container = "/$container";
12365:     } elsif ($context eq 'syllabus') {
12366:         $container = $url;
12367:     } else {
12368:         $container = $Apache::lonnet::perlvar{'lonDocRoot'}.$env{'form.filename'};
12369:     }
12370:     my (%allfiles,%codebase,$output,$content);
12371:     my @changes = &get_env_multiple('form.namechange');
12372:     unless ((@changes > 0)  || ($context eq 'syllabus')) {
12373:         if (wantarray) {
12374:             return ('',0,0); 
12375:         } else {
12376:             return;
12377:         }
12378:     }
12379:     if (($context eq 'portfolio') || ($context eq 'coursedoc') || 
12380:         ($context eq 'manage_dependencies') || ($context eq 'syllabus')) {
12381:         unless ($container =~ m{^/uploaded/\Q$udom\E/\Q$uname\E/}) {
12382:             if (wantarray) {
12383:                 return ('',0,0);
12384:             } else {
12385:                 return;
12386:             }
12387:         } 
12388:         $content = &Apache::lonnet::getfile($container);
12389:         if ($content eq '-1') {
12390:             if (wantarray) {
12391:                 return ('',0,0);
12392:             } else {
12393:                 return;
12394:             }
12395:         }
12396:     } else {
12397:         unless ($container =~ /^\Q$dir_root\E/) {
12398:             if (wantarray) {
12399:                 return ('',0,0);
12400:             } else {
12401:                 return;
12402:             }
12403:         } 
12404:         if (open(my $fh,'<',$container)) {
12405:             $content = join('', <$fh>);
12406:             close($fh);
12407:         } else {
12408:             if (wantarray) {
12409:                 return ('',0,0);
12410:             } else {
12411:                 return;
12412:             }
12413:         }
12414:     }
12415:     my ($count,$codebasecount) = (0,0);
12416:     my $mm = new File::MMagic;
12417:     my $mime_type = $mm->checktype_contents($content);
12418:     if ($mime_type eq 'text/html') {
12419:         my $parse_result = 
12420:             &Apache::lonnet::extract_embedded_items($container,\%allfiles,
12421:                                                     \%codebase,\$content);
12422:         if ($parse_result eq 'ok') {
12423:             foreach my $i (@changes) {
12424:                 my $orig = &unescape($env{'form.embedded_orig_'.$i});
12425:                 my $ref = &unescape($env{'form.embedded_ref_'.$i});
12426:                 if ($allfiles{$ref}) {
12427:                     my $newname =  $orig;
12428:                     my ($attrib_regexp,$codebase);
12429:                     $attrib_regexp = &unescape($env{'form.embedded_attrib_'.$i});
12430:                     if ($attrib_regexp =~ /:/) {
12431:                         $attrib_regexp =~ s/\:/|/g;
12432:                     }
12433:                     if ($content =~ m{($attrib_regexp\s*=\s*['"]?)\Q$ref\E(['"]?)}) {
12434:                         my $numchg = ($content =~ s{($attrib_regexp\s*=\s*['"]?)\Q$ref\E(['"]?)}{$1$newname$2}gi);
12435:                         $count += $numchg;
12436:                         $allfiles{$newname} = $allfiles{$ref};
12437:                         delete($allfiles{$ref});
12438:                     }
12439:                     if ($env{'form.embedded_codebase_'.$i} ne '') {
12440:                         $codebase = &unescape($env{'form.embedded_codebase_'.$i});
12441:                         my $numchg = ($content =~ s/(codebase\s*=\s*["']?)\Q$codebase\E(["']?)/$1.$2/i); #' stupid emacs
12442:                         $codebasecount ++;
12443:                     }
12444:                 }
12445:             }
12446:             my $skiprewrites;
12447:             if ($count || $codebasecount) {
12448:                 my $saveresult;
12449:                 if (($context eq 'portfolio') || ($context eq 'coursedoc') || 
12450:                     ($context eq 'manage_dependencies') || ($context eq 'syllabus')) {
12451:                     my $url = &Apache::lonnet::store_edited_file($container,$content,$udom,$uname,\$saveresult);
12452:                     if ($url eq $container) {
12453:                         my ($fname) = ($container =~ m{/([^/]+)$});
12454:                         $output = '<p>'.&mt('Updated [quant,_1,reference] in [_2].',
12455:                                             $count,'<span class="LC_filename">'.
12456:                                             $fname.'</span>').'</p>';
12457:                     } else {
12458:                          $output = '<p class="LC_error">'.
12459:                                    &mt('Error: update failed for: [_1].',
12460:                                    '<span class="LC_filename">'.
12461:                                    $container.'</span>').'</p>';
12462:                     }
12463:                     if ($context eq 'syllabus') {
12464:                         unless ($saveresult eq 'ok') {
12465:                             $skiprewrites = 1;
12466:                         }
12467:                     }
12468:                 } else {
12469:                     if (open(my $fh,'>',$container)) {
12470:                         print $fh $content;
12471:                         close($fh);
12472:                         $output = '<p>'.&mt('Updated [quant,_1,reference] in [_2].',
12473:                                   $count,'<span class="LC_filename">'.
12474:                                   $container.'</span>').'</p>';
12475:                     } else {
12476:                          $output = '<p class="LC_error">'.
12477:                                    &mt('Error: could not update [_1].',
12478:                                    '<span class="LC_filename">'.
12479:                                    $container.'</span>').'</p>';
12480:                     }
12481:                 }
12482:             }
12483:             if (($context eq 'syllabus') && (!$skiprewrites)) {
12484:                 my ($actionurl,$state);
12485:                 $actionurl = "/public/$udom/$uname/syllabus";
12486:                 my ($ignore,$num,$numpathchanges,$existing,$mapping) =
12487:                     &ask_for_embedded_content($actionurl,$state,\%allfiles,
12488:                                               \%codebase,
12489:                                               {'context' => 'rewrites',
12490:                                                'ignore_remote_references' => 1,});
12491:                 if (ref($mapping) eq 'HASH') {
12492:                     my $rewrites = 0;
12493:                     foreach my $key (keys(%{$mapping})) {
12494:                         next if ($key =~ m{^https?://});
12495:                         my $ref = $mapping->{$key};
12496:                         my $newname = "/uploaded/$udom/$uname/portfolio/syllabus/$key";
12497:                         my $attrib;
12498:                         if (ref($allfiles{$mapping->{$key}}) eq 'ARRAY') {
12499:                             $attrib = join('|',@{$allfiles{$mapping->{$key}}});
12500:                         }
12501:                         if ($content =~ m{($attrib\s*=\s*['"]?)\Q$ref\E(['"]?)}) {
12502:                             my $numchg = ($content =~ s{($attrib\s*=\s*['"]?)\Q$ref\E(['"]?)}{$1$newname$2}gi);
12503:                             $rewrites += $numchg;
12504:                         }
12505:                     }
12506:                     if ($rewrites) {
12507:                         my $saveresult;
12508:                         my $url = &Apache::lonnet::store_edited_file($container,$content,$udom,$uname,\$saveresult);
12509:                         if ($url eq $container) {
12510:                             my ($fname) = ($container =~ m{/([^/]+)$});
12511:                             $output .= '<p>'.&mt('Rewrote [quant,_1,link] as [quant,_1,absolute link] in [_2].',
12512:                                             $count,'<span class="LC_filename">'.
12513:                                             $fname.'</span>').'</p>';
12514:                         } else {
12515:                             $output .= '<p class="LC_error">'.
12516:                                        &mt('Error: could not update links in [_1].',
12517:                                        '<span class="LC_filename">'.
12518:                                        $container.'</span>').'</p>';
12519: 
12520:                         }
12521:                     }
12522:                 }
12523:             }
12524:         } else {
12525:             &logthis('Failed to parse '.$container.
12526:                      ' to modify references: '.$parse_result);
12527:         }
12528:     }
12529:     if (wantarray) {
12530:         return ($output,$count,$codebasecount);
12531:     } else {
12532:         return $output;
12533:     }
12534: }
12535: 
12536: sub check_for_existing {
12537:     my ($path,$fname,$element) = @_;
12538:     my ($state,$msg);
12539:     if (-d $path.'/'.$fname) {
12540:         $state = 'exists';
12541:         $msg = &mt('Unable to upload [_1]. A directory by that name was found in [_2].','<span class="LC_filename">'.$fname.'</span>',$path);
12542:     } elsif (-e $path.'/'.$fname) {
12543:         $state = 'exists';
12544:         $msg = &mt('Unable to upload [_1]. A file by that name was found in [_2].','<span class="LC_filename">'.$fname.'</span>',$path);
12545:     }
12546:     if ($state eq 'exists') {
12547:         $msg = '<span class="LC_error">'.$msg.'</span><br />';
12548:     }
12549:     return ($state,$msg);
12550: }
12551: 
12552: sub check_for_upload {
12553:     my ($path,$fname,$group,$element,$portfolio_root,$port_path,
12554:         $disk_quota,$current_disk_usage,$uname,$udom) = @_;
12555:     my $filesize = length($env{'form.'.$element});
12556:     if (!$filesize) {
12557:         my $msg = '<span class="LC_error">'.
12558:                   &mt('Unable to upload [_1]. (size = [_2] bytes)', 
12559:                       '<span class="LC_filename">'.$fname.'</span>',
12560:                       $filesize).'<br />'.
12561:                   &mt('Either the file you attempted to upload was empty, or your web browser was unable to read its contents.').'<br />'.
12562:                   '</span>';
12563:         return ('zero_bytes',$msg);
12564:     }
12565:     $filesize =  $filesize/1000; #express in k (1024?)
12566:     my $getpropath = 1;
12567:     my ($dirlistref,$listerror) =
12568:          &Apache::lonnet::dirlist($portfolio_root.$path,$udom,$uname,$getpropath);
12569:     my $found_file = 0;
12570:     my $locked_file = 0;
12571:     my @lockers;
12572:     my $navmap;
12573:     if ($env{'request.course.id'}) {
12574:         $navmap = Apache::lonnavmaps::navmap->new();
12575:     }
12576:     if (ref($dirlistref) eq 'ARRAY') {
12577:         foreach my $line (@{$dirlistref}) {
12578:             my ($file_name,$rest)=split(/\&/,$line,2);
12579:             if ($file_name eq $fname){
12580:                 $file_name = $path.$file_name;
12581:                 if ($group ne '') {
12582:                     $file_name = $group.$file_name;
12583:                 }
12584:                 $found_file = 1;
12585:                 if (&Apache::lonnet::is_locked($file_name,$udom,$uname,\@lockers) eq 'true') {
12586:                     foreach my $lock (@lockers) {
12587:                         if (ref($lock) eq 'ARRAY') {
12588:                             my ($symb,$crsid) = @{$lock};
12589:                             if ($crsid eq $env{'request.course.id'}) {
12590:                                 if (ref($navmap)) {
12591:                                     my $res = $navmap->getBySymb($symb);
12592:                                     foreach my $part (@{$res->parts()}) { 
12593:                                         my ($slot_status,$slot_time,$slot_name)=$res->check_for_slot($part);
12594:                                         unless (($slot_status == $res->RESERVED) ||
12595:                                                 ($slot_status == $res->RESERVED_LOCATION)) {
12596:                                             $locked_file = 1;
12597:                                         }
12598:                                     }
12599:                                 } else {
12600:                                     $locked_file = 1;
12601:                                 }
12602:                             } else {
12603:                                 $locked_file = 1;
12604:                             }
12605:                         }
12606:                    }
12607:                 } else {
12608:                     my @info = split(/\&/,$rest);
12609:                     my $currsize = $info[6]/1000;
12610:                     if ($currsize < $filesize) {
12611:                         my $extra = $filesize - $currsize;
12612:                         if (($current_disk_usage + $extra) > $disk_quota) {
12613:                             my $msg = '<p class="LC_warning">'.
12614:                                       &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.',
12615:                                           '<span class="LC_filename">'.$fname.'</span>',$filesize,$currsize).'</p>'.
12616:                                       '<p>'.&mt('Disk quota is [_1] kilobytes. Your current disk usage is [_2] kilobytes.',
12617:                                                    $disk_quota,$current_disk_usage).'</p>';
12618:                             return ('will_exceed_quota',$msg);
12619:                         }
12620:                     }
12621:                 }
12622:             }
12623:         }
12624:     }
12625:     if (($current_disk_usage + $filesize) > $disk_quota){
12626:         my $msg = '<p class="LC_warning">'.
12627:                 &mt('Unable to upload [_1]. (size = [_2] kilobytes). Disk quota will be exceeded.','<span class="LC_filename">'.$fname.'</span>',$filesize).'</p>'.
12628:                   '<p>'.&mt('Disk quota is [_1] kilobytes. Your current disk usage is [_2] kilobytes.',$disk_quota,$current_disk_usage).'</p>';
12629:         return ('will_exceed_quota',$msg);
12630:     } elsif ($found_file) {
12631:         if ($locked_file) {
12632:             my $msg = '<p class="LC_warning">';
12633:             $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>');
12634:             $msg .= '</p>';
12635:             $msg .= &mt('You will be able to rename or delete existing [_1] after a grade has been assigned.','<span class="LC_filename">'.$fname.'</span>');
12636:             return ('file_locked',$msg);
12637:         } else {
12638:             my $msg = '<p class="LC_error">';
12639:             $msg .= &mt(' A file by that name: [_1] was found in [_2].','<span class="LC_filename">'.$fname.'</span>',$port_path.$env{'form.currentpath'});
12640:             $msg .= '</p>';
12641:             return ('existingfile',$msg);
12642:         }
12643:     }
12644: }
12645: 
12646: sub check_for_traversal {
12647:     my ($path,$url,$toplevel) = @_;
12648:     my @parts=split(/\//,$path);
12649:     my $cleanpath;
12650:     my $fullpath = $url;
12651:     for (my $i=0;$i<@parts;$i++) {
12652:         next if ($parts[$i] eq '.');
12653:         if ($parts[$i] eq '..') {
12654:             $fullpath =~ s{([^/]+/)$}{};
12655:         } else {
12656:             $fullpath .= $parts[$i].'/';
12657:         }
12658:     }
12659:     if ($fullpath =~ /^\Q$url\E(.*)$/) {
12660:         $cleanpath = $1;
12661:     } elsif ($fullpath =~ /^\Q$toplevel\E(.*)$/) {
12662:         my $curr_toprel = $1;
12663:         my @parts = split(/\//,$curr_toprel);
12664:         my ($url_toprel) = ($url =~ /^\Q$toplevel\E(.*)$/);
12665:         my @urlparts = split(/\//,$url_toprel);
12666:         my $doubledots;
12667:         my $startdiff = -1;
12668:         for (my $i=0; $i<@urlparts; $i++) {
12669:             if ($startdiff == -1) {
12670:                 unless ($urlparts[$i] eq $parts[$i]) {
12671:                     $startdiff = $i;
12672:                     $doubledots .= '../';
12673:                 }
12674:             } else {
12675:                 $doubledots .= '../';
12676:             }
12677:         }
12678:         if ($startdiff > -1) {
12679:             $cleanpath = $doubledots;
12680:             for (my $i=$startdiff; $i<@parts; $i++) {
12681:                 $cleanpath .= $parts[$i].'/';
12682:             }
12683:         }
12684:     }
12685:     $cleanpath =~ s{(/)$}{};
12686:     return $cleanpath;
12687: }
12688: 
12689: sub is_archive_file {
12690:     my ($mimetype) = @_;
12691:     if (($mimetype eq 'application/octet-stream') ||
12692:         ($mimetype eq 'application/x-stuffit') ||
12693:         ($mimetype =~ m{^application/(x\-)?(compressed|tar|zip|tgz|gz|gtar|gzip|gunzip|bz|bz2|bzip2)})) {
12694:         return 1;
12695:     }
12696:     return;
12697: }
12698: 
12699: sub decompress_form {
12700:     my ($mimetype,$archiveurl,$action,$noextract,$hiddenelements,$dirlist) = @_;
12701:     my %lt = &Apache::lonlocal::texthash (
12702:         this => 'This file is an archive file.',
12703:         camt => 'This file is a Camtasia archive file.',
12704:         itsc => 'Its contents are as follows:',
12705:         youm => 'You may wish to extract its contents.',
12706:         extr => 'Extract contents',
12707:         auto => 'LON-CAPA can process the files automatically, or you can decide how each should be handled.',
12708:         proa => 'Process automatically?',
12709:         yes  => 'Yes',
12710:         no   => 'No',
12711:         fold => 'Title for folder containing movie',
12712:         movi => 'Title for page containing embedded movie', 
12713:     );
12714:     my $fileloc = &Apache::lonnet::filelocation(undef,$archiveurl);
12715:     my ($is_camtasia,$topdir,%toplevel,@paths);
12716:     my $info = &list_archive_contents($fileloc,\@paths);
12717:     if (@paths) {
12718:         foreach my $path (@paths) {
12719:             $path =~ s{^/}{};
12720:             if ($path =~ m{^([^/]+)/$}) {
12721:                 $topdir = $1;
12722:             }
12723:             if ($path =~ m{^([^/]+)/}) {
12724:                 $toplevel{$1} = $path;
12725:             } else {
12726:                 $toplevel{$path} = $path;
12727:             }
12728:         }
12729:     }
12730:     if ($mimetype =~ m{^application/(x\-)?(compressed|zip)}) {
12731:         my @camtasia6 = ("$topdir/","$topdir/index.html",
12732:                         "$topdir/media/",
12733:                         "$topdir/media/$topdir.mp4",
12734:                         "$topdir/media/FirstFrame.png",
12735:                         "$topdir/media/player.swf",
12736:                         "$topdir/media/swfobject.js",
12737:                         "$topdir/media/expressInstall.swf");
12738:         my @camtasia8_1 = ("$topdir/","$topdir/$topdir.html",
12739:                          "$topdir/$topdir.mp4",
12740:                          "$topdir/$topdir\_config.xml",
12741:                          "$topdir/$topdir\_controller.swf",
12742:                          "$topdir/$topdir\_embed.css",
12743:                          "$topdir/$topdir\_First_Frame.png",
12744:                          "$topdir/$topdir\_player.html",
12745:                          "$topdir/$topdir\_Thumbnails.png",
12746:                          "$topdir/playerProductInstall.swf",
12747:                          "$topdir/scripts/",
12748:                          "$topdir/scripts/config_xml.js",
12749:                          "$topdir/scripts/handlebars.js",
12750:                          "$topdir/scripts/jquery-1.7.1.min.js",
12751:                          "$topdir/scripts/jquery-ui-1.8.15.custom.min.js",
12752:                          "$topdir/scripts/modernizr.js",
12753:                          "$topdir/scripts/player-min.js",
12754:                          "$topdir/scripts/swfobject.js",
12755:                          "$topdir/skins/",
12756:                          "$topdir/skins/configuration_express.xml",
12757:                          "$topdir/skins/express_show/",
12758:                          "$topdir/skins/express_show/player-min.css",
12759:                          "$topdir/skins/express_show/spritesheet.png");
12760:         my @camtasia8_4 = ("$topdir/","$topdir/$topdir.html",
12761:                          "$topdir/$topdir.mp4",
12762:                          "$topdir/$topdir\_config.xml",
12763:                          "$topdir/$topdir\_controller.swf",
12764:                          "$topdir/$topdir\_embed.css",
12765:                          "$topdir/$topdir\_First_Frame.png",
12766:                          "$topdir/$topdir\_player.html",
12767:                          "$topdir/$topdir\_Thumbnails.png",
12768:                          "$topdir/playerProductInstall.swf",
12769:                          "$topdir/scripts/",
12770:                          "$topdir/scripts/config_xml.js",
12771:                          "$topdir/scripts/techsmith-smart-player.min.js",
12772:                          "$topdir/skins/",
12773:                          "$topdir/skins/configuration_express.xml",
12774:                          "$topdir/skins/express_show/",
12775:                          "$topdir/skins/express_show/spritesheet.min.css",
12776:                          "$topdir/skins/express_show/spritesheet.png",
12777:                          "$topdir/skins/express_show/techsmith-smart-player.min.css");
12778:         my @diffs = &compare_arrays(\@paths,\@camtasia6);
12779:         if (@diffs == 0) {
12780:             $is_camtasia = 6;
12781:         } else {
12782:             @diffs = &compare_arrays(\@paths,\@camtasia8_1);
12783:             if (@diffs == 0) {
12784:                 $is_camtasia = 8;
12785:             } else {
12786:                 @diffs = &compare_arrays(\@paths,\@camtasia8_4);
12787:                 if (@diffs == 0) {
12788:                     $is_camtasia = 8;
12789:                 }
12790:             }
12791:         }
12792:     }
12793:     my $output;
12794:     if ($is_camtasia) {
12795:         $output = <<"ENDCAM";
12796: <script type="text/javascript" language="Javascript">
12797: // <![CDATA[
12798: 
12799: function camtasiaToggle() {
12800:     for (var i=0; i<document.uploaded_decompress.autoextract_camtasia.length; i++) {
12801:         if (document.uploaded_decompress.autoextract_camtasia[i].checked) {
12802:             if (document.uploaded_decompress.autoextract_camtasia[i].value == $is_camtasia) {
12803:                 document.getElementById('camtasia_titles').style.display='block';
12804:             } else {
12805:                 document.getElementById('camtasia_titles').style.display='none';
12806:             }
12807:         }
12808:     }
12809:     return;
12810: }
12811: 
12812: // ]]>
12813: </script>
12814: <p>$lt{'camt'}</p>
12815: ENDCAM
12816:     } else {
12817:         $output = '<p>'.$lt{'this'};
12818:         if ($info eq '') {
12819:             $output .= ' '.$lt{'youm'}.'</p>'."\n";
12820:         } else {
12821:             $output .= ' '.$lt{'itsc'}.'</p>'."\n".
12822:                        '<div><pre>'.$info.'</pre></div>';
12823:         }
12824:     }
12825:     $output .= '<form name="uploaded_decompress" action="'.$action.'" method="post">'."\n";
12826:     my $duplicates;
12827:     my $num = 0;
12828:     if (ref($dirlist) eq 'ARRAY') {
12829:         foreach my $item (@{$dirlist}) {
12830:             if (ref($item) eq 'ARRAY') {
12831:                 if (exists($toplevel{$item->[0]})) {
12832:                     $duplicates .= 
12833:                         &start_data_table_row().
12834:                         '<td><label><input type="radio" name="archive_overwrite_'.$num.'" '.
12835:                         'value="0" checked="checked" />'.&mt('No').'</label>'.
12836:                         '&nbsp;<label><input type="radio" name="archive_overwrite_'.$num.'" '.
12837:                         'value="1" />'.&mt('Yes').'</label>'.
12838:                         '<input type="hidden" name="archive_overwrite_name_'.$num.'" value="'.$item->[0].'" /></td>'."\n".
12839:                         '<td>'.$item->[0].'</td>';
12840:                     if ($item->[2]) {
12841:                         $duplicates .= '<td>'.&mt('Directory').'</td>';
12842:                     } else {
12843:                         $duplicates .= '<td>'.&mt('File').'</td>';
12844:                     }
12845:                     $duplicates .= '<td>'.$item->[3].'</td>'.
12846:                                    '<td>'.
12847:                                    &Apache::lonlocal::locallocaltime($item->[4]).
12848:                                    '</td>'.
12849:                                    &end_data_table_row();
12850:                     $num ++;
12851:                 }
12852:             }
12853:         }
12854:     }
12855:     my $itemcount;
12856:     if (@paths > 0) {
12857:         $itemcount = scalar(@paths);
12858:     } else {
12859:         $itemcount = 1;
12860:     }
12861:     if ($is_camtasia) {
12862:         $output .= $lt{'auto'}.'<br />'.
12863:                    '<span class="LC_nobreak">'.$lt{'proa'}.'<label>'.
12864:                    '<input type="radio" name="autoextract_camtasia" value="'.$is_camtasia.'" onclick="javascript:camtasiaToggle();" checked="checked" />'.
12865:                    $lt{'yes'}.'</label>&nbsp;<label>'.
12866:                    '<input type="radio" name="autoextract_camtasia" value="0" onclick="javascript:camtasiaToggle();" />'.
12867:                    $lt{'no'}.'</label></span><br />'.
12868:                    '<div id="camtasia_titles" style="display:block">'.
12869:                    &Apache::lonhtmlcommon::start_pick_box().
12870:                    &Apache::lonhtmlcommon::row_title($lt{'fold'}).
12871:                    '<input type="textbox" name="camtasia_foldername" value="'.$env{'form.comment'}.'" />'."\n".
12872:                    &Apache::lonhtmlcommon::row_closure().
12873:                    &Apache::lonhtmlcommon::row_title($lt{'movi'}).
12874:                    '<input type="textbox" name="camtasia_moviename" value="" />'."\n".
12875:                    &Apache::lonhtmlcommon::row_closure(1).
12876:                    &Apache::lonhtmlcommon::end_pick_box().
12877:                    '</div>';
12878:     }
12879:     $output .= 
12880:         '<input type="hidden" name="archive_overwrite_total" value="'.$num.'" />'.
12881:         '<input type="hidden" name="archive_itemcount" value="'.$itemcount.'" />'.
12882:         "\n";
12883:     if ($duplicates ne '') {
12884:         $output .= '<p><span class="LC_warning">'.
12885:                    &mt('Warning: decompression of the archive will overwrite the following items which already exist:').'</span><br />'.  
12886:                    &start_data_table().
12887:                    &start_data_table_header_row().
12888:                    '<th>'.&mt('Overwrite?').'</th>'.
12889:                    '<th>'.&mt('Name').'</th>'.
12890:                    '<th>'.&mt('Type').'</th>'.
12891:                    '<th>'.&mt('Size').'</th>'.
12892:                    '<th>'.&mt('Last modified').'</th>'.
12893:                    &end_data_table_header_row().
12894:                    $duplicates.
12895:                    &end_data_table().
12896:                    '</p>';
12897:     }
12898:     $output .= '<input type="hidden" name="archiveurl" value="'.$archiveurl.'" />'."\n";
12899:     if (ref($hiddenelements) eq 'HASH') {
12900:         foreach my $hidden (sort(keys(%{$hiddenelements}))) {
12901:             $output .= '<input type="hidden" name="'.$hidden.'" value="'.$hiddenelements->{$hidden}.'" />'."\n";
12902:         }
12903:     }
12904:     $output .= <<"END";
12905: <br />
12906: <input type="submit" name="decompress" value="$lt{'extr'}" />
12907: </form>
12908: $noextract
12909: END
12910:     return $output;
12911: }
12912: 
12913: sub decompression_utility {
12914:     my ($program) = @_;
12915:     my @utilities = ('tar','gunzip','bunzip2','unzip'); 
12916:     my $location;
12917:     if (grep(/^\Q$program\E$/,@utilities)) { 
12918:         foreach my $dir ('/bin/','/usr/bin/','/usr/local/bin/','/sbin/',
12919:                          '/usr/sbin/') {
12920:             if (-x $dir.$program) {
12921:                 $location = $dir.$program;
12922:                 last;
12923:             }
12924:         }
12925:     }
12926:     return $location;
12927: }
12928: 
12929: sub list_archive_contents {
12930:     my ($file,$pathsref) = @_;
12931:     my (@cmd,$output);
12932:     my $needsregexp;
12933:     if ($file =~ /\.zip$/) {
12934:         @cmd = (&decompression_utility('unzip'),"-l");
12935:         $needsregexp = 1;
12936:     } elsif (($file =~ m/\.tar\.gz$/) ||
12937:              ($file =~ /\.tgz$/)) {
12938:         @cmd = (&decompression_utility('tar'),"-ztf");
12939:     } elsif ($file =~ /\.tar\.bz2$/) {
12940:         @cmd = (&decompression_utility('tar'),"-jtf");
12941:     } elsif ($file =~ m|\.tar$|) {
12942:         @cmd = (&decompression_utility('tar'),"-tf");
12943:     }
12944:     if (@cmd) {
12945:         undef($!);
12946:         undef($@);
12947:         if (open(my $fh,"-|", @cmd, $file)) {
12948:             while (my $line = <$fh>) {
12949:                 $output .= $line;
12950:                 chomp($line);
12951:                 my $item;
12952:                 if ($needsregexp) {
12953:                     ($item) = ($line =~ /^\s*\d+\s+[\d\-]+\s+[\d:]+\s*(.+)$/); 
12954:                 } else {
12955:                     $item = $line;
12956:                 }
12957:                 if ($item ne '') {
12958:                     unless (grep(/^\Q$item\E$/,@{$pathsref})) {
12959:                         push(@{$pathsref},$item);
12960:                     } 
12961:                 }
12962:             }
12963:             close($fh);
12964:         }
12965:     }
12966:     return $output;
12967: }
12968: 
12969: sub decompress_uploaded_file {
12970:     my ($file,$dir) = @_;
12971:     &Apache::lonnet::appenv({'cgi.file' => $file});
12972:     &Apache::lonnet::appenv({'cgi.dir' => $dir});
12973:     my $result = &Apache::lonnet::ssi_body('/cgi-bin/decompress.pl');
12974:     my ($handle) = ($env{'user.environment'} =~m{/([^/]+)\.id$});
12975:     my $lonidsdir = $Apache::lonnet::perlvar{'lonIDsDir'};
12976:     &Apache::lonnet::transfer_profile_to_env($lonidsdir,$handle,1);
12977:     my $decompressed = $env{'cgi.decompressed'};
12978:     &Apache::lonnet::delenv('cgi.file');
12979:     &Apache::lonnet::delenv('cgi.dir');
12980:     &Apache::lonnet::delenv('cgi.decompressed');
12981:     return ($decompressed,$result);
12982: }
12983: 
12984: sub process_decompression {
12985:     my ($docudom,$docuname,$file,$destination,$dir_root,$hiddenelem) = @_;
12986:     unless (($dir_root eq '/userfiles') && ($destination =~ m{^(docs|supplemental)/(default|\d+)/\d+$})) {
12987:         return '<p class="LC_error">'.&mt('Not extracted.').'<br />'.
12988:                &mt('Unexpected file path.').'</p>'."\n";
12989:     }
12990:     unless (($docudom =~ /^$match_domain$/) && ($docuname =~ /^$match_courseid$/)) {
12991:         return '<p class="LC_error">'.&mt('Not extracted.').'<br />'.
12992:                &mt('Unexpected course context.').'</p>'."\n";
12993:     }
12994:     unless ($file eq &Apache::lonnet::clean_filename($file)) {
12995:         return '<p class="LC_error">'.&mt('Not extracted.').'<br />'.
12996:                &mt('Filename contained unexpected characters.').'</p>'."\n";
12997:     }
12998:     my ($dir,$error,$warning,$output);
12999:     if ($file !~ /\.(zip|tar|bz2|gz|tar.gz|tar.bz2|tgz)$/i) {
13000:         $error = &mt('Filename not a supported archive file type.').
13001:                  '<br />'.&mt('Filename should end with one of: [_1].',
13002:                               '.zip, .tar, .bz2, .gz, .tar.gz, .tar.bz2, .tgz');
13003:     } else {
13004:         my $docuhome = &Apache::lonnet::homeserver($docuname,$docudom);
13005:         if ($docuhome eq 'no_host') {
13006:             $error = &mt('Could not determine home server for course.');
13007:         } else {
13008:             my @ids=&Apache::lonnet::current_machine_ids();
13009:             my $currdir = "$dir_root/$destination";
13010:             if (grep(/^\Q$docuhome\E$/,@ids)) {
13011:                 $dir = &LONCAPA::propath($docudom,$docuname).
13012:                        "$dir_root/$destination";
13013:             } else {
13014:                 $dir = $Apache::lonnet::perlvar{'lonDocRoot'}.
13015:                        "$dir_root/$docudom/$docuname/$destination";
13016:                 unless (&Apache::lonnet::repcopy_userfile("$dir/$file") eq 'ok') {
13017:                     $error = &mt('Archive file not found.');
13018:                 }
13019:             }
13020:             my (@to_overwrite,@to_skip);
13021:             if ($env{'form.archive_overwrite_total'} > 0) {
13022:                 my $total = $env{'form.archive_overwrite_total'};
13023:                 for (my $i=0; $i<$total; $i++) {
13024:                     if ($env{'form.archive_overwrite_'.$i} == 1) {
13025:                         push(@to_overwrite,$env{'form.archive_overwrite_name_'.$i});
13026:                     } elsif ($env{'form.archive_overwrite_'.$i} == 0) {
13027:                         push(@to_skip,$env{'form.archive_overwrite_name_'.$i});
13028:                     }
13029:                 }
13030:             }
13031:             my $numskip = scalar(@to_skip);
13032:             my $numoverwrite = scalar(@to_overwrite);
13033:             if (($numskip) && (!$numoverwrite)) {
13034:                 $warning = &mt('All items in the archive file already exist, and no overwriting of existing files has been requested.');         
13035:             } elsif ($dir eq '') {
13036:                 $error = &mt('Directory containing archive file unavailable.');
13037:             } elsif (!$error) {
13038:                 my ($decompressed,$display);
13039:                 if (($numskip) || ($numoverwrite)) {
13040:                     my $tempdir = time.'_'.$$.int(rand(10000));
13041:                     mkdir("$dir/$tempdir",0755);
13042:                     if (&File::Copy::move("$dir/$file","$dir/$tempdir/$file")) {
13043:                         ($decompressed,$display) =
13044:                             &decompress_uploaded_file($file,"$dir/$tempdir");
13045:                         foreach my $item (@to_skip) {
13046:                             if (($item ne '') && ($item !~ /\.\./)) {
13047:                                 if (-f "$dir/$tempdir/$item") {
13048:                                     unlink("$dir/$tempdir/$item");
13049:                                 } elsif (-d "$dir/$tempdir/$item") {
13050:                                     &File::Path::remove_tree("$dir/$tempdir/$item",{ safe => 1 });
13051:                                 }
13052:                             }
13053:                         }
13054:                         foreach my $item (@to_overwrite) {
13055:                             if ((-e "$dir/$tempdir/$item") && (-e "$dir/$item")) {
13056:                                 if (($item ne '') && ($item !~ /\.\./)) {
13057:                                     if (-f "$dir/$item") {
13058:                                         unlink("$dir/$item");
13059:                                     } elsif (-d "$dir/$item") {
13060:                                         &File::Path::remove_tree("$dir/$item",{ safe => 1 });
13061:                                     }
13062:                                     &File::Copy::move("$dir/$tempdir/$item","$dir/$item");
13063:                                 }
13064:                             }
13065:                         }
13066:                         if (&File::Copy::move("$dir/$tempdir/$file","$dir/$file")) {
13067:                             &File::Path::remove_tree("$dir/$tempdir",{ safe => 1 });
13068:                         }
13069:                     }
13070:                 } else {
13071:                     ($decompressed,$display) = 
13072:                         &decompress_uploaded_file($file,$dir);
13073:                 }
13074:                 if ($decompressed eq 'ok') {
13075:                     $output = '<p class="LC_info">'.
13076:                               &mt('Files extracted successfully from archive.').
13077:                               '</p>'."\n";
13078:                     my ($warning,$result,@contents);
13079:                     my ($newdirlistref,$newlisterror) =
13080:                         &Apache::lonnet::dirlist($currdir,$docudom,
13081:                                                  $docuname,1);
13082:                     my (%is_dir,%changes,@newitems);
13083:                     my $dirptr = 16384;
13084:                     if (ref($newdirlistref) eq 'ARRAY') {
13085:                         foreach my $dir_line (@{$newdirlistref}) {
13086:                             my ($item,undef,undef,$testdir)=split(/\&/,$dir_line,5);
13087:                             unless (($item =~ /^\.+$/) || ($item eq $file)) { 
13088:                                 push(@newitems,$item);
13089:                                 if ($dirptr&$testdir) {
13090:                                     $is_dir{$item} = 1;
13091:                                 }
13092:                                 $changes{$item} = 1;
13093:                             }
13094:                         }
13095:                     }
13096:                     if (keys(%changes) > 0) {
13097:                         foreach my $item (sort(@newitems)) {
13098:                             if ($changes{$item}) {
13099:                                 push(@contents,$item);
13100:                             }
13101:                         }
13102:                     }
13103:                     if (@contents > 0) {
13104:                         my $wantform;
13105:                         unless ($env{'form.autoextract_camtasia'}) {
13106:                             $wantform = 1;
13107:                         }
13108:                         my (%children,%parent,%dirorder,%titles);
13109:                         my ($count,$datatable) = &get_extracted($docudom,$docuname,
13110:                                                                 $currdir,\%is_dir,
13111:                                                                 \%children,\%parent,
13112:                                                                 \@contents,\%dirorder,
13113:                                                                 \%titles,$wantform);
13114:                         if ($datatable ne '') {
13115:                             $output .= &archive_options_form('decompressed',$datatable,
13116:                                                              $count,$hiddenelem);
13117:                             my $startcount = 6;
13118:                             $output .= &archive_javascript($startcount,$count,
13119:                                                            \%titles,\%children);
13120:                         }
13121:                         if ($env{'form.autoextract_camtasia'}) {
13122:                             my $version = $env{'form.autoextract_camtasia'};
13123:                             my %displayed;
13124:                             my $total = 1;
13125:                             $env{'form.archive_directory'} = [];
13126:                             foreach my $i (sort { $a <=> $b } keys(%dirorder)) {
13127:                                 my $path = join('/',map { $titles{$_}; } @{$dirorder{$i}});
13128:                                 $path =~ s{/$}{};
13129:                                 my $item;
13130:                                 if ($path ne '') {
13131:                                     $item = "$path/$titles{$i}";
13132:                                 } else {
13133:                                     $item = $titles{$i};
13134:                                 }
13135:                                 $env{'form.archive_content_'.$i} = "$dir_root/$destination/$item";
13136:                                 if ($item eq $contents[0]) {
13137:                                     push(@{$env{'form.archive_directory'}},$i);
13138:                                     $env{'form.archive_'.$i} = 'display';
13139:                                     $env{'form.archive_title_'.$i} = $env{'form.camtasia_foldername'};
13140:                                     $displayed{'folder'} = $i;
13141:                                 } elsif ((($item eq "$contents[0]/index.html") && ($version == 6)) ||
13142:                                          (($item eq "$contents[0]/$contents[0]".'.html') && ($version == 8))) {
13143:                                     $env{'form.archive_'.$i} = 'display';
13144:                                     $env{'form.archive_title_'.$i} = $env{'form.camtasia_moviename'};
13145:                                     $displayed{'web'} = $i;
13146:                                 } else {
13147:                                     if ((($item eq "$contents[0]/media") && ($version == 6)) ||
13148:                                         ((($item eq "$contents[0]/scripts") || ($item eq "$contents[0]/skins") ||
13149:                                              ($item eq "$contents[0]/skins/express_show")) && ($version == 8))) {
13150:                                         push(@{$env{'form.archive_directory'}},$i);
13151:                                     }
13152:                                     $env{'form.archive_'.$i} = 'dependency';
13153:                                 }
13154:                                 $total ++;
13155:                             }
13156:                             for (my $i=1; $i<$total; $i++) {
13157:                                 next if ($i == $displayed{'web'});
13158:                                 next if ($i == $displayed{'folder'});
13159:                                 $env{'form.archive_dependent_on_'.$i} = $displayed{'web'};
13160:                             }
13161:                             $env{'form.phase'} = 'decompress_cleanup';
13162:                             $env{'form.archivedelete'} = 1;
13163:                             $env{'form.archive_count'} = $total-1;
13164:                             $output .=
13165:                                 &process_extracted_files('coursedocs',$docudom,
13166:                                                          $docuname,$destination,
13167:                                                          $dir_root,$hiddenelem);
13168:                         }
13169:                     } else {
13170:                         $warning = &mt('No new items extracted from archive file.');
13171:                     }
13172:                 } else {
13173:                     $output = $display;
13174:                     $error = &mt('An error occurred during extraction from the archive file.');
13175:                 }
13176:             }
13177:         }
13178:     }
13179:     if ($error) {
13180:         $output .= '<p class="LC_error">'.&mt('Not extracted.').'<br />'.
13181:                    $error.'</p>'."\n";
13182:     }
13183:     if ($warning) {
13184:         $output .= '<p class="LC_warning">'.$warning.'</p>'."\n";
13185:     }
13186:     return $output;
13187: }
13188: 
13189: sub get_extracted {
13190:     my ($docudom,$docuname,$currdir,$is_dir,$children,$parent,$contents,$dirorder,
13191:         $titles,$wantform) = @_;
13192:     my $count = 0;
13193:     my $depth = 0;
13194:     my $datatable;
13195:     my @hierarchy;
13196:     return unless ((ref($is_dir) eq 'HASH') && (ref($children) eq 'HASH') &&
13197:                    (ref($parent) eq 'HASH') && (ref($contents) eq 'ARRAY') &&
13198:                    (ref($dirorder) eq 'HASH') && (ref($titles) eq 'HASH'));
13199:     foreach my $item (@{$contents}) {
13200:         $count ++;
13201:         @{$dirorder->{$count}} = @hierarchy;
13202:         $titles->{$count} = $item;
13203:         &archive_hierarchy($depth,$count,$parent,$children);
13204:         if ($wantform) {
13205:             $datatable .= &archive_row($is_dir->{$item},$item,
13206:                                        $currdir,$depth,$count);
13207:         }
13208:         if ($is_dir->{$item}) {
13209:             $depth ++;
13210:             push(@hierarchy,$count);
13211:             $parent->{$depth} = $count;
13212:             $datatable .=
13213:                 &recurse_extracted_archive("$currdir/$item",$docudom,$docuname,
13214:                                            \$depth,\$count,\@hierarchy,$dirorder,
13215:                                            $children,$parent,$titles,$wantform);
13216:             $depth --;
13217:             pop(@hierarchy);
13218:         }
13219:     }
13220:     return ($count,$datatable);
13221: }
13222: 
13223: sub recurse_extracted_archive {
13224:     my ($currdir,$docudom,$docuname,$depth,$count,$hierarchy,$dirorder,
13225:         $children,$parent,$titles,$wantform) = @_;
13226:     my $result='';
13227:     unless ((ref($depth)) && (ref($count)) && (ref($hierarchy) eq 'ARRAY') &&
13228:             (ref($children) eq 'HASH') && (ref($parent) eq 'HASH') &&
13229:             (ref($dirorder) eq 'HASH')) {
13230:         return $result;
13231:     }
13232:     my $dirptr = 16384;
13233:     my ($newdirlistref,$newlisterror) =
13234:         &Apache::lonnet::dirlist($currdir,$docudom,$docuname,1);
13235:     if (ref($newdirlistref) eq 'ARRAY') {
13236:         foreach my $dir_line (@{$newdirlistref}) {
13237:             my ($item,undef,undef,$testdir)=split(/\&/,$dir_line,5);
13238:             unless ($item =~ /^\.+$/) {
13239:                 $$count ++;
13240:                 @{$dirorder->{$$count}} = @{$hierarchy};
13241:                 $titles->{$$count} = $item;
13242:                 &archive_hierarchy($$depth,$$count,$parent,$children);
13243: 
13244:                 my $is_dir;
13245:                 if ($dirptr&$testdir) {
13246:                     $is_dir = 1;
13247:                 }
13248:                 if ($wantform) {
13249:                     $result .= &archive_row($is_dir,$item,$currdir,$$depth,$$count);
13250:                 }
13251:                 if ($is_dir) {
13252:                     $$depth ++;
13253:                     push(@{$hierarchy},$$count);
13254:                     $parent->{$$depth} = $$count;
13255:                     $result .=
13256:                         &recurse_extracted_archive("$currdir/$item",$docudom,
13257:                                                    $docuname,$depth,$count,
13258:                                                    $hierarchy,$dirorder,$children,
13259:                                                    $parent,$titles,$wantform);
13260:                     $$depth --;
13261:                     pop(@{$hierarchy});
13262:                 }
13263:             }
13264:         }
13265:     }
13266:     return $result;
13267: }
13268: 
13269: sub archive_hierarchy {
13270:     my ($depth,$count,$parent,$children) =@_;
13271:     if ((ref($parent) eq 'HASH') && (ref($children) eq 'HASH')) {
13272:         if (exists($parent->{$depth})) {
13273:              $children->{$parent->{$depth}} .= $count.':';
13274:         }
13275:     }
13276:     return;
13277: }
13278: 
13279: sub archive_row {
13280:     my ($is_dir,$item,$currdir,$depth,$count) = @_;
13281:     my ($name) = ($item =~ m{([^/]+)$});
13282:     my %choices = &Apache::lonlocal::texthash (
13283:                                        'display'    => 'Add as file',
13284:                                        'dependency' => 'Include as dependency',
13285:                                        'discard'    => 'Discard',
13286:                                       );
13287:     if ($is_dir) {
13288:         $choices{'display'} = &mt('Add as folder'); 
13289:     }
13290:     my $output = &start_data_table_row().'<td align="right">'.$count.'</td>'."\n";
13291:     my $offset = 0;
13292:     foreach my $action ('display','dependency','discard') {
13293:         $offset ++;
13294:         if ($action ne 'display') {
13295:             $offset ++;
13296:         }  
13297:         $output .= '<td><span class="LC_nobreak">'.
13298:                    '<label><input type="radio" name="archive_'.$count.
13299:                    '" id="archive_'.$action.'_'.$count.'" value="'.$action.'"';
13300:         my $text = $choices{$action};
13301:         if ($is_dir) {
13302:             $output .= ' onclick="javascript:propagateCheck(this.form,'."'$count'".');"';
13303:             if ($action eq 'display') {
13304:                 $text = &mt('Add as folder');
13305:             }
13306:         } else {
13307:             $output .= ' onclick="javascript:dependencyCheck(this.form,'."$count,$offset".');"';
13308: 
13309:         }
13310:         $output .= ' />&nbsp;'.$choices{$action}.'</label></span>';
13311:         if ($action eq 'dependency') {
13312:             $output .= '<div id="arc_depon_'.$count.'" style="display:none;">'."\n".
13313:                        &mt('Used by:').'&nbsp;<select name="archive_dependent_on_'.$count.'" '.
13314:                        'onchange="propagateSelect(this.form,'."$count,$offset".')">'."\n".
13315:                        '<option value=""></option>'."\n".
13316:                        '</select>'."\n".
13317:                        '</div>';
13318:         } elsif ($action eq 'display') {
13319:             $output .= '<div id="arc_title_'.$count.'" style="display:none;">'."\n".
13320:                        &mt('Title:').'&nbsp;<input type="text" name="archive_title_'.$count.'" id="archive_title_'.$count.'" />'."\n".
13321:                        '</div>';
13322:         }
13323:         $output .= '</td>';
13324:     }
13325:     $output .= '<td><input type="hidden" name="archive_content_'.$count.'" value="'.
13326:                &HTML::Entities::encode("$currdir/$item",'"<>&').'" />'.('&nbsp;' x 2);
13327:     for (my $i=0; $i<$depth; $i++) {
13328:         $output .= ('<img src="/adm/lonIcons/whitespace1.gif" class="LC_docs_spacer" alt="" />' x2)."\n";
13329:     }
13330:     if ($is_dir) {
13331:         $output .= '<img src="/adm/lonIcons/navmap.folder.open.gif" alt="" />&nbsp;'."\n".
13332:                    '<input type="hidden" name="archive_directory" value="'.$count.'" />'."\n";
13333:     } else {
13334:         $output .= '<input type="hidden" name="archive_file" value="'.$count.'" />'."\n";
13335:     }
13336:     $output .= '&nbsp;'.$name.'</td>'."\n".
13337:                &end_data_table_row();
13338:     return $output;
13339: }
13340: 
13341: sub archive_options_form {
13342:     my ($form,$display,$count,$hiddenelem) = @_;
13343:     my %lt = &Apache::lonlocal::texthash(
13344:                perm => 'Permanently remove archive file?',
13345:                hows => 'How should each extracted item be incorporated in the course?',
13346:                cont => 'Content actions for all',
13347:                addf => 'Add as folder/file',
13348:                incd => 'Include as dependency for a displayed file',
13349:                disc => 'Discard',
13350:                no   => 'No',
13351:                yes  => 'Yes',
13352:                save => 'Save',
13353:     );
13354:     my $output = <<"END";
13355: <form name="$form" method="post" action="">
13356: <p><span class="LC_nobreak">$lt{'perm'}&nbsp;
13357: <label>
13358:   <input type="radio" name="archivedelete" value="0" checked="checked" />$lt{'no'}
13359: </label>
13360: &nbsp;
13361: <label>
13362:   <input type="radio" name="archivedelete" value="1" />$lt{'yes'}</label>
13363: </span>
13364: </p>
13365: <input type="hidden" name="phase" value="decompress_cleanup" />
13366: <br />$lt{'hows'}
13367: <div class="LC_columnSection">
13368:   <fieldset>
13369:     <legend>$lt{'cont'}</legend>
13370:     <input type="button" value="$lt{'addf'}" onclick="javascript:checkAll(document.$form,'display');" /> 
13371:     &nbsp;&nbsp;<input type="button" value="$lt{'incd'}" onclick="javascript:checkAll(document.$form,'dependency');" />
13372:     &nbsp;&nbsp;<input type="button" value="$lt{'disc'}" onclick="javascript:checkAll(document.$form,'discard');" />
13373:   </fieldset>
13374: </div>
13375: END
13376:     return $output.
13377:            &start_data_table()."\n".
13378:            $display."\n".
13379:            &end_data_table()."\n".
13380:            '<input type="hidden" name="archive_count" value="'.$count.'" />'.
13381:            $hiddenelem.
13382:            '<br /><input type="submit" name="archive_submit" value="'.$lt{'save'}.'" />'.
13383:            '</form>';
13384: }
13385: 
13386: sub archive_javascript {
13387:     my ($startcount,$numitems,$titles,$children) = @_;
13388:     return unless ((ref($titles) eq 'HASH') && (ref($children) eq 'HASH'));
13389:     my $maintitle = $env{'form.comment'};
13390:     my $scripttag = <<START;
13391: <script type="text/javascript">
13392: // <![CDATA[
13393: 
13394: function checkAll(form,prefix) {
13395:     var idstr =  new RegExp("^archive_"+prefix+"_\\\\d+\$");
13396:     for (var i=0; i < form.elements.length; i++) {
13397:         var id = form.elements[i].id;
13398:         if ((id != '') && (id != undefined)) {
13399:             if (idstr.test(id)) {
13400:                 if (form.elements[i].type == 'radio') {
13401:                     form.elements[i].checked = true;
13402:                     var nostart = i-$startcount;
13403:                     var offset = nostart%7;
13404:                     var count = (nostart-offset)/7;    
13405:                     dependencyCheck(form,count,offset);
13406:                 }
13407:             }
13408:         }
13409:     }
13410: }
13411: 
13412: function propagateCheck(form,count) {
13413:     if (count > 0) {
13414:         var startelement = $startcount + ((count-1) * 7);
13415:         for (var j=1; j<6; j++) {
13416:             if ((j != 2) && (j != 4)) {
13417:                 var item = startelement + j; 
13418:                 if (form.elements[item].type == 'radio') {
13419:                     if (form.elements[item].checked) {
13420:                         containerCheck(form,count,j);
13421:                         break;
13422:                     }
13423:                 }
13424:             }
13425:         }
13426:     }
13427: }
13428: 
13429: numitems = $numitems
13430: var titles = new Array(numitems);
13431: var parents = new Array(numitems);
13432: for (var i=0; i<numitems; i++) {
13433:     parents[i] = new Array;
13434: }
13435: var maintitle = '$maintitle';
13436: 
13437: START
13438: 
13439:     foreach my $container (sort { $a <=> $b } (keys(%{$children}))) {
13440:         my @contents = split(/:/,$children->{$container});
13441:         for (my $i=0; $i<@contents; $i ++) {
13442:             $scripttag .= 'parents['.$container.']['.$i.'] = '.$contents[$i]."\n";
13443:         }
13444:     }
13445: 
13446:     foreach my $key (sort { $a <=> $b } (keys(%{$titles}))) {
13447:         $scripttag .= "titles[$key] = '".$titles->{$key}."';\n";
13448:     }
13449: 
13450:     $scripttag .= <<END;
13451: 
13452: function containerCheck(form,count,offset) {
13453:     if (count > 0) {
13454:         dependencyCheck(form,count,offset);
13455:         var item = (offset+$startcount)+7*(count-1);
13456:         form.elements[item].checked = true;
13457:         if(Object.prototype.toString.call(parents[count]) === '[object Array]') {
13458:             if (parents[count].length > 0) {
13459:                 for (var j=0; j<parents[count].length; j++) {
13460:                     containerCheck(form,parents[count][j],offset);
13461:                 }
13462:             }
13463:         }
13464:     }
13465: }
13466: 
13467: function dependencyCheck(form,count,offset) {
13468:     if (count > 0) {
13469:         var chosen = (offset+$startcount)+7*(count-1);
13470:         var depitem = $startcount + ((count-1) * 7) + 4;
13471:         var currtype = form.elements[depitem].type;
13472:         if (form.elements[chosen].value == 'dependency') {
13473:             document.getElementById('arc_depon_'+count).style.display='block'; 
13474:             form.elements[depitem].options.length = 0;
13475:             form.elements[depitem].options[0] = new Option('Select','',true,true);
13476:             for (var i=1; i<=numitems; i++) {
13477:                 if (i == count) {
13478:                     continue;
13479:                 }
13480:                 var startelement = $startcount + (i-1) * 7;
13481:                 for (var j=1; j<6; j++) {
13482:                     if ((j != 2) && (j!= 4)) {
13483:                         var item = startelement + j;
13484:                         if (form.elements[item].type == 'radio') {
13485:                             if (form.elements[item].checked) {
13486:                                 if (form.elements[item].value == 'display') {
13487:                                     var n = form.elements[depitem].options.length;
13488:                                     form.elements[depitem].options[n] = new Option(titles[i],i,false,false);
13489:                                 }
13490:                             }
13491:                         }
13492:                     }
13493:                 }
13494:             }
13495:         } else {
13496:             document.getElementById('arc_depon_'+count).style.display='none';
13497:             form.elements[depitem].options.length = 0;
13498:             form.elements[depitem].options[0] = new Option('Select','',true,true);
13499:         }
13500:         titleCheck(form,count,offset);
13501:     }
13502: }
13503: 
13504: function propagateSelect(form,count,offset) {
13505:     if (count > 0) {
13506:         var item = (1+offset+$startcount)+7*(count-1);
13507:         var picked = form.elements[item].options[form.elements[item].selectedIndex].value; 
13508:         if (Object.prototype.toString.call(parents[count]) === '[object Array]') {
13509:             if (parents[count].length > 0) {
13510:                 for (var j=0; j<parents[count].length; j++) {
13511:                     containerSelect(form,parents[count][j],offset,picked);
13512:                 }
13513:             }
13514:         }
13515:     }
13516: }
13517: 
13518: function containerSelect(form,count,offset,picked) {
13519:     if (count > 0) {
13520:         var item = (offset+$startcount)+7*(count-1);
13521:         if (form.elements[item].type == 'radio') {
13522:             if (form.elements[item].value == 'dependency') {
13523:                 if (form.elements[item+1].type == 'select-one') {
13524:                     for (var i=0; i<form.elements[item+1].options.length; i++) {
13525:                         if (form.elements[item+1].options[i].value == picked) {
13526:                             form.elements[item+1].selectedIndex = i;
13527:                             break;
13528:                         }
13529:                     }
13530:                 }
13531:                 if (Object.prototype.toString.call(parents[count]) === '[object Array]') {
13532:                     if (parents[count].length > 0) {
13533:                         for (var j=0; j<parents[count].length; j++) {
13534:                             containerSelect(form,parents[count][j],offset,picked);
13535:                         }
13536:                     }
13537:                 }
13538:             }
13539:         }
13540:     }
13541: }
13542: 
13543: function titleCheck(form,count,offset) {
13544:     if (count > 0) {
13545:         var chosen = (offset+$startcount)+7*(count-1);
13546:         var depitem = $startcount + ((count-1) * 7) + 2;
13547:         var currtype = form.elements[depitem].type;
13548:         if (form.elements[chosen].value == 'display') {
13549:             document.getElementById('arc_title_'+count).style.display='block';
13550:             if ((count==1) && ((parents[count].length > 0) || (numitems == 1))) {
13551:                 document.getElementById('archive_title_'+count).value=maintitle;
13552:             }
13553:         } else {
13554:             document.getElementById('arc_title_'+count).style.display='none';
13555:             if (currtype == 'text') { 
13556:                 document.getElementById('archive_title_'+count).value='';
13557:             }
13558:         }
13559:     }
13560:     return;
13561: }
13562: 
13563: // ]]>
13564: </script>
13565: END
13566:     return $scripttag;
13567: }
13568: 
13569: sub process_extracted_files {
13570:     my ($context,$docudom,$docuname,$destination,$dir_root,$hiddenelem) = @_;
13571:     my $numitems = $env{'form.archive_count'};
13572:     return if ((!$numitems) || ($numitems =~ /\D/));
13573:     my @ids=&Apache::lonnet::current_machine_ids();
13574:     my ($prefix,$pathtocheck,$dir,$ishome,$error,$warning,%toplevelitems,%is_dir,
13575:         %folders,%containers,%mapinner,%prompttofetch);
13576:     my $docuhome = &Apache::lonnet::homeserver($docuname,$docudom);
13577:     if (grep(/^\Q$docuhome\E$/,@ids)) {
13578:         $prefix = &LONCAPA::propath($docudom,$docuname);
13579:         $pathtocheck = "$dir_root/$destination";
13580:         $dir = $dir_root;
13581:         $ishome = 1;
13582:     } else {
13583:         $prefix = $Apache::lonnet::perlvar{'lonDocRoot'};
13584:         $pathtocheck = "$dir_root/$docudom/$docuname/$destination";
13585:         $dir = "$dir_root/$docudom/$docuname";
13586:     }
13587:     my $currdir = "$dir_root/$destination";
13588:     (my $docstype,$mapinner{'0'}) = ($destination =~ m{^(docs|supplemental)/(\w+)/});
13589:     if ($env{'form.folderpath'}) {
13590:         my @items = split('&',$env{'form.folderpath'});
13591:         $folders{'0'} = $items[-2];
13592:         if ($env{'form.folderpath'} =~ /\:1$/) {
13593:             $containers{'0'}='page';
13594:         } else {
13595:             $containers{'0'}='sequence';
13596:         }
13597:     }
13598:     my @archdirs = &get_env_multiple('form.archive_directory');
13599:     if ($numitems) {
13600:         for (my $i=1; $i<=$numitems; $i++) {
13601:             my $path = $env{'form.archive_content_'.$i};
13602:             if ($path =~ m{^\Q$pathtocheck\E/([^/]+)$}) {
13603:                 my $item = $1;
13604:                 $toplevelitems{$item} = $i;
13605:                 if (grep(/^\Q$i\E$/,@archdirs)) {
13606:                     $is_dir{$item} = 1;
13607:                 }
13608:             }
13609:         }
13610:     }
13611:     my ($output,%children,%parent,%titles,%dirorder,$result);
13612:     if (keys(%toplevelitems) > 0) {
13613:         my @contents = sort(keys(%toplevelitems));
13614:         (my $count,undef) = &get_extracted($docudom,$docuname,$currdir,\%is_dir,\%children,
13615:                                            \%parent,\@contents,\%dirorder,\%titles);
13616:     }
13617:     my (%referrer,%orphaned,%todelete,%todeletedir,%newdest,%newseqid);
13618:     if ($numitems) {
13619:         for (my $i=1; $i<=$numitems; $i++) {
13620:             next if ($env{'form.archive_'.$i} eq 'dependency');
13621:             my $path = $env{'form.archive_content_'.$i};
13622:             if ($path =~ /^\Q$pathtocheck\E/) {
13623:                 if ($env{'form.archive_'.$i} eq 'discard') {
13624:                     if ($prefix ne '' && $path ne '') {
13625:                         if (-e $prefix.$path) {
13626:                             if ((@archdirs > 0) && 
13627:                                 (grep(/^\Q$i\E$/,@archdirs))) {
13628:                                 $todeletedir{$prefix.$path} = 1;
13629:                             } else {
13630:                                 $todelete{$prefix.$path} = 1;
13631:                             }
13632:                         }
13633:                     }
13634:                 } elsif ($env{'form.archive_'.$i} eq 'display') {
13635:                     my ($docstitle,$title,$url,$outer);
13636:                     ($title) = ($path =~ m{/([^/]+)$});
13637:                     $docstitle = $env{'form.archive_title_'.$i};
13638:                     if ($docstitle eq '') {
13639:                         $docstitle = $title;
13640:                     }
13641:                     $outer = 0;
13642:                     if (ref($dirorder{$i}) eq 'ARRAY') {
13643:                         if (@{$dirorder{$i}} > 0) {
13644:                             foreach my $item (reverse(@{$dirorder{$i}})) {
13645:                                 if ($env{'form.archive_'.$item} eq 'display') {
13646:                                     $outer = $item;
13647:                                     last;
13648:                                 }
13649:                             }
13650:                         }
13651:                     }
13652:                     my ($errtext,$fatal) = 
13653:                         &LONCAPA::map::mapread('/uploaded/'.$docudom.'/'.$docuname.
13654:                                                '/'.$folders{$outer}.'.'.
13655:                                                $containers{$outer});
13656:                     next if ($fatal);
13657:                     if ((@archdirs > 0) && (grep(/^\Q$i\E$/,@archdirs))) {
13658:                         if ($context eq 'coursedocs') {
13659:                             $mapinner{$i} = time;
13660:                             $folders{$i} = 'default_'.$mapinner{$i};
13661:                             $containers{$i} = 'sequence';
13662:                             my $url = '/uploaded/'.$docudom.'/'.$docuname.'/'.
13663:                                       $folders{$i}.'.'.$containers{$i};
13664:                             my $newidx = &LONCAPA::map::getresidx();
13665:                             $LONCAPA::map::resources[$newidx]=
13666:                                 $docstitle.':'.$url.':false:normal:res';
13667:                             push(@LONCAPA::map::order,$newidx);
13668:                             my ($outtext,$errtext) =
13669:                                 &LONCAPA::map::storemap('/uploaded/'.$docudom.'/'.
13670:                                                         $docuname.'/'.$folders{$outer}.
13671:                                                         '.'.$containers{$outer},1,1);
13672:                             $newseqid{$i} = $newidx;
13673:                             unless ($errtext) {
13674:                                 $result .=  '<li>'.&mt('Folder: [_1] added to course',
13675:                                                        &HTML::Entities::encode($docstitle,'<>&"'))..
13676:                                             '</li>'."\n";
13677:                             }
13678:                         }
13679:                     } else {
13680:                         if ($context eq 'coursedocs') {
13681:                             my $newidx=&LONCAPA::map::getresidx();
13682:                             my $url = '/uploaded/'.$docudom.'/'.$docuname.'/'.
13683:                                       $docstype.'/'.$mapinner{$outer}.'/'.$newidx.'/'.
13684:                                       $title;
13685:                             if (($outer !~ /\D/) && ($mapinner{$outer} !~ /\D/) && ($newidx !~ /\D/)) {
13686:                                 if (!-e "$prefix$dir/$docstype/$mapinner{$outer}") {
13687:                                     mkdir("$prefix$dir/$docstype/$mapinner{$outer}",0755);
13688:                                 }
13689:                                 if (!-e "$prefix$dir/$docstype/$mapinner{$outer}/$newidx") {
13690:                                     mkdir("$prefix$dir/$docstype/$mapinner{$outer}/$newidx");
13691:                                 }
13692:                                 if (-e "$prefix$dir/$docstype/$mapinner{$outer}/$newidx") {
13693:                                     if (rename("$prefix$path","$prefix$dir/$docstype/$mapinner{$outer}/$newidx/$title")) {
13694:                                         $newdest{$i} = "$prefix$dir/$docstype/$mapinner{$outer}/$newidx";
13695:                                         unless ($ishome) {
13696:                                             my $fetch = "$newdest{$i}/$title";
13697:                                             $fetch =~ s/^\Q$prefix$dir\E//;
13698:                                             $prompttofetch{$fetch} = 1;
13699:                                         }
13700:                                    }
13701:                                 }
13702:                                 $LONCAPA::map::resources[$newidx]=
13703:                                     $docstitle.':'.$url.':false:normal:res';
13704:                                 push(@LONCAPA::map::order, $newidx);
13705:                                 my ($outtext,$errtext)=
13706:                                     &LONCAPA::map::storemap('/uploaded/'.$docudom.'/'.
13707:                                                             $docuname.'/'.$folders{$outer}.
13708:                                                             '.'.$containers{$outer},1,1);
13709:                                 unless ($errtext) {
13710:                                     if (-e "$prefix$dir/$docstype/$mapinner{$outer}/$newidx/$title") {
13711:                                         $result .= '<li>'.&mt('File: [_1] added to course',
13712:                                                               &HTML::Entities::encode($docstitle,'<>&"')).
13713:                                                    '</li>'."\n";
13714:                                     }
13715:                                 }
13716:                             } else {
13717:                                 $warning .= &mt('Item extracted from archive: [_1] has unexpected path.',
13718:                                                 &HTML::Entities::encode($path,'<>&"')).'<br />';
13719:                             }
13720:                         }
13721:                     }
13722:                 }
13723:             } else {
13724:                 $warning .= &mt('Item extracted from archive: [_1] has unexpected path.',
13725:                                 &HTML::Entities::encode($path,'<>&"')).'<br />';
13726:             }
13727:         }
13728:         for (my $i=1; $i<=$numitems; $i++) {
13729:             next unless ($env{'form.archive_'.$i} eq 'dependency');
13730:             my $path = $env{'form.archive_content_'.$i};
13731:             if ($path =~ /^\Q$pathtocheck\E/) {
13732:                 my ($title) = ($path =~ m{/([^/]+)$});
13733:                 $referrer{$i} = $env{'form.archive_dependent_on_'.$i};
13734:                 if ($env{'form.archive_'.$referrer{$i}} eq 'display') {
13735:                     if (ref($dirorder{$i}) eq 'ARRAY') {
13736:                         my ($itemidx,$fullpath,$relpath);
13737:                         if (ref($dirorder{$referrer{$i}}) eq 'ARRAY') {
13738:                             my $container = $dirorder{$referrer{$i}}->[-1];
13739:                             for (my $j=0; $j<@{$dirorder{$i}}; $j++) {
13740:                                 if ($dirorder{$i}->[$j] eq $container) {
13741:                                     $itemidx = $j;
13742:                                 }
13743:                             }
13744:                         }
13745:                         if ($itemidx eq '') {
13746:                             $itemidx =  0;
13747:                         }
13748:                         if (grep(/^\Q$referrer{$i}\E$/,@archdirs)) {
13749:                             if ($mapinner{$referrer{$i}}) {
13750:                                 $fullpath = "$prefix$dir/$docstype/$mapinner{$referrer{$i}}";
13751:                                 for (my $j=$itemidx; $j<@{$dirorder{$i}}; $j++) {
13752:                                     if (grep(/^\Q$dirorder{$i}->[$j]\E$/,@archdirs)) {
13753:                                         unless (defined($newseqid{$dirorder{$i}->[$j]})) {
13754:                                             $fullpath .= '/'.$titles{$dirorder{$i}->[$j]};
13755:                                             $relpath .= '/'.$titles{$dirorder{$i}->[$j]};
13756:                                             if (!-e $fullpath) {
13757:                                                 mkdir($fullpath,0755);
13758:                                             }
13759:                                         }
13760:                                     } else {
13761:                                         last;
13762:                                     }
13763:                                 }
13764:                             }
13765:                         } elsif ($newdest{$referrer{$i}}) {
13766:                             $fullpath = $newdest{$referrer{$i}};
13767:                             for (my $j=$itemidx; $j<@{$dirorder{$i}}; $j++) {
13768:                                 if ($env{'form.archive_'.$dirorder{$i}->[$j]} eq 'discard') {
13769:                                     $orphaned{$i} = $env{'form.archive_'.$dirorder{$i}->[$j]};
13770:                                     last;
13771:                                 } elsif (grep(/^\Q$dirorder{$i}->[$j]\E$/,@archdirs)) {
13772:                                     unless (defined($newseqid{$dirorder{$i}->[$j]})) {
13773:                                         $fullpath .= '/'.$titles{$dirorder{$i}->[$j]};
13774:                                         $relpath .= '/'.$titles{$dirorder{$i}->[$j]};
13775:                                         if (!-e $fullpath) {
13776:                                             mkdir($fullpath,0755);
13777:                                         }
13778:                                     }
13779:                                 } else {
13780:                                     last;
13781:                                 }
13782:                             }
13783:                         }
13784:                         if ($fullpath ne '') {
13785:                             if (-e "$prefix$path") {
13786:                                 unless (rename("$prefix$path","$fullpath/$title")) {
13787:                                      $warning .= &mt('Failed to rename dependency').'<br />';
13788:                                 }
13789:                             }
13790:                             if (-e "$fullpath/$title") {
13791:                                 my $showpath;
13792:                                 if ($relpath ne '') {
13793:                                     $showpath = "$relpath/$title";
13794:                                 } else {
13795:                                     $showpath = "/$title";
13796:                                 }
13797:                                 $result .= '<li>'.&mt('[_1] included as a dependency',
13798:                                                       &HTML::Entities::encode($showpath,'<>&"')).
13799:                                            '</li>'."\n";
13800:                                 unless ($ishome) {
13801:                                     my $fetch = "$fullpath/$title";
13802:                                     $fetch =~ s/^\Q$prefix$dir\E//;
13803:                                     $prompttofetch{$fetch} = 1;
13804:                                 }
13805:                             }
13806:                         }
13807:                     }
13808:                 } elsif ($env{'form.archive_'.$referrer{$i}} eq 'discard') {
13809:                     $warning .= &mt('[_1] is a dependency of [_2], which was discarded.',
13810:                                     &HTML::Entities::encode($path,'<>&"'),
13811:                                     &HTML::Entities::encode($env{'form.archive_content_'.$referrer{$i}},'<>&"')).
13812:                                 '<br />';
13813:                 }
13814:             } else {
13815:                 $warning .= &mt('Item extracted from archive: [_1] has unexpected path.',
13816:                                 &HTML::Entities::encode($path)).'<br />';
13817:             }
13818:         }
13819:         if (keys(%todelete)) {
13820:             foreach my $key (keys(%todelete)) {
13821:                 unlink($key);
13822:             }
13823:         }
13824:         if (keys(%todeletedir)) {
13825:             foreach my $key (keys(%todeletedir)) {
13826:                 rmdir($key);
13827:             }
13828:         }
13829:         foreach my $dir (sort(keys(%is_dir))) {
13830:             if (($pathtocheck ne '') && ($dir ne ''))  {
13831:                 &cleanup_empty_dirs($prefix."$pathtocheck/$dir");
13832:             }
13833:         }
13834:         if ($result ne '') {
13835:             $output .= '<ul>'."\n".
13836:                        $result."\n".
13837:                        '</ul>';
13838:         }
13839:         unless ($ishome) {
13840:             my $replicationfail;
13841:             foreach my $item (keys(%prompttofetch)) {
13842:                 my $fetchresult= &Apache::lonnet::reply('fetchuserfile:'.$item,$docuhome);
13843:                 unless ($fetchresult eq 'ok') {
13844:                     $replicationfail .= '<li>'.$item.'</li>'."\n";
13845:                 }
13846:             }
13847:             if ($replicationfail) {
13848:                 $output .= '<p class="LC_error">'.
13849:                            &mt('Course home server failed to retrieve:').'<ul>'.
13850:                            $replicationfail.
13851:                            '</ul></p>';
13852:             }
13853:         }
13854:     } else {
13855:         $warning = &mt('No items found in archive.');
13856:     }
13857:     if ($error) {
13858:         $output .= '<p class="LC_error">'.&mt('Not extracted.').'<br />'.
13859:                    $error.'</p>'."\n";
13860:     }
13861:     if ($warning) {
13862:         $output .= '<p class="LC_warning">'.$warning.'</p>'."\n";
13863:     }
13864:     return $output;
13865: }
13866: 
13867: sub cleanup_empty_dirs {
13868:     my ($path) = @_;
13869:     if (($path ne '') && (-d $path)) {
13870:         if (opendir(my $dirh,$path)) {
13871:             my @dircontents = grep(!/^\./,readdir($dirh));
13872:             my $numitems = 0;
13873:             foreach my $item (@dircontents) {
13874:                 if (-d "$path/$item") {
13875:                     &cleanup_empty_dirs("$path/$item");
13876:                     if (-e "$path/$item") {
13877:                         $numitems ++;
13878:                     }
13879:                 } else {
13880:                     $numitems ++;
13881:                 }
13882:             }
13883:             if ($numitems == 0) {
13884:                 rmdir($path);
13885:             }
13886:             closedir($dirh);
13887:         }
13888:     }
13889:     return;
13890: }
13891: 
13892: =pod
13893: 
13894: =item * &get_folder_hierarchy()
13895: 
13896: Provides hierarchy of names of folders/sub-folders containing the current
13897: item,
13898: 
13899: Inputs: 3
13900:      - $navmap - navmaps object
13901: 
13902:      - $map - url for map (either the trigger itself, or map containing
13903:                            the resource, which is the trigger).
13904: 
13905:      - $showitem - 1 => show title for map itself; 0 => do not show.
13906: 
13907: Outputs: 1 @pathitems - array of folder/subfolder names.
13908: 
13909: =cut
13910: 
13911: sub get_folder_hierarchy {
13912:     my ($navmap,$map,$showitem) = @_;
13913:     my @pathitems;
13914:     if (ref($navmap)) {
13915:         my $mapres = $navmap->getResourceByUrl($map);
13916:         if (ref($mapres)) {
13917:             my $pcslist = $mapres->map_hierarchy();
13918:             if ($pcslist ne '') {
13919:                 my @pcs = split(/,/,$pcslist);
13920:                 foreach my $pc (@pcs) {
13921:                     if ($pc == 1) {
13922:                         push(@pathitems,&mt('Main Content'));
13923:                     } else {
13924:                         my $res = $navmap->getByMapPc($pc);
13925:                         if (ref($res)) {
13926:                             my $title = $res->compTitle();
13927:                             $title =~ s/\W+/_/g;
13928:                             if ($title ne '') {
13929:                                 push(@pathitems,$title);
13930:                             }
13931:                         }
13932:                     }
13933:                 }
13934:             }
13935:             if ($showitem) {
13936:                 if ($mapres->{ID} eq '0.0') {
13937:                     push(@pathitems,&mt('Main Content'));
13938:                 } else {
13939:                     my $maptitle = $mapres->compTitle();
13940:                     $maptitle =~ s/\W+/_/g;
13941:                     if ($maptitle ne '') {
13942:                         push(@pathitems,$maptitle);
13943:                     }
13944:                 }
13945:             }
13946:         }
13947:     }
13948:     return @pathitems;
13949: }
13950: 
13951: =pod
13952: 
13953: =item * &get_turnedin_filepath()
13954: 
13955: Determines path in a user's portfolio file for storage of files uploaded
13956: to a specific essayresponse or dropbox item.
13957: 
13958: Inputs: 3 required + 1 optional.
13959: $symb is symb for resource, $uname and $udom are for current user (required).
13960: $caller is optional (can be "submission", if routine is called when storing
13961: an upoaded file when "Submit Answer" button was pressed).
13962: 
13963: Returns array containing $path and $multiresp. 
13964: $path is path in portfolio.  $multiresp is 1 if this resource contains more
13965: than one file upload item.  Callers of routine should append partid as a 
13966: subdirectory to $path in cases where $multiresp is 1.
13967: 
13968: Called by: homework/essayresponse.pm and homework/structuretags.pm
13969: 
13970: =cut
13971: 
13972: sub get_turnedin_filepath {
13973:     my ($symb,$uname,$udom,$caller) = @_;
13974:     my ($map,$resid,$resurl)=&Apache::lonnet::decode_symb($symb);
13975:     my $turnindir;
13976:     my %userhash = &Apache::lonnet::userenvironment($udom,$uname,'turnindir');
13977:     $turnindir = $userhash{'turnindir'};
13978:     my ($path,$multiresp);
13979:     if ($turnindir eq '') {
13980:         if ($caller eq 'submission') {
13981:             $turnindir = &mt('turned in');
13982:             $turnindir =~ s/\W+/_/g;
13983:             my %newhash = (
13984:                             'turnindir' => $turnindir,
13985:                           );
13986:             &Apache::lonnet::put('environment',\%newhash,$udom,$uname);
13987:         }
13988:     }
13989:     if ($turnindir ne '') {
13990:         $path = '/'.$turnindir.'/';
13991:         my ($multipart,$turnin,@pathitems);
13992:         my $navmap = Apache::lonnavmaps::navmap->new();
13993:         if (defined($navmap)) {
13994:             my $mapres = $navmap->getResourceByUrl($map);
13995:             if (ref($mapres)) {
13996:                 my $pcslist = $mapres->map_hierarchy();
13997:                 if ($pcslist ne '') {
13998:                     foreach my $pc (split(/,/,$pcslist)) {
13999:                         my $res = $navmap->getByMapPc($pc);
14000:                         if (ref($res)) {
14001:                             my $title = $res->compTitle();
14002:                             $title =~ s/\W+/_/g;
14003:                             if ($title ne '') {
14004:                                 if (($pc > 1) && (length($title) > 12)) {
14005:                                     $title = substr($title,0,12);
14006:                                 }
14007:                                 push(@pathitems,$title);
14008:                             }
14009:                         }
14010:                     }
14011:                 }
14012:                 my $maptitle = $mapres->compTitle();
14013:                 $maptitle =~ s/\W+/_/g;
14014:                 if ($maptitle ne '') {
14015:                     if (length($maptitle) > 12) {
14016:                         $maptitle = substr($maptitle,0,12);
14017:                     }
14018:                     push(@pathitems,$maptitle);
14019:                 }
14020:                 unless ($env{'request.state'} eq 'construct') {
14021:                     my $res = $navmap->getBySymb($symb);
14022:                     if (ref($res)) {
14023:                         my $partlist = $res->parts();
14024:                         my $totaluploads = 0;
14025:                         if (ref($partlist) eq 'ARRAY') {
14026:                             foreach my $part (@{$partlist}) {
14027:                                 my @types = $res->responseType($part);
14028:                                 my @ids = $res->responseIds($part);
14029:                                 for (my $i=0; $i < scalar(@ids); $i++) {
14030:                                     if ($types[$i] eq 'essay') {
14031:                                         my $partid = $part.'_'.$ids[$i];
14032:                                         if (&Apache::lonnet::EXT("resource.$partid.uploadedfiletypes") ne '') {
14033:                                             $totaluploads ++;
14034:                                         }
14035:                                     }
14036:                                 }
14037:                             }
14038:                             if ($totaluploads > 1) {
14039:                                 $multiresp = 1;
14040:                             }
14041:                         }
14042:                     }
14043:                 }
14044:             } else {
14045:                 return;
14046:             }
14047:         } else {
14048:             return;
14049:         }
14050:         my $restitle=&Apache::lonnet::gettitle($symb);
14051:         $restitle =~ s/\W+/_/g;
14052:         if ($restitle eq '') {
14053:             $restitle = ($resurl =~ m{/[^/]+$});
14054:             if ($restitle eq '') {
14055:                 $restitle = time;
14056:             }
14057:         }
14058:         if (length($restitle) > 12) {
14059:             $restitle = substr($restitle,0,12);
14060:         }
14061:         push(@pathitems,$restitle);
14062:         $path .= join('/',@pathitems);
14063:     }
14064:     return ($path,$multiresp);
14065: }
14066: 
14067: =pod
14068: 
14069: =back
14070: 
14071: =head1 CSV Upload/Handling functions
14072: 
14073: =over 4
14074: 
14075: =item * &upfile_store($r)
14076: 
14077: Store uploaded file, $r should be the HTTP Request object,
14078: needs $env{'form.upfile'}
14079: returns $datatoken to be put into hidden field
14080: 
14081: =cut
14082: 
14083: sub upfile_store {
14084:     my $r=shift;
14085:     $env{'form.upfile'}=~s/\r/\n/gs;
14086:     $env{'form.upfile'}=~s/\f/\n/gs;
14087:     $env{'form.upfile'}=~s/\n+/\n/gs;
14088:     $env{'form.upfile'}=~s/\n+$//gs;
14089: 
14090:     my $datatoken = &valid_datatoken($env{'user.name'}.'_'.$env{'user.domain'}.
14091:                                      '_enroll_'.$env{'request.course.id'}.'_'.
14092:                                      time.'_'.$$);
14093:     return if ($datatoken eq '');
14094: 
14095:     {
14096:         my $datafile = $r->dir_config('lonDaemons').
14097:                            '/tmp/'.$datatoken.'.tmp';
14098:         if ( open(my $fh,'>',$datafile) ) {
14099:             print $fh $env{'form.upfile'};
14100:             close($fh);
14101:         }
14102:     }
14103:     return $datatoken;
14104: }
14105: 
14106: =pod
14107: 
14108: =item * &load_tmp_file($r,$datatoken)
14109: 
14110: Load uploaded file from tmp, $r should be the HTTP Request object,
14111: $datatoken is the name to assign to the temporary file.
14112: sets $env{'form.upfile'} to the contents of the file
14113: 
14114: =cut
14115: 
14116: sub load_tmp_file {
14117:     my ($r,$datatoken) = @_;
14118:     return if ($datatoken eq '');
14119:     my @studentdata=();
14120:     {
14121:         my $studentfile = $r->dir_config('lonDaemons').
14122:                               '/tmp/'.$datatoken.'.tmp';
14123:         if ( open(my $fh,'<',$studentfile) ) {
14124:             @studentdata=<$fh>;
14125:             close($fh);
14126:         }
14127:     }
14128:     $env{'form.upfile'}=join('',@studentdata);
14129: }
14130: 
14131: sub valid_datatoken {
14132:     my ($datatoken) = @_;
14133:     if ($datatoken =~ /^$match_username\_$match_domain\_enroll_(|$match_domain\_$match_courseid)\_\d+_\d+$/) {
14134:         return $datatoken;
14135:     }
14136:     return;
14137: }
14138: 
14139: =pod
14140: 
14141: =item * &upfile_record_sep()
14142: 
14143: Separate uploaded file into records
14144: returns array of records,
14145: needs $env{'form.upfile'} and $env{'form.upfiletype'}
14146: 
14147: =cut
14148: 
14149: sub upfile_record_sep {
14150:     if ($env{'form.upfiletype'} eq 'xml') {
14151:     } else {
14152: 	my @records;
14153: 	foreach my $line (split(/\n/,$env{'form.upfile'})) {
14154: 	    if ($line=~/^\s*$/) { next; }
14155: 	    push(@records,$line);
14156: 	}
14157: 	return @records;
14158:     }
14159: }
14160: 
14161: =pod
14162: 
14163: =item * &record_sep($record)
14164: 
14165: Separate a record into fields $record should be an item from the upfile_record_sep(), needs $env{'form.upfiletype'}
14166: 
14167: =cut
14168: 
14169: sub takeleft {
14170:     my $index=shift;
14171:     return substr('0000'.$index,-4,4);
14172: }
14173: 
14174: sub record_sep {
14175:     my $record=shift;
14176:     my %components=();
14177:     if ($env{'form.upfiletype'} eq 'xml') {
14178:     } elsif ($env{'form.upfiletype'} eq 'space') {
14179:         my $i=0;
14180:         foreach my $field (split(/\s+/,$record)) {
14181:             $field=~s/^(\"|\')//;
14182:             $field=~s/(\"|\')$//;
14183:             $components{&takeleft($i)}=$field;
14184:             $i++;
14185:         }
14186:     } elsif ($env{'form.upfiletype'} eq 'tab') {
14187:         my $i=0;
14188:         foreach my $field (split(/\t/,$record)) {
14189:             $field=~s/^(\"|\')//;
14190:             $field=~s/(\"|\')$//;
14191:             $components{&takeleft($i)}=$field;
14192:             $i++;
14193:         }
14194:     } else {
14195:         my $separator=',';
14196:         if ($env{'form.upfiletype'} eq 'semisv') {
14197:             $separator=';';
14198:         }
14199:         my $i=0;
14200: # the character we are looking for to indicate the end of a quote or a record 
14201:         my $looking_for=$separator;
14202: # do not add the characters to the fields
14203:         my $ignore=0;
14204: # we just encountered a separator (or the beginning of the record)
14205:         my $just_found_separator=1;
14206: # store the field we are working on here
14207:         my $field='';
14208: # work our way through all characters in record
14209:         foreach my $character ($record=~/(.)/g) {
14210:             if ($character eq $looking_for) {
14211:                if ($character ne $separator) {
14212: # Found the end of a quote, again looking for separator
14213:                   $looking_for=$separator;
14214:                   $ignore=1;
14215:                } else {
14216: # Found a separator, store away what we got
14217:                   $components{&takeleft($i)}=$field;
14218: 	          $i++;
14219:                   $just_found_separator=1;
14220:                   $ignore=0;
14221:                   $field='';
14222:                }
14223:                next;
14224:             }
14225: # single or double quotation marks after a separator indicate beginning of a quote
14226: # we are now looking for the end of the quote and need to ignore separators
14227:             if ((($character eq '"') || ($character eq "'")) && ($just_found_separator))  {
14228:                $looking_for=$character;
14229:                next;
14230:             }
14231: # ignore would be true after we reached the end of a quote
14232:             if ($ignore) { next; }
14233:             if (($just_found_separator) && ($character=~/\s/)) { next; }
14234:             $field.=$character;
14235:             $just_found_separator=0; 
14236:         }
14237: # catch the very last entry, since we never encountered the separator
14238:         $components{&takeleft($i)}=$field;
14239:     }
14240:     return %components;
14241: }
14242: 
14243: ######################################################
14244: ######################################################
14245: 
14246: =pod
14247: 
14248: =item * &upfile_select_html()
14249: 
14250: Return HTML code to select a file from the users machine and specify 
14251: the file type.
14252: 
14253: =cut
14254: 
14255: ######################################################
14256: ######################################################
14257: sub upfile_select_html {
14258:     my %Types = (
14259:                  csv   => &mt('CSV (comma separated values, spreadsheet)'),
14260:                  semisv => &mt('Semicolon separated values'),
14261:                  space => &mt('Space separated'),
14262:                  tab   => &mt('Tabulator separated'),
14263: #                 xml   => &mt('HTML/XML'),
14264:                  );
14265:     my $Str = '<input type="file" name="upfile" size="50" />'.
14266:         '<br />'.&mt('Type').': <select name="upfiletype">';
14267:     foreach my $type (sort(keys(%Types))) {
14268:         $Str .= '<option value="'.$type.'" >'.$Types{$type}."</option>\n";
14269:     }
14270:     $Str .= "</select>\n";
14271:     return $Str;
14272: }
14273: 
14274: sub get_samples {
14275:     my ($records,$toget) = @_;
14276:     my @samples=({});
14277:     my $got=0;
14278:     foreach my $rec (@$records) {
14279: 	my %temp = &record_sep($rec);
14280: 	if (! grep(/\S/, values(%temp))) { next; }
14281: 	if (%temp) {
14282: 	    $samples[$got]=\%temp;
14283: 	    $got++;
14284: 	    if ($got == $toget) { last; }
14285: 	}
14286:     }
14287:     return \@samples;
14288: }
14289: 
14290: ######################################################
14291: ######################################################
14292: 
14293: =pod
14294: 
14295: =item * &csv_print_samples($r,$records)
14296: 
14297: Prints a table of sample values from each column uploaded $r is an
14298: Apache Request ref, $records is an arrayref from
14299: &Apache::loncommon::upfile_record_sep
14300: 
14301: =cut
14302: 
14303: ######################################################
14304: ######################################################
14305: sub csv_print_samples {
14306:     my ($r,$records) = @_;
14307:     my $samples = &get_samples($records,5);
14308: 
14309:     $r->print(&mt('Samples').'<br />'.&start_data_table().
14310:               &start_data_table_header_row());
14311:     foreach my $sample (sort({$a <=> $b} keys(%{ $samples->[0] }))) { 
14312:         $r->print('<th>'.&mt('Column [_1]',($sample+1)).'</th>'); }
14313:     $r->print(&end_data_table_header_row());
14314:     foreach my $hash (@$samples) {
14315: 	$r->print(&start_data_table_row());
14316: 	foreach my $sample (sort({$a <=> $b} keys(%{ $samples->[0] }))) {
14317: 	    $r->print('<td>');
14318: 	    if (defined($$hash{$sample})) { $r->print($$hash{$sample}); }
14319: 	    $r->print('</td>');
14320: 	}
14321: 	$r->print(&end_data_table_row());
14322:     }
14323:     $r->print(&end_data_table().'<br />'."\n");
14324: }
14325: 
14326: ######################################################
14327: ######################################################
14328: 
14329: =pod
14330: 
14331: =item * &csv_print_select_table($r,$records,$d)
14332: 
14333: Prints a table to create associations between values and table columns.
14334: 
14335: $r is an Apache Request ref,
14336: $records is an arrayref from &Apache::loncommon::upfile_record_sep,
14337: $d is an array of 2 element arrays (internal name, displayed name,defaultcol)
14338: 
14339: =cut
14340: 
14341: ######################################################
14342: ######################################################
14343: sub csv_print_select_table {
14344:     my ($r,$records,$d) = @_;
14345:     my $i=0;
14346:     my $samples = &get_samples($records,1);
14347:     $r->print(&mt('Associate columns with student attributes.')."\n".
14348: 	      &start_data_table().&start_data_table_header_row().
14349:               '<th>'.&mt('Attribute').'</th>'.
14350:               '<th>'.&mt('Column').'</th>'.
14351:               &end_data_table_header_row()."\n");
14352:     foreach my $array_ref (@$d) {
14353: 	my ($value,$display,$defaultcol)=@{ $array_ref };
14354: 	$r->print(&start_data_table_row().'<td>'.$display.'</td>');
14355: 
14356: 	$r->print('<td><select name="f'.$i.'"'.
14357: 		  ' onchange="javascript:flip(this.form,'.$i.');">');
14358: 	$r->print('<option value="none"></option>');
14359: 	foreach my $sample (sort({$a <=> $b} keys(%{ $samples->[0] }))) {
14360: 	    $r->print('<option value="'.$sample.'"'.
14361:                       ($sample eq $defaultcol ? ' selected="selected" ' : '').
14362:                       '>'.&mt('Column [_1]',($sample+1)).'</option>');
14363: 	}
14364: 	$r->print('</select></td>'.&end_data_table_row()."\n");
14365: 	$i++;
14366:     }
14367:     $r->print(&end_data_table());
14368:     $i--;
14369:     return $i;
14370: }
14371: 
14372: ######################################################
14373: ######################################################
14374: 
14375: =pod
14376: 
14377: =item * &csv_samples_select_table($r,$records,$d)
14378: 
14379: Prints a table of sample values from the upload and can make associate samples to internal names.
14380: 
14381: $r is an Apache Request ref,
14382: $records is an arrayref from &Apache::loncommon::upfile_record_sep,
14383: $d is an array of 2 element arrays (internal name, displayed name)
14384: 
14385: =cut
14386: 
14387: ######################################################
14388: ######################################################
14389: sub csv_samples_select_table {
14390:     my ($r,$records,$d) = @_;
14391:     my $i=0;
14392:     #
14393:     my $max_samples = 5;
14394:     my $samples = &get_samples($records,$max_samples);
14395:     $r->print(&start_data_table().
14396:               &start_data_table_header_row().'<th>'.
14397:               &mt('Field').'</th><th>'.&mt('Samples').'</th>'.
14398:               &end_data_table_header_row());
14399: 
14400:     foreach my $key (sort(keys(%{ $samples->[0] }))) {
14401: 	$r->print(&start_data_table_row().'<td><select name="f'.$i.'"'.
14402: 		  ' onchange="javascript:flip(this.form,'.$i.');">');
14403: 	foreach my $option (@$d) {
14404: 	    my ($value,$display,$defaultcol)=@{ $option };
14405: 	    $r->print('<option value="'.$value.'"'.
14406:                       ($i eq $defaultcol ? ' selected="selected" ':'').'>'.
14407:                       $display.'</option>');
14408: 	}
14409: 	$r->print('</select></td><td>');
14410: 	foreach my $line (0..($max_samples-1)) {
14411: 	    if (defined($samples->[$line]{$key})) { 
14412: 		$r->print($samples->[$line]{$key}."<br />\n"); 
14413: 	    }
14414: 	}
14415: 	$r->print('</td>'.&end_data_table_row());
14416: 	$i++;
14417:     }
14418:     $r->print(&end_data_table());
14419:     $i--;
14420:     return($i);
14421: }
14422: 
14423: ######################################################
14424: ######################################################
14425: 
14426: =pod
14427: 
14428: =item * &clean_excel_name($name)
14429: 
14430: Returns a replacement for $name which does not contain any illegal characters.
14431: 
14432: =cut
14433: 
14434: ######################################################
14435: ######################################################
14436: sub clean_excel_name {
14437:     my ($name) = @_;
14438:     $name =~ s/[:\*\?\/\\]//g;
14439:     if (length($name) > 31) {
14440:         $name = substr($name,0,31);
14441:     }
14442:     return $name;
14443: }
14444: 
14445: =pod
14446: 
14447: =item * &check_if_partid_hidden($id,$symb,$udom,$uname)
14448: 
14449: Returns either 1 or undef
14450: 
14451: 1 if the part is to be hidden, undef if it is to be shown
14452: 
14453: Arguments are:
14454: 
14455: $id the id of the part to be checked
14456: $symb, optional the symb of the resource to check
14457: $udom, optional the domain of the user to check for
14458: $uname, optional the username of the user to check for
14459: 
14460: =cut
14461: 
14462: sub check_if_partid_hidden {
14463:     my ($id,$symb,$udom,$uname) = @_;
14464:     my $hiddenparts=&Apache::lonnet::EXT('resource.0.hiddenparts',
14465: 					 $symb,$udom,$uname);
14466:     my $truth=1;
14467:     #if the string starts with !, then the list is the list to show not hide
14468:     if ($hiddenparts=~s/^\s*!//) { $truth=undef; }
14469:     my @hiddenlist=split(/,/,$hiddenparts);
14470:     foreach my $checkid (@hiddenlist) {
14471: 	if ($checkid =~ /^\s*\Q$id\E\s*$/) { return $truth; }
14472:     }
14473:     return !$truth;
14474: }
14475: 
14476: 
14477: ############################################################
14478: ############################################################
14479: 
14480: =pod
14481: 
14482: =back 
14483: 
14484: =head1 cgi-bin script and graphing routines
14485: 
14486: =over 4
14487: 
14488: =item * &get_cgi_id()
14489: 
14490: Inputs: none
14491: 
14492: Returns an id which can be used to pass environment variables
14493: to various cgi-bin scripts.  These environment variables will
14494: be removed from the users environment after a given time by
14495: the routine &Apache::lonnet::transfer_profile_to_env.
14496: 
14497: =cut
14498: 
14499: ############################################################
14500: ############################################################
14501: my $uniq=0;
14502: sub get_cgi_id {
14503:     $uniq=($uniq+1)%100000;
14504:     return (time.'_'.$$.'_'.$uniq);
14505: }
14506: 
14507: ############################################################
14508: ############################################################
14509: 
14510: =pod
14511: 
14512: =item * &DrawBarGraph()
14513: 
14514: Facilitates the plotting of data in a (stacked) bar graph.
14515: Puts plot definition data into the users environment in order for 
14516: graph.png to plot it.  Returns an <img> tag for the plot.
14517: The bars on the plot are labeled '1','2',...,'n'.
14518: 
14519: Inputs:
14520: 
14521: =over 4
14522: 
14523: =item $Title: string, the title of the plot
14524: 
14525: =item $xlabel: string, text describing the X-axis of the plot
14526: 
14527: =item $ylabel: string, text describing the Y-axis of the plot
14528: 
14529: =item $Max: scalar, the maximum Y value to use in the plot
14530: If $Max is < any data point, the graph will not be rendered.
14531: 
14532: =item $colors: array ref holding the colors to be used for the data sets when
14533: they are plotted.  If undefined, default values will be used.
14534: 
14535: =item $labels: array ref holding the labels to use on the x-axis for the bars.
14536: 
14537: =item @Values: An array of array references.  Each array reference holds data
14538: to be plotted in a stacked bar chart.
14539: 
14540: =item If the final element of @Values is a hash reference the key/value
14541: pairs will be added to the graph definition.
14542: 
14543: =back
14544: 
14545: Returns:
14546: 
14547: An <img> tag which references graph.png and the appropriate identifying
14548: information for the plot.
14549: 
14550: =cut
14551: 
14552: ############################################################
14553: ############################################################
14554: sub DrawBarGraph {
14555:     my ($Title,$xlabel,$ylabel,$Max,$colors,$labels,@Values)=@_;
14556:     #
14557:     if (! defined($colors)) {
14558:         $colors = ['#33ff00', 
14559:                   '#0033cc', '#990000', '#aaaa66', '#663399', '#ff9933',
14560:                   '#66ccff', '#ff9999', '#cccc33', '#660000', '#33cc66',
14561:                   ]; 
14562:     }
14563:     my $extra_settings = {};
14564:     if (ref($Values[-1]) eq 'HASH') {
14565:         $extra_settings = pop(@Values);
14566:     }
14567:     #
14568:     my $identifier = &get_cgi_id();
14569:     my $id = 'cgi.'.$identifier;        
14570:     if (! @Values || ref($Values[0]) ne 'ARRAY') {
14571:         return '';
14572:     }
14573:     #
14574:     my @Labels;
14575:     if (defined($labels)) {
14576:         @Labels = @$labels;
14577:     } else {
14578:         for (my $i=0;$i<@{$Values[0]};$i++) {
14579:             push(@Labels,$i+1);
14580:         }
14581:     }
14582:     #
14583:     my $NumBars = scalar(@{$Values[0]});
14584:     if ($NumBars < scalar(@Labels)) { $NumBars = scalar(@Labels); }
14585:     my %ValuesHash;
14586:     my $NumSets=1;
14587:     foreach my $array (@Values) {
14588:         next if (! ref($array));
14589:         $ValuesHash{$id.'.data.'.$NumSets++} = 
14590:             join(',',@$array);
14591:     }
14592:     #
14593:     my ($height,$width,$xskip,$bar_width) = (200,120,1,15);
14594:     if ($NumBars < 3) {
14595:         $width = 120+$NumBars*32;
14596:         $xskip = 1;
14597:         $bar_width = 30;
14598:     } elsif ($NumBars < 5) {
14599:         $width = 120+$NumBars*20;
14600:         $xskip = 1;
14601:         $bar_width = 20;
14602:     } elsif ($NumBars < 10) {
14603:         $width = 120+$NumBars*15;
14604:         $xskip = 1;
14605:         $bar_width = 15;
14606:     } elsif ($NumBars <= 25) {
14607:         $width = 120+$NumBars*11;
14608:         $xskip = 5;
14609:         $bar_width = 8;
14610:     } elsif ($NumBars <= 50) {
14611:         $width = 120+$NumBars*8;
14612:         $xskip = 5;
14613:         $bar_width = 4;
14614:     } else {
14615:         $width = 120+$NumBars*8;
14616:         $xskip = 5;
14617:         $bar_width = 4;
14618:     }
14619:     #
14620:     $Max = 1 if ($Max < 1);
14621:     if ( int($Max) < $Max ) {
14622:         $Max++;
14623:         $Max = int($Max);
14624:     }
14625:     $Title  = '' if (! defined($Title));
14626:     $xlabel = '' if (! defined($xlabel));
14627:     $ylabel = '' if (! defined($ylabel));
14628:     $ValuesHash{$id.'.title'}    = &escape($Title);
14629:     $ValuesHash{$id.'.xlabel'}   = &escape($xlabel);
14630:     $ValuesHash{$id.'.ylabel'}   = &escape($ylabel);
14631:     $ValuesHash{$id.'.y_max_value'} = $Max;
14632:     $ValuesHash{$id.'.NumBars'}  = $NumBars;
14633:     $ValuesHash{$id.'.NumSets'}  = $NumSets;
14634:     $ValuesHash{$id.'.PlotType'} = 'bar';
14635:     $ValuesHash{$id.'.Colors'}   = join(',',@{$colors});
14636:     $ValuesHash{$id.'.height'}   = $height;
14637:     $ValuesHash{$id.'.width'}    = $width;
14638:     $ValuesHash{$id.'.xskip'}    = $xskip;
14639:     $ValuesHash{$id.'.bar_width'} = $bar_width;
14640:     $ValuesHash{$id.'.labels'} = join(',',@Labels);
14641:     #
14642:     # Deal with other parameters
14643:     while (my ($key,$value) = each(%$extra_settings)) {
14644:         $ValuesHash{$id.'.'.$key} = $value;
14645:     }
14646:     #
14647:     &Apache::lonnet::appenv(\%ValuesHash);
14648:     return '<img src="/cgi-bin/graph.png?'.$identifier.'" border="1" />';
14649: }
14650: 
14651: ############################################################
14652: ############################################################
14653: 
14654: =pod
14655: 
14656: =item * &DrawXYGraph()
14657: 
14658: Facilitates the plotting of data in an XY graph.
14659: Puts plot definition data into the users environment in order for 
14660: graph.png to plot it.  Returns an <img> tag for the plot.
14661: 
14662: Inputs:
14663: 
14664: =over 4
14665: 
14666: =item $Title: string, the title of the plot
14667: 
14668: =item $xlabel: string, text describing the X-axis of the plot
14669: 
14670: =item $ylabel: string, text describing the Y-axis of the plot
14671: 
14672: =item $Max: scalar, the maximum Y value to use in the plot
14673: If $Max is < any data point, the graph will not be rendered.
14674: 
14675: =item $colors: Array ref containing the hex color codes for the data to be 
14676: plotted in.  If undefined, default values will be used.
14677: 
14678: =item $Xlabels: Array ref containing the labels to be used for the X-axis.
14679: 
14680: =item $Ydata: Array ref containing Array refs.  
14681: Each of the contained arrays will be plotted as a separate curve.
14682: 
14683: =item %Values: hash indicating or overriding any default values which are 
14684: passed to graph.png.  
14685: Possible values are: width, xskip, x_ticks, x_tick_offset, among others.
14686: 
14687: =back
14688: 
14689: Returns:
14690: 
14691: An <img> tag which references graph.png and the appropriate identifying
14692: information for the plot.
14693: 
14694: =cut
14695: 
14696: ############################################################
14697: ############################################################
14698: sub DrawXYGraph {
14699:     my ($Title,$xlabel,$ylabel,$Max,$colors,$Xlabels,$Ydata,%Values)=@_;
14700:     #
14701:     # Create the identifier for the graph
14702:     my $identifier = &get_cgi_id();
14703:     my $id = 'cgi.'.$identifier;
14704:     #
14705:     $Title  = '' if (! defined($Title));
14706:     $xlabel = '' if (! defined($xlabel));
14707:     $ylabel = '' if (! defined($ylabel));
14708:     my %ValuesHash = 
14709:         (
14710:          $id.'.title'  => &escape($Title),
14711:          $id.'.xlabel' => &escape($xlabel),
14712:          $id.'.ylabel' => &escape($ylabel),
14713:          $id.'.y_max_value'=> $Max,
14714:          $id.'.labels'     => join(',',@$Xlabels),
14715:          $id.'.PlotType'   => 'XY',
14716:          );
14717:     #
14718:     if (defined($colors) && ref($colors) eq 'ARRAY') {
14719:         $ValuesHash{$id.'.Colors'}   = join(',',@{$colors});
14720:     }
14721:     #
14722:     if (! ref($Ydata) || ref($Ydata) ne 'ARRAY') {
14723:         return '';
14724:     }
14725:     my $NumSets=1;
14726:     foreach my $array (@{$Ydata}){
14727:         next if (! ref($array));
14728:         $ValuesHash{$id.'.data.'.$NumSets++} = join(',',@$array);
14729:     }
14730:     $ValuesHash{$id.'.NumSets'} = $NumSets-1;
14731:     #
14732:     # Deal with other parameters
14733:     while (my ($key,$value) = each(%Values)) {
14734:         $ValuesHash{$id.'.'.$key} = $value;
14735:     }
14736:     #
14737:     &Apache::lonnet::appenv(\%ValuesHash);
14738:     return '<img src="/cgi-bin/graph.png?'.$identifier.'" border="1" />';
14739: }
14740: 
14741: ############################################################
14742: ############################################################
14743: 
14744: =pod
14745: 
14746: =item * &DrawXYYGraph()
14747: 
14748: Facilitates the plotting of data in an XY graph with two Y axes.
14749: Puts plot definition data into the users environment in order for 
14750: graph.png to plot it.  Returns an <img> tag for the plot.
14751: 
14752: Inputs:
14753: 
14754: =over 4
14755: 
14756: =item $Title: string, the title of the plot
14757: 
14758: =item $xlabel: string, text describing the X-axis of the plot
14759: 
14760: =item $ylabel: string, text describing the Y-axis of the plot
14761: 
14762: =item $colors: Array ref containing the hex color codes for the data to be 
14763: plotted in.  If undefined, default values will be used.
14764: 
14765: =item $Xlabels: Array ref containing the labels to be used for the X-axis.
14766: 
14767: =item $Ydata1: The first data set
14768: 
14769: =item $Min1: The minimum value of the left Y-axis
14770: 
14771: =item $Max1: The maximum value of the left Y-axis
14772: 
14773: =item $Ydata2: The second data set
14774: 
14775: =item $Min2: The minimum value of the right Y-axis
14776: 
14777: =item $Max2: The maximum value of the left Y-axis
14778: 
14779: =item %Values: hash indicating or overriding any default values which are 
14780: passed to graph.png.  
14781: Possible values are: width, xskip, x_ticks, x_tick_offset, among others.
14782: 
14783: =back
14784: 
14785: Returns:
14786: 
14787: An <img> tag which references graph.png and the appropriate identifying
14788: information for the plot.
14789: 
14790: =cut
14791: 
14792: ############################################################
14793: ############################################################
14794: sub DrawXYYGraph {
14795:     my ($Title,$xlabel,$ylabel,$colors,$Xlabels,$Ydata1,$Min1,$Max1,
14796:                                         $Ydata2,$Min2,$Max2,%Values)=@_;
14797:     #
14798:     # Create the identifier for the graph
14799:     my $identifier = &get_cgi_id();
14800:     my $id = 'cgi.'.$identifier;
14801:     #
14802:     $Title  = '' if (! defined($Title));
14803:     $xlabel = '' if (! defined($xlabel));
14804:     $ylabel = '' if (! defined($ylabel));
14805:     my %ValuesHash = 
14806:         (
14807:          $id.'.title'  => &escape($Title),
14808:          $id.'.xlabel' => &escape($xlabel),
14809:          $id.'.ylabel' => &escape($ylabel),
14810:          $id.'.labels' => join(',',@$Xlabels),
14811:          $id.'.PlotType' => 'XY',
14812:          $id.'.NumSets' => 2,
14813:          $id.'.two_axes' => 1,
14814:          $id.'.y1_max_value' => $Max1,
14815:          $id.'.y1_min_value' => $Min1,
14816:          $id.'.y2_max_value' => $Max2,
14817:          $id.'.y2_min_value' => $Min2,
14818:          );
14819:     #
14820:     if (defined($colors) && ref($colors) eq 'ARRAY') {
14821:         $ValuesHash{$id.'.Colors'}   = join(',',@{$colors});
14822:     }
14823:     #
14824:     if (! ref($Ydata1) || ref($Ydata1) ne 'ARRAY' ||
14825:         ! ref($Ydata2) || ref($Ydata2) ne 'ARRAY'){
14826:         return '';
14827:     }
14828:     my $NumSets=1;
14829:     foreach my $array ($Ydata1,$Ydata2){
14830:         next if (! ref($array));
14831:         $ValuesHash{$id.'.data.'.$NumSets++} = join(',',@$array);
14832:     }
14833:     #
14834:     # Deal with other parameters
14835:     while (my ($key,$value) = each(%Values)) {
14836:         $ValuesHash{$id.'.'.$key} = $value;
14837:     }
14838:     #
14839:     &Apache::lonnet::appenv(\%ValuesHash);
14840:     return '<img src="/cgi-bin/graph.png?'.$identifier.'" border="1" />';
14841: }
14842: 
14843: ############################################################
14844: ############################################################
14845: 
14846: =pod
14847: 
14848: =back 
14849: 
14850: =head1 Statistics helper routines?  
14851: 
14852: Bad place for them but what the hell.
14853: 
14854: =over 4
14855: 
14856: =item * &chartlink()
14857: 
14858: Returns a link to the chart for a specific student.  
14859: 
14860: Inputs:
14861: 
14862: =over 4
14863: 
14864: =item $linktext: The text of the link
14865: 
14866: =item $sname: The students username
14867: 
14868: =item $sdomain: The students domain
14869: 
14870: =back
14871: 
14872: =back
14873: 
14874: =cut
14875: 
14876: ############################################################
14877: ############################################################
14878: sub chartlink {
14879:     my ($linktext, $sname, $sdomain) = @_;
14880:     my $link = '<a href="/adm/statistics?reportSelected=student_assessment'.
14881:         '&amp;SelectedStudent='.&escape($sname.':'.$sdomain).
14882:         '&amp;chartoutputmode='.HTML::Entities::encode('html, with all links').
14883:        '">'.$linktext.'</a>';
14884: }
14885: 
14886: #######################################################
14887: #######################################################
14888: 
14889: =pod
14890: 
14891: =head1 Course Environment Routines
14892: 
14893: =over 4
14894: 
14895: =item * &restore_course_settings()
14896: 
14897: =item * &store_course_settings()
14898: 
14899: Restores/Store indicated form parameters from the course environment.
14900: Will not overwrite existing values of the form parameters.
14901: 
14902: Inputs: 
14903: a scalar describing the data (e.g. 'chart', 'problem_analysis')
14904: 
14905: a hash ref describing the data to be stored.  For example:
14906:    
14907: %Save_Parameters = ('Status' => 'scalar',
14908:     'chartoutputmode' => 'scalar',
14909:     'chartoutputdata' => 'scalar',
14910:     'Section' => 'array',
14911:     'Group' => 'array',
14912:     'StudentData' => 'array',
14913:     'Maps' => 'array');
14914: 
14915: Returns: both routines return nothing
14916: 
14917: =back
14918: 
14919: =cut
14920: 
14921: #######################################################
14922: #######################################################
14923: sub store_course_settings {
14924:     return &store_settings($env{'request.course.id'},@_);
14925: }
14926: 
14927: sub store_settings {
14928:     # save to the environment
14929:     # appenv the same items, just to be safe
14930:     my $udom  = $env{'user.domain'};
14931:     my $uname = $env{'user.name'};
14932:     my ($context,$prefix,$Settings) = @_;
14933:     my %SaveHash;
14934:     my %AppHash;
14935:     while (my ($setting,$type) = each(%$Settings)) {
14936:         my $basename = join('.','internal',$context,$prefix,$setting);
14937:         my $envname = 'environment.'.$basename;
14938:         if (exists($env{'form.'.$setting})) {
14939:             # Save this value away
14940:             if ($type eq 'scalar' &&
14941:                 (! exists($env{$envname}) || 
14942:                  $env{$envname} ne $env{'form.'.$setting})) {
14943:                 $SaveHash{$basename} = $env{'form.'.$setting};
14944:                 $AppHash{$envname}   = $env{'form.'.$setting};
14945:             } elsif ($type eq 'array') {
14946:                 my $stored_form;
14947:                 if (ref($env{'form.'.$setting})) {
14948:                     $stored_form = join(',',
14949:                                         map {
14950:                                             &escape($_);
14951:                                         } sort(@{$env{'form.'.$setting}}));
14952:                 } else {
14953:                     $stored_form = 
14954:                         &escape($env{'form.'.$setting});
14955:                 }
14956:                 # Determine if the array contents are the same.
14957:                 if ($stored_form ne $env{$envname}) {
14958:                     $SaveHash{$basename} = $stored_form;
14959:                     $AppHash{$envname}   = $stored_form;
14960:                 }
14961:             }
14962:         }
14963:     }
14964:     my $put_result = &Apache::lonnet::put('environment',\%SaveHash,
14965:                                           $udom,$uname);
14966:     if ($put_result !~ /^(ok|delayed)/) {
14967:         &Apache::lonnet::logthis('unable to save form parameters, '.
14968:                                  'got error:'.$put_result);
14969:     }
14970:     # Make sure these settings stick around in this session, too
14971:     &Apache::lonnet::appenv(\%AppHash);
14972:     return;
14973: }
14974: 
14975: sub restore_course_settings {
14976:     return &restore_settings($env{'request.course.id'},@_);
14977: }
14978: 
14979: sub restore_settings {
14980:     my ($context,$prefix,$Settings) = @_;
14981:     while (my ($setting,$type) = each(%$Settings)) {
14982:         next if (exists($env{'form.'.$setting}));
14983:         my $envname = 'environment.internal.'.$context.'.'.$prefix.
14984:             '.'.$setting;
14985:         if (exists($env{$envname})) {
14986:             if ($type eq 'scalar') {
14987:                 $env{'form.'.$setting} = $env{$envname};
14988:             } elsif ($type eq 'array') {
14989:                 $env{'form.'.$setting} = [ 
14990:                                            map { 
14991:                                                &unescape($_); 
14992:                                            } split(',',$env{$envname})
14993:                                            ];
14994:             }
14995:         }
14996:     }
14997: }
14998: 
14999: #######################################################
15000: #######################################################
15001: 
15002: =pod
15003: 
15004: =head1 Domain E-mail Routines  
15005: 
15006: =over 4
15007: 
15008: =item * &build_recipient_list()
15009: 
15010: Build recipient lists for following types of e-mail:
15011: (a) Error Reports, (b) Package Updates, (c) lonstatus warnings/errors
15012: (d) Help requests, (e) Course requests needing approval, (f) loncapa
15013: module change checking, student/employee ID conflict checks, as
15014: generated by lonerrorhandler.pm, CHECKRPMS, loncron,
15015: lonsupportreq.pm, loncoursequeueadmin.pm, searchcat.pl respectively.
15016: 
15017: Inputs:
15018: defmail (scalar - email address of default recipient),
15019: mailing type (scalar: errormail, packagesmail, helpdeskmail,
15020: requestsmail, updatesmail, or idconflictsmail).
15021: 
15022: defdom (domain for which to retrieve configuration settings),
15023: 
15024: origmail (scalar - email address of recipient from loncapa.conf,
15025: i.e., predates configuration by DC via domainprefs.pm
15026: 
15027: $requname username of requester (if mailing type is helpdeskmail)
15028: 
15029: $requdom domain of requester (if mailing type is helpdeskmail)
15030: 
15031: $reqemail e-mail address of requester (if mailing type is helpdeskmail)
15032: 
15033: Returns: comma separated list of addresses to which to send e-mail.
15034: 
15035: =back
15036: 
15037: =cut
15038: 
15039: ############################################################
15040: ############################################################
15041: sub build_recipient_list {
15042:     my ($defmail,$mailing,$defdom,$origmail,$requname,$requdom,$reqemail) = @_;
15043:     my @recipients;
15044:     my ($otheremails,$lastresort,$allbcc,$addtext);
15045:     my %domconfig =
15046:         &Apache::lonnet::get_dom('configuration',['contacts'],$defdom);
15047:     if (ref($domconfig{'contacts'}) eq 'HASH') {
15048:         if (exists($domconfig{'contacts'}{$mailing})) {
15049:             if (ref($domconfig{'contacts'}{$mailing}) eq 'HASH') {
15050:                 my @contacts = ('adminemail','supportemail');
15051:                 foreach my $item (@contacts) {
15052:                     if ($domconfig{'contacts'}{$mailing}{$item}) {
15053:                         my $addr = $domconfig{'contacts'}{$item}; 
15054:                         if (!grep(/^\Q$addr\E$/,@recipients)) {
15055:                             push(@recipients,$addr);
15056:                         }
15057:                     }
15058:                 }
15059:                 $otheremails = $domconfig{'contacts'}{$mailing}{'others'};
15060:                 if ($mailing eq 'helpdeskmail') {
15061:                     if ($domconfig{'contacts'}{$mailing}{'bcc'}) {
15062:                         my @bccs = split(/,/,$domconfig{'contacts'}{$mailing}{'bcc'});
15063:                         my @ok_bccs;
15064:                         foreach my $bcc (@bccs) {
15065:                             $bcc =~ s/^\s+//g;
15066:                             $bcc =~ s/\s+$//g;
15067:                             if ($bcc =~ m/^[^\@]+\@[^\@]+$/) {
15068:                                 if (!(grep(/^\Q$bcc\E$/,@ok_bccs))) {
15069:                                     push(@ok_bccs,$bcc);
15070:                                 }
15071:                             }
15072:                         }
15073:                         if (@ok_bccs > 0) {
15074:                             $allbcc = join(', ',@ok_bccs);
15075:                         }
15076:                     }
15077:                     $addtext = $domconfig{'contacts'}{$mailing}{'include'};
15078:                 }
15079:             }
15080:         } elsif ($origmail ne '') {
15081:             $lastresort = $origmail;
15082:         }
15083:         if ($mailing eq 'helpdeskmail') {
15084:             if ((ref($domconfig{'contacts'}{'overrides'}) eq 'HASH') &&
15085:                 (keys(%{$domconfig{'contacts'}{'overrides'}}))) {
15086:                 my ($inststatus,$inststatus_checked);
15087:                 if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '') &&
15088:                     ($env{'user.domain'} ne 'public')) {
15089:                     $inststatus_checked = 1;
15090:                     $inststatus = $env{'environment.inststatus'};
15091:                 }
15092:                 unless ($inststatus_checked) {
15093:                     if (($requname ne '') && ($requdom ne '')) {
15094:                         if (($requname =~ /^$match_username$/) &&
15095:                             ($requdom =~ /^$match_domain$/) &&
15096:                             (&Apache::lonnet::domain($requdom))) {
15097:                             my $requhome = &Apache::lonnet::homeserver($requname,
15098:                                                                       $requdom);
15099:                             unless ($requhome eq 'no_host') {
15100:                                 my %userenv = &Apache::lonnet::userenvironment($requdom,$requname,'inststatus');
15101:                                 $inststatus = $userenv{'inststatus'};
15102:                                 $inststatus_checked = 1;
15103:                             }
15104:                         }
15105:                     }
15106:                 }
15107:                 unless ($inststatus_checked) {
15108:                     if ($reqemail =~ /^[^\@]+\@[^\@]+$/) {
15109:                         my %srch = (srchby     => 'email',
15110:                                     srchdomain => $defdom,
15111:                                     srchterm   => $reqemail,
15112:                                     srchtype   => 'exact');
15113:                         my %srch_results = &Apache::lonnet::usersearch(\%srch);
15114:                         foreach my $uname (keys(%srch_results)) {
15115:                             if (ref($srch_results{$uname}{'inststatus'}) eq 'ARRAY') {
15116:                                 $inststatus = join(',',@{$srch_results{$uname}{'inststatus'}});
15117:                                 $inststatus_checked = 1;
15118:                                 last;
15119:                             }
15120:                         }
15121:                         unless ($inststatus_checked) {
15122:                             my ($dirsrchres,%srch_results) = &Apache::lonnet::inst_directory_query(\%srch);
15123:                             if ($dirsrchres eq 'ok') {
15124:                                 foreach my $uname (keys(%srch_results)) {
15125:                                     if (ref($srch_results{$uname}{'inststatus'}) eq 'ARRAY') {
15126:                                         $inststatus = join(',',@{$srch_results{$uname}{'inststatus'}});
15127:                                         $inststatus_checked = 1;
15128:                                         last;
15129:                                     }
15130:                                 }
15131:                             }
15132:                         }
15133:                     }
15134:                 }
15135:                 if ($inststatus ne '') {
15136:                     foreach my $status (split(/\:/,$inststatus)) {
15137:                         if (ref($domconfig{'contacts'}{'overrides'}{$status}) eq 'HASH') {
15138:                             my @contacts = ('adminemail','supportemail');
15139:                             foreach my $item (@contacts) {
15140:                                 if ($domconfig{'contacts'}{'overrides'}{$status}{$item}) {
15141:                                     my $addr = $domconfig{'contacts'}{'overrides'}{$status};
15142:                                     if (!grep(/^\Q$addr\E$/,@recipients)) {
15143:                                         push(@recipients,$addr);
15144:                                     }
15145:                                 }
15146:                             }
15147:                             $otheremails = $domconfig{'contacts'}{'overrides'}{$status}{'others'};
15148:                             if ($domconfig{'contacts'}{'overrides'}{$status}{'bcc'}) {
15149:                                 my @bccs = split(/,/,$domconfig{'contacts'}{'overrides'}{$status}{'bcc'});
15150:                                 my @ok_bccs;
15151:                                 foreach my $bcc (@bccs) {
15152:                                     $bcc =~ s/^\s+//g;
15153:                                     $bcc =~ s/\s+$//g;
15154:                                     if ($bcc =~ m/^[^\@]+\@[^\@]+$/) {
15155:                                         if (!(grep(/^\Q$bcc\E$/,@ok_bccs))) {
15156:                                             push(@ok_bccs,$bcc);
15157:                                         }
15158:                                     }
15159:                                 }
15160:                                 if (@ok_bccs > 0) {
15161:                                     $allbcc = join(', ',@ok_bccs);
15162:                                 }
15163:                             }
15164:                             $addtext = $domconfig{'contacts'}{'overrides'}{$status}{'include'};
15165:                             last;
15166:                         }
15167:                     }
15168:                 }
15169:             }
15170:         }
15171:     } elsif ($origmail ne '') {
15172:         $lastresort = $origmail;
15173:     }
15174:     if (($mailing eq 'helpdeskmail') && ($lastresort ne '')) {
15175:         unless (grep(/^\Q$defdom\E$/,&Apache::lonnet::current_machine_domains())) {
15176:             my $lonhost = $Apache::lonnet::perlvar{'lonHostID'};
15177:             my $machinedom = $Apache::lonnet::perlvar{'lonDefDomain'};
15178:             my %what = (
15179:                           perlvar => 1,
15180:                        );
15181:             my $primary = &Apache::lonnet::domain($defdom,'primary');
15182:             if ($primary) {
15183:                 my $gotaddr;
15184:                 my ($result,$returnhash) =
15185:                     &Apache::lonnet::get_remote_globals($primary,{ perlvar => 1 });
15186:                 if (($result eq 'ok') && (ref($returnhash) eq 'HASH')) {
15187:                     if ($returnhash->{'lonSupportEMail'} =~ /^[^\@]+\@[^\@]+$/) {
15188:                         $lastresort = $returnhash->{'lonSupportEMail'};
15189:                         $gotaddr = 1;
15190:                     }
15191:                 }
15192:                 unless ($gotaddr) {
15193:                     my $uintdom = &Apache::lonnet::internet_dom($primary);
15194:                     my $intdom = &Apache::lonnet::internet_dom($lonhost);
15195:                     unless ($uintdom eq $intdom) {
15196:                         my %domconfig =
15197:                             &Apache::lonnet::get_dom('configuration',['contacts'],$machinedom);
15198:                         if (ref($domconfig{'contacts'}) eq 'HASH') {
15199:                             if (ref($domconfig{'contacts'}{'otherdomsmail'}) eq 'HASH') {
15200:                                 my @contacts = ('adminemail','supportemail');
15201:                                 foreach my $item (@contacts) {
15202:                                     if ($domconfig{'contacts'}{'otherdomsmail'}{$item}) {
15203:                                         my $addr = $domconfig{'contacts'}{$item};
15204:                                         if (!grep(/^\Q$addr\E$/,@recipients)) {
15205:                                             push(@recipients,$addr);
15206:                                         }
15207:                                     }
15208:                                 }
15209:                                 if ($domconfig{'contacts'}{'otherdomsmail'}{'others'}) {
15210:                                     $otheremails = $domconfig{'contacts'}{'otherdomsmail'}{'others'};
15211:                                 }
15212:                                 if ($domconfig{'contacts'}{'otherdomsmail'}{'bcc'}) {
15213:                                     my @bccs = split(/,/,$domconfig{'contacts'}{'otherdomsmail'}{'bcc'});
15214:                                     my @ok_bccs;
15215:                                     foreach my $bcc (@bccs) {
15216:                                         $bcc =~ s/^\s+//g;
15217:                                         $bcc =~ s/\s+$//g;
15218:                                         if ($bcc =~ m/^[^\@]+\@[^\@]+$/) {
15219:                                             if (!(grep(/^\Q$bcc\E$/,@ok_bccs))) {
15220:                                                 push(@ok_bccs,$bcc);
15221:                                             }
15222:                                         }
15223:                                     }
15224:                                     if (@ok_bccs > 0) {
15225:                                         $allbcc = join(', ',@ok_bccs);
15226:                                     }
15227:                                 }
15228:                                 $addtext = $domconfig{'contacts'}{'otherdomsmail'}{'include'};
15229:                             }
15230:                         }
15231:                     }
15232:                 }
15233:             }
15234:         }
15235:     }
15236:     if (defined($defmail)) {
15237:         if ($defmail ne '') {
15238:             push(@recipients,$defmail);
15239:         }
15240:     }
15241:     if ($otheremails) {
15242:         my @others;
15243:         if ($otheremails =~ /,/) {
15244:             @others = split(/,/,$otheremails);
15245:         } else {
15246:             push(@others,$otheremails);
15247:         }
15248:         foreach my $addr (@others) {
15249:             if (!grep(/^\Q$addr\E$/,@recipients)) {
15250:                 push(@recipients,$addr);
15251:             }
15252:         }
15253:     }
15254:     if ($mailing eq 'helpdeskmail') {
15255:         if ((!@recipients) && ($lastresort ne '')) {
15256:             push(@recipients,$lastresort);
15257:         }
15258:     } elsif ($lastresort ne '') {
15259:         if (!grep(/^\Q$lastresort\E$/,@recipients)) {
15260:             push(@recipients,$lastresort);
15261:         }
15262:     }
15263:     my $recipientlist = join(',',@recipients);
15264:     if (wantarray) {
15265:         return ($recipientlist,$allbcc,$addtext);
15266:     } else {
15267:         return $recipientlist;
15268:     }
15269: }
15270: 
15271: ############################################################
15272: ############################################################
15273: 
15274: =pod
15275: 
15276: =head1 Course Catalog Routines
15277: 
15278: =over 4
15279: 
15280: =item * &gather_categories()
15281: 
15282: Converts category definitions - keys of categories hash stored in  
15283: coursecategories in configuration.db on the primary library server in a 
15284: domain - to an array.  Also generates javascript and idx hash used to 
15285: generate Domain Coordinator interface for editing Course Categories.
15286: 
15287: Inputs:
15288: 
15289: categories (reference to hash of category definitions).
15290: 
15291: cats (reference to array of arrays/hashes which encapsulates hierarchy of
15292:       categories and subcategories).
15293: 
15294: idx (reference to hash of counters used in Domain Coordinator interface for 
15295:       editing Course Categories).
15296: 
15297: jsarray (reference to array of categories used to create Javascript arrays for
15298:          Domain Coordinator interface for editing Course Categories).
15299: 
15300: Returns: nothing
15301: 
15302: Side effects: populates cats, idx and jsarray. 
15303: 
15304: =cut
15305: 
15306: sub gather_categories {
15307:     my ($categories,$cats,$idx,$jsarray) = @_;
15308:     my %counters;
15309:     my $num = 0;
15310:     foreach my $item (keys(%{$categories})) {
15311:         my ($cat,$container,$depth) = map { &unescape($_); } split(/:/,$item);
15312:         if ($container eq '' && $depth == 0) {
15313:             $cats->[$depth][$categories->{$item}] = $cat;
15314:         } else {
15315:             $cats->[$depth]{$container}[$categories->{$item}] = $cat;
15316:         }
15317:         my ($escitem,$tail) = split(/:/,$item,2);
15318:         if ($counters{$tail} eq '') {
15319:             $counters{$tail} = $num;
15320:             $num ++;
15321:         }
15322:         if (ref($idx) eq 'HASH') {
15323:             $idx->{$item} = $counters{$tail};
15324:         }
15325:         if (ref($jsarray) eq 'ARRAY') {
15326:             push(@{$jsarray->[$counters{$tail}]},$item);
15327:         }
15328:     }
15329:     return;
15330: }
15331: 
15332: =pod
15333: 
15334: =item * &extract_categories()
15335: 
15336: Used to generate breadcrumb trails for course categories.
15337: 
15338: Inputs:
15339: 
15340: categories (reference to hash of category definitions).
15341: 
15342: cats (reference to array of arrays/hashes which encapsulates hierarchy of
15343:       categories and subcategories).
15344: 
15345: trails (reference to array of breacrumb trails for each category).
15346: 
15347: allitems (reference to hash - key is category key 
15348:          (format: escaped(name):escaped(parent category):depth in hierarchy).
15349: 
15350: idx (reference to hash of counters used in Domain Coordinator interface for
15351:       editing Course Categories).
15352: 
15353: jsarray (reference to array of categories used to create Javascript arrays for
15354:          Domain Coordinator interface for editing Course Categories).
15355: 
15356: subcats (reference to hash of arrays containing all subcategories within each 
15357:          category, -recursive)
15358: 
15359: maxd (reference to hash used to hold max depth for all top-level categories).
15360: 
15361: Returns: nothing
15362: 
15363: Side effects: populates trails and allitems hash references.
15364: 
15365: =cut
15366: 
15367: sub extract_categories {
15368:     my ($categories,$cats,$trails,$allitems,$idx,$jsarray,$subcats,$maxd) = @_;
15369:     if (ref($categories) eq 'HASH') {
15370:         &gather_categories($categories,$cats,$idx,$jsarray);
15371:         if (ref($cats->[0]) eq 'ARRAY') {
15372:             for (my $i=0; $i<@{$cats->[0]}; $i++) {
15373:                 my $name = $cats->[0][$i];
15374:                 my $item = &escape($name).'::0';
15375:                 my $trailstr;
15376:                 if ($name eq 'instcode') {
15377:                     $trailstr = &mt('Official courses (with institutional codes)');
15378:                 } elsif ($name eq 'communities') {
15379:                     $trailstr = &mt('Communities');
15380:                 } else {
15381:                     $trailstr = $name;
15382:                 }
15383:                 if ($allitems->{$item} eq '') {
15384:                     push(@{$trails},$trailstr);
15385:                     $allitems->{$item} = scalar(@{$trails})-1;
15386:                 }
15387:                 my @parents = ($name);
15388:                 if (ref($cats->[1]{$name}) eq 'ARRAY') {
15389:                     for (my $j=0; $j<@{$cats->[1]{$name}}; $j++) {
15390:                         my $category = $cats->[1]{$name}[$j];
15391:                         if (ref($subcats) eq 'HASH') {
15392:                             push(@{$subcats->{$item}},&escape($category).':'.&escape($name).':1');
15393:                         }
15394:                         &recurse_categories($cats,2,$category,$trails,$allitems,\@parents,$subcats,$maxd);
15395:                     }
15396:                 } else {
15397:                     if (ref($subcats) eq 'HASH') {
15398:                         $subcats->{$item} = [];
15399:                     }
15400:                     if (ref($maxd) eq 'HASH') {
15401:                         $maxd->{$name} = 1;
15402:                     }
15403:                 }
15404:             }
15405:         }
15406:     }
15407:     return;
15408: }
15409: 
15410: =pod
15411: 
15412: =item * &recurse_categories()
15413: 
15414: Recursively used to generate breadcrumb trails for course categories.
15415: 
15416: Inputs:
15417: 
15418: cats (reference to array of arrays/hashes which encapsulates hierarchy of
15419:       categories and subcategories).
15420: 
15421: depth (current depth in hierarchy of categories and sub-categories - 0 indexed).
15422: 
15423: category (current course category, for which breadcrumb trail is being generated).
15424: 
15425: trails (reference to array of breadcrumb trails for each category).
15426: 
15427: allitems (reference to hash - key is category key
15428:          (format: escaped(name):escaped(parent category):depth in hierarchy).
15429: 
15430: parents (array containing containers directories for current category, 
15431:          back to top level). 
15432: 
15433: Returns: nothing
15434: 
15435: Side effects: populates trails and allitems hash references
15436: 
15437: =cut
15438: 
15439: sub recurse_categories {
15440:     my ($cats,$depth,$category,$trails,$allitems,$parents,$subcats,$maxd) = @_;
15441:     my $shallower = $depth - 1;
15442:     if (ref($cats->[$depth]{$category}) eq 'ARRAY') {
15443:         for (my $k=0; $k<@{$cats->[$depth]{$category}}; $k++) {
15444:             my $name = $cats->[$depth]{$category}[$k];
15445:             my $item = &escape($category).':'.&escape($parents->[-1]).':'.$shallower;
15446:             my $trailstr = join(' &raquo; ',(@{$parents},$category));
15447:             if ($allitems->{$item} eq '') {
15448:                 push(@{$trails},$trailstr);
15449:                 $allitems->{$item} = scalar(@{$trails})-1;
15450:             }
15451:             my $deeper = $depth+1;
15452:             push(@{$parents},$category);
15453:             if (ref($subcats) eq 'HASH') {
15454:                 my $subcat = &escape($name).':'.$category.':'.$depth;
15455:                 for (my $j=@{$parents}; $j>=0; $j--) {
15456:                     my $higher;
15457:                     if ($j > 0) {
15458:                         $higher = &escape($parents->[$j]).':'.
15459:                                   &escape($parents->[$j-1]).':'.$j;
15460:                     } else {
15461:                         $higher = &escape($parents->[$j]).'::'.$j;
15462:                     }
15463:                     push(@{$subcats->{$higher}},$subcat);
15464:                 }
15465:             }
15466:             &recurse_categories($cats,$deeper,$name,$trails,$allitems,$parents,
15467:                                 $subcats,$maxd);
15468:             pop(@{$parents});
15469:         }
15470:     } else {
15471:         my $item = &escape($category).':'.&escape($parents->[-1]).':'.$shallower;
15472:         my $trailstr = join(' &raquo; ',(@{$parents},$category));
15473:         if ($allitems->{$item} eq '') {
15474:             push(@{$trails},$trailstr);
15475:             $allitems->{$item} = scalar(@{$trails})-1;
15476:         }
15477:         if (ref($maxd) eq 'HASH') {
15478:             if ($depth > $maxd->{$parents->[0]}) {
15479:                 $maxd->{$parents->[0]} = $depth;
15480:             }
15481:         }
15482:     }
15483:     return;
15484: }
15485: 
15486: =pod
15487: 
15488: =item * &assign_categories_table()
15489: 
15490: Create a datatable for display of hierarchical categories in a domain,
15491: with checkboxes to allow a course to be categorized. 
15492: 
15493: Inputs:
15494: 
15495: cathash - reference to hash of categories defined for the domain (from
15496:           configuration.db)
15497: 
15498: currcat - scalar with an & separated list of categories assigned to a course. 
15499: 
15500: type    - scalar contains course type (Course or Community).
15501: 
15502: disabled - scalar (optional) contains disabled="disabled" if input elements are
15503:            to be readonly (e.g., Domain Helpdesk role viewing course settings).
15504: 
15505: Returns: $output (markup to be displayed) 
15506: 
15507: =cut
15508: 
15509: sub assign_categories_table {
15510:     my ($cathash,$currcat,$type,$disabled) = @_;
15511:     my $output;
15512:     if (ref($cathash) eq 'HASH') {
15513:         my (@cats,@trails,%allitems,%idx,@jsarray,%maxd,@path,$maxdepth);
15514:         &extract_categories($cathash,\@cats,\@trails,\%allitems,\%idx,\@jsarray,\%maxd);
15515:         $maxdepth = scalar(@cats);
15516:         if (@cats > 0) {
15517:             my $itemcount = 0;
15518:             if (ref($cats[0]) eq 'ARRAY') {
15519:                 my @currcategories;
15520:                 if ($currcat ne '') {
15521:                     @currcategories = split('&',$currcat);
15522:                 }
15523:                 my $table;
15524:                 for (my $i=0; $i<@{$cats[0]}; $i++) {
15525:                     my $parent = $cats[0][$i];
15526:                     next if ($parent eq 'instcode');
15527:                     if ($type eq 'Community') {
15528:                         next unless ($parent eq 'communities');
15529:                     } else {
15530:                         next if ($parent eq 'communities');
15531:                     }
15532:                     my $css_class = $itemcount%2?' class="LC_odd_row"':'';
15533:                     my $item = &escape($parent).'::0';
15534:                     my $checked = '';
15535:                     if (@currcategories > 0) {
15536:                         if (grep(/^\Q$item\E$/,@currcategories)) {
15537:                             $checked = ' checked="checked"';
15538:                         }
15539:                     }
15540:                     my $parent_title = $parent;
15541:                     if ($parent eq 'communities') {
15542:                         $parent_title = &mt('Communities');
15543:                     }
15544:                     $table .= '<tr '.$css_class.'><td><span class="LC_nobreak">'.
15545:                               '<input type="checkbox" name="usecategory" value="'.
15546:                               $item.'"'.$checked.$disabled.' />'.$parent_title.'</span>'.
15547:                               '<input type="hidden" name="catname" value="'.$parent.'" /></td>';
15548:                     my $depth = 1;
15549:                     push(@path,$parent);
15550:                     $table .= &assign_category_rows($itemcount,\@cats,$depth,$parent,\@path,\@currcategories,$disabled);
15551:                     pop(@path);
15552:                     $table .= '</tr><tr><td colspan="'.$maxdepth.'" class="LC_row_separator"></td></tr>';
15553:                     $itemcount ++;
15554:                 }
15555:                 if ($itemcount) {
15556:                     $output = &Apache::loncommon::start_data_table().
15557:                               $table.
15558:                               &Apache::loncommon::end_data_table();
15559:                 }
15560:             }
15561:         }
15562:     }
15563:     return $output;
15564: }
15565: 
15566: =pod
15567: 
15568: =item * &assign_category_rows()
15569: 
15570: Create a datatable row for display of nested categories in a domain,
15571: with checkboxes to allow a course to be categorized,called recursively.
15572: 
15573: Inputs:
15574: 
15575: itemcount - track row number for alternating colors
15576: 
15577: cats - reference to array of arrays/hashes which encapsulates hierarchy of
15578:       categories and subcategories.
15579: 
15580: depth - current depth in hierarchy of categories and sub-categories - 0 indexed.
15581: 
15582: parent - parent of current category item
15583: 
15584: path - Array containing all categories back up through the hierarchy from the
15585:        current category to the top level.
15586: 
15587: currcategories - reference to array of current categories assigned to the course
15588: 
15589: disabled - scalar (optional) contains disabled="disabled" if input elements are
15590:            to be readonly (e.g., Domain Helpdesk role viewing course settings).
15591: 
15592: Returns: $output (markup to be displayed).
15593: 
15594: =cut
15595: 
15596: sub assign_category_rows {
15597:     my ($itemcount,$cats,$depth,$parent,$path,$currcategories,$disabled) = @_;
15598:     my ($text,$name,$item,$chgstr);
15599:     if (ref($cats) eq 'ARRAY') {
15600:         my $maxdepth = scalar(@{$cats});
15601:         if (ref($cats->[$depth]) eq 'HASH') {
15602:             if (ref($cats->[$depth]{$parent}) eq 'ARRAY') {
15603:                 my $numchildren = @{$cats->[$depth]{$parent}};
15604:                 my $css_class = $itemcount%2?' class="LC_odd_row"':'';
15605:                 $text .= '<td><table class="LC_data_table">';
15606:                 for (my $j=0; $j<$numchildren; $j++) {
15607:                     $name = $cats->[$depth]{$parent}[$j];
15608:                     $item = &escape($name).':'.&escape($parent).':'.$depth;
15609:                     my $deeper = $depth+1;
15610:                     my $checked = '';
15611:                     if (ref($currcategories) eq 'ARRAY') {
15612:                         if (@{$currcategories} > 0) {
15613:                             if (grep(/^\Q$item\E$/,@{$currcategories})) {
15614:                                 $checked = ' checked="checked"';
15615:                             }
15616:                         }
15617:                     }
15618:                     $text .= '<tr><td><span class="LC_nobreak"><label>'.
15619:                              '<input type="checkbox" name="usecategory" value="'.
15620:                              $item.'"'.$checked.$disabled.' />'.$name.'</label></span>'.
15621:                              '<input type="hidden" name="catname" value="'.$name.'" />'.
15622:                              '</td><td>';
15623:                     if (ref($path) eq 'ARRAY') {
15624:                         push(@{$path},$name);
15625:                         $text .= &assign_category_rows($itemcount,$cats,$deeper,$name,$path,$currcategories,$disabled);
15626:                         pop(@{$path});
15627:                     }
15628:                     $text .= '</td></tr>';
15629:                 }
15630:                 $text .= '</table></td>';
15631:             }
15632:         }
15633:     }
15634:     return $text;
15635: }
15636: 
15637: =pod
15638: 
15639: =back
15640: 
15641: =cut
15642: 
15643: ############################################################
15644: ############################################################
15645: 
15646: 
15647: sub commit_customrole {
15648:     my ($udom,$uname,$url,$three,$four,$five,$start,$end,$context) = @_;
15649:     my $output = &mt('Assigning custom role').' "'.$five.'" by '.$four.':'.$three.' in '.$url.
15650:                          ($start?', '.&mt('starting').' '.localtime($start):'').
15651:                          ($end?', ending '.localtime($end):'').': <b>'.
15652:               &Apache::lonnet::assigncustomrole(
15653:                  $udom,$uname,$url,$three,$four,$five,$end,$start,undef,undef,$context).
15654:                  '</b><br />';
15655:     return $output;
15656: }
15657: 
15658: sub commit_standardrole {
15659:     my ($udom,$uname,$url,$three,$start,$end,$one,$two,$sec,$context,$credits) = @_;
15660:     my ($output,$logmsg,$linefeed);
15661:     if ($context eq 'auto') {
15662:         $linefeed = "\n";
15663:     } else {
15664:         $linefeed = "<br />\n";
15665:     }  
15666:     if ($three eq 'st') {
15667:         my $result = &commit_studentrole(\$logmsg,$udom,$uname,$url,$three,$start,$end,
15668:                                          $one,$two,$sec,$context,$credits);
15669:         if (($result =~ /^error/) || ($result eq 'not_in_class') || 
15670:             ($result eq 'unknown_course') || ($result eq 'refused')) {
15671:             $output = $logmsg.' '.&mt('Error: ').$result."\n"; 
15672:         } else {
15673:             $output = $logmsg.$linefeed.&mt('Assigning').' '.$three.' in '.$url.
15674:                ($start?', '.&mt('starting').' '.localtime($start):'').
15675:                ($end?', '.&mt('ending').' '.localtime($end):'').': ';
15676:             if ($context eq 'auto') {
15677:                 $output .= $result.$linefeed.&mt('Add to classlist').': ok';
15678:             } else {
15679:                $output .= '<b>'.$result.'</b>'.$linefeed.
15680:                &mt('Add to classlist').': <b>ok</b>';
15681:             }
15682:             $output .= $linefeed;
15683:         }
15684:     } else {
15685:         $output = &mt('Assigning').' '.$three.' in '.$url.
15686:                ($start?', '.&mt('starting').' '.localtime($start):'').
15687:                ($end?', '.&mt('ending').' '.localtime($end):'').': ';
15688:         my $result = &Apache::lonnet::assignrole($udom,$uname,$url,$three,$end,$start,'','',$context);
15689:         if ($context eq 'auto') {
15690:             $output .= $result.$linefeed;
15691:         } else {
15692:             $output .= '<b>'.$result.'</b>'.$linefeed;
15693:         }
15694:     }
15695:     return $output;
15696: }
15697: 
15698: sub commit_studentrole {
15699:     my ($logmsg,$udom,$uname,$url,$three,$start,$end,$one,$two,$sec,$context,
15700:         $credits) = @_;
15701:     my ($result,$linefeed,$oldsecurl,$newsecurl);
15702:     if ($context eq 'auto') {
15703:         $linefeed = "\n";
15704:     } else {
15705:         $linefeed = '<br />'."\n";
15706:     }
15707:     if (defined($one) && defined($two)) {
15708:         my $cid=$one.'_'.$two;
15709:         my $oldsec=&Apache::lonnet::getsection($udom,$uname,$cid);
15710:         my $secchange = 0;
15711:         my $expire_role_result;
15712:         my $modify_section_result;
15713:         if ($oldsec ne '-1') { 
15714:             if ($oldsec ne $sec) {
15715:                 $secchange = 1;
15716:                 my $now = time;
15717:                 my $uurl='/'.$cid;
15718:                 $uurl=~s/\_/\//g;
15719:                 if ($oldsec) {
15720:                     $uurl.='/'.$oldsec;
15721:                 }
15722:                 $oldsecurl = $uurl;
15723:                 $expire_role_result = 
15724:                     &Apache::lonnet::assignrole($udom,$uname,$uurl,'st',$now,'','',$context);
15725:                 if ($env{'request.course.sec'} ne '') { 
15726:                     if ($expire_role_result eq 'refused') {
15727:                         my @roles = ('st');
15728:                         my @statuses = ('previous');
15729:                         my @roledoms = ($one);
15730:                         my $withsec = 1;
15731:                         my %roleshash = 
15732:                             &Apache::lonnet::get_my_roles($uname,$udom,'userroles',
15733:                                               \@statuses,\@roles,\@roledoms,$withsec);
15734:                         if (defined ($roleshash{$two.':'.$one.':st:'.$oldsec})) {
15735:                             my ($oldstart,$oldend) = 
15736:                                 split(':',$roleshash{$two.':'.$one.':st:'.$oldsec});
15737:                             if ($oldend > 0 && $oldend <= $now) {
15738:                                 $expire_role_result = 'ok';
15739:                             }
15740:                         }
15741:                     }
15742:                 }
15743:                 $result = $expire_role_result;
15744:             }
15745:         }
15746:         if (($expire_role_result eq 'ok') || ($secchange == 0)) {
15747:             $modify_section_result = 
15748:                 &Apache::lonnet::modify_student_enrollment($udom,$uname,undef,undef,
15749:                                                            undef,undef,undef,$sec,
15750:                                                            $end,$start,'','',$cid,
15751:                                                            '',$context,$credits);
15752:             if ($modify_section_result =~ /^ok/) {
15753:                 if ($secchange == 1) {
15754:                     if ($sec eq '') {
15755:                         $$logmsg .= &mt('Section for [_1] switched from (possibly expired) old section: [_2] to student role without a section.',$uname,$oldsec).$linefeed;
15756:                     } else {
15757:                         $$logmsg .= &mt('Section for [_1] switched from (possibly expired) old section: [_2] to new section: [_3].',$uname,$oldsec,$sec).$linefeed;
15758:                     }
15759:                 } elsif ($oldsec eq '-1') {
15760:                     if ($sec eq '') {
15761:                         $$logmsg .= &mt('New student role without a section for [_1] in course [_2].',$uname,$cid).$linefeed;
15762:                     } else {
15763:                         $$logmsg .= &mt('New student role for [_1] in section [_2] in course [_3].',$uname,$sec,$cid).$linefeed;
15764:                     }
15765:                 } else {
15766:                     if ($sec eq '') {
15767:                         $$logmsg .= &mt('Student [_1] assigned to course [_2] without a section.',$uname,$cid).$linefeed;
15768:                     } else {
15769:                         $$logmsg .= &mt('Student [_1] assigned to section [_2] in course [_3].',$uname,$sec,$cid).$linefeed;
15770:                     }
15771:                 }
15772:             } else {
15773:                 if ($secchange) {       
15774:                     $$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;
15775:                 } else {
15776:                     $$logmsg .= &mt('Error when attempting to modify role for [_1] for section: "[_2]" in course [_3] -error:',$uname,$sec,$cid).' '.$modify_section_result.$linefeed;
15777:                 }
15778:             }
15779:             $result = $modify_section_result;
15780:         } elsif ($secchange == 1) {
15781:             if ($oldsec eq '') {
15782:                 $$logmsg .= &mt('Error when attempting to expire existing role without a section for [_1] in course [_2] -error: ',$uname,$cid).' '.$expire_role_result.$linefeed;
15783:             } else {
15784:                 $$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;
15785:             }
15786:             if ($expire_role_result eq 'refused') {
15787:                 my $newsecurl = '/'.$cid;
15788:                 $newsecurl =~ s/\_/\//g;
15789:                 if ($sec ne '') {
15790:                     $newsecurl.='/'.$sec;
15791:                 }
15792:                 if (&Apache::lonnet::allowed('cst',$newsecurl) && !(&Apache::lonnet::allowed('cst',$oldsecurl))) {
15793:                     if ($sec eq '') {
15794:                         $$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;
15795:                     } else {
15796:                         $$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;
15797:                     }
15798:                 }
15799:             }
15800:         }
15801:     } else {
15802:         $$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;
15803:         $result = "error: incomplete course id\n";
15804:     }
15805:     return $result;
15806: }
15807: 
15808: sub show_role_extent {
15809:     my ($scope,$context,$role) = @_;
15810:     $scope =~ s{^/}{};
15811:     my @courseroles = &Apache::lonuserutils::roles_by_context('course',1);
15812:     push(@courseroles,'co');
15813:     my @authorroles = &Apache::lonuserutils::roles_by_context('author');
15814:     if (($context eq 'course') || (grep(/^\Q$role\E/,@courseroles))) {
15815:         $scope =~ s{/}{_};
15816:         return '<span class="LC_cusr_emph">'.$env{'course.'.$scope.'.description'}.'</span>';
15817:     } elsif (($context eq 'author') || (grep(/^\Q$role\E/,@authorroles))) {
15818:         my ($audom,$auname) = split(/\//,$scope);
15819:         return &mt('[_1] Author Space','<span class="LC_cusr_emph">'.
15820:                    &Apache::loncommon::plainname($auname,$audom).'</span>');
15821:     } else {
15822:         $scope =~ s{/$}{};
15823:         return &mt('Domain: [_1]','<span class="LC_cusr_emph">'.
15824:                    &Apache::lonnet::domain($scope,'description').'</span>');
15825:     }
15826: }
15827: 
15828: ############################################################
15829: ############################################################
15830: 
15831: sub check_clone {
15832:     my ($args,$linefeed) = @_;
15833:     my $cloneid='/'.$args->{'clonedomain'}.'/'.$args->{'clonecourse'};
15834:     my ($clonecrsudom,$clonecrsunum)= &LONCAPA::split_courseid($cloneid);
15835:     my $clonehome=&Apache::lonnet::homeserver($clonecrsunum,$clonecrsudom);
15836:     my $clonetitle;
15837:     my @clonemsg;
15838:     my $can_clone = 0;
15839:     my $lctype = lc($args->{'crstype'});
15840:     if ($lctype ne 'community') {
15841:         $lctype = 'course';
15842:     }
15843:     if ($clonehome eq 'no_host') {
15844:         if ($args->{'crstype'} eq 'Community') {
15845:             push(@clonemsg,({
15846:                               mt => 'No new community created.',
15847:                               args => [],
15848:                             },
15849:                             {
15850:                               mt => 'A new community could not be cloned from the specified original - [_1] - because it is a non-existent community.',
15851:                               args => [$args->{'clonedomain'}.':'.$args->{'clonedomain'}],
15852:                             }));
15853:         } else {
15854:             push(@clonemsg,({
15855:                               mt => 'No new course created.',
15856:                               args => [],
15857:                             },
15858:                             {
15859:                               mt => 'A new course could not be cloned from the specified original - [_1] - because it is a non-existent course.',
15860:                               args => [$args->{'clonecourse'}.':'.$args->{'clonedomain'}],
15861:                             }));
15862:         }
15863:     } else {
15864: 	my %clonedesc = &Apache::lonnet::coursedescription($cloneid,{'one_time' => 1});
15865:         $clonetitle = $clonedesc{'description'};
15866:         if ($args->{'crstype'} eq 'Community') {
15867:             if ($clonedesc{'type'} ne 'Community') {
15868:                 push(@clonemsg,({
15869:                                   mt => 'No new community created.',
15870:                                   args => [],
15871:                                 },
15872:                                 {
15873:                                   mt => 'A new community could not be cloned from the specified original - [_1] - because it is a course not a community.',
15874:                                   args => [$args->{'clonecourse'}.':'.$args->{'clonedomain'}],
15875:                                 }));
15876:                 return ($can_clone,\@clonemsg,$cloneid,$clonehome);
15877:             }
15878:         }
15879: 	if (($env{'request.role.domain'} eq $args->{'clonedomain'}) &&
15880:             (&Apache::lonnet::allowed('ccc',$env{'request.role.domain'}))) {
15881: 	    $can_clone = 1;
15882: 	} else {
15883: 	    my %clonehash = &Apache::lonnet::get('environment',['cloners','internal.coursecode'],
15884: 						 $args->{'clonedomain'},$args->{'clonecourse'});
15885:             if ($clonehash{'cloners'} eq '') {
15886:                 my %domdefs = &Apache::lonnet::get_domain_defaults($args->{'course_domain'});
15887:                 if ($domdefs{'canclone'}) {
15888:                     unless ($domdefs{'canclone'} eq 'none') {
15889:                         if ($domdefs{'canclone'} eq 'domain') {
15890:                             if ($args->{'ccdomain'} eq $args->{'clonedomain'}) {
15891:                                 $can_clone = 1;
15892:                             }
15893:                         } elsif (($clonehash{'internal.coursecode'}) && ($args->{'crscode'}) &&
15894:                                  ($args->{'clonedomain'} eq  $args->{'course_domain'})) {
15895:                             if (&Apache::lonnet::default_instcode_cloning($args->{'clonedomain'},$domdefs{'canclone'},
15896:                                                                           $clonehash{'internal.coursecode'},$args->{'crscode'})) {
15897:                                 $can_clone = 1;
15898:                             }
15899:                         }
15900:                     }
15901:                 }
15902:             } else {
15903: 	        my @cloners = split(/,/,$clonehash{'cloners'});
15904:                 if (grep(/^\*$/,@cloners)) {
15905:                     $can_clone = 1;
15906:                 } elsif (grep(/^\*\:\Q$args->{'ccdomain'}\E$/,@cloners)) {
15907:                     $can_clone = 1;
15908:                 } elsif (grep(/^\Q$args->{'ccuname'}\E:\Q$args->{'ccdomain'}\E$/,@cloners)) {
15909:                     $can_clone = 1;
15910:                 }
15911:                 unless ($can_clone) {
15912:                     if (($clonehash{'internal.coursecode'}) && ($args->{'crscode'}) &&
15913:                         ($args->{'clonedomain'} eq  $args->{'course_domain'})) {
15914:                         my (%gotdomdefaults,%gotcodedefaults);
15915:                         foreach my $cloner (@cloners) {
15916:                             if (($cloner ne '*') && ($cloner !~ /^\*\:$match_domain$/) &&
15917:                                 ($cloner !~ /^$match_username\:$match_domain$/) && ($cloner ne '')) {
15918:                                 my (%codedefaults,@code_order);
15919:                                 if (ref($gotcodedefaults{$args->{'clonedomain'}}) eq 'HASH') {
15920:                                     if (ref($gotcodedefaults{$args->{'clonedomain'}}{'defaults'}) eq 'HASH') {
15921:                                         %codedefaults = %{$gotcodedefaults{$args->{'clonedomain'}}{'defaults'}};
15922:                                     }
15923:                                     if (ref($gotcodedefaults{$args->{'clonedomain'}}{'order'}) eq 'ARRAY') {
15924:                                         @code_order = @{$gotcodedefaults{$args->{'clonedomain'}}{'order'}};
15925:                                     }
15926:                                 } else {
15927:                                     &Apache::lonnet::auto_instcode_defaults($args->{'clonedomain'},
15928:                                                                             \%codedefaults,
15929:                                                                             \@code_order);
15930:                                     $gotcodedefaults{$args->{'clonedomain'}}{'defaults'} = \%codedefaults;
15931:                                     $gotcodedefaults{$args->{'clonedomain'}}{'order'} = \@code_order;
15932:                                 }
15933:                                 if (@code_order > 0) {
15934:                                     if (&Apache::lonnet::check_instcode_cloning(\%codedefaults,\@code_order,
15935:                                                                                 $cloner,$clonehash{'internal.coursecode'},
15936:                                                                                 $args->{'crscode'})) {
15937:                                         $can_clone = 1;
15938:                                         last;
15939:                                     }
15940:                                 }
15941:                             }
15942:                         }
15943:                     }
15944:                 }
15945:             }
15946:             unless ($can_clone) {
15947:                 my $ccrole = 'cc';
15948:                 if ($args->{'crstype'} eq 'Community') {
15949:                     $ccrole = 'co';
15950:                 }
15951:                 my %roleshash =
15952:                     &Apache::lonnet::get_my_roles($args->{'ccuname'},
15953:                                                   $args->{'ccdomain'},
15954:                                                   'userroles',['active'],[$ccrole],
15955:                                                   [$args->{'clonedomain'}]);
15956:                 if ($roleshash{$args->{'clonecourse'}.':'.$args->{'clonedomain'}.':'.$ccrole}) {
15957:                     $can_clone = 1;
15958:                 } elsif (&Apache::lonnet::is_course_owner($args->{'clonedomain'},$args->{'clonecourse'},
15959:                                                           $args->{'ccuname'},$args->{'ccdomain'})) {
15960:                     $can_clone = 1;
15961:                 }
15962:             }
15963:             unless ($can_clone) {
15964:                 if ($args->{'crstype'} eq 'Community') {
15965:                     push(@clonemsg,({
15966:                                       mt => 'No new community created.',
15967:                                       args => [],
15968:                                     },
15969:                                     {
15970:                                       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]).',
15971:                                       args => [$args->{'ccuname'}.':'.$args->{'ccdomain'},$clonedesc{'description'}],
15972:                                     }));
15973:                 } else {
15974:                     push(@clonemsg,({
15975:                                       mt => 'No new course created.',
15976:                                       args => [],
15977:                                     },
15978:                                     {
15979:                                       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]).',
15980:                                       args => [$args->{'ccuname'}.':'.$args->{'ccdomain'},$clonedesc{'description'}],
15981:                                     }));
15982: 	        }
15983: 	    }
15984:         }
15985:     }
15986:     return ($can_clone,\@clonemsg,$cloneid,$clonehome,$clonetitle);
15987: }
15988: 
15989: sub construct_course {
15990:     my ($args,$logmsg,$courseid,$crsudom,$crsunum,$udom,$uname,$context,
15991:         $cnum,$category,$coderef,$callercontext,$user_lh) = @_;
15992:     my ($outcome,$msgref,$clonemsgref);
15993:     my $linefeed =  '<br />'."\n";
15994:     if ($context eq 'auto') {
15995:         $linefeed = "\n";
15996:     }
15997: 
15998: #
15999: # Are we cloning?
16000: #
16001:     my ($can_clone,$cloneid,$clonehome,$clonetitle);
16002:     if (($args->{'clonecourse'}) && ($args->{'clonedomain'})) {
16003: 	($can_clone,$clonemsgref,$cloneid,$clonehome,$clonetitle) = &check_clone($args,$linefeed);
16004:         if (!$can_clone) {
16005: 	    return (0,$outcome,$clonemsgref);
16006: 	}
16007:     }
16008: 
16009: #
16010: # Open course
16011: #
16012:     my $crstype = lc($args->{'crstype'});
16013:     my %cenv=();
16014:     $$courseid=&Apache::lonnet::createcourse($args->{'course_domain'},
16015:                                              $args->{'cdescr'},
16016:                                              $args->{'curl'},
16017:                                              $args->{'course_home'},
16018:                                              $args->{'nonstandard'},
16019:                                              $args->{'crscode'},
16020:                                              $args->{'ccuname'}.':'.
16021:                                              $args->{'ccdomain'},
16022:                                              $args->{'crstype'},
16023:                                              $cnum,$context,$category,
16024:                                              $callercontext);
16025: 
16026:     # Note: The testing routines depend on this being output; see 
16027:     # Utils::Course. This needs to at least be output as a comment
16028:     # if anyone ever decides to not show this, and Utils::Course::new
16029:     # will need to be suitably modified.
16030:     if (($callercontext eq 'auto') && ($user_lh ne '')) {
16031:         $outcome .= &mt_user($user_lh,'New LON-CAPA [_1] ID: [_2]',$crstype,$$courseid).$linefeed;
16032:     } else {
16033:         $outcome .= &mt('New LON-CAPA [_1] ID: [_2]',$crstype,$$courseid).$linefeed;
16034:     }
16035:     if ($$courseid =~ /^error:/) {
16036:         return (0,$outcome,$clonemsgref);
16037:     }
16038: 
16039: #
16040: # Check if created correctly
16041: #
16042:     ($$crsudom,$$crsunum)= &LONCAPA::split_courseid($$courseid);
16043:     my $crsuhome=&Apache::lonnet::homeserver($$crsunum,$$crsudom);
16044:     if ($crsuhome eq 'no_host') {
16045:         if (($callercontext eq 'auto') && ($user_lh ne '')) {
16046:             $outcome .= &mt_user($user_lh,
16047:                             'Course creation failed, unrecognized course home server.');
16048:         } else {
16049:             $outcome .= &mt('Course creation failed, unrecognized course home server.');
16050:         }
16051:         $outcome .= $linefeed;
16052:         return (0,$outcome,$clonemsgref);
16053:     }
16054:     $outcome .= &mt('Created on').': '.$crsuhome.$linefeed;
16055: 
16056: #
16057: # Do the cloning
16058: #
16059:     my @clonemsg;
16060:     if ($can_clone && $cloneid) {
16061:         push(@clonemsg,
16062:                       {
16063:                           mt => 'Created [_1] by cloning from [_2]',
16064:                           args => [$crstype,$clonetitle],
16065:                       });
16066: 	my %oldcenv=&Apache::lonnet::dump('environment',$$crsudom,$$crsunum);
16067: # Copy all files
16068:         my @info =
16069:             &Apache::lonclonecourse::copycoursefiles($cloneid,$$courseid,$args->{'datemode'},
16070:                                                      $args->{'dateshift'},$args->{'crscode'},
16071:                                                      $args->{'ccuname'}.':'.$args->{'ccdomain'},
16072:                                                      $args->{'tinyurls'});
16073:         if (@info) {
16074:             push(@clonemsg,@info);
16075:         }
16076: # Restore URL
16077: 	$cenv{'url'}=$oldcenv{'url'};
16078: # Restore title
16079: 	$cenv{'description'}=$oldcenv{'description'};
16080: # Restore creation date, creator and creation context.
16081:         $cenv{'internal.created'}=$oldcenv{'internal.created'};
16082:         $cenv{'internal.creator'}=$oldcenv{'internal.creator'};
16083:         $cenv{'internal.creationcontext'}=$oldcenv{'internal.creationcontext'};
16084: # Mark as cloned
16085: 	$cenv{'clonedfrom'}=$cloneid;
16086: # Need to clone grading mode
16087:         my %newenv=&Apache::lonnet::get('environment',['grading'],$$crsudom,$$crsunum);
16088:         $cenv{'grading'}=$newenv{'grading'};
16089: # Do not clone these environment entries
16090:         &Apache::lonnet::del('environment',
16091:                   ['default_enrollment_start_date',
16092:                    'default_enrollment_end_date',
16093:                    'question.email',
16094:                    'policy.email',
16095:                    'comment.email',
16096:                    'pch.users.denied',
16097:                    'plc.users.denied',
16098:                    'hidefromcat',
16099:                    'checkforpriv',
16100:                    'categories'],
16101:                    $$crsudom,$$crsunum);
16102:         if ($args->{'textbook'}) {
16103:             $cenv{'internal.textbook'} = $args->{'textbook'};
16104:         }
16105:     }
16106: 
16107: #
16108: # Set environment (will override cloned, if existing)
16109: #
16110:     my @sections = ();
16111:     my @xlists = ();
16112:     if ($args->{'crstype'}) {
16113:         $cenv{'type'}=$args->{'crstype'};
16114:     }
16115:     if ($args->{'crsid'}) {
16116:         $cenv{'courseid'}=$args->{'crsid'};
16117:     }
16118:     if ($args->{'crscode'}) {
16119:         $cenv{'internal.coursecode'}=$args->{'crscode'};
16120:     }
16121:     if ($args->{'crsquota'} ne '') {
16122:         $cenv{'internal.coursequota'}=$args->{'crsquota'};
16123:     } else {
16124:         $cenv{'internal.coursequota'}=$args->{'crsquota'} = 20;
16125:     }
16126:     if ($args->{'ccuname'}) {
16127:         $cenv{'internal.courseowner'} = $args->{'ccuname'}.
16128:                                         ':'.$args->{'ccdomain'};
16129:     } else {
16130:         $cenv{'internal.courseowner'} = $args->{'curruser'};
16131:     }
16132:     if ($args->{'defaultcredits'}) {
16133:         $cenv{'internal.defaultcredits'} = $args->{'defaultcredits'};
16134:     }
16135:     my @badclasses = (); # Used to accumulate sections/crosslistings that did not pass classlist access check for course owner.
16136:     if ($args->{'crssections'}) {
16137:         $cenv{'internal.sectionnums'} = '';
16138:         if ($args->{'crssections'} =~ m/,/) {
16139:             @sections = split/,/,$args->{'crssections'};
16140:         } else {
16141:             $sections[0] = $args->{'crssections'};
16142:         }
16143:         if (@sections > 0) {
16144:             foreach my $item (@sections) {
16145:                 my ($sec,$gp) = split/:/,$item;
16146:                 my $class = $args->{'crscode'}.$sec;
16147:                 my $addcheck = &Apache::lonnet::auto_new_course($$crsunum,$$crsudom,$class,$cenv{'internal.courseowner'});
16148:                 $cenv{'internal.sectionnums'} .= $item.',';
16149:                 unless ($addcheck eq 'ok') {
16150:                     push(@badclasses,$class);
16151:                 }
16152:             }
16153:             $cenv{'internal.sectionnums'} =~ s/,$//;
16154:         }
16155:     }
16156: # do not hide course coordinator from staff listing, 
16157: # even if privileged
16158:     $cenv{'nothideprivileged'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
16159: # add course coordinator's domain to domains to check for privileged users
16160: # if different to course domain
16161:     if ($$crsudom ne $args->{'ccdomain'}) {
16162:         $cenv{'checkforpriv'} = $args->{'ccdomain'};
16163:     }
16164: # add crosslistings
16165:     if ($args->{'crsxlist'}) {
16166:         $cenv{'internal.crosslistings'}='';
16167:         if ($args->{'crsxlist'} =~ m/,/) {
16168:             @xlists = split/,/,$args->{'crsxlist'};
16169:         } else {
16170:             $xlists[0] = $args->{'crsxlist'};
16171:         }
16172:         if (@xlists > 0) {
16173:             foreach my $item (@xlists) {
16174:                 my ($xl,$gp) = split/:/,$item;
16175:                 my $addcheck =  &Apache::lonnet::auto_new_course($$crsunum,$$crsudom,$xl,$cenv{'internal.courseowner'});
16176:                 $cenv{'internal.crosslistings'} .= $item.',';
16177:                 unless ($addcheck eq 'ok') {
16178:                     push(@badclasses,$xl);
16179:                 }
16180:             }
16181:             $cenv{'internal.crosslistings'} =~ s/,$//;
16182:         }
16183:     }
16184:     if ($args->{'autoadds'}) {
16185:         $cenv{'internal.autoadds'}=$args->{'autoadds'};
16186:     }
16187:     if ($args->{'autodrops'}) {
16188:         $cenv{'internal.autodrops'}=$args->{'autodrops'};
16189:     }
16190: # check for notification of enrollment changes
16191:     my @notified = ();
16192:     if ($args->{'notify_owner'}) {
16193:         if ($args->{'ccuname'} ne '') {
16194:             push(@notified,$args->{'ccuname'}.':'.$args->{'ccdomain'});
16195:         }
16196:     }
16197:     if ($args->{'notify_dc'}) {
16198:         if ($uname ne '') { 
16199:             push(@notified,$uname.':'.$udom);
16200:         }
16201:     }
16202:     if (@notified > 0) {
16203:         my $notifylist;
16204:         if (@notified > 1) {
16205:             $notifylist = join(',',@notified);
16206:         } else {
16207:             $notifylist = $notified[0];
16208:         }
16209:         $cenv{'internal.notifylist'} = $notifylist;
16210:     }
16211:     if (@badclasses > 0) {
16212:         my %lt=&Apache::lonlocal::texthash(
16213:                 'tclb' => 'The courses listed below were included as sections or crosslistings affiliated with your new LON-CAPA course.',
16214:                 'howi' => 'However, if automated course roster updates are enabled for this class, these particular sections/crosslistings are not guaranteed to contribute towards enrollment.',
16215:                 'itis' => 'It is possible that rights to access enrollment for these classes will be available through assignment of co-owners.',
16216:         );
16217:         my $badclass_msg = $lt{'tclb'}.$linefeed.$lt{'howi'}.$linefeed.
16218:                            &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'};
16219:         if ($context eq 'auto') {
16220:             $outcome .= $badclass_msg.$linefeed;
16221:         } else {
16222:             $outcome .= '<div class="LC_warning">'.$badclass_msg.$linefeed.'<ul>'."\n";
16223:         }
16224:         foreach my $item (@badclasses) {
16225:             if ($context eq 'auto') {
16226:                 $outcome .= " - $item\n";
16227:             } else {
16228:                 $outcome .= "<li>$item</li>\n";
16229:             }
16230:         }
16231:         if ($context eq 'auto') {
16232:             $outcome .= $linefeed;
16233:         } else {
16234:             $outcome .= "</ul><br /><br /></div>\n";
16235:         }
16236:     }
16237:     if ($args->{'no_end_date'}) {
16238:         $args->{'endaccess'} = 0;
16239:     }
16240:     $cenv{'internal.autostart'}=$args->{'enrollstart'};
16241:     $cenv{'internal.autoend'}=$args->{'enrollend'};
16242:     $cenv{'default_enrollment_start_date'}=$args->{'startaccess'};
16243:     $cenv{'default_enrollment_end_date'}=$args->{'endaccess'};
16244:     if ($args->{'showphotos'}) {
16245:       $cenv{'internal.showphotos'}=$args->{'showphotos'};
16246:     }
16247:     $cenv{'internal.authtype'} = $args->{'authtype'};
16248:     $cenv{'internal.autharg'} = $args->{'autharg'}; 
16249:     if ( ($cenv{'internal.authtype'} =~ /^krb/) && ($cenv{'internal.autoadds'} == 1)) {
16250:         if (! defined($cenv{'internal.autharg'}) || $cenv{'internal.autharg'}  eq '') {
16251:             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'); 
16252:             if ($context eq 'auto') {
16253:                 $outcome .= $krb_msg;
16254:             } else {
16255:                 $outcome .= '<span class="LC_error">'.$krb_msg.'</span>';
16256:             }
16257:             $outcome .= $linefeed;
16258:         }
16259:     }
16260:     if (($args->{'ccdomain'}) && ($args->{'ccuname'})) {
16261:        if ($args->{'setpolicy'}) {
16262:            $cenv{'policy.email'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
16263:        }
16264:        if ($args->{'setcontent'}) {
16265:            $cenv{'question.email'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
16266:        }
16267:        if ($args->{'setcomment'}) {
16268:            $cenv{'comment.email'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
16269:        }
16270:     }
16271:     if ($args->{'reshome'}) {
16272: 	$cenv{'reshome'}=$args->{'reshome'}.'/';
16273: 	$cenv{'reshome'}=~s/\/+$/\//;
16274:     }
16275: #
16276: # course has keyed access
16277: #
16278:     if ($args->{'setkeys'}) {
16279:        $cenv{'keyaccess'}='yes';
16280:     }
16281: # if specified, key authority is not course, but user
16282: # only active if keyaccess is yes
16283:     if ($args->{'keyauth'}) {
16284: 	my ($user,$domain) = split(':',$args->{'keyauth'});
16285: 	$user = &LONCAPA::clean_username($user);
16286: 	$domain = &LONCAPA::clean_username($domain);
16287: 	if ($user ne '' && $domain ne '') {
16288: 	    $cenv{'keyauth'}=$user.':'.$domain;
16289: 	}
16290:     }
16291: 
16292: #
16293: #  generate and store uniquecode (available to course requester), if course should have one.
16294: #
16295:     if ($args->{'uniquecode'}) {
16296:         my ($code,$error) = &make_unique_code($$crsudom,$$crsunum);
16297:         if ($code) {
16298:             $cenv{'internal.uniquecode'} = $code;
16299:             my %crsinfo =
16300:                 &Apache::lonnet::courseiddump($$crsudom,'.',1,'.','.',$$crsunum,undef,undef,'.');
16301:             if (ref($crsinfo{$$crsudom.'_'.$$crsunum}) eq 'HASH') {
16302:                 $crsinfo{$$crsudom.'_'.$$crsunum}{'uniquecode'} = $code;
16303:                 my $putres = &Apache::lonnet::courseidput($$crsudom,\%crsinfo,$crsuhome,'notime');
16304:             }
16305:             if (ref($coderef)) {
16306:                 $$coderef = $code;
16307:             }
16308:         }
16309:     }
16310: 
16311:     if ($args->{'disresdis'}) {
16312:         $cenv{'pch.roles.denied'}='st';
16313:     }
16314:     if ($args->{'disablechat'}) {
16315:         $cenv{'plc.roles.denied'}='st';
16316:     }
16317: 
16318:     # Record we've not yet viewed the Course Initialization Helper for this 
16319:     # course
16320:     $cenv{'course.helper.not.run'} = 1;
16321:     #
16322:     # Use new Randomseed
16323:     #
16324:     $cenv{'rndseed'}=&Apache::lonnet::latest_rnd_algorithm_id();;
16325:     $cenv{'receiptalg'}=&Apache::lonnet::latest_receipt_algorithm_id();;
16326:     #
16327:     # The encryption code and receipt prefix for this course
16328:     #
16329:     $cenv{'internal.encseed'}=$Apache::lonnet::perlvar{'lonReceipt'}.$$.time.int(rand(9999));
16330:     $cenv{'internal.encpref'}=100+int(9*rand(99));
16331:     #
16332:     # By default, use standard grading
16333:     if (!defined($cenv{'grading'})) { $cenv{'grading'} = 'standard'; }
16334: 
16335:     $outcome .= $linefeed.&mt('Setting environment').': '.                 
16336:           &Apache::lonnet::put('environment',\%cenv,$$crsudom,$$crsunum).$linefeed;
16337: #
16338: # Open all assignments
16339: #
16340:     if ($args->{'openall'}) {
16341:        my $opendate = time;
16342:        if ($args->{'openallfrom'} =~ /^\d+$/) {
16343:            $opendate = $args->{'openallfrom'};
16344:        }
16345:        my $storeunder=$$crsudom.'_'.$$crsunum.'.0.opendate';
16346:        my %storecontent = ($storeunder         => $opendate,
16347:                            $storeunder.'.type' => 'date_start');
16348:        $outcome .= &mt('All assignments open starting [_1]',
16349:                        &Apache::lonlocal::locallocaltime($opendate)).': '.
16350:                    &Apache::lonnet::cput
16351:                        ('resourcedata',\%storecontent,$$crsudom,$$crsunum).$linefeed;
16352:    }
16353: #
16354: # Set first page
16355: #
16356:     unless (($args->{'nonstandard'}) || ($args->{'firstres'} eq 'blank')
16357: 	    || ($cloneid)) {
16358: 	use LONCAPA::map;
16359: 	$outcome .= &mt('Setting first resource').': ';
16360: 
16361: 	my $map = '/uploaded/'.$$crsudom.'/'.$$crsunum.'/default.sequence';
16362:         my ($errtext,$fatal)=&LONCAPA::map::mapread($map);
16363: 
16364:         $outcome .= ($fatal?$errtext:'read ok').' - ';
16365:         my $title; my $url;
16366:         if ($args->{'firstres'} eq 'syl') {
16367: 	    $title=&mt('Syllabus');
16368:             $url='/public/'.$$crsudom.'/'.$$crsunum.'/syllabus';
16369:         } else {
16370:             $title=&mt('Table of Contents');
16371:             $url='/adm/navmaps';
16372:         }
16373: 
16374:         $LONCAPA::map::resources[1]=$title.':'.$url.':false:start:res';
16375: 	(my $outtext,$errtext) = &LONCAPA::map::storemap($map,1);
16376: 
16377: 	if ($errtext) { $fatal=2; }
16378:         $outcome .= ($fatal?$errtext:'write ok').$linefeed;
16379:     }
16380: 
16381:     return (1,$outcome,\@clonemsg);
16382: }
16383: 
16384: sub make_unique_code {
16385:     my ($cdom,$cnum) = @_;
16386:     # get lock on uniquecodes db
16387:     my $lockhash = {
16388:                       $cnum."\0".'uniquecodes' => $env{'user.name'}.
16389:                                                   ':'.$env{'user.domain'},
16390:                    };
16391:     my $tries = 0;
16392:     my $gotlock = &Apache::lonnet::newput_dom('uniquecodes',$lockhash,$cdom);
16393:     my ($code,$error);
16394: 
16395:     while (($gotlock ne 'ok') && ($tries<3)) {
16396:         $tries ++;
16397:         sleep 1;
16398:         $gotlock = &Apache::lonnet::newput_dom('uniquecodes',$lockhash,$cdom);
16399:     }
16400:     if ($gotlock eq 'ok') {
16401:         my %currcodes = &Apache::lonnet::dump_dom('uniquecodes',$cdom);
16402:         my $gotcode;
16403:         my $attempts = 0;
16404:         while ((!$gotcode) && ($attempts < 100)) {
16405:             $code = &generate_code();
16406:             if (!exists($currcodes{$code})) {
16407:                 $gotcode = 1;
16408:                 unless (&Apache::lonnet::newput_dom('uniquecodes',{ $code => $cnum },$cdom) eq 'ok') {
16409:                     $error = 'nostore';
16410:                 }
16411:             }
16412:             $attempts ++;
16413:         }
16414:         my @del_lock = ($cnum."\0".'uniquecodes');
16415:         my $dellockoutcome = &Apache::lonnet::del_dom('uniquecodes',\@del_lock,$cdom);
16416:     } else {
16417:         $error = 'nolock';
16418:     }
16419:     return ($code,$error);
16420: }
16421: 
16422: sub generate_code {
16423:     my $code;
16424:     my @letts = qw(B C D G H J K M N P Q R S T V W X Z);
16425:     for (my $i=0; $i<6; $i++) {
16426:         my $lettnum = int (rand 2);
16427:         my $item = '';
16428:         if ($lettnum) {
16429:             $item = $letts[int( rand(18) )];
16430:         } else {
16431:             $item = 1+int( rand(8) );
16432:         }
16433:         $code .= $item;
16434:     }
16435:     return $code;
16436: }
16437: 
16438: ############################################################
16439: ############################################################
16440: 
16441: #SD
16442: # only Community and Course, or anything else?
16443: sub course_type {
16444:     my ($cid) = @_;
16445:     if (!defined($cid)) {
16446:         $cid = $env{'request.course.id'};
16447:     }
16448:     if (defined($env{'course.'.$cid.'.type'})) {
16449:         return $env{'course.'.$cid.'.type'};
16450:     } else {
16451:         return 'Course';
16452:     }
16453: }
16454: 
16455: sub group_term {
16456:     my $crstype = &course_type();
16457:     my %names = (
16458:                   'Course' => 'group',
16459:                   'Community' => 'group',
16460:                 );
16461:     return $names{$crstype};
16462: }
16463: 
16464: sub course_types {
16465:     my @types = ('official','unofficial','community','textbook');
16466:     my %typename = (
16467:                          official   => 'Official course',
16468:                          unofficial => 'Unofficial course',
16469:                          community  => 'Community',
16470:                          textbook   => 'Textbook course',
16471:                    );
16472:     return (\@types,\%typename);
16473: }
16474: 
16475: sub icon {
16476:     my ($file)=@_;
16477:     my $curfext = lc((split(/\./,$file))[-1]);
16478:     my $iconname=$Apache::lonnet::perlvar{'lonIconsURL'}.'/unknown.gif';
16479:     my $embstyle = &Apache::loncommon::fileembstyle($curfext);
16480:     if (!(!defined($embstyle) || $embstyle eq 'unk' || $embstyle eq 'hdn')) {
16481: 	if (-e  $Apache::lonnet::perlvar{'lonDocRoot'}.'/'.
16482: 	          $Apache::lonnet::perlvar{'lonIconsURL'}.'/'.
16483: 	            $curfext.".gif") {
16484: 	    $iconname=$Apache::lonnet::perlvar{'lonIconsURL'}.'/'.
16485: 		$curfext.".gif";
16486: 	}
16487:     }
16488:     return &lonhttpdurl($iconname);
16489: } 
16490: 
16491: sub lonhttpdurl {
16492: #
16493: # Had been used for "small fry" static images on separate port 8080.
16494: # Modify here if lightweight http functionality desired again.
16495: # Currently eliminated due to increasing firewall issues.
16496: #
16497:     my ($url)=@_;
16498:     return $url;
16499: }
16500: 
16501: sub connection_aborted {
16502:     my ($r)=@_;
16503:     $r->print(" ");$r->rflush();
16504:     my $c = $r->connection;
16505:     return $c->aborted();
16506: }
16507: 
16508: #    Escapes strings that may have embedded 's that will be put into
16509: #    strings as 'strings'.
16510: sub escape_single {
16511:     my ($input) = @_;
16512:     $input =~ s/\\/\\\\/g;	# Escape the \'s..(must be first)>
16513:     $input =~ s/\'/\\\'/g;	# Esacpe the 's....
16514:     return $input;
16515: }
16516: 
16517: #  Same as escape_single, but escape's "'s  This 
16518: #  can be used for  "strings"
16519: sub escape_double {
16520:     my ($input) = @_;
16521:     $input =~ s/\\/\\\\/g;	# Escape the /'s..(must be first)>
16522:     $input =~ s/\"/\\\"/g;	# Esacpe the "s....
16523:     return $input;
16524: }
16525:  
16526: #   Escapes the last element of a full URL.
16527: sub escape_url {
16528:     my ($url)   = @_;
16529:     my @urlslices = split(/\//, $url,-1);
16530:     my $lastitem = &escape(pop(@urlslices));
16531:     return &HTML::Entities::encode(join('/',@urlslices),"'").'/'.$lastitem;
16532: }
16533: 
16534: sub compare_arrays {
16535:     my ($arrayref1,$arrayref2) = @_;
16536:     my (@difference,%count);
16537:     @difference = ();
16538:     %count = ();
16539:     if ((ref($arrayref1) eq 'ARRAY') && (ref($arrayref2) eq 'ARRAY')) {
16540:         foreach my $element (@{$arrayref1}, @{$arrayref2}) { $count{$element}++; }
16541:         foreach my $element (keys(%count)) {
16542:             if ($count{$element} == 1) {
16543:                 push(@difference,$element);
16544:             }
16545:         }
16546:     }
16547:     return @difference;
16548: }
16549: 
16550: sub lon_status_items {
16551:     my %defaults = (
16552:                      E         => 100,
16553:                      W         => 4,
16554:                      N         => 1,
16555:                      U         => 5,
16556:                      threshold => 200,
16557:                      sysmail   => 2500,
16558:                    );
16559:     my %names = (
16560:                    E => 'Errors',
16561:                    W => 'Warnings',
16562:                    N => 'Notices',
16563:                    U => 'Unsent',
16564:                 );
16565:     return (\%defaults,\%names);
16566: }
16567: 
16568: # -------------------------------------------------------- Initialize user login
16569: sub init_user_environment {
16570:     my ($r, $username, $domain, $authhost, $form, $args) = @_;
16571:     my $lonids=$Apache::lonnet::perlvar{'lonIDsDir'};
16572: 
16573:     my $public=($username eq 'public' && $domain eq 'public');
16574: 
16575: # See if old ID present, if so, remove
16576: 
16577:     my ($filename,$cookie,$userroles,$firstaccenv,$timerintenv);
16578:     my $now=time;
16579: 
16580:     if ($public) {
16581: 	my $max_public=100;
16582: 	my $oldest;
16583: 	my $oldest_time=0;
16584: 	for(my $next=1;$next<=$max_public;$next++) {
16585: 	    if (-e $lonids."/publicuser_$next.id") {
16586: 		my $mtime=(stat($lonids."/publicuser_$next.id"))[9];
16587: 		if ($mtime<$oldest_time || !$oldest_time) {
16588: 		    $oldest_time=$mtime;
16589: 		    $oldest=$next;
16590: 		}
16591: 	    } else {
16592: 		$cookie="publicuser_$next";
16593: 		last;
16594: 	    }
16595: 	}
16596: 	if (!$cookie) { $cookie="publicuser_$oldest"; }
16597:     } else {
16598: 	# if this isn't a robot, kill any existing non-robot sessions
16599: 	if (!$args->{'robot'}) {
16600: 	    opendir(DIR,$lonids);
16601: 	    while ($filename=readdir(DIR)) {
16602: 		if ($filename=~/^$username\_\d+\_$domain\_$authhost\.id$/) {
16603:                     if (tie(my %oldenv,'GDBM_File',"$lonids/$filename",
16604:                             &GDBM_READER(),0640)) {
16605:                         my $linkedfile;
16606:                         if (exists($oldenv{'user.linkedenv'})) {
16607:                             $linkedfile = $oldenv{'user.linkedenv'};
16608:                         }
16609:                         untie(%oldenv);
16610:                         if (unlink("$lonids/$filename")) {
16611:                             if ($linkedfile =~ /^[a-f0-9]+_linked$/) {
16612:                                 if (-l "$lonids/$linkedfile.id") {
16613:                                     unlink("$lonids/$linkedfile.id");
16614:                                 }
16615:                             }
16616:                         }
16617:                     } else {
16618:                         unlink($lonids.'/'.$filename);
16619:                     }
16620: 		}
16621: 	    }
16622: 	    closedir(DIR);
16623: # If there is a undeleted lockfile for the user's paste buffer remove it.
16624:             my $namespace = 'nohist_courseeditor';
16625:             my $lockingkey = 'paste'."\0".'locked_num';
16626:             my %lockhash = &Apache::lonnet::get($namespace,[$lockingkey],
16627:                                                 $domain,$username);
16628:             if (exists($lockhash{$lockingkey})) {
16629:                 my $delresult = &Apache::lonnet::del($namespace,[$lockingkey],$domain,$username);
16630:                 unless ($delresult eq 'ok') {
16631:                     &Apache::lonnet::logthis("Failed to delete paste buffer locking key in $namespace for ".$username.":".$domain." Result was: $delresult");
16632:                 }
16633:             }
16634: 	}
16635: # Give them a new cookie
16636: 	my $id = ($args->{'robot'} ? 'robot'.$args->{'robot'}
16637: 		                   : $now.$$.int(rand(10000)));
16638: 	$cookie="$username\_$id\_$domain\_$authhost";
16639:     
16640: # Initialize roles
16641: 
16642: 	($userroles,$firstaccenv,$timerintenv) = 
16643:             &Apache::lonnet::rolesinit($domain,$username,$authhost);
16644:     }
16645: # ------------------------------------ Check browser type and MathML capability
16646: 
16647:     my ($httpbrowser,$clientbrowser,$clientversion,$clientmathml,$clientunicode,
16648:         $clientos,$clientmobile,$clientinfo,$clientosversion) = &decode_user_agent($r);
16649: 
16650: # ------------------------------------------------------------- Get environment
16651: 
16652:     my %userenv = &Apache::lonnet::dump('environment',$domain,$username);
16653:     my ($tmp) = keys(%userenv);
16654:     if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
16655:     } else {
16656: 	undef(%userenv);
16657:     }
16658:     if (($userenv{'interface'}) && (!$form->{'interface'})) {
16659: 	$form->{'interface'}=$userenv{'interface'};
16660:     }
16661:     if ($userenv{'texengine'} eq 'ttm') { $clientmathml=1; }
16662: 
16663: # --------------- Do not trust query string to be put directly into environment
16664:     foreach my $option ('interface','localpath','localres') {
16665:         $form->{$option}=~s/[\n\r\=]//gs;
16666:     }
16667: # --------------------------------------------------------- Write first profile
16668: 
16669:     {
16670:         my $ip = &Apache::lonnet::get_requestor_ip();
16671: 	my %initial_env = 
16672: 	    ("user.name"          => $username,
16673: 	     "user.domain"        => $domain,
16674: 	     "user.home"          => $authhost,
16675: 	     "browser.type"       => $clientbrowser,
16676: 	     "browser.version"    => $clientversion,
16677: 	     "browser.mathml"     => $clientmathml,
16678: 	     "browser.unicode"    => $clientunicode,
16679: 	     "browser.os"         => $clientos,
16680:              "browser.mobile"     => $clientmobile,
16681:              "browser.info"       => $clientinfo,
16682:              "browser.osversion"  => $clientosversion,
16683: 	     "server.domain"      => $Apache::lonnet::perlvar{'lonDefDomain'},
16684: 	     "request.course.fn"  => '',
16685: 	     "request.course.uri" => '',
16686: 	     "request.course.sec" => '',
16687: 	     "request.role"       => 'cm',
16688: 	     "request.role.adv"   => $env{'user.adv'},
16689: 	     "request.host"       => $ip,);
16690: 
16691:         if ($form->{'localpath'}) {
16692: 	    $initial_env{"browser.localpath"}  = $form->{'localpath'};
16693: 	    $initial_env{"browser.localres"}   = $form->{'localres'};
16694:         }
16695: 	
16696: 	if ($form->{'interface'}) {
16697: 	    $form->{'interface'}=~s/\W//gs;
16698: 	    $initial_env{"browser.interface"} = $form->{'interface'};
16699: 	    $env{'browser.interface'}=$form->{'interface'};
16700: 	}
16701: 
16702:         if ($form->{'iptoken'}) {
16703:             my $lonhost = $r->dir_config('lonHostID');
16704:             $initial_env{"user.noloadbalance"} = $lonhost;
16705:             $env{'user.noloadbalance'} = $lonhost;
16706:         }
16707: 
16708:         if ($form->{'noloadbalance'}) {
16709:             my @hosts = &Apache::lonnet::current_machine_ids();
16710:             my $hosthere = $form->{'noloadbalance'};
16711:             if (grep(/^\Q$hosthere\E$/,@hosts)) {
16712:                 $initial_env{"user.noloadbalance"} = $hosthere;
16713:                 $env{'user.noloadbalance'} = $hosthere;
16714:             }
16715:         }
16716: 
16717:         unless ($domain eq 'public') {
16718:             my %is_adv = ( is_adv => $env{'user.adv'} );
16719:             my %domdef = &Apache::lonnet::get_domain_defaults($domain);
16720: 
16721:             foreach my $tool ('aboutme','blog','webdav','portfolio','timezone') {
16722:                 $userenv{'availabletools.'.$tool} = 
16723:                     &Apache::lonnet::usertools_access($username,$domain,$tool,'reload',
16724:                                                       undef,\%userenv,\%domdef,\%is_adv);
16725:             }
16726: 
16727:             foreach my $crstype ('official','unofficial','community','textbook') {
16728:                 $userenv{'canrequest.'.$crstype} =
16729:                     &Apache::lonnet::usertools_access($username,$domain,$crstype,
16730:                                                       'reload','requestcourses',
16731:                                                       \%userenv,\%domdef,\%is_adv);
16732:             }
16733: 
16734:             $userenv{'canrequest.author'} =
16735:                 &Apache::lonnet::usertools_access($username,$domain,'requestauthor',
16736:                                                   'reload','requestauthor',
16737:                                                   \%userenv,\%domdef,\%is_adv);
16738:             my %reqauthor = &Apache::lonnet::get('requestauthor',['author_status','author'],
16739:                                                  $domain,$username);
16740:             my $reqstatus = $reqauthor{'author_status'};
16741:             if ($reqstatus eq 'approval' || $reqstatus eq 'approved') {
16742:                 if (ref($reqauthor{'author'}) eq 'HASH') {
16743:                     $userenv{'requestauthorqueued'} = $reqstatus.':'.
16744:                                                       $reqauthor{'author'}{'timestamp'};
16745:                 }
16746:             }
16747:         }
16748: 
16749: 	$env{'user.environment'} = "$lonids/$cookie.id";
16750: 
16751: 	if (tie(my %disk_env,'GDBM_File',"$lonids/$cookie.id",
16752: 		 &GDBM_WRCREAT(),0640)) {
16753: 	    &_add_to_env(\%disk_env,\%initial_env);
16754: 	    &_add_to_env(\%disk_env,\%userenv,'environment.');
16755: 	    &_add_to_env(\%disk_env,$userroles);
16756:             if (ref($firstaccenv) eq 'HASH') {
16757:                 &_add_to_env(\%disk_env,$firstaccenv);
16758:             }
16759:             if (ref($timerintenv) eq 'HASH') {
16760:                 &_add_to_env(\%disk_env,$timerintenv);
16761:             }
16762: 	    if (ref($args->{'extra_env'})) {
16763: 		&_add_to_env(\%disk_env,$args->{'extra_env'});
16764: 	    }
16765: 	    untie(%disk_env);
16766: 	} else {
16767: 	    &Apache::lonnet::logthis("<span style=\"color:blue;\">WARNING: ".
16768: 			   'Could not create environment storage in lonauth: '.$!.'</span>');
16769: 	    return 'error: '.$!;
16770: 	}
16771:     }
16772:     $env{'request.role'}='cm';
16773:     $env{'request.role.adv'}=$env{'user.adv'};
16774:     $env{'browser.type'}=$clientbrowser;
16775: 
16776:     return $cookie;
16777: 
16778: }
16779: 
16780: sub _add_to_env {
16781:     my ($idf,$env_data,$prefix) = @_;
16782:     if (ref($env_data) eq 'HASH') {
16783:         while (my ($key,$value) = each(%$env_data)) {
16784: 	    $idf->{$prefix.$key} = $value;
16785: 	    $env{$prefix.$key}   = $value;
16786:         }
16787:     }
16788: }
16789: 
16790: # --- Get the symbolic name of a problem and the url
16791: sub get_symb {
16792:     my ($request,$silent) = @_;
16793:     (my $url=$env{'form.url'}) =~ s-^https?\://($ENV{'SERVER_NAME'}|$ENV{'HTTP_HOST'})--;
16794:     my $symb=($env{'form.symb'} ne '' ? $env{'form.symb'} : (&Apache::lonnet::symbread($url)));
16795:     if ($symb eq '') {
16796:         if (!$silent) {
16797:             if (ref($request)) { 
16798:                 $request->print("Unable to handle ambiguous references:$url:.");
16799:             }
16800:             return ();
16801:         }
16802:     }
16803:     &Apache::lonenc::check_decrypt(\$symb);
16804:     return ($symb);
16805: }
16806: 
16807: # --------------------------------------------------------------Get annotation
16808: 
16809: sub get_annotation {
16810:     my ($symb,$enc) = @_;
16811: 
16812:     my $key = $symb;
16813:     if (!$enc) {
16814:         $key =
16815:             &Apache::lonnet::clutter((&Apache::lonnet::decode_symb($symb))[2]);
16816:     }
16817:     my %annotation=&Apache::lonnet::get('nohist_annotations',[$key]);
16818:     return $annotation{$key};
16819: }
16820: 
16821: sub clean_symb {
16822:     my ($symb,$delete_enc) = @_;
16823: 
16824:     &Apache::lonenc::check_decrypt(\$symb);
16825:     my $enc = $env{'request.enc'};
16826:     if ($delete_enc) {
16827:         delete($env{'request.enc'});
16828:     }
16829: 
16830:     return ($symb,$enc);
16831: }
16832: 
16833: ############################################################
16834: ############################################################
16835: 
16836: =pod
16837: 
16838: =head1 Routines for building display used to search for courses
16839: 
16840: 
16841: =over 4
16842: 
16843: =item * &build_filters()
16844: 
16845: Create markup for a table used to set filters to use when selecting
16846: courses in a domain.  Used by lonpickcourse.pm, lonmodifycourse.pm
16847: and quotacheck.pl
16848: 
16849: 
16850: Inputs:
16851: 
16852: filterlist - anonymous array of fields to include as potential filters
16853: 
16854: crstype - course type
16855: 
16856: roleelement - fifth arg in selectcourse_link() populates fifth arg in javascript: opencrsbrowser() function, used
16857:               to pop-open a course selector (will contain "extra element").
16858: 
16859: multelement - if multiple course selections will be allowed, this will be a hidden form element: name: multiple; value: 1
16860: 
16861: filter - anonymous hash of criteria and their values
16862: 
16863: action - form action
16864: 
16865: numfiltersref - ref to scalar (count of number of elements in institutional codes -- e.g., 4 for year, semester, department, and number)
16866: 
16867: caller - caller context (e.g., set to 'modifycourse' when routine is called from lonmodifycourse.pm)
16868: 
16869: cloneruname - username of owner of new course who wants to clone
16870: 
16871: clonerudom - domain of owner of new course who wants to clone
16872: 
16873: typeelem - text to use for left column in row containing course type (i.e., Course, Community or Course/Community)
16874: 
16875: codetitlesref - reference to array of titles of components in institutional codes (official courses)
16876: 
16877: codedom - domain
16878: 
16879: formname - value of form element named "form".
16880: 
16881: fixeddom - domain, if fixed.
16882: 
16883: prevphase - value to assign to form element named "phase" when going back to the previous screen
16884: 
16885: cnameelement - name of form element in form on opener page which will receive title of selected course
16886: 
16887: cnumelement - name of form element in form on opener page which will receive courseID  of selected course
16888: 
16889: cdomelement - name of form element in form on opener page which will receive domain of selected course
16890: 
16891: setroles - includes access constraint identifier when setting a roles-based condition for acces to a portfolio file
16892: 
16893: clonetext - hidden form elements containing list of courses cloneable by intended course owner when DC creates a course
16894: 
16895: clonewarning - warning message about missing information for intended course owner when DC creates a course
16896: 
16897: 
16898: Returns: $output - HTML for display of search criteria, and hidden form elements.
16899: 
16900: 
16901: Side Effects: None
16902: 
16903: =cut
16904: 
16905: # ---------------------------------------------- search for courses based on last activity etc.
16906: 
16907: sub build_filters {
16908:     my ($filterlist,$crstype,$roleelement,$multelement,$filter,$action,
16909:         $numtitlesref,$caller,$cloneruname,$clonerudom,$typeelement,
16910:         $codetitlesref,$codedom,$formname,$fixeddom,$prevphase,
16911:         $cnameelement,$cnumelement,$cdomelement,$setroles,
16912:         $clonetext,$clonewarning) = @_;
16913:     my ($list,$jscript);
16914:     my $onchange = 'javascript:updateFilters(this)';
16915:     my ($domainselectform,$sincefilterform,$createdfilterform,
16916:         $ownerdomselectform,$persondomselectform,$instcodeform,
16917:         $typeselectform,$instcodetitle);
16918:     if ($formname eq '') {
16919:         $formname = $caller;
16920:     }
16921:     foreach my $item (@{$filterlist}) {
16922:         unless (($item eq 'descriptfilter') || ($item eq 'instcodefilter') ||
16923:                 ($item eq 'sincefilter') || ($item eq 'createdfilter')) {
16924:             if ($item eq 'domainfilter') {
16925:                 $filter->{$item} = &LONCAPA::clean_domain($filter->{$item});
16926:             } elsif ($item eq 'coursefilter') {
16927:                 $filter->{$item} = &LONCAPA::clean_courseid($filter->{$item});
16928:             } elsif ($item eq 'ownerfilter') {
16929:                 $filter->{$item} = &LONCAPA::clean_username($filter->{$item});
16930:             } elsif ($item eq 'ownerdomfilter') {
16931:                 $filter->{'ownerdomfilter'} =
16932:                     &LONCAPA::clean_domain($filter->{$item});
16933:                 $ownerdomselectform = &select_dom_form($filter->{'ownerdomfilter'},
16934:                                                        'ownerdomfilter',1);
16935:             } elsif ($item eq 'personfilter') {
16936:                 $filter->{$item} = &LONCAPA::clean_username($filter->{$item});
16937:             } elsif ($item eq 'persondomfilter') {
16938:                 $persondomselectform = &select_dom_form($filter->{'persondomfilter'},
16939:                                                         'persondomfilter',1);
16940:             } else {
16941:                 $filter->{$item} =~ s/\W//g;
16942:             }
16943:             if (!$filter->{$item}) {
16944:                 $filter->{$item} = '';
16945:             }
16946:         }
16947:         if ($item eq 'domainfilter') {
16948:             my $allow_blank = 1;
16949:             if ($formname eq 'portform') {
16950:                 $allow_blank=0;
16951:             } elsif ($formname eq 'studentform') {
16952:                 $allow_blank=0;
16953:             }
16954:             if ($fixeddom) {
16955:                 $domainselectform = '<input type="hidden" name="domainfilter"'.
16956:                                     ' value="'.$codedom.'" />'.
16957:                                     &Apache::lonnet::domain($codedom,'description');
16958:             } else {
16959:                 $domainselectform = &select_dom_form($filter->{$item},
16960:                                                      'domainfilter',
16961:                                                       $allow_blank,'',$onchange);
16962:             }
16963:         } else {
16964:             $list->{$item} = &HTML::Entities::encode($filter->{$item},'<>&"');
16965:         }
16966:     }
16967: 
16968:     # last course activity filter and selection
16969:     $sincefilterform = &timebased_select_form('sincefilter',$filter);
16970: 
16971:     # course created filter and selection
16972:     if (exists($filter->{'createdfilter'})) {
16973:         $createdfilterform = &timebased_select_form('createdfilter',$filter);
16974:     }
16975: 
16976:     my %lt = &Apache::lonlocal::texthash(
16977:                 'cac' => "$crstype Activity",
16978:                 'ccr' => "$crstype Created",
16979:                 'cde' => "$crstype Title",
16980:                 'cdo' => "$crstype Domain",
16981:                 'ins' => 'Institutional Code',
16982:                 'inc' => 'Institutional Categorization',
16983:                 'cow' => "$crstype Owner/Co-owner",
16984:                 'cop' => "$crstype Personnel Includes",
16985:                 'cog' => 'Type',
16986:              );
16987: 
16988:     if (($formname eq 'ccrs') || ($formname eq 'requestcrs')) {
16989:         my $typeval = 'Course';
16990:         if ($crstype eq 'Community') {
16991:             $typeval = 'Community';
16992:         }
16993:         $typeselectform = '<input type="hidden" name="type" value="'.$typeval.'" />';
16994:     } else {
16995:         $typeselectform =  '<select name="type" size="1"';
16996:         if ($onchange) {
16997:             $typeselectform .= ' onchange="'.$onchange.'"';
16998:         }
16999:         $typeselectform .= '>'."\n";
17000:         foreach my $posstype ('Course','Community') {
17001:             $typeselectform.='<option value="'.$posstype.'"'.
17002:                 ($posstype eq $crstype ? ' selected="selected" ' : ''). ">".&mt($posstype)."</option>\n";
17003:         }
17004:         $typeselectform.="</select>";
17005:     }
17006: 
17007:     my ($cloneableonlyform,$cloneabletitle);
17008:     if (exists($filter->{'cloneableonly'})) {
17009:         my $cloneableon = '';
17010:         my $cloneableoff = ' checked="checked"';
17011:         if ($filter->{'cloneableonly'}) {
17012:             $cloneableon = $cloneableoff;
17013:             $cloneableoff = '';
17014:         }
17015:         $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>';
17016:         if ($formname eq 'ccrs') {
17017:             $cloneabletitle = &mt('Cloneable for [_1]',$cloneruname.':'.$clonerudom);
17018:         } else {
17019:             $cloneabletitle = &mt('Cloneable by you');
17020:         }
17021:     }
17022:     my $officialjs;
17023:     if ($crstype eq 'Course') {
17024:         if (exists($filter->{'instcodefilter'})) {
17025: #            if (($fixeddom) || ($formname eq 'requestcrs') ||
17026: #                ($formname eq 'modifycourse') || ($formname eq 'filterpicker')) {
17027:             if ($codedom) {
17028:                 $officialjs = 1;
17029:                 ($instcodeform,$jscript,$$numtitlesref) =
17030:                     &Apache::courseclassifier::instcode_selectors($codedom,'filterpicker',
17031:                                                                   $officialjs,$codetitlesref);
17032:                 if ($jscript) {
17033:                     $jscript = '<script type="text/javascript">'."\n".
17034:                                '// <![CDATA['."\n".
17035:                                $jscript."\n".
17036:                                '// ]]>'."\n".
17037:                                '</script>'."\n";
17038:                 }
17039:             }
17040:             if ($instcodeform eq '') {
17041:                 $instcodeform =
17042:                     '<input type="text" name="instcodefilter" size="10" value="'.
17043:                     $list->{'instcodefilter'}.'" />';
17044:                 $instcodetitle = $lt{'ins'};
17045:             } else {
17046:                 $instcodetitle = $lt{'inc'};
17047:             }
17048:             if ($fixeddom) {
17049:                 $instcodetitle .= '<br />('.$codedom.')';
17050:             }
17051:         }
17052:     }
17053:     my $output = qq|
17054: <form method="post" name="filterpicker" action="$action">
17055: <input type="hidden" name="form" value="$formname" />
17056: |;
17057:     if ($formname eq 'modifycourse') {
17058:         $output .= '<input type="hidden" name="phase" value="courselist" />'."\n".
17059:                    '<input type="hidden" name="prevphase" value="'.
17060:                    $prevphase.'" />'."\n";
17061:     } elsif ($formname eq 'quotacheck') {
17062:         $output .= qq|
17063: <input type="hidden" name="sortby" value="" />
17064: <input type="hidden" name="sortorder" value="" />
17065: |;
17066:     } else {
17067:         my $name_input;
17068:         if ($cnameelement ne '') {
17069:             $name_input = '<input type="hidden" name="cnameelement" value="'.
17070:                           $cnameelement.'" />';
17071:         }
17072:         $output .= qq|
17073: <input type="hidden" name="cnumelement" value="$cnumelement" />
17074: <input type="hidden" name="cdomelement" value="$cdomelement" />
17075: $name_input
17076: $roleelement
17077: $multelement
17078: $typeelement
17079: |;
17080:         if ($formname eq 'portform') {
17081:             $output .= '<input type="hidden" name="setroles" value="'.$setroles.'" />'."\n";
17082:         }
17083:     }
17084:     if ($fixeddom) {
17085:         $output .= '<input type="hidden" name="fixeddom" value="'.$fixeddom.'" />'."\n";
17086:     }
17087:     $output .= "<br />\n".&Apache::lonhtmlcommon::start_pick_box();
17088:     if ($sincefilterform) {
17089:         $output .= &Apache::lonhtmlcommon::row_title($lt{'cac'})
17090:                   .$sincefilterform
17091:                   .&Apache::lonhtmlcommon::row_closure();
17092:     }
17093:     if ($createdfilterform) {
17094:         $output .= &Apache::lonhtmlcommon::row_title($lt{'ccr'})
17095:                   .$createdfilterform
17096:                   .&Apache::lonhtmlcommon::row_closure();
17097:     }
17098:     if ($domainselectform) {
17099:         $output .= &Apache::lonhtmlcommon::row_title($lt{'cdo'})
17100:                   .$domainselectform
17101:                   .&Apache::lonhtmlcommon::row_closure();
17102:     }
17103:     if ($typeselectform) {
17104:         if (($formname eq 'ccrs') || ($formname eq 'requestcrs')) {
17105:             $output .= $typeselectform;
17106:         } else {
17107:             $output .= &Apache::lonhtmlcommon::row_title($lt{'cog'})
17108:                       .$typeselectform
17109:                       .&Apache::lonhtmlcommon::row_closure();
17110:         }
17111:     }
17112:     if ($instcodeform) {
17113:         $output .= &Apache::lonhtmlcommon::row_title($instcodetitle)
17114:                   .$instcodeform
17115:                   .&Apache::lonhtmlcommon::row_closure();
17116:     }
17117:     if (exists($filter->{'ownerfilter'})) {
17118:         $output .= &Apache::lonhtmlcommon::row_title($lt{'cow'}).
17119:                    '<table><tr><td>'.&mt('Username').'<br />'.
17120:                    '<input type="text" name="ownerfilter" size="20" value="'.
17121:                    $list->{'ownerfilter'}.'" /></td><td>'.&mt('Domain').'<br />'.
17122:                    $ownerdomselectform.'</td></tr></table>'.
17123:                    &Apache::lonhtmlcommon::row_closure();
17124:     }
17125:     if (exists($filter->{'personfilter'})) {
17126:         $output .= &Apache::lonhtmlcommon::row_title($lt{'cop'}).
17127:                    '<table><tr><td>'.&mt('Username').'<br />'.
17128:                    '<input type="text" name="personfilter" size="20" value="'.
17129:                    $list->{'personfilter'}.'" /></td><td>'.&mt('Domain').'<br />'.
17130:                    $persondomselectform.'</td></tr></table>'.
17131:                    &Apache::lonhtmlcommon::row_closure();
17132:     }
17133:     if (exists($filter->{'coursefilter'})) {
17134:         $output .= &Apache::lonhtmlcommon::row_title(&mt('LON-CAPA course ID'))
17135:                   .'<input type="text" name="coursefilter" size="25" value="'
17136:                   .$list->{'coursefilter'}.'" />'
17137:                   .&Apache::lonhtmlcommon::row_closure();
17138:     }
17139:     if ($cloneableonlyform) {
17140:         $output .= &Apache::lonhtmlcommon::row_title($cloneabletitle).
17141:                    $cloneableonlyform.&Apache::lonhtmlcommon::row_closure();
17142:     }
17143:     if (exists($filter->{'descriptfilter'})) {
17144:         $output .= &Apache::lonhtmlcommon::row_title($lt{'cde'})
17145:                   .'<input type="text" name="descriptfilter" size="40" value="'
17146:                   .$list->{'descriptfilter'}.'" />'
17147:                   .&Apache::lonhtmlcommon::row_closure(1);
17148:     }
17149:     $output .= &Apache::lonhtmlcommon::end_pick_box().'<p>'.$clonetext."\n".
17150:                '<input type="hidden" name="updater" value="" />'."\n".
17151:                '<input type="submit" name="gosearch" value="'.
17152:                &mt('Search').'" /></p>'."\n".'</form>'."\n".'<hr />'."\n";
17153:     return $jscript.$clonewarning.$output;
17154: }
17155: 
17156: =pod
17157: 
17158: =item * &timebased_select_form()
17159: 
17160: Create markup for a dropdown list used to select a time-based
17161: filter e.g., Course Activity, Course Created, when searching for courses
17162: or communities
17163: 
17164: Inputs:
17165: 
17166: item - name of form element (sincefilter or createdfilter)
17167: 
17168: filter - anonymous hash of criteria and their values
17169: 
17170: Returns: HTML for a select box contained a blank, then six time selections,
17171:          with value set in incoming form variables currently selected.
17172: 
17173: Side Effects: None
17174: 
17175: =cut
17176: 
17177: sub timebased_select_form {
17178:     my ($item,$filter) = @_;
17179:     if (ref($filter) eq 'HASH') {
17180:         $filter->{$item} =~ s/[^\d-]//g;
17181:         if (!$filter->{$item}) { $filter->{$item}=-1; }
17182:         return &select_form(
17183:                             $filter->{$item},
17184:                             $item,
17185:                             {      '-1' => '',
17186:                                 '86400' => &mt('today'),
17187:                                '604800' => &mt('last week'),
17188:                               '2592000' => &mt('last month'),
17189:                               '7776000' => &mt('last three months'),
17190:                              '15552000' => &mt('last six months'),
17191:                              '31104000' => &mt('last year'),
17192:                     'select_form_order' =>
17193:                            ['-1','86400','604800','2592000','7776000',
17194:                             '15552000','31104000']});
17195:     }
17196: }
17197: 
17198: =pod
17199: 
17200: =item * &js_changer()
17201: 
17202: Create script tag containing Javascript used to submit course search form
17203: when course type or domain is changed, and also to hide 'Searching ...' on
17204: page load completion for page showing search result.
17205: 
17206: Inputs: None
17207: 
17208: Returns: markup containing updateFilters() and hideSearching() javascript functions.
17209: 
17210: Side Effects: None
17211: 
17212: =cut
17213: 
17214: sub js_changer {
17215:     return <<ENDJS;
17216: <script type="text/javascript">
17217: // <![CDATA[
17218: function updateFilters(caller) {
17219:     if (typeof(caller) != "undefined") {
17220:         document.filterpicker.updater.value = caller.name;
17221:     }
17222:     document.filterpicker.submit();
17223: }
17224: 
17225: function hideSearching() {
17226:     if (document.getElementById('searching')) {
17227:         document.getElementById('searching').style.display = 'none';
17228:     }
17229:     return;
17230: }
17231: 
17232: // ]]>
17233: </script>
17234: 
17235: ENDJS
17236: }
17237: 
17238: =pod
17239: 
17240: =item * &search_courses()
17241: 
17242: Process selected filters form course search form and pass to lonnet::courseiddump
17243: to retrieve a hash for which keys are courseIDs which match the selected filters.
17244: 
17245: Inputs:
17246: 
17247: dom - domain being searched
17248: 
17249: type - course type ('Course' or 'Community' or '.' if any).
17250: 
17251: filter - anonymous hash of criteria and their values
17252: 
17253: numtitles - for institutional codes - number of categories
17254: 
17255: cloneruname - optional username of new course owner
17256: 
17257: clonerudom - optional domain of new course owner
17258: 
17259: domcloner - optional "domcloner" flag; has value=1 if user has ccc priv in domain being filtered by,
17260:             (used when DC is using course creation form)
17261: 
17262: codetitles - reference to array of titles of components in institutional codes (official courses).
17263: 
17264: cc_clone - escaped comma separated list of courses for which course cloner has active CC role
17265:            (and so can clone automatically)
17266: 
17267: reqcrsdom - domain of new course, where search_courses is used to identify potential courses to clone
17268: 
17269: reqinstcode - institutional code of new course, where search_courses is used to identify potential
17270:               courses to clone
17271: 
17272: Returns: %courses - hash of courses satisfying search criteria, keys = course IDs, values are corresponding colon-separated escaped description, institutional code, owner and type.
17273: 
17274: 
17275: Side Effects: None
17276: 
17277: =cut
17278: 
17279: 
17280: sub search_courses {
17281:     my ($dom,$type,$filter,$numtitles,$cloneruname,$clonerudom,$domcloner,$codetitles,
17282:         $cc_clone,$reqcrsdom,$reqinstcode) = @_;
17283:     my (%courses,%showcourses,$cloner);
17284:     if (($filter->{'ownerfilter'} ne '') ||
17285:         ($filter->{'ownerdomfilter'} ne '')) {
17286:         $filter->{'combownerfilter'} = $filter->{'ownerfilter'}.':'.
17287:                                        $filter->{'ownerdomfilter'};
17288:     }
17289:     foreach my $item ('descriptfilter','coursefilter','combownerfilter') {
17290:         if (!$filter->{$item}) {
17291:             $filter->{$item}='.';
17292:         }
17293:     }
17294:     my $now = time;
17295:     my $timefilter =
17296:        ($filter->{'sincefilter'}==-1?1:$now-$filter->{'sincefilter'});
17297:     my ($createdbefore,$createdafter);
17298:     if (($filter->{'createdfilter'} ne '') && ($filter->{'createdfilter'} !=-1)) {
17299:         $createdbefore = $now;
17300:         $createdafter = $now-$filter->{'createdfilter'};
17301:     }
17302:     my ($instcodefilter,$regexpok);
17303:     if ($numtitles) {
17304:         if ($env{'form.official'} eq 'on') {
17305:             $instcodefilter =
17306:                 &Apache::courseclassifier::instcode_search_str($dom,$numtitles,$codetitles);
17307:             $regexpok = 1;
17308:         } elsif ($env{'form.official'} eq 'off') {
17309:             $instcodefilter = &Apache::courseclassifier::instcode_search_str($dom,$numtitles,$codetitles);
17310:             unless ($instcodefilter eq '') {
17311:                 $regexpok = -1;
17312:             }
17313:         }
17314:     } else {
17315:         $instcodefilter = $filter->{'instcodefilter'};
17316:     }
17317:     if ($instcodefilter eq '') { $instcodefilter = '.'; }
17318:     if ($type eq '') { $type = '.'; }
17319: 
17320:     if (($clonerudom ne '') && ($cloneruname ne '')) {
17321:         $cloner = $cloneruname.':'.$clonerudom;
17322:     }
17323:     %courses = &Apache::lonnet::courseiddump($dom,
17324:                                              $filter->{'descriptfilter'},
17325:                                              $timefilter,
17326:                                              $instcodefilter,
17327:                                              $filter->{'combownerfilter'},
17328:                                              $filter->{'coursefilter'},
17329:                                              undef,undef,$type,$regexpok,undef,undef,
17330:                                              undef,undef,$cloner,$cc_clone,
17331:                                              $filter->{'cloneableonly'},
17332:                                              $createdbefore,$createdafter,undef,
17333:                                              $domcloner,undef,$reqcrsdom,$reqinstcode);
17334:     if (($filter->{'personfilter'} ne '') && ($filter->{'persondomfilter'} ne '')) {
17335:         my $ccrole;
17336:         if ($type eq 'Community') {
17337:             $ccrole = 'co';
17338:         } else {
17339:             $ccrole = 'cc';
17340:         }
17341:         my %rolehash = &Apache::lonnet::get_my_roles($filter->{'personfilter'},
17342:                                                      $filter->{'persondomfilter'},
17343:                                                      'userroles',undef,
17344:                                                      [$ccrole,'in','ad','ep','ta','cr'],
17345:                                                      $dom);
17346:         foreach my $role (keys(%rolehash)) {
17347:             my ($cnum,$cdom,$courserole) = split(':',$role);
17348:             my $cid = $cdom.'_'.$cnum;
17349:             if (exists($courses{$cid})) {
17350:                 if (ref($courses{$cid}) eq 'HASH') {
17351:                     if (ref($courses{$cid}{roles}) eq 'ARRAY') {
17352:                         if (!grep(/^\Q$courserole\E$/,@{$courses{$cid}{roles}})) {
17353:                             push(@{$courses{$cid}{roles}},$courserole);
17354:                         }
17355:                     } else {
17356:                         $courses{$cid}{roles} = [$courserole];
17357:                     }
17358:                     $showcourses{$cid} = $courses{$cid};
17359:                 }
17360:             }
17361:         }
17362:         %courses = %showcourses;
17363:     }
17364:     return %courses;
17365: }
17366: 
17367: =pod
17368: 
17369: =back
17370: 
17371: =head1 Routines for version requirements for current course.
17372: 
17373: =over 4
17374: 
17375: =item * &check_release_required()
17376: 
17377: Compares required LON-CAPA version with version on server, and
17378: if required version is newer looks for a server with the required version.
17379: 
17380: Looks first at servers in user's owen domain; if none suitable, looks at
17381: servers in course's domain are permitted to host sessions for user's domain.
17382: 
17383: Inputs:
17384: 
17385: $loncaparev - Version on current server (format: Major.Minor.Subrelease-datestamp)
17386: 
17387: $courseid - Course ID of current course
17388: 
17389: $rolecode - User's current role in course (for switchserver query string).
17390: 
17391: $required - LON-CAPA version needed by course (format: Major.Minor).
17392: 
17393: 
17394: Returns:
17395: 
17396: $switchserver - query string tp append to /adm/switchserver call (if
17397:                 current server's LON-CAPA version is too old.
17398: 
17399: $warning - Message is displayed if no suitable server could be found.
17400: 
17401: =cut
17402: 
17403: sub check_release_required {
17404:     my ($loncaparev,$courseid,$rolecode,$required) = @_;
17405:     my ($switchserver,$warning);
17406:     if ($required ne '') {
17407:         my ($reqdmajor,$reqdminor) = ($required =~ /^(\d+)\.(\d+)$/);
17408:         my ($major,$minor) = ($loncaparev =~ /^\'?(\d+)\.(\d+)\.[\w.\-]+\'?$/);
17409:         if ($reqdmajor ne '' && $reqdminor ne '') {
17410:             my $otherserver;
17411:             if (($major eq '' && $minor eq '') ||
17412:                 (($reqdmajor > $major) || (($reqdmajor == $major) && ($reqdminor > $minor)))) {
17413:                 my ($userdomserver) = &Apache::lonnet::choose_server($env{'user.domain'},undef,$required,1);
17414:                 my $switchlcrev =
17415:                     &Apache::lonnet::get_server_loncaparev($env{'user.domain'},
17416:                                                            $userdomserver);
17417:                 my ($swmajor,$swminor) = ($switchlcrev =~ /^\'?(\d+)\.(\d+)\.[\w.\-]+\'?$/);
17418:                 if (($swmajor eq '' && $swminor eq '') || ($reqdmajor > $swmajor) ||
17419:                     (($reqdmajor == $swmajor) && ($reqdminor > $swminor))) {
17420:                     my $cdom = $env{'course.'.$courseid.'.domain'};
17421:                     if ($cdom ne $env{'user.domain'}) {
17422:                         my ($coursedomserver,$coursehostname) = &Apache::lonnet::choose_server($cdom,undef,$required,1);
17423:                         my $serverhomeID = &Apache::lonnet::get_server_homeID($coursehostname);
17424:                         my $serverhomedom = &Apache::lonnet::host_domain($serverhomeID);
17425:                         my %defdomdefaults = &Apache::lonnet::get_domain_defaults($serverhomedom);
17426:                         my %udomdefaults = &Apache::lonnet::get_domain_defaults($env{'user.domain'});
17427:                         my $remoterev = &Apache::lonnet::get_server_loncaparev($serverhomedom,$coursedomserver);
17428:                         my $canhost =
17429:                             &Apache::lonnet::can_host_session($env{'user.domain'},
17430:                                                               $coursedomserver,
17431:                                                               $remoterev,
17432:                                                               $udomdefaults{'remotesessions'},
17433:                                                               $defdomdefaults{'hostedsessions'});
17434: 
17435:                         if ($canhost) {
17436:                             $otherserver = $coursedomserver;
17437:                         } else {
17438:                             $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.");
17439:                         }
17440:                     } else {
17441:                         $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).");
17442:                     }
17443:                 } else {
17444:                     $otherserver = $userdomserver;
17445:                 }
17446:             }
17447:             if ($otherserver ne '') {
17448:                 $switchserver = 'otherserver='.$otherserver.'&amp;role='.$rolecode;
17449:             }
17450:         }
17451:     }
17452:     return ($switchserver,$warning);
17453: }
17454: 
17455: =pod
17456: 
17457: =item * &check_release_result()
17458: 
17459: Inputs:
17460: 
17461: $switchwarning - Warning message if no suitable server found to host session.
17462: 
17463: $switchserver - query string to append to /adm/switchserver containing lonHostID
17464:                 and current role.
17465: 
17466: Returns: HTML to display with information about requirement to switch server.
17467:          Either displaying warning with link to Roles/Courses screen or
17468:          display link to switchserver.
17469: 
17470: =cut
17471: 
17472: sub check_release_result {
17473:     my ($switchwarning,$switchserver) = @_;
17474:     my $output = &start_page('Selected course unavailable on this server').
17475:                  '<p class="LC_warning">';
17476:     if ($switchwarning) {
17477:         $output .= $switchwarning.'<br /><a href="/adm/roles">';
17478:         if (&show_course()) {
17479:             $output .= &mt('Display courses');
17480:         } else {
17481:             $output .= &mt('Display roles');
17482:         }
17483:         $output .= '</a>';
17484:     } elsif ($switchserver) {
17485:         $output .= &mt('This course requires a newer version of LON-CAPA than is installed on this server.').
17486:                    '<br />'.
17487:                    '<a href="/adm/switchserver?'.$switchserver.'">'.
17488:                    &mt('Switch Server').
17489:                    '</a>';
17490:     }
17491:     $output .= '</p>'.&end_page();
17492:     return $output;
17493: }
17494: 
17495: =pod
17496: 
17497: =item * &needs_coursereinit()
17498: 
17499: Determine if course contents stored for user's session needs to be
17500: refreshed, because content has changed since "Big Hash" last tied.
17501: 
17502: Check for change is made if time last checked is more than 10 minutes ago
17503: (by default).
17504: 
17505: Inputs:
17506: 
17507: $loncaparev - Version on current server (format: Major.Minor.Subrelease-datestamp)
17508: 
17509: $interval (optional) - Time which may elapse (in s) between last check for content
17510:                        change in current course. (default: 600 s).
17511: 
17512: Returns: an array; first element is:
17513: 
17514: =over 4
17515: 
17516: 'switch' - if content updates mean user's session
17517:            needs to be switched to a server running a newer LON-CAPA version
17518: 
17519: 'update' - if course session needs to be refreshed (i.e., Big Hash needs to be reloaded)
17520:            on current server hosting user's session
17521: 
17522: ''       - if no action required.
17523: 
17524: =back
17525: 
17526: If first item element is 'switch':
17527: 
17528: second item is $switchwarning - Warning message if no suitable server found to host session.
17529: 
17530: third item is $switchserver - query string to append to /adm/switchserver containing lonHostID
17531:                               and current role.
17532: 
17533: otherwise: no other elements returned.
17534: 
17535: =back
17536: 
17537: =cut
17538: 
17539: sub needs_coursereinit {
17540:     my ($loncaparev,$interval) = @_;
17541:     return() unless ($env{'request.course.id'} && $env{'request.course.tied'});
17542:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
17543:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
17544:     my $now = time;
17545:     if ($interval eq '') {
17546:         $interval = 600;
17547:     }
17548:     if (($now-$env{'request.course.timechecked'})>$interval) {
17549:         &Apache::lonnet::appenv({'request.course.timechecked'=>$now});
17550:         my $blocked = &blocking_status('reinit',undef,$cnum,$cdom,undef,1);
17551:         if ($blocked) {
17552:             return ();
17553:         }
17554:         my $lastchange = &Apache::lonnet::get_coursechange($cdom,$cnum);
17555:         if ($lastchange > $env{'request.course.tied'}) {
17556:             my %curr_reqd_hash = &Apache::lonnet::userenvironment($cdom,$cnum,'internal.releaserequired');
17557:             if ($curr_reqd_hash{'internal.releaserequired'} ne '') {
17558:                 my $required = $env{'course.'.$cdom.'_'.$cnum.'.internal.releaserequired'};
17559:                 if ($curr_reqd_hash{'internal.releaserequired'} ne $required) {
17560:                     &Apache::lonnet::appenv({'course.'.$cdom.'_'.$cnum.'.internal.releaserequired' =>
17561:                                              $curr_reqd_hash{'internal.releaserequired'}});
17562:                     my ($switchserver,$switchwarning) =
17563:                         &check_release_required($loncaparev,$cdom.'_'.$cnum,$env{'request.role'},
17564:                                                 $curr_reqd_hash{'internal.releaserequired'});
17565:                     if ($switchwarning ne '' || $switchserver ne '') {
17566:                         return ('switch',$switchwarning,$switchserver);
17567:                     }
17568:                 }
17569:             }
17570:             return ('update');
17571:         }
17572:     }
17573:     return ();
17574: }
17575: 
17576: sub update_content_constraints {
17577:     my ($cdom,$cnum,$chome,$cid) = @_;
17578:     my %curr_reqd_hash = &Apache::lonnet::userenvironment($cdom,$cnum,'internal.releaserequired');
17579:     my ($reqdmajor,$reqdminor) = split(/\./,$curr_reqd_hash{'internal.releaserequired'});
17580:     my %checkresponsetypes;
17581:     foreach my $key (keys(%Apache::lonnet::needsrelease)) {
17582:         my ($item,$name,$value) = split(/:/,$key);
17583:         if ($item eq 'resourcetag') {
17584:             if ($name eq 'responsetype') {
17585:                 $checkresponsetypes{$value} = $Apache::lonnet::needsrelease{$key}
17586:             }
17587:         }
17588:     }
17589:     my $navmap = Apache::lonnavmaps::navmap->new();
17590:     if (defined($navmap)) {
17591:         my %allresponses;
17592:         foreach my $res ($navmap->retrieveResources(undef,sub { $_[0]->is_problem() },1,0)) {
17593:             my %responses = $res->responseTypes();
17594:             foreach my $key (keys(%responses)) {
17595:                 next unless(exists($checkresponsetypes{$key}));
17596:                 $allresponses{$key} += $responses{$key};
17597:             }
17598:         }
17599:         foreach my $key (keys(%allresponses)) {
17600:             my ($major,$minor) = split(/\./,$checkresponsetypes{$key});
17601:             if (($major > $reqdmajor) || ($major == $reqdmajor && $minor > $reqdminor)) {
17602:                 ($reqdmajor,$reqdminor) = ($major,$minor);
17603:             }
17604:         }
17605:         undef($navmap);
17606:     }
17607:     unless (($reqdmajor eq '') && ($reqdminor eq '')) {
17608:         &Apache::lonnet::update_released_required($reqdmajor.'.'.$reqdminor,$cdom,$cnum,$chome,$cid);
17609:     }
17610:     return;
17611: }
17612: 
17613: sub allmaps_incourse {
17614:     my ($cdom,$cnum,$chome,$cid) = @_;
17615:     if ($cdom eq '' || $cnum eq '' || $chome eq '' || $cid eq '') {
17616:         $cid = $env{'request.course.id'};
17617:         $cdom = $env{'course.'.$cid.'.domain'};
17618:         $cnum = $env{'course.'.$cid.'.num'};
17619:         $chome = $env{'course.'.$cid.'.home'};
17620:     }
17621:     my %allmaps = ();
17622:     my $lastchange =
17623:         &Apache::lonnet::get_coursechange($cdom,$cnum);
17624:     if ($lastchange > $env{'request.course.tied'}) {
17625:         my ($furl,$ferr) = &Apache::lonuserstate::readmap("$cdom/$cnum");
17626:         unless ($ferr) {
17627:             &update_content_constraints($cdom,$cnum,$chome,$cid);
17628:         }
17629:     }
17630:     my $navmap = Apache::lonnavmaps::navmap->new();
17631:     if (defined($navmap)) {
17632:         foreach my $res ($navmap->retrieveResources(undef,sub { $_[0]->is_map() },1,0,1)) {
17633:             $allmaps{$res->src()} = 1;
17634:         }
17635:     }
17636:     return \%allmaps;
17637: }
17638: 
17639: sub parse_supplemental_title {
17640:     my ($title) = @_;
17641: 
17642:     my ($foldertitle,$renametitle);
17643:     if ($title =~ /&amp;&amp;&amp;/) {
17644:         $title = &HTML::Entites::decode($title);
17645:     }
17646:     if ($title =~ m/^(\d+)___&&&___($match_username)___&&&___($match_domain)___&&&___(.*)$/) {
17647:         $renametitle=$4;
17648:         my ($time,$uname,$udom) = ($1,$2,$3);
17649:         $foldertitle=&Apache::lontexconvert::msgtexconverted($4);
17650:         my $name =  &plainname($uname,$udom);
17651:         $name = &HTML::Entities::encode($name,'"<>&\'');
17652:         $renametitle = &HTML::Entities::encode($renametitle,'"<>&\'');
17653:         $title='<i>'.&Apache::lonlocal::locallocaltime($time).'</i> '.
17654:             $name.': <br />'.$foldertitle;
17655:     }
17656:     if (wantarray) {
17657:         return ($title,$foldertitle,$renametitle);
17658:     }
17659:     return $title;
17660: }
17661: 
17662: sub recurse_supplemental {
17663:     my ($cnum,$cdom,$suppmap,$numfiles,$errors) = @_;
17664:     if ($suppmap) {
17665:         my ($errtext,$fatal) = &LONCAPA::map::mapread('/uploaded/'.$cdom.'/'.$cnum.'/'.$suppmap);
17666:         if ($fatal) {
17667:             $errors ++;
17668:         } else {
17669:             if ($#LONCAPA::map::resources > 0) {
17670:                 foreach my $res (@LONCAPA::map::resources) {
17671:                     my ($title,$src,$ext,$type,$status)=split(/\:/,$res);
17672:                     if (($src ne '') && ($status eq 'res')) {
17673:                         if ($src =~ m{^\Q/uploaded/$cdom/$cnum/\E(supplemental_\d+\.sequence)$}) {
17674:                             ($numfiles,$errors) = &recurse_supplemental($cnum,$cdom,$1,$numfiles,$errors);
17675:                         } else {
17676:                             $numfiles ++;
17677:                         }
17678:                     }
17679:                 }
17680:             }
17681:         }
17682:     }
17683:     return ($numfiles,$errors);
17684: }
17685: 
17686: sub symb_to_docspath {
17687:     my ($symb,$navmapref) = @_;
17688:     return unless ($symb && ref($navmapref));
17689:     my ($mapurl,$id,$resurl) = &Apache::lonnet::decode_symb($symb);
17690:     if ($resurl=~/\.(sequence|page)$/) {
17691:         $mapurl=$resurl;
17692:     } elsif ($resurl eq 'adm/navmaps') {
17693:         $mapurl=$env{'course.'.$env{'request.course.id'}.'.url'};
17694:     }
17695:     my $mapresobj;
17696:     unless (ref($$navmapref)) {
17697:         $$navmapref = Apache::lonnavmaps::navmap->new();
17698:     }
17699:     if (ref($$navmapref)) {
17700:         $mapresobj = $$navmapref->getResourceByUrl($mapurl);
17701:     }
17702:     $mapurl=~s{^.*/([^/]+)\.(\w+)$}{$1};
17703:     my $type=$2;
17704:     my $path;
17705:     if (ref($mapresobj)) {
17706:         my $pcslist = $mapresobj->map_hierarchy();
17707:         if ($pcslist ne '') {
17708:             foreach my $pc (split(/,/,$pcslist)) {
17709:                 next if ($pc <= 1);
17710:                 my $res = $$navmapref->getByMapPc($pc);
17711:                 if (ref($res)) {
17712:                     my $thisurl = $res->src();
17713:                     $thisurl=~s{^.*/([^/]+)\.\w+$}{$1};
17714:                     my $thistitle = $res->title();
17715:                     $path .= '&'.
17716:                              &Apache::lonhtmlcommon::entity_encode($thisurl).'&'.
17717:                              &escape($thistitle).
17718:                              ':'.$res->randompick().
17719:                              ':'.$res->randomout().
17720:                              ':'.$res->encrypted().
17721:                              ':'.$res->randomorder().
17722:                              ':'.$res->is_page();
17723:                 }
17724:             }
17725:         }
17726:         $path =~ s/^\&//;
17727:         my $maptitle = $mapresobj->title();
17728:         if ($mapurl eq 'default') {
17729:             $maptitle = 'Main Content';
17730:         }
17731:         $path .= (($path ne '')? '&' : '').
17732:                  &Apache::lonhtmlcommon::entity_encode($mapurl).'&'.
17733:                  &escape($maptitle).
17734:                  ':'.$mapresobj->randompick().
17735:                  ':'.$mapresobj->randomout().
17736:                  ':'.$mapresobj->encrypted().
17737:                  ':'.$mapresobj->randomorder().
17738:                  ':'.$mapresobj->is_page();
17739:     } else {
17740:         my $maptitle = &Apache::lonnet::gettitle($mapurl);
17741:         my $ispage = (($type eq 'page')? 1 : '');
17742:         if ($mapurl eq 'default') {
17743:             $maptitle = 'Main Content';
17744:         }
17745:         $path = &Apache::lonhtmlcommon::entity_encode($mapurl).'&'.
17746:                 &escape($maptitle).':::::'.$ispage;
17747:     }
17748:     unless ($mapurl eq 'default') {
17749:         $path = 'default&'.
17750:                 &escape('Main Content').
17751:                 ':::::&'.$path;
17752:     }
17753:     return $path;
17754: }
17755: 
17756: sub captcha_display {
17757:     my ($context,$lonhost,$defdom) = @_;
17758:     my ($output,$error);
17759:     my ($captcha,$pubkey,$privkey,$version) =
17760:         &get_captcha_config($context,$lonhost,$defdom);
17761:     if ($captcha eq 'original') {
17762:         $output = &create_captcha();
17763:         unless ($output) {
17764:             $error = 'captcha';
17765:         }
17766:     } elsif ($captcha eq 'recaptcha') {
17767:         $output = &create_recaptcha($pubkey,$version);
17768:         unless ($output) {
17769:             $error = 'recaptcha';
17770:         }
17771:     }
17772:     return ($output,$error,$captcha,$version);
17773: }
17774: 
17775: sub captcha_response {
17776:     my ($context,$lonhost,$defdom) = @_;
17777:     my ($captcha_chk,$captcha_error);
17778:     my ($captcha,$pubkey,$privkey,$version) = &get_captcha_config($context,$lonhost,$defdom);
17779:     if ($captcha eq 'original') {
17780:         ($captcha_chk,$captcha_error) = &check_captcha();
17781:     } elsif ($captcha eq 'recaptcha') {
17782:         $captcha_chk = &check_recaptcha($privkey,$version);
17783:     } else {
17784:         $captcha_chk = 1;
17785:     }
17786:     return ($captcha_chk,$captcha_error);
17787: }
17788: 
17789: sub get_captcha_config {
17790:     my ($context,$lonhost,$dom_in_effect) = @_;
17791:     my ($captcha,$pubkey,$privkey,$version,$hashtocheck);
17792:     my $hostname = &Apache::lonnet::hostname($lonhost);
17793:     my $serverhomeID = &Apache::lonnet::get_server_homeID($hostname);
17794:     my $serverhomedom = &Apache::lonnet::host_domain($serverhomeID);
17795:     if ($context eq 'usercreation') {
17796:         my %domconfig = &Apache::lonnet::get_dom('configuration',[$context],$serverhomedom);
17797:         if (ref($domconfig{$context}) eq 'HASH') {
17798:             $hashtocheck = $domconfig{$context}{'cancreate'};
17799:             if (ref($hashtocheck) eq 'HASH') {
17800:                 if ($hashtocheck->{'captcha'} eq 'recaptcha') {
17801:                     if (ref($hashtocheck->{'recaptchakeys'}) eq 'HASH') {
17802:                         $pubkey = $hashtocheck->{'recaptchakeys'}{'public'};
17803:                         $privkey = $hashtocheck->{'recaptchakeys'}{'private'};
17804:                     }
17805:                     if ($privkey && $pubkey) {
17806:                         $captcha = 'recaptcha';
17807:                         $version = $hashtocheck->{'recaptchaversion'};
17808:                         if ($version ne '2') {
17809:                             $version = 1;
17810:                         }
17811:                     } else {
17812:                         $captcha = 'original';
17813:                     }
17814:                 } elsif ($hashtocheck->{'captcha'} ne 'notused') {
17815:                     $captcha = 'original';
17816:                 }
17817:             }
17818:         } else {
17819:             $captcha = 'captcha';
17820:         }
17821:     } elsif ($context eq 'login') {
17822:         my %domconfhash = &Apache::loncommon::get_domainconf($serverhomedom);
17823:         if ($domconfhash{$serverhomedom.'.login.captcha'} eq 'recaptcha') {
17824:             $pubkey = $domconfhash{$serverhomedom.'.login.recaptchakeys_public'};
17825:             $privkey = $domconfhash{$serverhomedom.'.login.recaptchakeys_private'};
17826:             if ($privkey && $pubkey) {
17827:                 $captcha = 'recaptcha';
17828:                 $version = $domconfhash{$serverhomedom.'.login.recaptchaversion'};
17829:                 if ($version ne '2') {
17830:                     $version = 1;
17831:                 }
17832:             } else {
17833:                 $captcha = 'original';
17834:             }
17835:         } elsif ($domconfhash{$serverhomedom.'.login.captcha'} eq 'original') {
17836:             $captcha = 'original';
17837:         }
17838:     } elsif ($context eq 'passwords') {
17839:         if ($dom_in_effect) {
17840:             my %passwdconf = &Apache::lonnet::get_passwdconf($dom_in_effect);
17841:             if ($passwdconf{'captcha'} eq 'recaptcha') {
17842:                 if (ref($passwdconf{'recaptchakeys'}) eq 'HASH') {
17843:                     $pubkey = $passwdconf{'recaptchakeys'}{'public'};
17844:                     $privkey = $passwdconf{'recaptchakeys'}{'private'};
17845:                 }
17846:                 if ($privkey && $pubkey) {
17847:                     $captcha = 'recaptcha';
17848:                     $version = $passwdconf{'recaptchaversion'};
17849:                     if ($version ne '2') {
17850:                         $version = 1;
17851:                     }
17852:                 } else {
17853:                     $captcha = 'original';
17854:                 }
17855:             } elsif ($passwdconf{'captcha'} ne 'notused') {
17856:                 $captcha = 'original';
17857:             }
17858:         }
17859:     }
17860:     return ($captcha,$pubkey,$privkey,$version);
17861: }
17862: 
17863: sub create_captcha {
17864:     my %captcha_params = &captcha_settings();
17865:     my ($output,$maxtries,$tries) = ('',10,0);
17866:     while ($tries < $maxtries) {
17867:         $tries ++;
17868:         my $captcha = Authen::Captcha->new (
17869:                                            output_folder => $captcha_params{'output_dir'},
17870:                                            data_folder   => $captcha_params{'db_dir'},
17871:                                           );
17872:         my $md5sum = $captcha->generate_code($captcha_params{'numchars'});
17873: 
17874:         if (-e $Apache::lonnet::perlvar{'lonCaptchaDir'}.'/'.$md5sum.'.png') {
17875:             $output = '<input type="hidden" name="crypt" value="'.$md5sum.'" />'."\n".
17876:                       '<span class="LC_nobreak">'.
17877:                       &mt('Type in the letters/numbers shown below').'&nbsp;'.
17878:                       '<input type="text" size="5" name="code" value="" autocomplete="off" />'.
17879:                       '</span><br />'.
17880:                       '<img src="'.$captcha_params{'www_output_dir'}.'/'.$md5sum.'.png" alt="captcha" />';
17881:             last;
17882:         }
17883:     }
17884:     if ($output eq '') {
17885:         &Apache::lonnet::logthis("Failed to create Captcha code after $tries attempts.");
17886:     }
17887:     return $output;
17888: }
17889: 
17890: sub captcha_settings {
17891:     my %captcha_params = (
17892:                            output_dir     => $Apache::lonnet::perlvar{'lonCaptchaDir'},
17893:                            www_output_dir => "/captchaspool",
17894:                            db_dir         => $Apache::lonnet::perlvar{'lonCaptchaDb'},
17895:                            numchars       => '5',
17896:                          );
17897:     return %captcha_params;
17898: }
17899: 
17900: sub check_captcha {
17901:     my ($captcha_chk,$captcha_error);
17902:     my $code = $env{'form.code'};
17903:     my $md5sum = $env{'form.crypt'};
17904:     my %captcha_params = &captcha_settings();
17905:     my $captcha = Authen::Captcha->new(
17906:                       output_folder => $captcha_params{'output_dir'},
17907:                       data_folder   => $captcha_params{'db_dir'},
17908:                   );
17909:     $captcha_chk = $captcha->check_code($code,$md5sum);
17910:     my %captcha_hash = (
17911:                         0       => 'Code not checked (file error)',
17912:                        -1      => 'Failed: code expired',
17913:                        -2      => 'Failed: invalid code (not in database)',
17914:                        -3      => 'Failed: invalid code (code does not match crypt)',
17915:     );
17916:     if ($captcha_chk != 1) {
17917:         $captcha_error = $captcha_hash{$captcha_chk}
17918:     }
17919:     return ($captcha_chk,$captcha_error);
17920: }
17921: 
17922: sub create_recaptcha {
17923:     my ($pubkey,$version) = @_;
17924:     if ($version >= 2) {
17925:         return '<div class="g-recaptcha" data-sitekey="'.$pubkey.'"></div>'.
17926:                '<div style="padding:0;clear:both;margin:0;border:0"></div>';
17927:     } else {
17928:         my $use_ssl;
17929:         if ($ENV{'SERVER_PORT'} == 443) {
17930:             $use_ssl = 1;
17931:         }
17932:         my $captcha = Captcha::reCAPTCHA->new;
17933:         return $captcha->get_options_setter({theme => 'white'})."\n".
17934:                $captcha->get_html($pubkey,undef,$use_ssl).
17935:                &mt('If the text is hard to read, [_1] will replace them.',
17936:                    '<img src="/res/adm/pages/refresh.gif" alt="reCAPTCHA refresh" />').
17937:                '<br /><br />';
17938:      }
17939: }
17940: 
17941: sub check_recaptcha {
17942:     my ($privkey,$version) = @_;
17943:     my $captcha_chk;
17944:     my $ip = &Apache::lonnet::get_requestor_ip(); 
17945:     if ($version >= 2) {
17946:         my $ua = LWP::UserAgent->new;
17947:         $ua->timeout(10);
17948:         my %info = (
17949:                      secret   => $privkey,
17950:                      response => $env{'form.g-recaptcha-response'},
17951:                      remoteip => $ip,
17952:                    );
17953:         my $response = $ua->post('https://www.google.com/recaptcha/api/siteverify',\%info);
17954:         if ($response->is_success)  {
17955:             my $data = JSON::DWIW->from_json($response->decoded_content);
17956:             if (ref($data) eq 'HASH') {
17957:                 if ($data->{'success'}) {
17958:                     $captcha_chk = 1;
17959:                 }
17960:             }
17961:         }
17962:     } else {
17963:         my $captcha = Captcha::reCAPTCHA->new;
17964:         my $captcha_result =
17965:             $captcha->check_answer(
17966:                                     $privkey,
17967:                                     $ip,
17968:                                     $env{'form.recaptcha_challenge_field'},
17969:                                     $env{'form.recaptcha_response_field'},
17970:                                   );
17971:         if ($captcha_result->{is_valid}) {
17972:             $captcha_chk = 1;
17973:         }
17974:     }
17975:     return $captcha_chk;
17976: }
17977: 
17978: sub emailusername_info {
17979:     my @fields = ('firstname','lastname','institution','web','location','officialemail','id');
17980:     my %titles = &Apache::lonlocal::texthash (
17981:                      lastname      => 'Last Name',
17982:                      firstname     => 'First Name',
17983:                      institution   => 'School/college/university',
17984:                      location      => "School's city, state/province, country",
17985:                      web           => "School's web address",
17986:                      officialemail => 'E-mail address at institution (if different)',
17987:                      id            => 'Student/Employee ID',
17988:                  );
17989:     return (\@fields,\%titles);
17990: }
17991: 
17992: sub cleanup_html {
17993:     my ($incoming) = @_;
17994:     my $outgoing;
17995:     if ($incoming ne '') {
17996:         $outgoing = $incoming;
17997:         $outgoing =~ s/;/&#059;/g;
17998:         $outgoing =~ s/\#/&#035;/g;
17999:         $outgoing =~ s/\&/&#038;/g;
18000:         $outgoing =~ s/</&#060;/g;
18001:         $outgoing =~ s/>/&#062;/g;
18002:         $outgoing =~ s/\(/&#040/g;
18003:         $outgoing =~ s/\)/&#041;/g;
18004:         $outgoing =~ s/"/&#034;/g;
18005:         $outgoing =~ s/'/&#039;/g;
18006:         $outgoing =~ s/\$/&#036;/g;
18007:         $outgoing =~ s{/}{&#047;}g;
18008:         $outgoing =~ s/=/&#061;/g;
18009:         $outgoing =~ s/\\/&#092;/g
18010:     }
18011:     return $outgoing;
18012: }
18013: 
18014: # Checks for critical messages and returns a redirect url if one exists.
18015: # $interval indicates how often to check for messages.
18016: # $context is the calling context -- roles, grades, contents, menu or flip.
18017: sub critical_redirect {
18018:     my ($interval,$context) = @_;
18019:     unless (($env{'user.domain'} ne '') && ($env{'user.name'} ne '')) {
18020:         return ();
18021:     }
18022:     if ((time-$env{'user.criticalcheck.time'})>$interval) {
18023:         if (($env{'request.course.id'}) && (($context eq 'flip') || ($context eq 'contents'))) {
18024:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
18025:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
18026:             my $blocked = &blocking_status('alert',undef,$cnum,$cdom,undef,1);
18027:             if ($blocked) {
18028:                 my $checkrole = "cm./$cdom/$cnum";
18029:                 if ($env{'request.course.sec'} ne '') {
18030:                     $checkrole .= "/$env{'request.course.sec'}";
18031:                 }
18032:                 unless ((&Apache::lonnet::allowed('evb',undef,undef,$checkrole)) &&
18033:                         ($env{'request.role'} !~ m{^st\./$cdom/$cnum})) {
18034:                     return;
18035:                 }
18036:             }
18037:         }
18038:         my @what=&Apache::lonnet::dump('critical', $env{'user.domain'},
18039:                                         $env{'user.name'});
18040:         &Apache::lonnet::appenv({'user.criticalcheck.time'=>time});
18041:         my $redirecturl;
18042:         if ($what[0]) {
18043:             if (($what[0] ne 'con_lost') && ($what[0] ne 'no_such_host') && ($what[0]!~/^error\:/)) {
18044:                 $redirecturl='/adm/email?critical=display';
18045:                 my $url=&Apache::lonnet::absolute_url().$redirecturl;
18046:                 return (1, $url);
18047:             }
18048:         }
18049:     }
18050:     return ();
18051: }
18052: 
18053: # Use:
18054: #   my $answer=reply("encrypt:passwd:$udom:$uname:$upass",$tryserver);
18055: #
18056: ##################################################
18057: #          password associated functions         #
18058: ##################################################
18059: sub des_keys {
18060:     # Make a new key for DES encryption.
18061:     # Each key has two parts which are returned separately.
18062:     # Please note:  Each key must be passed through the &hex function
18063:     # before it is output to the web browser.  The hex versions cannot
18064:     # be used to decrypt.
18065:     my @hexstr=('0','1','2','3','4','5','6','7',
18066:                 '8','9','a','b','c','d','e','f');
18067:     my $lkey='';
18068:     for (0..7) {
18069:         $lkey.=$hexstr[rand(15)];
18070:     }
18071:     my $ukey='';
18072:     for (0..7) {
18073:         $ukey.=$hexstr[rand(15)];
18074:     }
18075:     return ($lkey,$ukey);
18076: }
18077: 
18078: sub des_decrypt {
18079:     my ($key,$cyphertext) = @_;
18080:     my $keybin=pack("H16",$key);
18081:     my $cypher;
18082:     if ($Crypt::DES::VERSION>=2.03) {
18083:         $cypher=new Crypt::DES $keybin;
18084:     } else {
18085:         $cypher=new DES $keybin;
18086:     }
18087:     my $plaintext='';
18088:     my $cypherlength = length($cyphertext);
18089:     my $numchunks = int($cypherlength/32);
18090:     for (my $j=0; $j<$numchunks; $j++) {
18091:         my $start = $j*32;
18092:         my $cypherblock = substr($cyphertext,$start,32);
18093:         my $chunk =
18094:             $cypher->decrypt(unpack("a8",pack("H16",substr($cypherblock,0,16))));
18095:         $chunk .=
18096:             $cypher->decrypt(unpack("a8",pack("H16",substr($cypherblock,16,16))));
18097:         $chunk=substr($chunk,1,ord(substr($chunk,0,1)) );
18098:         $plaintext .= $chunk;
18099:     }
18100:     return $plaintext;
18101: }
18102: 
18103: sub get_requested_shorturls {
18104:     my ($cdom,$cnum,$navmap) = @_;
18105:     return unless (ref($navmap));
18106:     my ($numnew,$errors);
18107:     my @toshorten = &Apache::loncommon::get_env_multiple('form.addtiny');
18108:     if (@toshorten) {
18109:         my (%maps,%resources,%titles);
18110:         &Apache::loncourserespicker::enumerate_course_contents($navmap,\%maps,\%resources,\%titles,
18111:                                                                'shorturls',$cdom,$cnum);
18112:         if (keys(%resources)) {
18113:             my %tocreate;
18114:             foreach my $item (sort {$a <=> $b} (@toshorten)) {
18115:                 my $symb = $resources{$item};
18116:                 if ($symb) {
18117:                     $tocreate{$cnum.'&'.$symb} = 1;
18118:                 }
18119:             }
18120:             if (keys(%tocreate)) {
18121:                 ($numnew,$errors) = &make_short_symbs($cdom,$cnum,
18122:                                                       \%tocreate);
18123:             }
18124:         }
18125:     }
18126:     return ($numnew,$errors);
18127: }
18128: 
18129: sub make_short_symbs {
18130:     my ($cdom,$cnum,$tocreateref,$lockuser) = @_;
18131:     my ($numnew,@errors);
18132:     if (ref($tocreateref) eq 'HASH') {
18133:         my %tocreate = %{$tocreateref};
18134:         if (keys(%tocreate)) {
18135:             my %coursetiny = &Apache::lonnet::dump('tiny',$cdom,$cnum);
18136:             my $su = Short::URL->new(no_vowels => 1);
18137:             my $init = '';
18138:             my (%newunique,%addcourse,%courseonly,%failed);
18139:             # get lock on tiny db
18140:             my $now = time;
18141:             if ($lockuser eq '') {
18142:                 $lockuser = $env{'user.name'}.':'.$env{'user.domain'};
18143:             }
18144:             my $lockhash = {
18145:                                 "lock\0$now" => $lockuser,
18146:                             };
18147:             my $tries = 0;
18148:             my $gotlock = &Apache::lonnet::newput_dom('tiny',$lockhash,$cdom);
18149:             my ($code,$error);
18150:             while (($gotlock ne 'ok') && ($tries<3)) {
18151:                 $tries ++;
18152:                 sleep 1;
18153:                 $gotlock = &Apache::lonnet::newput_dom('tiny',$lockhash,$cdom);
18154:             }
18155:             if ($gotlock eq 'ok') {
18156:                 $init = &shorten_symbs($cdom,$init,$su,\%coursetiny,\%tocreate,\%newunique,
18157:                                        \%addcourse,\%courseonly,\%failed);
18158:                 if (keys(%failed)) {
18159:                     my $numfailed = scalar(keys(%failed));
18160:                     push(@errors,&mt('error: could not obtain unique six character URL for [quant,_1,resource]',$numfailed));
18161:                 }
18162:                 if (keys(%newunique)) {
18163:                     my $putres = &Apache::lonnet::newput_dom('tiny',\%newunique,$cdom);
18164:                     if ($putres eq 'ok') {
18165:                         $numnew = scalar(keys(%newunique));
18166:                         my $newputres = &Apache::lonnet::newput('tiny',\%addcourse,$cdom,$cnum);
18167:                         unless ($newputres eq 'ok') {
18168:                             push(@errors,&mt('error: could not store course look-up of short URLs'));
18169:                         }
18170:                     } else {
18171:                         push(@errors,&mt('error: could not store unique six character URLs'));
18172:                     }
18173:                 }
18174:                 my $dellockres = &Apache::lonnet::del_dom('tiny',["lock\0$now"],$cdom);
18175:                 unless ($dellockres eq 'ok') {
18176:                     push(@errors,&mt('error: could not release lockfile'));
18177:                 }
18178:             } else {
18179:                 push(@errors,&mt('error: could not obtain lockfile'));
18180:             }
18181:             if (keys(%courseonly)) {
18182:                 my $result = &Apache::lonnet::newput('tiny',\%courseonly,$cdom,$cnum);
18183:                 if ($result ne 'ok') {
18184:                     push(@errors,&mt('error: could not update course look-up of short URLs'));
18185:                 }
18186:             }
18187:         }
18188:     }
18189:     return ($numnew,\@errors);
18190: }
18191: 
18192: sub shorten_symbs {
18193:     my ($cdom,$init,$su,$coursetiny,$tocreate,$newunique,$addcourse,$courseonly,$failed) = @_;
18194:     return unless ((ref($su)) && (ref($coursetiny) eq 'HASH') && (ref($tocreate) eq 'HASH') &&
18195:                    (ref($newunique) eq 'HASH') && (ref($addcourse) eq 'HASH') &&
18196:                    (ref($courseonly) eq 'HASH') && (ref($failed) eq 'HASH'));
18197:     my (%possibles,%collisions);
18198:     foreach my $key (keys(%{$tocreate})) {
18199:         my $num = String::CRC32::crc32($key);
18200:         my $tiny = $su->encode($num,$init);
18201:         if ($tiny) {
18202:             $possibles{$tiny} = $key;
18203:         }
18204:     }
18205:     if (!$init) {
18206:         $init = 1;
18207:     } else {
18208:         $init ++;
18209:     }
18210:     if (keys(%possibles)) {
18211:         my @posstiny = keys(%possibles);
18212:         my $configuname = &Apache::lonnet::get_domainconfiguser($cdom);
18213:         my %currtiny = &Apache::lonnet::get('tiny',\@posstiny,$cdom,$configuname);
18214:         if (keys(%currtiny)) {
18215:             foreach my $key (keys(%currtiny)) {
18216:                 next if ($currtiny{$key} eq '');
18217:                 if ($currtiny{$key} eq $possibles{$key}) {
18218:                     my ($tcnum,$tsymb) = split(/\&/,$currtiny{$key});
18219:                     unless (($coursetiny->{$tsymb} eq $key) || ($addcourse->{$tsymb} eq $key) || ($courseonly->{$tsymb} eq $key)) {
18220:                         $courseonly->{$tsymb} = $key;
18221:                     }
18222:                 } else {
18223:                     $collisions{$possibles{$key}} = 1;
18224:                 }
18225:                 delete($possibles{$key});
18226:             }
18227:         }
18228:         foreach my $key (keys(%possibles)) {
18229:             $newunique->{$key} = $possibles{$key};
18230:             my ($tcnum,$tsymb) = split(/\&/,$possibles{$key});
18231:             unless (($coursetiny->{$tsymb} eq $key) || ($addcourse->{$tsymb} eq $key) || ($courseonly->{$tsymb} eq $key)) {
18232:                 $addcourse->{$tsymb} = $key;
18233:             }
18234:         }
18235:     }
18236:     if (keys(%collisions)) {
18237:         if ($init <5) {
18238:             if (!$init) {
18239:                 $init = 1;
18240:             } else {
18241:                 $init ++;
18242:             }
18243:             $init = &shorten_symbs($cdom,$init,$su,$coursetiny,\%collisions,
18244:                                    $newunique,$addcourse,$courseonly,$failed);
18245:         } else {
18246:             foreach my $key (keys(%collisions)) {
18247:                 $failed->{$key} = 1;
18248:                 $failed->{$key} = 1;
18249:             }
18250:         }
18251:     }
18252:     return $init;
18253: }
18254: 
18255: sub is_nonframeable {
18256:     my ($url,$absolute,$hostname,$ip,$nocache) = @_;
18257:     my ($remprotocol,$remhost) = ($url =~ m{^(https?)\://(([a-z0-9]+(-[a-z0-9]+)*\.)+[a-z]{2,})}i);
18258:     return if (($remprotocol eq '') || ($remhost eq ''));
18259: 
18260:     $remprotocol = lc($remprotocol);
18261:     $remhost = lc($remhost);
18262:     my $remport = 80;
18263:     if ($remprotocol eq 'https') {
18264:         $remport = 443;
18265:     }
18266:     my ($result,$cached) = &Apache::lonnet::is_cached_new('noiframe',$remhost.':'.$remport);
18267:     if ($cached) {
18268:         unless ($nocache) {
18269:             if ($result) {
18270:                 return 1;
18271:             } else {
18272:                 return 0;
18273:             }
18274:         }
18275:     }
18276:     my $uselink;
18277:     my $request = new HTTP::Request('HEAD',$url);
18278:     my $ua = LWP::UserAgent->new;
18279:     $ua->timeout(5);
18280:     my $response=$ua->request($request);
18281:     if ($response->is_success()) {
18282:         my $secpolicy = lc($response->header('content-security-policy'));
18283:         my $xframeop = lc($response->header('x-frame-options'));
18284:         $secpolicy =~ s/^\s+|\s+$//g;
18285:         $xframeop =~ s/^\s+|\s+$//g;
18286:         if (($secpolicy ne '') || ($xframeop ne '')) {
18287:             my $remotehost = $remprotocol.'://'.$remhost;
18288:             my ($origin,$protocol,$port);
18289:             if ($ENV{'SERVER_PORT'} =~/^\d+$/) {
18290:                 $port = $ENV{'SERVER_PORT'};
18291:             } else {
18292:                 $port = 80;
18293:             }
18294:             if ($absolute eq '') {
18295:                 $protocol = 'http:';
18296:                 if ($port == 443) {
18297:                     $protocol = 'https:';
18298:                 }
18299:                 $origin = $protocol.'//'.lc($hostname);
18300:             } else {
18301:                 $origin = lc($absolute);
18302:                 ($protocol,$hostname) = ($absolute =~ m{^(https?:)//([^/]+)$});
18303:             }
18304:             if (($secpolicy) && ($secpolicy =~ /\Qframe-ancestors\E([^;]*)(;|$)/)) {
18305:                 my $framepolicy = $1;
18306:                 $framepolicy =~ s/^\s+|\s+$//g;
18307:                 my @policies = split(/\s+/,$framepolicy);
18308:                 if (@policies) {
18309:                     if (grep(/^\Q'none'\E$/,@policies)) {
18310:                         $uselink = 1;
18311:                     } else {
18312:                         $uselink = 1;
18313:                         if ((grep(/^\Q*\E$/,@policies)) || (grep(/^\Q$protocol\E$/,@policies)) ||
18314:                                 (($origin ne '') && (grep(/^\Q$origin\E$/,@policies))) ||
18315:                                 (($ip ne '') && (grep(/^\Q$ip\E$/,@policies)))) {
18316:                             undef($uselink);
18317:                         }
18318:                         if ($uselink) {
18319:                             if (grep(/^\Q'self'\E$/,@policies)) {
18320:                                 if (($origin ne '') && ($remotehost eq $origin)) {
18321:                                     undef($uselink);
18322:                                 }
18323:                             }
18324:                         }
18325:                         if ($uselink) {
18326:                             my @possok;
18327:                             if ($ip ne '') {
18328:                                 push(@possok,$ip);
18329:                             }
18330:                             my $hoststr = '';
18331:                             foreach my $part (reverse(split(/\./,$hostname))) {
18332:                                 if ($hoststr eq '') {
18333:                                     $hoststr = $part;
18334:                                 } else {
18335:                                     $hoststr = "$part.$hoststr";
18336:                                 }
18337:                                 if ($hoststr eq $hostname) {
18338:                                     push(@possok,$hostname);
18339:                                 } else {
18340:                                     push(@possok,"*.$hoststr");
18341:                                 }
18342:                             }
18343:                             if (@possok) {
18344:                                 foreach my $poss (@possok) {
18345:                                     last if (!$uselink);
18346:                                     foreach my $policy (@policies) {
18347:                                         if ($policy =~ m{^(\Q$protocol\E//|)\Q$poss\E(\Q:$port\E|)$}) {
18348:                                             undef($uselink);
18349:                                             last;
18350:                                         }
18351:                                     }
18352:                                 }
18353:                             }
18354:                         }
18355:                     }
18356:                 }
18357:             } elsif ($xframeop ne '') {
18358:                 $uselink = 1;
18359:                 my @policies = split(/\s*,\s*/,$xframeop);
18360:                 if (@policies) {
18361:                     unless (grep(/^deny$/,@policies)) {
18362:                         if ($origin ne '') {
18363:                             if (grep(/^sameorigin$/,@policies)) {
18364:                                 if ($remotehost eq $origin) {
18365:                                     undef($uselink);
18366:                                 }
18367:                             }
18368:                             if ($uselink) {
18369:                                 foreach my $policy (@policies) {
18370:                                     if ($policy =~ /^allow-from\s*(.+)$/) {
18371:                                         my $allowfrom = $1;
18372:                                         if (($allowfrom ne '') && ($allowfrom eq $origin)) {
18373:                                             undef($uselink);
18374:                                             last;
18375:                                         }
18376:                                     }
18377:                                 }
18378:                             }
18379:                         }
18380:                     }
18381:                 }
18382:             }
18383:         }
18384:     }
18385:     if ($nocache) {
18386:         if ($cached) {
18387:             my $devalidate;
18388:             if ($uselink && !$result) {
18389:                 $devalidate = 1;
18390:             } elsif (!$uselink && $result) {
18391:                 $devalidate = 1;
18392:             }
18393:             if ($devalidate) {
18394:                 &Apache::lonnet::devalidate_cache_new('noiframe',$remhost.':'.$remport);
18395:             }
18396:         }
18397:     } else {
18398:         if ($uselink) {
18399:             $result = 1;
18400:         } else {
18401:             $result = 0;
18402:         }
18403:         &Apache::lonnet::do_cache_new('noiframe',$remhost.':'.$remport,$result,3600);
18404:     }
18405:     return $uselink;
18406: }
18407: 
18408: sub page_menu {
18409:     my ($menucolls,$menunum) = @_;
18410:     my %menu;
18411:     foreach my $item (split(/;/,$menucolls)) {
18412:         my ($num,$value) = split(/\%/,$item);
18413:         if ($num eq $menunum) {
18414:             my @entries = split(/\&/,$value);
18415:             foreach my $entry (@entries) {
18416:                 my ($name,$fields) = split(/=/,$entry);
18417:                 if (($name eq 'top') || ($name eq 'inline') || ($name eq 'foot') || ($name eq 'main')) {
18418:                     $menu{$name} = $fields;
18419:                 } else {
18420:                     my @shown;
18421:                     if ($fields =~ /,/) {
18422:                         @shown = split(/,/,$fields);
18423:                     } else {
18424:                         @shown = ($fields);
18425:                     }
18426:                     if (@shown) {
18427:                         foreach my $field (@shown) {
18428:                             next if ($field eq '');
18429:                             $menu{$field} = 1;
18430:                         }
18431:                     }
18432:                 }
18433:             }
18434:         }
18435:     }
18436:     return %menu;
18437: }
18438: 
18439: 1;
18440: __END__;
18441: 

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