File:  [LON-CAPA] / loncom / interface / loncommon.pm
Revision 1.1075.2.127.2.10: download - view: text, annotated - select for diffs
Mon May 25 18:46:14 2020 UTC (3 years, 11 months ago) by raeburn
Branches: version_2_11_2_msu
Diff to branchpoint 1.1075.2.127: preferred, unified
- For 2.11.2 (modified)
  Include changes in 1.1309 missed in 1.1075.2.127.2.7

    1: # The LearningOnline Network with CAPA
    2: # a pile of common routines
    3: #
    4: # $Id: loncommon.pm,v 1.1075.2.127.2.10 2020/05/25 18:46:14 raeburn Exp $
    5: #
    6: # Copyright Michigan State University Board of Trustees
    7: #
    8: # This file is part of the LearningOnline Network with CAPA (LON-CAPA).
    9: #
   10: # LON-CAPA is free software; you can redistribute it and/or modify
   11: # it under the terms of the GNU General Public License as published by
   12: # the Free Software Foundation; either version 2 of the License, or
   13: # (at your option) any later version.
   14: #
   15: # LON-CAPA is distributed in the hope that it will be useful,
   16: # but WITHOUT ANY WARRANTY; without even the implied warranty of
   17: # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   18: # GNU General Public License for more details.
   19: #
   20: # You should have received a copy of the GNU General Public License
   21: # along with LON-CAPA; if not, write to the Free Software
   22: # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
   23: #
   24: # /home/httpd/html/adm/gpl.txt
   25: #
   26: # http://www.lon-capa.org/
   27: #
   28: 
   29: # Makes a table out of the previous attempts
   30: # Inputs result_from_symbread, user, domain, course_id
   31: # Reads in non-network-related .tab files
   32: 
   33: # POD header:
   34: 
   35: =pod
   36: 
   37: =head1 NAME
   38: 
   39: Apache::loncommon - pile of common routines
   40: 
   41: =head1 SYNOPSIS
   42: 
   43: Common routines for manipulating connections, student answers,
   44:     domains, common Javascript fragments, etc.
   45: 
   46: =head1 OVERVIEW
   47: 
   48: A collection of commonly used subroutines that don't have a natural
   49: home anywhere else. This collection helps remove
   50: redundancy from other modules and increase efficiency of memory usage.
   51: 
   52: =cut 
   53: 
   54: # End of POD header
   55: package Apache::loncommon;
   56: 
   57: use strict;
   58: use Apache::lonnet;
   59: use GDBM_File;
   60: use POSIX qw(strftime mktime);
   61: use Apache::lonmenu();
   62: use Apache::lonenc();
   63: use Apache::lonlocal;
   64: use Apache::lonnet();
   65: use HTML::Entities;
   66: use Apache::lonhtmlcommon();
   67: use Apache::loncoursedata();
   68: use Apache::lontexconvert();
   69: use Apache::lonclonecourse();
   70: use Apache::lonuserutils();
   71: use Apache::lonuserstate();
   72: use Apache::courseclassifier();
   73: use LONCAPA qw(:DEFAULT :match);
   74: use DateTime::TimeZone;
   75: use DateTime::Locale;
   76: use Encode();
   77: use Authen::Captcha;
   78: use Captcha::reCAPTCHA;
   79: use JSON::DWIW;
   80: use LWP::UserAgent;
   81: use Crypt::DES;
   82: use DynaLoader; # for Crypt::DES version
   83: use File::Copy();
   84: use File::Path();
   85: use String::CRC32();
   86: use Short::URL();
   87: 
   88: # ---------------------------------------------- Designs
   89: use vars qw(%defaultdesign);
   90: 
   91: my $readit;
   92: 
   93: 
   94: ##
   95: ## Global Variables
   96: ##
   97: 
   98: 
   99: # ----------------------------------------------- SSI with retries:
  100: #
  101: 
  102: =pod
  103: 
  104: =head1 Server Side include with retries:
  105: 
  106: =over 4
  107: 
  108: =item * &ssi_with_retries(resource,retries form)
  109: 
  110: Performs an ssi with some number of retries.  Retries continue either
  111: until the result is ok or until the retry count supplied by the
  112: caller is exhausted.  
  113: 
  114: Inputs:
  115: 
  116: =over 4
  117: 
  118: resource   - Identifies the resource to insert.
  119: 
  120: retries    - Count of the number of retries allowed.
  121: 
  122: form       - Hash that identifies the rendering options.
  123: 
  124: =back
  125: 
  126: Returns:
  127: 
  128: =over 4
  129: 
  130: content    - The content of the response.  If retries were exhausted this is empty.
  131: 
  132: response   - The response from the last attempt (which may or may not have been successful.
  133: 
  134: =back
  135: 
  136: =back
  137: 
  138: =cut
  139: 
  140: sub ssi_with_retries {
  141:     my ($resource, $retries, %form) = @_;
  142: 
  143: 
  144:     my $ok = 0;			# True if we got a good response.
  145:     my $content;
  146:     my $response;
  147: 
  148:     # Try to get the ssi done. within the retries count:
  149: 
  150:     do {
  151: 	($content, $response) = &Apache::lonnet::ssi($resource, %form);
  152: 	$ok      = $response->is_success;
  153:         if (!$ok) {
  154:             &Apache::lonnet::logthis("Failed ssi_with_retries on $resource: ".$response->is_success.', '.$response->code.', '.$response->message);
  155:         }
  156: 	$retries--;
  157:     } while (!$ok && ($retries > 0));
  158: 
  159:     if (!$ok) {
  160: 	$content = '';		# On error return an empty content.
  161:     }
  162:     return ($content, $response);
  163: 
  164: }
  165: 
  166: 
  167: 
  168: # ----------------------------------------------- Filetypes/Languages/Copyright
  169: my %language;
  170: my %supported_language;
  171: my %latex_language;		# For choosing hyphenation in <transl..>
  172: my %latex_language_bykey;	# for choosing hyphenation from metadata
  173: my %cprtag;
  174: my %scprtag;
  175: my %fe; my %fd; my %fm;
  176: my %category_extensions;
  177: 
  178: # ---------------------------------------------- Thesaurus variables
  179: #
  180: # %Keywords:
  181: #      A hash used by &keyword to determine if a word is considered a keyword.
  182: # $thesaurus_db_file 
  183: #      Scalar containing the full path to the thesaurus database.
  184: 
  185: my %Keywords;
  186: my $thesaurus_db_file;
  187: 
  188: #
  189: # Initialize values from language.tab, copyright.tab, filetypes.tab,
  190: # thesaurus.tab, and filecategories.tab.
  191: #
  192: BEGIN {
  193:     # Variable initialization
  194:     $thesaurus_db_file = $Apache::lonnet::perlvar{'lonTabDir'}."/thesaurus.db";
  195:     #
  196:     unless ($readit) {
  197: # ------------------------------------------------------------------- languages
  198:     {
  199:         my $langtabfile = $Apache::lonnet::perlvar{'lonTabDir'}.
  200:                                    '/language.tab';
  201:         if ( open(my $fh,'<',$langtabfile) ) {
  202:             while (my $line = <$fh>) {
  203:                 next if ($line=~/^\#/);
  204:                 chomp($line);
  205:                 my ($key,$two,$country,$three,$enc,$val,$sup,$latex)=(split(/\t/,$line));
  206:                 $language{$key}=$val.' - '.$enc;
  207:                 if ($sup) {
  208:                     $supported_language{$key}=$sup;
  209:                 }
  210: 		if ($latex) {
  211: 		    $latex_language_bykey{$key} = $latex;
  212: 		    $latex_language{$two} = $latex;
  213: 		}
  214:             }
  215:             close($fh);
  216:         }
  217:     }
  218: # ------------------------------------------------------------------ copyrights
  219:     {
  220:         my $copyrightfile = $Apache::lonnet::perlvar{'lonIncludes'}.
  221:                                   '/copyright.tab';
  222:         if ( open (my $fh,'<',$copyrightfile) ) {
  223:             while (my $line = <$fh>) {
  224:                 next if ($line=~/^\#/);
  225:                 chomp($line);
  226:                 my ($key,$val)=(split(/\s+/,$line,2));
  227:                 $cprtag{$key}=$val;
  228:             }
  229:             close($fh);
  230:         }
  231:     }
  232: # ----------------------------------------------------------- source copyrights
  233:     {
  234:         my $sourcecopyrightfile = $Apache::lonnet::perlvar{'lonIncludes'}.
  235:                                   '/source_copyright.tab';
  236:         if ( open (my $fh,'<',$sourcecopyrightfile) ) {
  237:             while (my $line = <$fh>) {
  238:                 next if ($line =~ /^\#/);
  239:                 chomp($line);
  240:                 my ($key,$val)=(split(/\s+/,$line,2));
  241:                 $scprtag{$key}=$val;
  242:             }
  243:             close($fh);
  244:         }
  245:     }
  246: 
  247: # -------------------------------------------------------------- default domain designs
  248:     my $designdir=$Apache::lonnet::perlvar{'lonTabDir'}.'/lonDomColors';
  249:     my $designfile = $designdir.'/default.tab';
  250:     if ( open (my $fh,'<',$designfile) ) {
  251:         while (my $line = <$fh>) {
  252:             next if ($line =~ /^\#/);
  253:             chomp($line);
  254:             my ($key,$val)=(split(/\=/,$line));
  255:             if ($val) { $defaultdesign{$key}=$val; }
  256:         }
  257:         close($fh);
  258:     }
  259: 
  260: # ------------------------------------------------------------- file categories
  261:     {
  262:         my $categoryfile = $Apache::lonnet::perlvar{'lonTabDir'}.
  263:                                   '/filecategories.tab';
  264:         if ( open (my $fh,'<',$categoryfile) ) {
  265: 	    while (my $line = <$fh>) {
  266: 		next if ($line =~ /^\#/);
  267: 		chomp($line);
  268:                 my ($extension,$category)=(split(/\s+/,$line,2));
  269:                 push(@{$category_extensions{lc($category)}},$extension);
  270:             }
  271:             close($fh);
  272:         }
  273: 
  274:     }
  275: # ------------------------------------------------------------------ file types
  276:     {
  277:         my $typesfile = $Apache::lonnet::perlvar{'lonTabDir'}.
  278:                '/filetypes.tab';
  279:         if ( open (my $fh,'<',$typesfile) ) {
  280:             while (my $line = <$fh>) {
  281: 		next if ($line =~ /^\#/);
  282: 		chomp($line);
  283:                 my ($ending,$emb,$mime,$descr)=split(/\s+/,$line,4);
  284:                 if ($descr ne '') {
  285:                     $fe{$ending}=lc($emb);
  286:                     $fd{$ending}=$descr;
  287:                     if ($mime ne 'unk') { $fm{$ending}=$mime; }
  288:                 }
  289:             }
  290:             close($fh);
  291:         }
  292:     }
  293:     &Apache::lonnet::logthis(
  294:              "<span style='color:yellow;'>INFO: Read file types</span>");
  295:     $readit=1;
  296:     }  # end of unless($readit) 
  297:     
  298: }
  299: 
  300: ###############################################################
  301: ##           HTML and Javascript Helper Functions            ##
  302: ###############################################################
  303: 
  304: =pod 
  305: 
  306: =head1 HTML and Javascript Functions
  307: 
  308: =over 4
  309: 
  310: =item * &browser_and_searcher_javascript()
  311: 
  312: X<browsing, javascript>X<searching, javascript>Returns a string
  313: containing javascript with two functions, C<openbrowser> and
  314: C<opensearcher>. Returned string does not contain E<lt>scriptE<gt>
  315: tags.
  316: 
  317: =item * &openbrowser(formname,elementname,only,omit) [javascript]
  318: 
  319: inputs: formname, elementname, only, omit
  320: 
  321: formname and elementname indicate the name of the html form and name of
  322: the element that the results of the browsing selection are to be placed in. 
  323: 
  324: Specifying 'only' will restrict the browser to displaying only files
  325: with the given extension.  Can be a comma separated list.
  326: 
  327: Specifying 'omit' will restrict the browser to NOT displaying files
  328: with the given extension.  Can be a comma separated list.
  329: 
  330: =item * &opensearcher(formname,elementname) [javascript]
  331: 
  332: Inputs: formname, elementname
  333: 
  334: formname and elementname specify the name of the html form and the name
  335: of the element the selection from the search results will be placed in.
  336: 
  337: =cut
  338: 
  339: sub browser_and_searcher_javascript {
  340:     my ($mode)=@_;
  341:     if (!defined($mode)) { $mode='edit'; }
  342:     my $resurl=&escape_single(&lastresurl());
  343:     return <<END;
  344: // <!-- BEGIN LON-CAPA Internal
  345:     var editbrowser = null;
  346:     function openbrowser(formname,elementname,only,omit,titleelement) {
  347:         var url = '$resurl/?';
  348:         if (editbrowser == null) {
  349:             url += 'launch=1&';
  350:         }
  351:         url += 'catalogmode=interactive&';
  352:         url += 'mode=$mode&';
  353:         url += 'inhibitmenu=yes&';
  354:         url += 'form=' + formname + '&';
  355:         if (only != null) {
  356:             url += 'only=' + only + '&';
  357:         } else {
  358:             url += 'only=&';
  359: 	}
  360:         if (omit != null) {
  361:             url += 'omit=' + omit + '&';
  362:         } else {
  363:             url += 'omit=&';
  364: 	}
  365:         if (titleelement != null) {
  366:             url += 'titleelement=' + titleelement + '&';
  367:         } else {
  368: 	    url += 'titleelement=&';
  369: 	}
  370:         url += 'element=' + elementname + '';
  371:         var title = 'Browser';
  372:         var options = 'scrollbars=1,resizable=1,menubar=0,toolbar=1,location=1';
  373:         options += ',width=700,height=600';
  374:         editbrowser = open(url,title,options,'1');
  375:         editbrowser.focus();
  376:     }
  377:     var editsearcher;
  378:     function opensearcher(formname,elementname,titleelement) {
  379:         var url = '/adm/searchcat?';
  380:         if (editsearcher == null) {
  381:             url += 'launch=1&';
  382:         }
  383:         url += 'catalogmode=interactive&';
  384:         url += 'mode=$mode&';
  385:         url += 'form=' + formname + '&';
  386:         if (titleelement != null) {
  387:             url += 'titleelement=' + titleelement + '&';
  388:         } else {
  389: 	    url += 'titleelement=&';
  390: 	}
  391:         url += 'element=' + elementname + '';
  392:         var title = 'Search';
  393:         var options = 'scrollbars=1,resizable=1,menubar=0,toolbar=1,location=1';
  394:         options += ',width=700,height=600';
  395:         editsearcher = open(url,title,options,'1');
  396:         editsearcher.focus();
  397:     }
  398: // END LON-CAPA Internal -->
  399: END
  400: }
  401: 
  402: sub lastresurl {
  403:     if ($env{'environment.lastresurl'}) {
  404: 	return $env{'environment.lastresurl'}
  405:     } else {
  406: 	return '/res';
  407:     }
  408: }
  409: 
  410: sub storeresurl {
  411:     my $resurl=&Apache::lonnet::clutter(shift);
  412:     unless ($resurl=~/^\/res/) { return 0; }
  413:     $resurl=~s/\/$//;
  414:     &Apache::lonnet::put('environment',{'lastresurl' => $resurl});
  415:     &Apache::lonnet::appenv({'environment.lastresurl' => $resurl});
  416:     return 1;
  417: }
  418: 
  419: sub studentbrowser_javascript {
  420:    unless (
  421:             (($env{'request.course.id'}) && 
  422:              (&Apache::lonnet::allowed('srm',$env{'request.course.id'})
  423: 	      || &Apache::lonnet::allowed('srm',$env{'request.course.id'}.
  424: 					  '/'.$env{'request.course.sec'})
  425: 	      ))
  426:          || ($env{'request.role'}=~/^(au|dc|su)/)
  427:           ) { return ''; }  
  428:    return (<<'ENDSTDBRW');
  429: <script type="text/javascript" language="Javascript">
  430: // <![CDATA[
  431:     var stdeditbrowser;
  432:     function openstdbrowser(formname,uname,udom,clicker,roleflag,ignorefilter,courseadvonly) {
  433:         var url = '/adm/pickstudent?';
  434:         var filter;
  435: 	if (!ignorefilter) {
  436: 	    eval('filter=document.'+formname+'.'+uname+'.value;');
  437: 	}
  438:         if (filter != null) {
  439:            if (filter != '') {
  440:                url += 'filter='+filter+'&';
  441: 	   }
  442:         }
  443:         url += 'form=' + formname + '&unameelement='+uname+
  444:                                     '&udomelement='+udom+
  445:                                     '&clicker='+clicker;
  446: 	if (roleflag) { url+="&roles=1"; }
  447:         if (courseadvonly) { url+="&courseadvonly=1"; }
  448:         var title = 'Student_Browser';
  449:         var options = 'scrollbars=1,resizable=1,menubar=0';
  450:         options += ',width=700,height=600';
  451:         stdeditbrowser = open(url,title,options,'1');
  452:         stdeditbrowser.focus();
  453:     }
  454: // ]]>
  455: </script>
  456: ENDSTDBRW
  457: }
  458: 
  459: sub resourcebrowser_javascript {
  460:    unless ($env{'request.course.id'}) { return ''; }
  461:    return (<<'ENDRESBRW');
  462: <script type="text/javascript" language="Javascript">
  463: // <![CDATA[
  464:     var reseditbrowser;
  465:     function openresbrowser(formname,reslink) {
  466:         var url = '/adm/pickresource?form='+formname+'&reslink='+reslink;
  467:         var title = 'Resource_Browser';
  468:         var options = 'scrollbars=1,resizable=1,menubar=0';
  469:         options += ',width=700,height=500';
  470:         reseditbrowser = open(url,title,options,'1');
  471:         reseditbrowser.focus();
  472:     }
  473: // ]]>
  474: </script>
  475: ENDRESBRW
  476: }
  477: 
  478: sub selectstudent_link {
  479:    my ($form,$unameele,$udomele,$courseadvonly,$clickerid)=@_;
  480:    my $callargs = "'".&Apache::lonhtmlcommon::entity_encode($form)."','".
  481:                       &Apache::lonhtmlcommon::entity_encode($unameele)."','".
  482:                       &Apache::lonhtmlcommon::entity_encode($udomele)."'";
  483:    if ($env{'request.course.id'}) {  
  484:        if (!&Apache::lonnet::allowed('srm',$env{'request.course.id'})
  485: 	   && !&Apache::lonnet::allowed('srm',$env{'request.course.id'}.
  486: 					'/'.$env{'request.course.sec'})) {
  487: 	   return '';
  488:        }
  489:        $callargs.=",'".&Apache::lonhtmlcommon::entity_encode($clickerid)."'";
  490:        if ($courseadvonly)  {
  491:            $callargs .= ",'',1,1";
  492:        }
  493:        return '<span class="LC_nobreak">'.
  494:               '<a href="javascript:openstdbrowser('.$callargs.');">'.
  495:               &mt('Select User').'</a></span>';
  496:    }
  497:    if ($env{'request.role'}=~/^(au|dc|su)/) {
  498:        $callargs .= ",'',1"; 
  499:        return '<span class="LC_nobreak">'.
  500:               '<a href="javascript:openstdbrowser('.$callargs.');">'.
  501:               &mt('Select User').'</a></span>';
  502:    }
  503:    return '';
  504: }
  505: 
  506: sub selectresource_link {
  507:    my ($form,$reslink,$arg)=@_;
  508:    
  509:    my $callargs = "'".&Apache::lonhtmlcommon::entity_encode($form)."','".
  510:                       &Apache::lonhtmlcommon::entity_encode($reslink)."'";
  511:    unless ($env{'request.course.id'}) { return $arg; }
  512:    return '<span class="LC_nobreak">'.
  513:               '<a href="javascript:openresbrowser('.$callargs.');">'.
  514:               $arg.'</a></span>';
  515: }
  516: 
  517: 
  518: 
  519: sub authorbrowser_javascript {
  520:     return <<"ENDAUTHORBRW";
  521: <script type="text/javascript" language="JavaScript">
  522: // <![CDATA[
  523: var stdeditbrowser;
  524: 
  525: function openauthorbrowser(formname,udom) {
  526:     var url = '/adm/pickauthor?';
  527:     url += 'form='+formname+'&roledom='+udom;
  528:     var title = 'Author_Browser';
  529:     var options = 'scrollbars=1,resizable=1,menubar=0';
  530:     options += ',width=700,height=600';
  531:     stdeditbrowser = open(url,title,options,'1');
  532:     stdeditbrowser.focus();
  533: }
  534: 
  535: // ]]>
  536: </script>
  537: ENDAUTHORBRW
  538: }
  539: 
  540: sub coursebrowser_javascript {
  541:     my ($domainfilter,$sec_element,$formname,$role_element,$crstype,
  542:         $credits_element,$instcode) = @_;
  543:     my $wintitle = 'Course_Browser';
  544:     if ($crstype eq 'Community') {
  545:         $wintitle = 'Community_Browser';
  546:     }
  547:     my $id_functions = &javascript_index_functions();
  548:     my $output = '
  549: <script type="text/javascript" language="JavaScript">
  550: // <![CDATA[
  551:     var stdeditbrowser;'."\n";
  552: 
  553:     $output .= <<"ENDSTDBRW";
  554:     function opencrsbrowser(formname,uname,udom,desc,extra_element,multflag,type,type_elem) {
  555:         var url = '/adm/pickcourse?';
  556:         var formid = getFormIdByName(formname);
  557:         var domainfilter = getDomainFromSelectbox(formname,udom);
  558:         if (domainfilter != null) {
  559:            if (domainfilter != '') {
  560:                url += 'domainfilter='+domainfilter+'&';
  561: 	   }
  562:         }
  563:         url += 'form=' + formname + '&cnumelement='+uname+
  564: 	                            '&cdomelement='+udom+
  565:                                     '&cnameelement='+desc;
  566:         if (extra_element !=null && extra_element != '') {
  567:             if (formname == 'rolechoice' || formname == 'studentform') {
  568:                 url += '&roleelement='+extra_element;
  569:                 if (domainfilter == null || domainfilter == '') {
  570:                     url += '&domainfilter='+extra_element;
  571:                 }
  572:             }
  573:             else {
  574:                 if (formname == 'portform') {
  575:                     url += '&setroles='+extra_element;
  576:                 } else {
  577:                     if (formname == 'rules') {
  578:                         url += '&fixeddom='+extra_element; 
  579:                     }
  580:                 }
  581:             }     
  582:         }
  583:         if (type != null && type != '') {
  584:             url += '&type='+type;
  585:         }
  586:         if (type_elem != null && type_elem != '') {
  587:             url += '&typeelement='+type_elem;
  588:         }
  589:         if (formname == 'ccrs') {
  590:             var ownername = document.forms[formid].ccuname.value;
  591:             var ownerdom =  document.forms[formid].ccdomain.options[document.forms[formid].ccdomain.selectedIndex].value;
  592:             url += '&cloner='+ownername+':'+ownerdom;
  593:             if (type == 'Course') {
  594:                 url += '&crscode='+document.forms[formid].crscode.value;
  595:             }
  596:         }
  597:         if (formname == 'requestcrs') {
  598:             url += '&crsdom=$domainfilter&crscode=$instcode';
  599:         }
  600:         if (multflag !=null && multflag != '') {
  601:             url += '&multiple='+multflag;
  602:         }
  603:         var title = '$wintitle';
  604:         var options = 'scrollbars=1,resizable=1,menubar=0';
  605:         options += ',width=700,height=600';
  606:         stdeditbrowser = open(url,title,options,'1');
  607:         stdeditbrowser.focus();
  608:     }
  609: $id_functions
  610: ENDSTDBRW
  611:     if (($sec_element ne '') || ($role_element ne '') || ($credits_element ne '')) {
  612:         $output .= &setsec_javascript($sec_element,$formname,$role_element,
  613:                                       $credits_element);
  614:     }
  615:     $output .= '
  616: // ]]>
  617: </script>';
  618:     return $output;
  619: }
  620: 
  621: sub javascript_index_functions {
  622:     return <<"ENDJS";
  623: 
  624: function getFormIdByName(formname) {
  625:     for (var i=0;i<document.forms.length;i++) {
  626:         if (document.forms[i].name == formname) {
  627:             return i;
  628:         }
  629:     }
  630:     return -1;
  631: }
  632: 
  633: function getIndexByName(formid,item) {
  634:     for (var i=0;i<document.forms[formid].elements.length;i++) {
  635:         if (document.forms[formid].elements[i].name == item) {
  636:             return i;
  637:         }
  638:     }
  639:     return -1;
  640: }
  641: 
  642: function getDomainFromSelectbox(formname,udom) {
  643:     var userdom;
  644:     var formid = getFormIdByName(formname);
  645:     if (formid > -1) {
  646:         var domid = getIndexByName(formid,udom);
  647:         if (domid > -1) {
  648:             if (document.forms[formid].elements[domid].type == 'select-one') {
  649:                 userdom=document.forms[formid].elements[domid].options[document.forms[formid].elements[domid].selectedIndex].value;
  650:             }
  651:             if (document.forms[formid].elements[domid].type == 'hidden') {
  652:                 userdom=document.forms[formid].elements[domid].value;
  653:             }
  654:         }
  655:     }
  656:     return userdom;
  657: }
  658: 
  659: ENDJS
  660: 
  661: }
  662: 
  663: sub javascript_array_indexof {
  664:     return <<ENDJS;
  665: <script type="text/javascript" language="JavaScript">
  666: // <![CDATA[
  667: 
  668: if (!Array.prototype.indexOf) {
  669:     Array.prototype.indexOf = function (searchElement /*, fromIndex */ ) {
  670:         "use strict";
  671:         if (this === void 0 || this === null) {
  672:             throw new TypeError();
  673:         }
  674:         var t = Object(this);
  675:         var len = t.length >>> 0;
  676:         if (len === 0) {
  677:             return -1;
  678:         }
  679:         var n = 0;
  680:         if (arguments.length > 0) {
  681:             n = Number(arguments[1]);
  682:             if (n !== n) { // shortcut for verifying if it's NaN
  683:                 n = 0;
  684:             } else if (n !== 0 && n !== (1 / 0) && n !== -(1 / 0)) {
  685:                 n = (n > 0 || -1) * Math.floor(Math.abs(n));
  686:             }
  687:         }
  688:         if (n >= len) {
  689:             return -1;
  690:         }
  691:         var k = n >= 0 ? n : Math.max(len - Math.abs(n), 0);
  692:         for (; k < len; k++) {
  693:             if (k in t && t[k] === searchElement) {
  694:                 return k;
  695:             }
  696:         }
  697:         return -1;
  698:     }
  699: }
  700: 
  701: // ]]>
  702: </script>
  703: 
  704: ENDJS
  705: 
  706: }
  707: 
  708: sub userbrowser_javascript {
  709:     my $id_functions = &javascript_index_functions();
  710:     return <<"ENDUSERBRW";
  711: 
  712: function openuserbrowser(formname,uname,udom,ulast,ufirst,uemail,hideudom,crsdom,caller) {
  713:     var url = '/adm/pickuser?';
  714:     var userdom = getDomainFromSelectbox(formname,udom);
  715:     if (userdom != null) {
  716:        if (userdom != '') {
  717:            url += 'srchdom='+userdom+'&';
  718:        }
  719:     }
  720:     url += 'form=' + formname + '&unameelement='+uname+
  721:                                 '&udomelement='+udom+
  722:                                 '&ulastelement='+ulast+
  723:                                 '&ufirstelement='+ufirst+
  724:                                 '&uemailelement='+uemail+
  725:                                 '&hideudomelement='+hideudom+
  726:                                 '&coursedom='+crsdom;
  727:     if ((caller != null) && (caller != undefined)) {
  728:         url += '&caller='+caller;
  729:     }
  730:     var title = 'User_Browser';
  731:     var options = 'scrollbars=1,resizable=1,menubar=0';
  732:     options += ',width=700,height=600';
  733:     var stdeditbrowser = open(url,title,options,'1');
  734:     stdeditbrowser.focus();
  735: }
  736: 
  737: function fix_domain (formname,udom,origdom,uname) {
  738:     var formid = getFormIdByName(formname);
  739:     if (formid > -1) {
  740:         var unameid = getIndexByName(formid,uname);
  741:         var domid = getIndexByName(formid,udom);
  742:         var hidedomid = getIndexByName(formid,origdom);
  743:         if (hidedomid > -1) {
  744:             var fixeddom = document.forms[formid].elements[hidedomid].value;
  745:             var unameval = document.forms[formid].elements[unameid].value;
  746:             if ((fixeddom != '') && (fixeddom != undefined) && (fixeddom != null) && (unameval != '') && (unameval != undefined) && (unameval != null)) {
  747:                 if (domid > -1) {
  748:                     var slct = document.forms[formid].elements[domid];
  749:                     if (slct.type == 'select-one') {
  750:                         var i;
  751:                         for (i=0;i<slct.length;i++) {
  752:                             if (slct.options[i].value==fixeddom) { slct.selectedIndex=i; }
  753:                         }
  754:                     }
  755:                     if (slct.type == 'hidden') {
  756:                         slct.value = fixeddom;
  757:                     }
  758:                 }
  759:             }
  760:         }
  761:     }
  762:     return;
  763: }
  764: 
  765: $id_functions
  766: ENDUSERBRW
  767: }
  768: 
  769: sub setsec_javascript {
  770:     my ($sec_element,$formname,$role_element,$credits_element) = @_;
  771:     my (@courserolenames,@communityrolenames,$rolestr,$courserolestr,
  772:         $communityrolestr);
  773:     if ($role_element ne '') {
  774:         my @allroles = ('st','ta','ep','in','ad');
  775:         foreach my $crstype ('Course','Community') {
  776:             if ($crstype eq 'Community') {
  777:                 foreach my $role (@allroles) {
  778:                     push(@communityrolenames,&Apache::lonnet::plaintext($role,$crstype));
  779:                 }
  780:                 push(@communityrolenames,&Apache::lonnet::plaintext('co'));
  781:             } else {
  782:                 foreach my $role (@allroles) {
  783:                     push(@courserolenames,&Apache::lonnet::plaintext($role,$crstype));
  784:                 }
  785:                 push(@courserolenames,&Apache::lonnet::plaintext('cc'));
  786:             }
  787:         }
  788:         $rolestr = '"'.join('","',@allroles).'"';
  789:         $courserolestr = '"'.join('","',@courserolenames).'"';
  790:         $communityrolestr = '"'.join('","',@communityrolenames).'"';
  791:     }
  792:     my $setsections = qq|
  793: function setSect(sectionlist) {
  794:     var sectionsArray = new Array();
  795:     if ((sectionlist != '') && (typeof sectionlist != "undefined")) {
  796:         sectionsArray = sectionlist.split(",");
  797:     }
  798:     var numSections = sectionsArray.length;
  799:     document.$formname.$sec_element.length = 0;
  800:     if (numSections == 0) {
  801:         document.$formname.$sec_element.multiple=false;
  802:         document.$formname.$sec_element.size=1;
  803:         document.$formname.$sec_element.options[0] = new Option('No existing sections','',false,false)
  804:     } else {
  805:         if (numSections == 1) {
  806:             document.$formname.$sec_element.multiple=false;
  807:             document.$formname.$sec_element.size=1;
  808:             document.$formname.$sec_element.options[0] = new Option('Select','',true,true);
  809:             document.$formname.$sec_element.options[1] = new Option('No section','',false,false)
  810:             document.$formname.$sec_element.options[2] = new Option(sectionsArray[0],sectionsArray[0],false,false);
  811:         } else {
  812:             for (var i=0; i<numSections; i++) {
  813:                 document.$formname.$sec_element.options[i] = new Option(sectionsArray[i],sectionsArray[i],false,false)
  814:             }
  815:             document.$formname.$sec_element.multiple=true
  816:             if (numSections < 3) {
  817:                 document.$formname.$sec_element.size=numSections;
  818:             } else {
  819:                 document.$formname.$sec_element.size=3;
  820:             }
  821:             document.$formname.$sec_element.options[0].selected = false
  822:         }
  823:     }
  824: }
  825: 
  826: function setRole(crstype) {
  827: |;
  828:     if ($role_element eq '') {
  829:         $setsections .= '    return;
  830: }
  831: ';
  832:     } else {
  833:         $setsections .= qq|
  834:     var elementLength = document.$formname.$role_element.length;
  835:     var allroles = Array($rolestr);
  836:     var courserolenames = Array($courserolestr);
  837:     var communityrolenames = Array($communityrolestr);
  838:     if (elementLength != undefined) {
  839:         if (document.$formname.$role_element.options[5].value == 'cc') {
  840:             if (crstype == 'Course') {
  841:                 return;
  842:             } else {
  843:                 allroles[5] = 'co';
  844:                 for (var i=0; i<6; i++) {
  845:                     document.$formname.$role_element.options[i].value = allroles[i];
  846:                     document.$formname.$role_element.options[i].text = communityrolenames[i];
  847:                 }
  848:             }
  849:         } else {
  850:             if (crstype == 'Community') {
  851:                 return;
  852:             } else {
  853:                 allroles[5] = 'cc';
  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 = courserolenames[i];
  857:                 }
  858:             }
  859:         }
  860:     }
  861:     return;
  862: }
  863: |;
  864:     }
  865:     if ($credits_element) {
  866:         $setsections .= qq|
  867: function setCredits(defaultcredits) {
  868:     document.$formname.$credits_element.value = defaultcredits;
  869:     return;
  870: }
  871: |;
  872:     }
  873:     return $setsections;
  874: }
  875: 
  876: sub selectcourse_link {
  877:    my ($form,$unameele,$udomele,$desc,$extra_element,$multflag,$selecttype,
  878:        $typeelement) = @_;
  879:    my $type = $selecttype;
  880:    my $linktext = &mt('Select Course');
  881:    if ($selecttype eq 'Community') {
  882:        $linktext = &mt('Select Community');
  883:    } elsif ($selecttype eq 'Course/Community') {
  884:        $linktext = &mt('Select Course/Community');
  885:        $type = '';
  886:    } elsif ($selecttype eq 'Select') {
  887:        $linktext = &mt('Select');
  888:        $type = '';
  889:    }
  890:    return '<span class="LC_nobreak">'
  891:          ."<a href='"
  892:          .'javascript:opencrsbrowser("'.$form.'","'.$unameele
  893:          .'","'.$udomele.'","'.$desc.'","'.$extra_element
  894:          .'","'.$multflag.'","'.$type.'","'.$typeelement.'");'
  895:          ."'>".$linktext.'</a>'
  896:          .'</span>';
  897: }
  898: 
  899: sub selectauthor_link {
  900:    my ($form,$udom)=@_;
  901:    return '<a href="javascript:openauthorbrowser('."'$form','$udom'".');">'.
  902:           &mt('Select Author').'</a>';
  903: }
  904: 
  905: sub selectuser_link {
  906:     my ($form,$unameelem,$domelem,$lastelem,$firstelem,$emailelem,$hdomelem,
  907:         $coursedom,$linktext,$caller) = @_;
  908:     return '<a href="javascript:openuserbrowser('."'$form','$unameelem','$domelem',".
  909:            "'$lastelem','$firstelem','$emailelem','$hdomelem','$coursedom','$caller'".
  910:            ');">'.$linktext.'</a>';
  911: }
  912: 
  913: sub check_uncheck_jscript {
  914:     my $jscript = <<"ENDSCRT";
  915: function checkAll(field) {
  916:     if (field.length > 0) {
  917:         for (i = 0; i < field.length; i++) {
  918:             if (!field[i].disabled) {
  919:                 field[i].checked = true;
  920:             }
  921:         }
  922:     } else {
  923:         if (!field.disabled) {
  924:             field.checked = true;
  925:         }
  926:     }
  927: }
  928:  
  929: function uncheckAll(field) {
  930:     if (field.length > 0) {
  931:         for (i = 0; i < field.length; i++) {
  932:             field[i].checked = false ;
  933:         }
  934:     } else {
  935:         field.checked = false ;
  936:     }
  937: }
  938: ENDSCRT
  939:     return $jscript;
  940: }
  941: 
  942: sub select_timezone {
  943:    my ($name,$selected,$onchange,$includeempty,$disabled)=@_;
  944:    my $output='<select name="'.$name.'" '.$onchange.$disabled.'>'."\n";
  945:    if ($includeempty) {
  946:        $output .= '<option value=""';
  947:        if (($selected eq '') || ($selected eq 'local')) {
  948:            $output .= ' selected="selected" ';
  949:        }
  950:        $output .= '> </option>';
  951:    }
  952:    my @timezones = DateTime::TimeZone->all_names;
  953:    foreach my $tzone (@timezones) {
  954:        $output.= '<option value="'.$tzone.'"';
  955:        if ($tzone eq $selected) {
  956:            $output.=' selected="selected"';
  957:        }
  958:        $output.=">$tzone</option>\n";
  959:    }
  960:    $output.="</select>";
  961:    return $output;
  962: }
  963: 
  964: sub select_datelocale {
  965:     my ($name,$selected,$onchange,$includeempty,$disabled)=@_;
  966:     my $output='<select name="'.$name.'" '.$onchange.$disabled.'>'."\n";
  967:     if ($includeempty) {
  968:         $output .= '<option value=""';
  969:         if ($selected eq '') {
  970:             $output .= ' selected="selected" ';
  971:         }
  972:         $output .= '> </option>';
  973:     }
  974:     my @languages = &Apache::lonlocal::preferred_languages();
  975:     my (@possibles,%locale_names);
  976:     my @locales = DateTime::Locale->ids();
  977:     foreach my $id (@locales) {
  978:         if ($id ne '') {
  979:             my ($en_terr,$native_terr);
  980:             my $loc = DateTime::Locale->load($id);
  981:             if (ref($loc)) {
  982:                 $en_terr = $loc->name();
  983:                 $native_terr = $loc->native_name();
  984:                 if (grep(/^en$/,@languages) || !@languages) {
  985:                     if ($en_terr ne '') {
  986:                         $locale_names{$id} = '('.$en_terr.')';
  987:                     } elsif ($native_terr ne '') {
  988:                         $locale_names{$id} = $native_terr;
  989:                     }
  990:                 } else {
  991:                     if ($native_terr ne '') {
  992:                         $locale_names{$id} = $native_terr.' ';
  993:                     } elsif ($en_terr ne '') {
  994:                         $locale_names{$id} = '('.$en_terr.')';
  995:                     }
  996:                 }
  997:                 $locale_names{$id} = Encode::encode('UTF-8',$locale_names{$id});
  998:                 push(@possibles,$id);
  999:             }
 1000:         }
 1001:     }
 1002:     foreach my $item (sort(@possibles)) {
 1003:         $output.= '<option value="'.$item.'"';
 1004:         if ($item eq $selected) {
 1005:             $output.=' selected="selected"';
 1006:         }
 1007:         $output.=">$item";
 1008:         if ($locale_names{$item} ne '') {
 1009:             $output.='  '.$locale_names{$item};
 1010:         }
 1011:         $output.="</option>\n";
 1012:     }
 1013:     $output.="</select>";
 1014:     return $output;
 1015: }
 1016: 
 1017: sub select_language {
 1018:     my ($name,$selected,$includeempty,$noedit) = @_;
 1019:     my %langchoices;
 1020:     if ($includeempty) {
 1021:         %langchoices = ('' => 'No language preference');
 1022:     }
 1023:     foreach my $id (&languageids()) {
 1024:         my $code = &supportedlanguagecode($id);
 1025:         if ($code) {
 1026:             $langchoices{$code} = &plainlanguagedescription($id);
 1027:         }
 1028:     }
 1029:     %langchoices = &Apache::lonlocal::texthash(%langchoices);
 1030:     return &select_form($selected,$name,\%langchoices,undef,$noedit);
 1031: }
 1032: 
 1033: =pod
 1034: 
 1035: =item * &linked_select_forms(...)
 1036: 
 1037: linked_select_forms returns a string containing a <script></script> block
 1038: and html for two <select> menus.  The select menus will be linked in that
 1039: changing the value of the first menu will result in new values being placed
 1040: in the second menu.  The values in the select menu will appear in alphabetical
 1041: order unless a defined order is provided.
 1042: 
 1043: linked_select_forms takes the following ordered inputs:
 1044: 
 1045: =over 4
 1046: 
 1047: =item * $formname, the name of the <form> tag
 1048: 
 1049: =item * $middletext, the text which appears between the <select> tags
 1050: 
 1051: =item * $firstdefault, the default value for the first menu
 1052: 
 1053: =item * $firstselectname, the name of the first <select> tag
 1054: 
 1055: =item * $secondselectname, the name of the second <select> tag
 1056: 
 1057: =item * $hashref, a reference to a hash containing the data for the menus.
 1058: 
 1059: =item * $menuorder, the order of values in the first menu
 1060: 
 1061: =item * $onchangefirst, additional javascript call to execute for an onchange
 1062:         event for the first <select> tag
 1063: 
 1064: =item * $onchangesecond, additional javascript call to execute for an onchange
 1065:         event for the second <select> tag
 1066: 
 1067: =back 
 1068: 
 1069: Below is an example of such a hash.  Only the 'text', 'default', and 
 1070: 'select2' keys must appear as stated.  keys(%menu) are the possible 
 1071: values for the first select menu.  The text that coincides with the 
 1072: first menu value is given in $menu{$choice1}->{'text'}.  The values 
 1073: and text for the second menu are given in the hash pointed to by 
 1074: $menu{$choice1}->{'select2'}.  
 1075: 
 1076:  my %menu = ( A1 => { text =>"Choice A1" ,
 1077:                        default => "B3",
 1078:                        select2 => { 
 1079:                            B1 => "Choice B1",
 1080:                            B2 => "Choice B2",
 1081:                            B3 => "Choice B3",
 1082:                            B4 => "Choice B4"
 1083:                            },
 1084:                        order => ['B4','B3','B1','B2'],
 1085:                    },
 1086:                A2 => { text =>"Choice A2" ,
 1087:                        default => "C2",
 1088:                        select2 => { 
 1089:                            C1 => "Choice C1",
 1090:                            C2 => "Choice C2",
 1091:                            C3 => "Choice C3"
 1092:                            },
 1093:                        order => ['C2','C1','C3'],
 1094:                    },
 1095:                A3 => { text =>"Choice A3" ,
 1096:                        default => "D6",
 1097:                        select2 => { 
 1098:                            D1 => "Choice D1",
 1099:                            D2 => "Choice D2",
 1100:                            D3 => "Choice D3",
 1101:                            D4 => "Choice D4",
 1102:                            D5 => "Choice D5",
 1103:                            D6 => "Choice D6",
 1104:                            D7 => "Choice D7"
 1105:                            },
 1106:                        order => ['D4','D3','D2','D1','D7','D6','D5'],
 1107:                    }
 1108:                );
 1109: 
 1110: =cut
 1111: 
 1112: sub linked_select_forms {
 1113:     my ($formname,
 1114:         $middletext,
 1115:         $firstdefault,
 1116:         $firstselectname,
 1117:         $secondselectname, 
 1118:         $hashref,
 1119:         $menuorder,
 1120:         $onchangefirst,
 1121:         $onchangesecond
 1122:         ) = @_;
 1123:     my $second = "document.$formname.$secondselectname";
 1124:     my $first = "document.$formname.$firstselectname";
 1125:     # output the javascript to do the changing
 1126:     my $result = '';
 1127:     $result.='<script type="text/javascript" language="JavaScript">'."\n";
 1128:     $result.="// <![CDATA[\n";
 1129:     $result.="var select2data = new Object();\n";
 1130:     $" = '","';
 1131:     my $debug = '';
 1132:     foreach my $s1 (sort(keys(%$hashref))) {
 1133:         $result.="select2data.d_$s1 = new Object();\n";        
 1134:         $result.="select2data.d_$s1.def = new String('".
 1135:             $hashref->{$s1}->{'default'}."');\n";
 1136:         $result.="select2data.d_$s1.values = new Array(";
 1137:         my @s2values = sort(keys( %{ $hashref->{$s1}->{'select2'} } ));
 1138:         if (ref($hashref->{$s1}->{'order'}) eq 'ARRAY') {
 1139:             @s2values = @{$hashref->{$s1}->{'order'}};
 1140:         }
 1141:         $result.="\"@s2values\");\n";
 1142:         $result.="select2data.d_$s1.texts = new Array(";        
 1143:         my @s2texts;
 1144:         foreach my $value (@s2values) {
 1145:             push(@s2texts, $hashref->{$s1}->{'select2'}->{$value});
 1146:         }
 1147:         $result.="\"@s2texts\");\n";
 1148:     }
 1149:     $"=' ';
 1150:     $result.= <<"END";
 1151: 
 1152: function select1_changed() {
 1153:     // Determine new choice
 1154:     var newvalue = "d_" + $first.value;
 1155:     // update select2
 1156:     var values     = select2data[newvalue].values;
 1157:     var texts      = select2data[newvalue].texts;
 1158:     var select2def = select2data[newvalue].def;
 1159:     var i;
 1160:     // out with the old
 1161:     for (i = 0; i < $second.options.length; i++) {
 1162:         $second.options[i] = null;
 1163:     }
 1164:     // in with the nuclear
 1165:     for (i=0;i<values.length; i++) {
 1166:         $second.options[i] = new Option(values[i]);
 1167:         $second.options[i].value = values[i];
 1168:         $second.options[i].text = texts[i];
 1169:         if (values[i] == select2def) {
 1170:             $second.options[i].selected = true;
 1171:         }
 1172:     }
 1173: }
 1174: // ]]>
 1175: </script>
 1176: END
 1177:     # output the initial values for the selection lists
 1178:     $result .= "<select size=\"1\" name=\"$firstselectname\" onchange=\"select1_changed();$onchangefirst\">\n";
 1179:     my @order = sort(keys(%{$hashref}));
 1180:     if (ref($menuorder) eq 'ARRAY') {
 1181:         @order = @{$menuorder};
 1182:     }
 1183:     foreach my $value (@order) {
 1184:         $result.="    <option value=\"$value\" ";
 1185:         $result.=" selected=\"selected\" " if ($value eq $firstdefault);
 1186:         $result.=">".&mt($hashref->{$value}->{'text'})."</option>\n";
 1187:     }
 1188:     $result .= "</select>\n";
 1189:     my %select2 = %{$hashref->{$firstdefault}->{'select2'}};
 1190:     $result .= $middletext;
 1191:     $result .= "<select size=\"1\" name=\"$secondselectname\"";
 1192:     if ($onchangesecond) {
 1193:         $result .= ' onchange="'.$onchangesecond.'"';
 1194:     }
 1195:     $result .= ">\n";
 1196:     my $seconddefault = $hashref->{$firstdefault}->{'default'};
 1197:     
 1198:     my @secondorder = sort(keys(%select2));
 1199:     if (ref($hashref->{$firstdefault}->{'order'}) eq 'ARRAY') {
 1200:         @secondorder = @{$hashref->{$firstdefault}->{'order'}};
 1201:     }
 1202:     foreach my $value (@secondorder) {
 1203:         $result.="    <option value=\"$value\" ";        
 1204:         $result.=" selected=\"selected\" " if ($value eq $seconddefault);
 1205:         $result.=">".&mt($select2{$value})."</option>\n";
 1206:     }
 1207:     $result .= "</select>\n";
 1208:     #    return $debug;
 1209:     return $result;
 1210: }   #  end of sub linked_select_forms {
 1211: 
 1212: =pod
 1213: 
 1214: =item * &help_open_topic($topic,$text,$stayOnPage,$width,$height,$imgid)
 1215: 
 1216: Returns a string corresponding to an HTML link to the given help
 1217: $topic, where $topic corresponds to the name of a .tex file in
 1218: /home/httpd/html/adm/help/tex, with underscores replaced by
 1219: spaces. 
 1220: 
 1221: $text will optionally be linked to the same topic, allowing you to
 1222: link text in addition to the graphic. If you do not want to link
 1223: text, but wish to specify one of the later parameters, pass an
 1224: empty string. 
 1225: 
 1226: $stayOnPage is a value that will be interpreted as a boolean. If true,
 1227: the link will not open a new window. If false, the link will open
 1228: a new window using Javascript. (Default is false.) 
 1229: 
 1230: $width and $height are optional numerical parameters that will
 1231: override the width and height of the popped up window, which may
 1232: be useful for certain help topics with big pictures included.
 1233: 
 1234: $imgid is the id of the img tag used for the help icon. This may be
 1235: used in a javascript call to switch the image src.  See 
 1236: lonhtmlcommon::htmlareaselectactive() for an example.
 1237: 
 1238: =cut
 1239: 
 1240: sub help_open_topic {
 1241:     my ($topic, $text, $stayOnPage, $width, $height, $imgid) = @_;
 1242:     $text = "" if (not defined $text);
 1243:     $stayOnPage = 0 if (not defined $stayOnPage);
 1244:     $width = 500 if (not defined $width);
 1245:     $height = 400 if (not defined $height);
 1246:     my $filename = $topic;
 1247:     $filename =~ s/ /_/g;
 1248: 
 1249:     my $template = "";
 1250:     my $link;
 1251:     
 1252:     $topic=~s/\W/\_/g;
 1253: 
 1254:     if (!$stayOnPage) {
 1255:         if ($env{'browser.mobile'}) {
 1256: 	    $link = "javascript:openMyModal('/adm/help/${filename}.hlp',$width,$height,'yes');";
 1257:         } else {
 1258:             $link = "javascript:void(open('/adm/help/${filename}.hlp', 'Help_for_$topic', 'menubar=0,toolbar=1,scrollbars=1,width=$width,height=$height,resizable=yes'))";
 1259:         }
 1260:     } elsif ($stayOnPage eq 'popup') {
 1261:         $link = "javascript:void(open('/adm/help/${filename}.hlp', 'Help_for_$topic', 'menubar=0,toolbar=1,scrollbars=1,width=$width,height=$height,resizable=yes'))";
 1262:     } else {
 1263: 	$link = "/adm/help/${filename}.hlp";
 1264:     }
 1265: 
 1266:     # Add the text
 1267:     if ($text ne "") {	
 1268: 	$template.='<span class="LC_help_open_topic">'
 1269:                   .'<a target="_top" href="'.$link.'">'
 1270:                   .$text.'</a>';
 1271:     }
 1272: 
 1273:     # (Always) Add the graphic
 1274:     my $title = &mt('Online Help');
 1275:     my $helpicon=&lonhttpdurl("/adm/help/help.png");
 1276:     if ($imgid ne '') {
 1277:         $imgid = ' id="'.$imgid.'"';
 1278:     }
 1279:     $template.=' <a target="_top" href="'.$link.'" title="'.$title.'">'
 1280:               .'<img src="'.$helpicon.'" border="0"'
 1281:               .' alt="'.&mt('Help: [_1]',$topic).'"'
 1282:               .' title="'.$title.'" style="vertical-align:middle;"'.$imgid 
 1283:               .' /></a>';
 1284:     if ($text ne "") {	
 1285:         $template.='</span>';
 1286:     }
 1287:     return $template;
 1288: 
 1289: }
 1290: 
 1291: # This is a quicky function for Latex cheatsheet editing, since it 
 1292: # appears in at least four places
 1293: sub helpLatexCheatsheet {
 1294:     my ($topic,$text,$not_author,$stayOnPage) = @_;
 1295:     my $out;
 1296:     my $addOther = '';
 1297:     if ($topic) {
 1298: 	$addOther = '<span>'.&help_open_topic($topic,&mt($text),$stayOnPage, undef, 600).'</span> ';
 1299:     }
 1300:     $out = '<span>' # Start cheatsheet
 1301: 	  .$addOther
 1302:           .'<span>'
 1303: 	  .&help_open_topic('Greek_Symbols',&mt('Greek Symbols'),$stayOnPage,undef,600)
 1304: 	  .'</span> <span>'
 1305: 	  .&help_open_topic('Other_Symbols',&mt('Other Symbols'),$stayOnPage,undef,600)
 1306: 	  .'</span>';
 1307:     unless ($not_author) {
 1308:         $out .= ' <span>'
 1309: 	       .&help_open_topic('Authoring_Output_Tags',&mt('Output Tags'),$stayOnPage,undef,600)
 1310: 	       .'</span> <span>'
 1311:                .&help_open_topic('Authoring_Multilingual_Problems',&mt('Languages'),$stayOnPage,undef,600)
 1312:                .'</span>';
 1313:     }
 1314:     $out .= '</span>'; # End cheatsheet
 1315:     return $out;
 1316: }
 1317: 
 1318: sub general_help {
 1319:     my $helptopic='Student_Intro';
 1320:     if ($env{'request.role'}=~/^(ca|au)/) {
 1321: 	$helptopic='Authoring_Intro';
 1322:     } elsif ($env{'request.role'}=~/^(cc|co)/) {
 1323: 	$helptopic='Course_Coordination_Intro';
 1324:     } elsif ($env{'request.role'}=~/^dc/) {
 1325:         $helptopic='Domain_Coordination_Intro';
 1326:     }
 1327:     return $helptopic;
 1328: }
 1329: 
 1330: sub update_help_link {
 1331:     my ($topic,$component_help,$faq,$bug,$stayOnPage) = @_;
 1332:     my $origurl = $ENV{'REQUEST_URI'};
 1333:     $origurl=~s|^/~|/priv/|;
 1334:     my $timestamp = time;
 1335:     foreach my $datum (\$topic,\$component_help,\$faq,\$bug,\$origurl) {
 1336:         $$datum = &escape($$datum);
 1337:     }
 1338: 
 1339:     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";
 1340:     my $output .= <<"ENDOUTPUT";
 1341: <script type="text/javascript">
 1342: // <![CDATA[
 1343: banner_link = '$banner_link';
 1344: // ]]>
 1345: </script>
 1346: ENDOUTPUT
 1347:     return $output;
 1348: }
 1349: 
 1350: # now just updates the help link and generates a blue icon
 1351: sub help_open_menu {
 1352:     my ($topic,$component_help,$faq,$bug,$stayOnPage,$width,$height,$text) 
 1353: 	= @_;    
 1354:     $stayOnPage = 1;
 1355:     my $output;
 1356:     if ($component_help) {
 1357: 	if (!$text) {
 1358: 	    $output=&help_open_topic($component_help,undef,$stayOnPage,
 1359: 				       $width,$height);
 1360: 	} else {
 1361: 	    my $help_text;
 1362: 	    $help_text=&unescape($topic);
 1363: 	    $output='<table><tr><td>'.
 1364: 		&help_open_topic($component_help,$help_text,$stayOnPage,
 1365: 				 $width,$height).'</td></tr></table>';
 1366: 	}
 1367:     }
 1368:     my $banner_link = &update_help_link($topic,$component_help,$faq,$bug,$stayOnPage);
 1369:     return $output.$banner_link;
 1370: }
 1371: 
 1372: sub top_nav_help {
 1373:     my ($text) = @_;
 1374:     $text = &mt($text);
 1375:     my $stay_on_page;
 1376:     unless ($env{'environment.remote'} eq 'on') {
 1377:         $stay_on_page = 1;
 1378:     }
 1379:     my ($link,$banner_link);
 1380:     unless ($env{'request.noversionuri'} =~ m{^/adm/helpmenu}) {
 1381:         $link = ($stay_on_page) ? "javascript:helpMenu('display')"
 1382: 	                         : "javascript:helpMenu('open')";
 1383:         $banner_link = &update_help_link(undef,undef,undef,undef,$stay_on_page);
 1384:     }
 1385:     my $title = &mt('Get help');
 1386:     if ($link) {
 1387:         return <<"END";
 1388: $banner_link
 1389: <a href="$link" title="$title">$text</a>
 1390: END
 1391:     } else {
 1392:         return '&nbsp;'.$text.'&nbsp;';
 1393:     }
 1394: }
 1395: 
 1396: sub help_menu_js {
 1397:     my ($httphost) = @_;
 1398:     my $stayOnPage = 1;
 1399:     my $width = 620;
 1400:     my $height = 600;
 1401:     my $helptopic=&general_help();
 1402:     my $details_link = $httphost.'/adm/help/'.$helptopic.'.hlp';
 1403:     my $nothing=&Apache::lonhtmlcommon::javascript_nothing();
 1404:     my $start_page =
 1405:         &Apache::loncommon::start_page('Help Menu', undef,
 1406: 				       {'frameset'    => 1,
 1407: 					'js_ready'    => 1,
 1408:                                         'use_absolute' => $httphost, 
 1409: 					'add_entries' => {
 1410: 					    'border' => '0',
 1411: 					    'rows'   => "110,*",},});
 1412:     my $end_page =
 1413:         &Apache::loncommon::end_page({'frameset' => 1,
 1414: 				      'js_ready' => 1,});
 1415: 
 1416:     my $template .= <<"ENDTEMPLATE";
 1417: <script type="text/javascript">
 1418: // <![CDATA[
 1419: // <!-- BEGIN LON-CAPA Internal
 1420: var banner_link = '';
 1421: function helpMenu(target) {
 1422:     var caller = this;
 1423:     if (target == 'open') {
 1424:         var newWindow = null;
 1425:         try {
 1426:             newWindow =  window.open($nothing,"helpmenu","HEIGHT=$height,WIDTH=$width,resizable=yes,scrollbars=yes" )
 1427:         }
 1428:         catch(error) {
 1429:             writeHelp(caller);
 1430:             return;
 1431:         }
 1432:         if (newWindow) {
 1433:             caller = newWindow;
 1434:         }
 1435:     }
 1436:     writeHelp(caller);
 1437:     return;
 1438: }
 1439: function writeHelp(caller) {
 1440:     caller.document.writeln('$start_page\\n<frame name="bannerframe" src="'+banner_link+'" marginwidth="0" marginheight="0" frameborder="0">\\n');
 1441:     caller.document.writeln('<frame name="bodyframe" src="$details_link" marginwidth="0" marginheight="0" frameborder="0">\\n$end_page');
 1442:     caller.document.close();
 1443:     caller.focus();
 1444: }
 1445: // END LON-CAPA Internal -->
 1446: // ]]>
 1447: </script>
 1448: ENDTEMPLATE
 1449:     return $template;
 1450: }
 1451: 
 1452: sub help_open_bug {
 1453:     my ($topic, $text, $stayOnPage, $width, $height) = @_;
 1454:     unless ($env{'user.adv'}) { return ''; }
 1455:     unless ($Apache::lonnet::perlvar{'BugzillaHost'}) { return ''; }
 1456:     $text = "" if (not defined $text);
 1457: 	$stayOnPage=1;
 1458:     $width = 600 if (not defined $width);
 1459:     $height = 600 if (not defined $height);
 1460: 
 1461:     $topic=~s/\W+/\+/g;
 1462:     my $link='';
 1463:     my $template='';
 1464:     my $url=$Apache::lonnet::perlvar{'BugzillaHost'}.'enter_bug.cgi?product=LON-CAPA&amp;bug_file_loc='.
 1465: 	&escape($ENV{'REQUEST_URI'}).'&amp;component='.$topic;
 1466:     if (!$stayOnPage)
 1467:     {
 1468: 	$link = "javascript:void(open('$url', 'Bugzilla', 'menubar=0,toolbar=1,scrollbars=1,width=$width,height=$height,resizable=yes'))";
 1469:     }
 1470:     else
 1471:     {
 1472: 	$link = $url;
 1473:     }
 1474:     # Add the text
 1475:     if ($text ne "")
 1476:     {
 1477: 	$template .= 
 1478:   "<table bgcolor='#AA3333' cellspacing='1' cellpadding='1' border='0'><tr>".
 1479:   "<td bgcolor='#FF5555'><a target=\"_top\" href=\"$link\"><span style=\"color:#FFFFFF;font-size:10pt;\">$text</span></a>";
 1480:     }
 1481: 
 1482:     # Add the graphic
 1483:     my $title = &mt('Report a Bug');
 1484:     my $bugicon=&lonhttpdurl("/adm/lonMisc/smallBug.gif");
 1485:     $template .= <<"ENDTEMPLATE";
 1486:  <a target="_top" href="$link" title="$title"><img src="$bugicon" border="0" alt="(Bug: $topic)" /></a>
 1487: ENDTEMPLATE
 1488:     if ($text ne '') { $template.='</td></tr></table>' };
 1489:     return $template;
 1490: 
 1491: }
 1492: 
 1493: sub help_open_faq {
 1494:     my ($topic, $text, $stayOnPage, $width, $height) = @_;
 1495:     unless ($env{'user.adv'}) { return ''; }
 1496:     unless ($Apache::lonnet::perlvar{'FAQHost'}) { return ''; }
 1497:     $text = "" if (not defined $text);
 1498: 	$stayOnPage=1;
 1499:     $width = 350 if (not defined $width);
 1500:     $height = 400 if (not defined $height);
 1501: 
 1502:     $topic=~s/\W+/\+/g;
 1503:     my $link='';
 1504:     my $template='';
 1505:     my $url=$Apache::lonnet::perlvar{'FAQHost'}.'/fom/cache/'.$topic.'.html';
 1506:     if (!$stayOnPage)
 1507:     {
 1508: 	$link = "javascript:void(open('$url', 'FAQ-O-Matic', 'menubar=0,toolbar=1,scrollbars=1,width=$width,height=$height,resizable=yes'))";
 1509:     }
 1510:     else
 1511:     {
 1512: 	$link = $url;
 1513:     }
 1514: 
 1515:     # Add the text
 1516:     if ($text ne "")
 1517:     {
 1518: 	$template .= 
 1519:   "<table bgcolor='#337733' cellspacing='1' cellpadding='1' border='0'><tr>".
 1520:   "<td bgcolor='#448844'><a target=\"_top\" href=\"$link\"><span style=\"color:#FFFFFF; font-size:10pt;\">$text</span></a>";
 1521:     }
 1522: 
 1523:     # Add the graphic
 1524:     my $title = &mt('View the FAQ');
 1525:     my $faqicon=&lonhttpdurl("/adm/lonMisc/smallFAQ.gif");
 1526:     $template .= <<"ENDTEMPLATE";
 1527:  <a target="_top" href="$link" title="$title"><img src="$faqicon" border="0" alt="(FAQ: $topic)" /></a>
 1528: ENDTEMPLATE
 1529:     if ($text ne '') { $template.='</td></tr></table>' };
 1530:     return $template;
 1531: 
 1532: }
 1533: 
 1534: ###############################################################
 1535: ###############################################################
 1536: 
 1537: =pod
 1538: 
 1539: =item * &change_content_javascript():
 1540: 
 1541: This and the next function allow you to create small sections of an
 1542: otherwise static HTML page that you can update on the fly with
 1543: Javascript, even in Netscape 4.
 1544: 
 1545: The Javascript fragment returned by this function (no E<lt>scriptE<gt> tag)
 1546: must be written to the HTML page once. It will prove the Javascript
 1547: function "change(name, content)". Calling the change function with the
 1548: name of the section 
 1549: you want to update, matching the name passed to C<changable_area>, and
 1550: the new content you want to put in there, will put the content into
 1551: that area.
 1552: 
 1553: B<Note>: Netscape 4 only reserves enough space for the changable area
 1554: to contain room for the original contents. You need to "make space"
 1555: for whatever changes you wish to make, and be B<sure> to check your
 1556: code in Netscape 4. This feature in Netscape 4 is B<not> powerful;
 1557: it's adequate for updating a one-line status display, but little more.
 1558: This script will set the space to 100% width, so you only need to
 1559: worry about height in Netscape 4.
 1560: 
 1561: Modern browsers are much less limiting, and if you can commit to the
 1562: user not using Netscape 4, this feature may be used freely with
 1563: pretty much any HTML.
 1564: 
 1565: =cut
 1566: 
 1567: sub change_content_javascript {
 1568:     # If we're on Netscape 4, we need to use Layer-based code
 1569:     if ($env{'browser.type'} eq 'netscape' &&
 1570: 	$env{'browser.version'} =~ /^4\./) {
 1571: 	return (<<NETSCAPE4);
 1572: 	function change(name, content) {
 1573: 	    doc = document.layers[name+"___escape"].layers[0].document;
 1574: 	    doc.open();
 1575: 	    doc.write(content);
 1576: 	    doc.close();
 1577: 	}
 1578: NETSCAPE4
 1579:     } else {
 1580: 	# Otherwise, we need to use semi-standards-compliant code
 1581: 	# (technically, "innerHTML" isn't standard but the equivalent
 1582: 	# is really scary, and every useful browser supports it
 1583: 	return (<<DOMBASED);
 1584: 	function change(name, content) {
 1585: 	    element = document.getElementById(name);
 1586: 	    element.innerHTML = content;
 1587: 	}
 1588: DOMBASED
 1589:     }
 1590: }
 1591: 
 1592: =pod
 1593: 
 1594: =item * &changable_area($name,$origContent):
 1595: 
 1596: This provides a "changable area" that can be modified on the fly via
 1597: the Javascript code provided in C<change_content_javascript>. $name is
 1598: the name you will use to reference the area later; do not repeat the
 1599: same name on a given HTML page more then once. $origContent is what
 1600: the area will originally contain, which can be left blank.
 1601: 
 1602: =cut
 1603: 
 1604: sub changable_area {
 1605:     my ($name, $origContent) = @_;
 1606: 
 1607:     if ($env{'browser.type'} eq 'netscape' &&
 1608: 	$env{'browser.version'} =~ /^4\./) {
 1609: 	# If this is netscape 4, we need to use the Layer tag
 1610: 	return "<ilayer width='100%' id='${name}___escape' overflow='none'><layer width='100%' id='$name' overflow='none'>$origContent</layer></ilayer>";
 1611:     } else {
 1612: 	return "<span id='$name'>$origContent</span>";
 1613:     }
 1614: }
 1615: 
 1616: =pod
 1617: 
 1618: =item * &viewport_geometry_js 
 1619: 
 1620: Provides javascript object (Geometry) which can provide information about the viewport geometry for the client browser.
 1621: 
 1622: =cut
 1623: 
 1624: 
 1625: sub viewport_geometry_js { 
 1626:     return <<"GEOMETRY";
 1627: var Geometry = {};
 1628: function init_geometry() {
 1629:     if (Geometry.init) { return };
 1630:     Geometry.init=1;
 1631:     if (window.innerHeight) {
 1632:         Geometry.getViewportHeight   = function() { return window.innerHeight; };
 1633:         Geometry.getViewportWidth   = function() { return window.innerWidth; };
 1634:         Geometry.getHorizontalScroll = function() { return window.pageXOffset; };
 1635:         Geometry.getVerticalScroll   = function() { return window.pageYOffset; };
 1636:     }
 1637:     else if (document.documentElement && document.documentElement.clientHeight) {
 1638:         Geometry.getViewportHeight =
 1639:             function() { return document.documentElement.clientHeight; };
 1640:         Geometry.getViewportWidth =
 1641:             function() { return document.documentElement.clientWidth; };
 1642: 
 1643:         Geometry.getHorizontalScroll =
 1644:             function() { return document.documentElement.scrollLeft; };
 1645:         Geometry.getVerticalScroll =
 1646:             function() { return document.documentElement.scrollTop; };
 1647:     }
 1648:     else if (document.body.clientHeight) {
 1649:         Geometry.getViewportHeight =
 1650:             function() { return document.body.clientHeight; };
 1651:         Geometry.getViewportWidth =
 1652:             function() { return document.body.clientWidth; };
 1653:         Geometry.getHorizontalScroll =
 1654:             function() { return document.body.scrollLeft; };
 1655:         Geometry.getVerticalScroll =
 1656:             function() { return document.body.scrollTop; };
 1657:     }
 1658: }
 1659: 
 1660: GEOMETRY
 1661: }
 1662: 
 1663: =pod
 1664: 
 1665: =item * &viewport_size_js()
 1666: 
 1667: 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. 
 1668: 
 1669: =cut
 1670: 
 1671: sub viewport_size_js {
 1672:     my $geometry = &viewport_geometry_js();
 1673:     return <<"DIMS";
 1674: 
 1675: $geometry
 1676: 
 1677: function getViewportDims(width,height) {
 1678:     init_geometry();
 1679:     width.value = Geometry.getViewportWidth();
 1680:     height.value = Geometry.getViewportHeight();
 1681:     return;
 1682: }
 1683: 
 1684: DIMS
 1685: }
 1686: 
 1687: =pod
 1688: 
 1689: =item * &resize_textarea_js()
 1690: 
 1691: emits the needed javascript to resize a textarea to be as big as possible
 1692: 
 1693: creates a function resize_textrea that takes two IDs first should be
 1694: the id of the element to resize, second should be the id of a div that
 1695: surrounds everything that comes after the textarea, this routine needs
 1696: to be attached to the <body> for the onload and onresize events.
 1697: 
 1698: =back
 1699: 
 1700: =cut
 1701: 
 1702: sub resize_textarea_js {
 1703:     my $geometry = &viewport_geometry_js();
 1704:     return <<"RESIZE";
 1705:     <script type="text/javascript">
 1706: // <![CDATA[
 1707: $geometry
 1708: 
 1709: function getX(element) {
 1710:     var x = 0;
 1711:     while (element) {
 1712: 	x += element.offsetLeft;
 1713: 	element = element.offsetParent;
 1714:     }
 1715:     return x;
 1716: }
 1717: function getY(element) {
 1718:     var y = 0;
 1719:     while (element) {
 1720: 	y += element.offsetTop;
 1721: 	element = element.offsetParent;
 1722:     }
 1723:     return y;
 1724: }
 1725: 
 1726: 
 1727: function resize_textarea(textarea_id,bottom_id) {
 1728:     init_geometry();
 1729:     var textarea        = document.getElementById(textarea_id);
 1730:     //alert(textarea);
 1731: 
 1732:     var textarea_top    = getY(textarea);
 1733:     var textarea_height = textarea.offsetHeight;
 1734:     var bottom          = document.getElementById(bottom_id);
 1735:     var bottom_top      = getY(bottom);
 1736:     var bottom_height   = bottom.offsetHeight;
 1737:     var window_height   = Geometry.getViewportHeight();
 1738:     var fudge           = 23;
 1739:     var new_height      = window_height-fudge-textarea_top-bottom_height;
 1740:     if (new_height < 300) {
 1741: 	new_height = 300;
 1742:     }
 1743:     textarea.style.height=new_height+'px';
 1744: }
 1745: // ]]>
 1746: </script>
 1747: RESIZE
 1748: 
 1749: }
 1750: 
 1751: sub colorfuleditor_js {
 1752:     return <<"COLORFULEDIT"
 1753: <script type="text/javascript">
 1754: // <![CDATA[>
 1755:     function fold_box(curDepth, lastresource){
 1756: 
 1757:     // we need a list because there can be several blocks you need to fold in one tag
 1758:         var block = document.getElementsByName('foldblock_'+curDepth);
 1759:     // but there is only one folding button per tag
 1760:         var foldbutton = document.getElementById('folding_btn_'+curDepth);
 1761: 
 1762:         if(block.item(0).style.display == 'none'){
 1763: 
 1764:             foldbutton.value = '@{[&mt("Hide")]}';
 1765:             for (i = 0; i < block.length; i++){
 1766:                 block.item(i).style.display = '';
 1767:             }
 1768:         }else{
 1769: 
 1770:             foldbutton.value = '@{[&mt("Show")]}';
 1771:             for (i = 0; i < block.length; i++){
 1772:                 // block.item(i).style.visibility = 'collapse';
 1773:                 block.item(i).style.display = 'none';
 1774:             }
 1775:         };
 1776:         saveState(lastresource);
 1777:     }
 1778: 
 1779:     function saveState (lastresource) {
 1780: 
 1781:         var tag_list = getTagList();
 1782:         if(tag_list != null){
 1783:             var timestamp = new Date().getTime();
 1784:             var key = lastresource;
 1785: 
 1786:             // the value pattern is: 'time;key1,value1;key2,value2; ... '
 1787:             // starting with timestamp
 1788:             var value = timestamp+';';
 1789: 
 1790:             // building the list of key-value pairs
 1791:             for(var i = 0; i < tag_list.length; i++){
 1792:                 value += tag_list[i]+',';
 1793:                 value += document.getElementsByName(tag_list[i])[0].style.display+';';
 1794:             }
 1795: 
 1796:             // only iterate whole storage if nothing to override
 1797:             if(localStorage.getItem(key) == null){
 1798: 
 1799:                 // prevent storage from growing large
 1800:                 if(localStorage.length > 50){
 1801:                     var regex_getTimestamp = /^(?:\d)+;/;
 1802:                     var oldest_timestamp = regex_getTimestamp.exec(localStorage.key(0));
 1803:                     var oldest_key;
 1804: 
 1805:                     for(var i = 1; i < localStorage.length; i++){
 1806:                         if (regex_getTimestamp.exec(localStorage.key(i)) < oldest_timestamp) {
 1807:                             oldest_key = localStorage.key(i);
 1808:                             oldest_timestamp = regex_getTimestamp.exec(oldest_key);
 1809:                         }
 1810:                     }
 1811:                     localStorage.removeItem(oldest_key);
 1812:                 }
 1813:             }
 1814:             localStorage.setItem(key,value);
 1815:         }
 1816:     }
 1817: 
 1818:     // restore folding status of blocks (on page load)
 1819:     function restoreState (lastresource) {
 1820:         if(localStorage.getItem(lastresource) != null){
 1821:             var key = lastresource;
 1822:             var value = localStorage.getItem(key);
 1823:             var regex_delTimestamp = /^\d+;/;
 1824: 
 1825:             value.replace(regex_delTimestamp, '');
 1826: 
 1827:             var valueArr = value.split(';');
 1828:             var pairs;
 1829:             var elements;
 1830:             for (var i = 0; i < valueArr.length; i++){
 1831:                 pairs = valueArr[i].split(',');
 1832:                 elements = document.getElementsByName(pairs[0]);
 1833: 
 1834:                 for (var j = 0; j < elements.length; j++){
 1835:                     elements[j].style.display = pairs[1];
 1836:                     if (pairs[1] == "none"){
 1837:                         var regex_id = /([_\\d]+)\$/;
 1838:                         regex_id.exec(pairs[0]);
 1839:                         document.getElementById("folding_btn"+RegExp.\$1).value = "Show";
 1840:                     }
 1841:                 }
 1842:             }
 1843:         }
 1844:     }
 1845: 
 1846:     function getTagList () {
 1847: 
 1848:         var stringToSearch = document.lonhomework.innerHTML;
 1849: 
 1850:         var ret = new Array();
 1851:         var regex_findBlock = /(foldblock_.*?)"/g;
 1852:         var tag_list = stringToSearch.match(regex_findBlock);
 1853: 
 1854:         if(tag_list != null){
 1855:             for(var i = 0; i < tag_list.length; i++){
 1856:                 ret.push(tag_list[i].replace(/"/, ''));
 1857:             }
 1858:         }
 1859:         return ret;
 1860:     }
 1861: 
 1862:     function saveScrollPosition (resource) {
 1863:         var tag_list = getTagList();
 1864: 
 1865:         // we dont always want to jump to the first block
 1866:         // 170 is roughly above the "Problem Editing" header. we just want to save if the user scrolled down further than this
 1867:         if(\$(window).scrollTop() > 170){
 1868:             if(tag_list != null){
 1869:                 var result;
 1870:                 for(var i = 0; i < tag_list.length; i++){
 1871:                     if(isElementInViewport(tag_list[i])){
 1872:                         result += tag_list[i]+';';
 1873:                     }
 1874:                 }
 1875:                 sessionStorage.setItem('anchor_'+resource, result);
 1876:             }
 1877:         } else {
 1878:             // we dont need to save zero, just delete the item to leave everything tidy
 1879:             sessionStorage.removeItem('anchor_'+resource);
 1880:         }
 1881:     }
 1882: 
 1883:     function restoreScrollPosition(resource){
 1884: 
 1885:         var elem = sessionStorage.getItem('anchor_'+resource);
 1886:         if(elem != null){
 1887:             var tag_list = elem.split(';');
 1888:             var elem_list;
 1889: 
 1890:             for(var i = 0; i < tag_list.length; i++){
 1891:                 elem_list = document.getElementsByName(tag_list[i]);
 1892: 
 1893:                 if(elem_list.length > 0){
 1894:                     elem = elem_list[0];
 1895:                     break;
 1896:                 }
 1897:             }
 1898:             elem.scrollIntoView();
 1899:         }
 1900:     }
 1901: 
 1902:     function isElementInViewport(el) {
 1903: 
 1904:         // change to last element instead of first
 1905:         var elem = document.getElementsByName(el);
 1906:         var rect = elem[0].getBoundingClientRect();
 1907: 
 1908:         return (
 1909:             rect.top >= 0 &&
 1910:             rect.left >= 0 &&
 1911:             rect.bottom <= (window.innerHeight || document.documentElement.clientHeight) && /*or $(window).height() */
 1912:             rect.right <= (window.innerWidth || document.documentElement.clientWidth) /*or $(window).width() */
 1913:         );
 1914:     }
 1915: 
 1916:     function autosize(depth){
 1917:         var cmInst = window['cm'+depth];
 1918:         var fitsizeButton = document.getElementById('fitsize'+depth);
 1919: 
 1920:         // is fixed size, switching to dynamic
 1921:         if (sessionStorage.getItem("autosized_"+depth) == null) {
 1922:             cmInst.setSize("","auto");
 1923:             fitsizeButton.value = "@{[&mt('Fixed size')]}";
 1924:             sessionStorage.setItem("autosized_"+depth, "yes");
 1925: 
 1926:         // is dynamic size, switching to fixed
 1927:         } else {
 1928:             cmInst.setSize("","300px");
 1929:             fitsizeButton.value = "@{[&mt('Dynamic size')]}";
 1930:             sessionStorage.removeItem("autosized_"+depth);
 1931:         }
 1932:     }
 1933: 
 1934: 
 1935: 
 1936: // ]]>
 1937: </script>
 1938: COLORFULEDIT
 1939: }
 1940: 
 1941: sub xmleditor_js {
 1942:     return <<XMLEDIT
 1943: <script type="text/javascript" src="/adm/jQuery/addons/jquery-scrolltofixed.js"></script>
 1944: <script type="text/javascript">
 1945: // <![CDATA[>
 1946: 
 1947:     function saveScrollPosition (resource) {
 1948: 
 1949:         var scrollPos = \$(window).scrollTop();
 1950:         sessionStorage.setItem(resource,scrollPos);
 1951:     }
 1952: 
 1953:     function restoreScrollPosition(resource){
 1954: 
 1955:         var scrollPos = sessionStorage.getItem(resource);
 1956:         \$(window).scrollTop(scrollPos);
 1957:     }
 1958: 
 1959:     // unless internet explorer
 1960:     if (!(window.navigator.appName == "Microsoft Internet Explorer" && (document.documentMode || document.compatMode))){
 1961: 
 1962:         \$(document).ready(function() {
 1963:              \$(".LC_edit_actionbar").scrollToFixed(\{zIndex: 100\});
 1964:         });
 1965:     }
 1966: 
 1967:     // inserts text at cursor position into codemirror (xml editor only)
 1968:     function insertText(text){
 1969:         cm.focus();
 1970:         var curPos = cm.getCursor();
 1971:         cm.replaceRange(text.replace(/ESCAPEDSCRIPT/g,'script'), {line: curPos.line,ch: curPos.ch});
 1972:     }
 1973: // ]]>
 1974: </script>
 1975: XMLEDIT
 1976: }
 1977: 
 1978: sub insert_folding_button {
 1979:     my $curDepth = $Apache::lonxml::curdepth;
 1980:     my $lastresource = $env{'request.ambiguous'};
 1981: 
 1982:     return "<input type=\"button\" id=\"folding_btn_$curDepth\"
 1983:             value=\"".&mt('Hide')."\" onclick=\"fold_box('$curDepth','$lastresource')\">";
 1984: }
 1985: 
 1986: 
 1987: =pod
 1988: 
 1989: =head1 Excel and CSV file utility routines
 1990: 
 1991: =cut
 1992: 
 1993: ###############################################################
 1994: ###############################################################
 1995: 
 1996: =pod
 1997: 
 1998: =over 4
 1999: 
 2000: =item * &csv_translate($text) 
 2001: 
 2002: Translate $text to allow it to be output as a 'comma separated values' 
 2003: format.
 2004: 
 2005: =cut
 2006: 
 2007: ###############################################################
 2008: ###############################################################
 2009: sub csv_translate {
 2010:     my $text = shift;
 2011:     $text =~ s/\"/\"\"/g;
 2012:     $text =~ s/\n/ /g;
 2013:     return $text;
 2014: }
 2015: 
 2016: ###############################################################
 2017: ###############################################################
 2018: 
 2019: =pod
 2020: 
 2021: =item * &define_excel_formats()
 2022: 
 2023: Define some commonly used Excel cell formats.
 2024: 
 2025: Currently supported formats:
 2026: 
 2027: =over 4
 2028: 
 2029: =item header
 2030: 
 2031: =item bold
 2032: 
 2033: =item h1
 2034: 
 2035: =item h2
 2036: 
 2037: =item h3
 2038: 
 2039: =item h4
 2040: 
 2041: =item i
 2042: 
 2043: =item date
 2044: 
 2045: =back
 2046: 
 2047: Inputs: $workbook
 2048: 
 2049: Returns: $format, a hash reference.
 2050: 
 2051: 
 2052: =cut
 2053: 
 2054: ###############################################################
 2055: ###############################################################
 2056: sub define_excel_formats {
 2057:     my ($workbook) = @_;
 2058:     my $format;
 2059:     $format->{'header'} = $workbook->add_format(bold      => 1, 
 2060:                                                 bottom    => 1,
 2061:                                                 align     => 'center');
 2062:     $format->{'bold'} = $workbook->add_format(bold=>1);
 2063:     $format->{'h1'}   = $workbook->add_format(bold=>1, size=>18);
 2064:     $format->{'h2'}   = $workbook->add_format(bold=>1, size=>16);
 2065:     $format->{'h3'}   = $workbook->add_format(bold=>1, size=>14);
 2066:     $format->{'h4'}   = $workbook->add_format(bold=>1, size=>12);
 2067:     $format->{'i'}    = $workbook->add_format(italic=>1);
 2068:     $format->{'date'} = $workbook->add_format(num_format=>
 2069:                                             'mm/dd/yyyy hh:mm:ss');
 2070:     return $format;
 2071: }
 2072: 
 2073: ###############################################################
 2074: ###############################################################
 2075: 
 2076: =pod
 2077: 
 2078: =item * &create_workbook()
 2079: 
 2080: Create an Excel worksheet.  If it fails, output message on the
 2081: request object and return undefs.
 2082: 
 2083: Inputs: Apache request object
 2084: 
 2085: Returns (undef) on failure, 
 2086:     Excel worksheet object, scalar with filename, and formats 
 2087:     from &Apache::loncommon::define_excel_formats on success
 2088: 
 2089: =cut
 2090: 
 2091: ###############################################################
 2092: ###############################################################
 2093: sub create_workbook {
 2094:     my ($r) = @_;
 2095:         #
 2096:     # Create the excel spreadsheet
 2097:     my $filename = '/prtspool/'.
 2098:         $env{'user.name'}.'_'.$env{'user.domain'}.'_'.
 2099:         time.'_'.rand(1000000000).'.xls';
 2100:     my $workbook  = Spreadsheet::WriteExcel->new('/home/httpd'.$filename);
 2101:     if (! defined($workbook)) {
 2102:         $r->log_error("Error creating excel spreadsheet $filename: $!");
 2103:         $r->print(
 2104:             '<p class="LC_error">'
 2105:            .&mt('Problems occurred in creating the new Excel file.')
 2106:            .' '.&mt('This error has been logged.')
 2107:            .' '.&mt('Please alert your LON-CAPA administrator.')
 2108:            .'</p>'
 2109:         );
 2110:         return (undef);
 2111:     }
 2112:     #
 2113:     $workbook->set_tempdir(LONCAPA::tempdir());
 2114:     #
 2115:     my $format = &Apache::loncommon::define_excel_formats($workbook);
 2116:     return ($workbook,$filename,$format);
 2117: }
 2118: 
 2119: ###############################################################
 2120: ###############################################################
 2121: 
 2122: =pod
 2123: 
 2124: =item * &create_text_file()
 2125: 
 2126: Create a file to write to and eventually make available to the user.
 2127: If file creation fails, outputs an error message on the request object and 
 2128: return undefs.
 2129: 
 2130: Inputs: Apache request object, and file suffix
 2131: 
 2132: Returns (undef) on failure, 
 2133:     Filehandle and filename on success.
 2134: 
 2135: =cut
 2136: 
 2137: ###############################################################
 2138: ###############################################################
 2139: sub create_text_file {
 2140:     my ($r,$suffix) = @_;
 2141:     if (! defined($suffix)) { $suffix = 'txt'; };
 2142:     my $fh;
 2143:     my $filename = '/prtspool/'.
 2144:         $env{'user.name'}.'_'.$env{'user.domain'}.'_'.
 2145:         time.'_'.rand(1000000000).'.'.$suffix;
 2146:     $fh = Apache::File->new('>/home/httpd'.$filename);
 2147:     if (! defined($fh)) {
 2148:         $r->log_error("Couldn't open $filename for output $!");
 2149:         $r->print(
 2150:             '<p class="LC_error">'
 2151:            .&mt('Problems occurred in creating the output file.')
 2152:            .' '.&mt('This error has been logged.')
 2153:            .' '.&mt('Please alert your LON-CAPA administrator.')
 2154:            .'</p>'
 2155:         );
 2156:     }
 2157:     return ($fh,$filename)
 2158: }
 2159: 
 2160: 
 2161: =pod 
 2162: 
 2163: =back
 2164: 
 2165: =cut
 2166: 
 2167: ###############################################################
 2168: ##        Home server <option> list generating code          ##
 2169: ###############################################################
 2170: 
 2171: # ------------------------------------------
 2172: 
 2173: sub domain_select {
 2174:     my ($name,$value,$multiple)=@_;
 2175:     my %domains=map { 
 2176: 	$_ => $_.' '. &Apache::lonnet::domain($_,'description') 
 2177:     } &Apache::lonnet::all_domains();
 2178:     if ($multiple) {
 2179: 	$domains{''}=&mt('Any domain');
 2180: 	$domains{'select_form_order'} = [sort {lc($a) cmp lc($b) } (keys(%domains))];
 2181: 	return &multiple_select_form($name,$value,4,\%domains);
 2182:     } else {
 2183: 	$domains{'select_form_order'} = [sort {lc($a) cmp lc($b) } (keys(%domains))];
 2184: 	return &select_form($name,$value,\%domains);
 2185:     }
 2186: }
 2187: 
 2188: #-------------------------------------------
 2189: 
 2190: =pod
 2191: 
 2192: =head1 Routines for form select boxes
 2193: 
 2194: =over 4
 2195: 
 2196: =item * &multiple_select_form($name,$value,$size,$hash,$order)
 2197: 
 2198: Returns a string containing a <select> element int multiple mode
 2199: 
 2200: 
 2201: Args:
 2202:   $name - name of the <select> element
 2203:   $value - scalar or array ref of values that should already be selected
 2204:   $size - number of rows long the select element is
 2205:   $hash - the elements should be 'option' => 'shown text'
 2206:           (shown text should already have been &mt())
 2207:   $order - (optional) array ref of the order to show the elements in
 2208: 
 2209: =cut
 2210: 
 2211: #-------------------------------------------
 2212: sub multiple_select_form {
 2213:     my ($name,$value,$size,$hash,$order)=@_;
 2214:     my %selected = map { $_ => 1 } ref($value)?@{$value}:($value);
 2215:     my $output='';
 2216:     if (! defined($size)) {
 2217:         $size = 4;
 2218:         if (scalar(keys(%$hash))<4) {
 2219:             $size = scalar(keys(%$hash));
 2220:         }
 2221:     }
 2222:     $output.="\n".'<select name="'.$name.'" size="'.$size.'" multiple="multiple">';
 2223:     my @order;
 2224:     if (ref($order) eq 'ARRAY')  {
 2225:         @order = @{$order};
 2226:     } else {
 2227:         @order = sort(keys(%$hash));
 2228:     }
 2229:     if (exists($$hash{'select_form_order'})) {
 2230:         @order = @{$$hash{'select_form_order'}};
 2231:     }
 2232:         
 2233:     foreach my $key (@order) {
 2234:         $output.='<option value="'.&HTML::Entities::encode($key,'"<>&').'" ';
 2235:         $output.='selected="selected" ' if ($selected{$key});
 2236:         $output.='>'.$hash->{$key}."</option>\n";
 2237:     }
 2238:     $output.="</select>\n";
 2239:     return $output;
 2240: }
 2241: 
 2242: #-------------------------------------------
 2243: 
 2244: =pod
 2245: 
 2246: =item * &select_form($defdom,$name,$hashref,$onchange,$readonly)
 2247: 
 2248: Returns a string containing a <select name='$name' size='1'> form to 
 2249: allow a user to select options from a ref to a hash containing:
 2250: option_name => displayed text. An optional $onchange can include
 2251: a javascript onchange item, e.g., onchange="this.form.submit();".
 2252: An optional arg -- $readonly -- if true will cause the select form
 2253: to be disabled, e.g., for the case where an instructor has a section-
 2254: specific role, and is viewing/modifying parameters.  
 2255: 
 2256: See lonrights.pm for an example invocation and use.
 2257: 
 2258: =cut
 2259: 
 2260: #-------------------------------------------
 2261: sub select_form {
 2262:     my ($def,$name,$hashref,$onchange,$readonly) = @_;
 2263:     return unless (ref($hashref) eq 'HASH');
 2264:     if ($onchange) {
 2265:         $onchange = ' onchange="'.$onchange.'"';
 2266:     }
 2267:     my $selectform = "<select name=\"$name\" size=\"1\"$onchange>\n";
 2268:     my @keys;
 2269:     if (exists($hashref->{'select_form_order'})) {
 2270: 	@keys=@{$hashref->{'select_form_order'}};
 2271:     } else {
 2272: 	@keys=sort(keys(%{$hashref}));
 2273:     }
 2274:     foreach my $key (@keys) {
 2275:         $selectform.=
 2276: 	    '<option value="'.&HTML::Entities::encode($key,'"<>&').'" '.
 2277:             ($key eq $def ? 'selected="selected" ' : '').
 2278:                 ">".$hashref->{$key}."</option>\n";
 2279:     }
 2280:     $selectform.="</select>";
 2281:     return $selectform;
 2282: }
 2283: 
 2284: # For display filters
 2285: 
 2286: sub display_filter {
 2287:     my ($context) = @_;
 2288:     if (!$env{'form.show'}) { $env{'form.show'}=10; }
 2289:     if (!$env{'form.displayfilter'}) { $env{'form.displayfilter'}='currentfolder'; }
 2290:     my $phraseinput = 'hidden';
 2291:     my $includeinput = 'hidden';
 2292:     my ($checked,$includetypestext);
 2293:     if ($env{'form.displayfilter'} eq 'containing') {
 2294:         $phraseinput = 'text'; 
 2295:         if ($context eq 'parmslog') {
 2296:             $includeinput = 'checkbox';
 2297:             if ($env{'form.includetypes'}) {
 2298:                 $checked = ' checked="checked"';
 2299:             }
 2300:             $includetypestext = &mt('Include parameter types');
 2301:         }
 2302:     } else {
 2303:         $includetypestext = '&nbsp;';
 2304:     }
 2305:     my ($additional,$secondid,$thirdid);
 2306:     if ($context eq 'parmslog') {
 2307:         $additional = 
 2308:             '<label><input type="'.$includeinput.'" name="includetypes"'. 
 2309:             $checked.' name="includetypes" value="1" id="includetypes" />'.
 2310:             '&nbsp;<span id="includetypestext">'.$includetypestext.'</span>'.
 2311:             '</label>';
 2312:         $secondid = 'includetypes';
 2313:         $thirdid = 'includetypestext';
 2314:     }
 2315:     my $onchange = "javascript:toggleHistoryOptions(this,'containingphrase','$context',
 2316:                                                     '$secondid','$thirdid')";
 2317:     return '<span class="LC_nobreak"><label>'.&mt('Records: [_1]',
 2318: 			       &Apache::lonmeta::selectbox('show',$env{'form.show'},undef,
 2319: 							   (&mt('all'),10,20,50,100,1000,10000))).
 2320: 	   '</label></span> <span class="LC_nobreak">'.
 2321:            &mt('Filter: [_1]',
 2322: 	   &select_form($env{'form.displayfilter'},
 2323: 			'displayfilter',
 2324: 			{'currentfolder' => 'Current folder/page',
 2325: 			 'containing' => 'Containing phrase',
 2326: 			 'none' => 'None'},$onchange)).'&nbsp;'.
 2327: 			 '<input type="'.$phraseinput.'" name="containingphrase" id="containingphrase" size="30" value="'.
 2328:                          &HTML::Entities::encode($env{'form.containingphrase'}).
 2329:                          '" />'.$additional;
 2330: }
 2331: 
 2332: sub display_filter_js {
 2333:     my $includetext = &mt('Include parameter types');
 2334:     return <<"ENDJS";
 2335:   
 2336: function toggleHistoryOptions(setter,firstid,context,secondid,thirdid) {
 2337:     var firstType = 'hidden';
 2338:     if (setter.options[setter.selectedIndex].value == 'containing') {
 2339:         firstType = 'text';
 2340:     }
 2341:     firstObject = document.getElementById(firstid);
 2342:     if (typeof(firstObject) == 'object') {
 2343:         if (firstObject.type != firstType) {
 2344:             changeInputType(firstObject,firstType);
 2345:         }
 2346:     }
 2347:     if (context == 'parmslog') {
 2348:         var secondType = 'hidden';
 2349:         if (firstType == 'text') {
 2350:             secondType = 'checkbox';
 2351:         }
 2352:         secondObject = document.getElementById(secondid);  
 2353:         if (typeof(secondObject) == 'object') {
 2354:             if (secondObject.type != secondType) {
 2355:                 changeInputType(secondObject,secondType);
 2356:             }
 2357:         }
 2358:         var textItem = document.getElementById(thirdid);
 2359:         var currtext = textItem.innerHTML;
 2360:         var newtext;
 2361:         if (firstType == 'text') {
 2362:             newtext = '$includetext';
 2363:         } else {
 2364:             newtext = '&nbsp;';
 2365:         }
 2366:         if (currtext != newtext) {
 2367:             textItem.innerHTML = newtext;
 2368:         }
 2369:     }
 2370:     return;
 2371: }
 2372: 
 2373: function changeInputType(oldObject,newType) {
 2374:     var newObject = document.createElement('input');
 2375:     newObject.type = newType;
 2376:     if (oldObject.size) {
 2377:         newObject.size = oldObject.size;
 2378:     }
 2379:     if (oldObject.value) {
 2380:         newObject.value = oldObject.value;
 2381:     }
 2382:     if (oldObject.name) {
 2383:         newObject.name = oldObject.name;
 2384:     }
 2385:     if (oldObject.id) {
 2386:         newObject.id = oldObject.id;
 2387:     }
 2388:     oldObject.parentNode.replaceChild(newObject,oldObject);
 2389:     return;
 2390: }
 2391: 
 2392: ENDJS
 2393: }
 2394: 
 2395: sub gradeleveldescription {
 2396:     my $gradelevel=shift;
 2397:     my %gradelevels=(0 => 'Not specified',
 2398: 		     1 => 'Grade 1',
 2399: 		     2 => 'Grade 2',
 2400: 		     3 => 'Grade 3',
 2401: 		     4 => 'Grade 4',
 2402: 		     5 => 'Grade 5',
 2403: 		     6 => 'Grade 6',
 2404: 		     7 => 'Grade 7',
 2405: 		     8 => 'Grade 8',
 2406: 		     9 => 'Grade 9',
 2407: 		     10 => 'Grade 10',
 2408: 		     11 => 'Grade 11',
 2409: 		     12 => 'Grade 12',
 2410: 		     13 => 'Grade 13',
 2411: 		     14 => '100 Level',
 2412: 		     15 => '200 Level',
 2413: 		     16 => '300 Level',
 2414: 		     17 => '400 Level',
 2415: 		     18 => 'Graduate Level');
 2416:     return &mt($gradelevels{$gradelevel});
 2417: }
 2418: 
 2419: sub select_level_form {
 2420:     my ($deflevel,$name)=@_;
 2421:     unless ($deflevel) { $deflevel=0; }
 2422:     my $selectform = "<select name=\"$name\" size=\"1\">\n";
 2423:     for (my $i=0; $i<=18; $i++) {
 2424:         $selectform.="<option value=\"$i\" ".
 2425:             ($i==$deflevel ? 'selected="selected" ' : '').
 2426:                 ">".&gradeleveldescription($i)."</option>\n";
 2427:     }
 2428:     $selectform.="</select>";
 2429:     return $selectform;
 2430: }
 2431: 
 2432: #-------------------------------------------
 2433: 
 2434: =pod
 2435: 
 2436: =item * &select_dom_form($defdom,$name,$includeempty,$showdomdesc,$onchange,$incdoms,$excdoms,$disabled)
 2437: 
 2438: Returns a string containing a <select name='$name' size='1'> form to 
 2439: allow a user to select the domain to preform an operation in.  
 2440: See loncreateuser.pm for an example invocation and use.
 2441: 
 2442: If the $includeempty flag is set, it also includes an empty choice ("no domain
 2443: selected");
 2444: 
 2445: If the $showdomdesc flag is set, the domain name is followed by the domain description.
 2446: 
 2447: 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.
 2448: 
 2449: The optional $incdoms is a reference to an array of domains which will be the only available options.
 2450: 
 2451: The optional $excdoms is a reference to an array of domains which will be excluded from the available options.
 2452: 
 2453: The optional $disabled argument, if true, adds the disabled attribute to the select tag. 
 2454: 
 2455: =cut
 2456: 
 2457: #-------------------------------------------
 2458: sub select_dom_form {
 2459:     my ($defdom,$name,$includeempty,$showdomdesc,$onchange,$incdoms,$excdoms,$disabled) = @_;
 2460:     if ($onchange) {
 2461:         $onchange = ' onchange="'.$onchange.'"';
 2462:     }
 2463:     if ($disabled) {
 2464:         $disabled = ' disabled="disabled"';
 2465:     }
 2466:     my (@domains,%exclude);
 2467:     if (ref($incdoms) eq 'ARRAY') {
 2468:         @domains = sort {lc($a) cmp lc($b)} (@{$incdoms});
 2469:     } else {
 2470:         @domains = sort {lc($a) cmp lc($b)} (&Apache::lonnet::all_domains());
 2471:     }
 2472:     if ($includeempty) { @domains=('',@domains); }
 2473:     if (ref($excdoms) eq 'ARRAY') {
 2474:         map { $exclude{$_} = 1; } @{$excdoms};
 2475:     }
 2476:     my $selectdomain = "<select name=\"$name\" size=\"1\"$onchange$disabled>\n";
 2477:     foreach my $dom (@domains) {
 2478:         next if ($exclude{$dom});
 2479:         $selectdomain.="<option value=\"$dom\" ".
 2480:             ($dom eq $defdom ? 'selected="selected" ' : '').'>'.$dom;
 2481:         if ($showdomdesc) {
 2482:             if ($dom ne '') {
 2483:                 my $domdesc = &Apache::lonnet::domain($dom,'description');
 2484:                 if ($domdesc ne '') {
 2485:                     $selectdomain .= ' ('.$domdesc.')';
 2486:                 }
 2487:             } 
 2488:         }
 2489:         $selectdomain .= "</option>\n";
 2490:     }
 2491:     $selectdomain.="</select>";
 2492:     return $selectdomain;
 2493: }
 2494: 
 2495: #-------------------------------------------
 2496: 
 2497: =pod
 2498: 
 2499: =item * &home_server_form_item($domain,$name,$defaultflag)
 2500: 
 2501: input: 4 arguments (two required, two optional) - 
 2502:     $domain - domain of new user
 2503:     $name - name of form element
 2504:     $default - Value of 'default' causes a default item to be first 
 2505:                             option, and selected by default. 
 2506:     $hide - Value of 'hide' causes hiding of the name of the server, 
 2507:                             if 1 server found, or default, if 0 found.
 2508: output: returns 2 items: 
 2509: (a) form element which contains either:
 2510:    (i) <select name="$name">
 2511:         <option value="$hostid1">$hostid $servers{$hostid}</option>
 2512:         <option value="$hostid2">$hostid $servers{$hostid}</option>       
 2513:        </select>
 2514:        form item if there are multiple library servers in $domain, or
 2515:    (ii) an <input type="hidden" name="$name" value="$hostid" /> form item 
 2516:        if there is only one library server in $domain.
 2517: 
 2518: (b) number of library servers found.
 2519: 
 2520: See loncreateuser.pm for example of use.
 2521: 
 2522: =cut
 2523: 
 2524: #-------------------------------------------
 2525: sub home_server_form_item {
 2526:     my ($domain,$name,$default,$hide) = @_;
 2527:     my %servers = &Apache::lonnet::get_servers($domain,'library');
 2528:     my $result;
 2529:     my $numlib = keys(%servers);
 2530:     if ($numlib > 1) {
 2531:         $result .= '<select name="'.$name.'" />'."\n";
 2532:         if ($default) {
 2533:             $result .= '<option value="default" selected="selected">'.&mt('default').
 2534:                        '</option>'."\n";
 2535:         }
 2536:         foreach my $hostid (sort(keys(%servers))) {
 2537:             $result.= '<option value="'.$hostid.'">'.
 2538: 	              $hostid.' '.$servers{$hostid}."</option>\n";
 2539:         }
 2540:         $result .= '</select>'."\n";
 2541:     } elsif ($numlib == 1) {
 2542:         my $hostid;
 2543:         foreach my $item (keys(%servers)) {
 2544:             $hostid = $item;
 2545:         }
 2546:         $result .= '<input type="hidden" name="'.$name.'" value="'.
 2547:                    $hostid.'" />';
 2548:                    if (!$hide) {
 2549:                        $result .= $hostid.' '.$servers{$hostid};
 2550:                    }
 2551:                    $result .= "\n";
 2552:     } elsif ($default) {
 2553:         $result .= '<input type="hidden" name="'.$name.
 2554:                    '" value="default" />';
 2555:                    if (!$hide) {
 2556:                        $result .= &mt('default');
 2557:                    }
 2558:                    $result .= "\n";
 2559:     }
 2560:     return ($result,$numlib);
 2561: }
 2562: 
 2563: =pod
 2564: 
 2565: =back 
 2566: 
 2567: =cut
 2568: 
 2569: ###############################################################
 2570: ##                  Decoding User Agent                      ##
 2571: ###############################################################
 2572: 
 2573: =pod
 2574: 
 2575: =head1 Decoding the User Agent
 2576: 
 2577: =over 4
 2578: 
 2579: =item * &decode_user_agent()
 2580: 
 2581: Inputs: $r
 2582: 
 2583: Outputs:
 2584: 
 2585: =over 4
 2586: 
 2587: =item * $httpbrowser
 2588: 
 2589: =item * $clientbrowser
 2590: 
 2591: =item * $clientversion
 2592: 
 2593: =item * $clientmathml
 2594: 
 2595: =item * $clientunicode
 2596: 
 2597: =item * $clientos
 2598: 
 2599: =item * $clientmobile
 2600: 
 2601: =item * $clientinfo
 2602: 
 2603: =item * $clientosversion
 2604: 
 2605: =back
 2606: 
 2607: =back 
 2608: 
 2609: =cut
 2610: 
 2611: ###############################################################
 2612: ###############################################################
 2613: sub decode_user_agent {
 2614:     my ($r)=@_;
 2615:     my @browsertype=split(/\&/,$Apache::lonnet::perlvar{"lonBrowsDet"});
 2616:     my %mathcap=split(/\&/,$$Apache::lonnet::perlvar{"lonMathML"});
 2617:     my $httpbrowser=$ENV{"HTTP_USER_AGENT"};
 2618:     if (!$httpbrowser && $r) { $httpbrowser=$r->header_in('User-Agent'); }
 2619:     my $clientbrowser='unknown';
 2620:     my $clientversion='0';
 2621:     my $clientmathml='';
 2622:     my $clientunicode='0';
 2623:     my $clientmobile=0;
 2624:     my $clientosversion='';
 2625:     for (my $i=0;$i<=$#browsertype;$i++) {
 2626:         my ($bname,$match,$notmatch,$vreg,$minv,$univ)=split(/\%/,$browsertype[$i]);
 2627: 	if (($httpbrowser=~/$match/i)  && ($httpbrowser!~/$notmatch/i)) {
 2628: 	    $clientbrowser=$bname;
 2629:             $httpbrowser=~/$vreg/i;
 2630: 	    $clientversion=$1;
 2631:             $clientmathml=($clientversion>=$minv);
 2632:             $clientunicode=($clientversion>=$univ);
 2633: 	}
 2634:     }
 2635:     my $clientos='unknown';
 2636:     my $clientinfo;
 2637:     if (($httpbrowser=~/linux/i) ||
 2638:         ($httpbrowser=~/unix/i) ||
 2639:         ($httpbrowser=~/ux/i) ||
 2640:         ($httpbrowser=~/solaris/i)) { $clientos='unix'; }
 2641:     if (($httpbrowser=~/vax/i) ||
 2642:         ($httpbrowser=~/vms/i)) { $clientos='vms'; }
 2643:     if ($httpbrowser=~/next/i) { $clientos='next'; }
 2644:     if (($httpbrowser=~/mac/i) ||
 2645:         ($httpbrowser=~/powerpc/i)) { $clientos='mac'; }
 2646:     if ($httpbrowser=~/win/i) {
 2647:         $clientos='win';
 2648:         if ($httpbrowser =~/Windows\s+NT\s+(\d+\.\d+)/i) {
 2649:             $clientosversion = $1;
 2650:         }
 2651:     }
 2652:     if ($httpbrowser=~/embed/i) { $clientos='pda'; }
 2653:     if ($httpbrowser=~/(Android|iPod|iPad|iPhone|webOS|Blackberry|Windows Phone|Opera m(?:ob|in)|Fennec)/i) {
 2654:         $clientmobile=lc($1);
 2655:     }
 2656:     if ($httpbrowser=~ m{Firefox/(\d+\.\d+)}) {
 2657:         $clientinfo = 'firefox-'.$1;
 2658:     } elsif ($httpbrowser=~ m{chromeframe/(\d+\.\d+)\.}) {
 2659:         $clientinfo = 'chromeframe-'.$1;
 2660:     }
 2661:     return ($httpbrowser,$clientbrowser,$clientversion,$clientmathml,
 2662:             $clientunicode,$clientos,$clientmobile,$clientinfo,
 2663:             $clientosversion);
 2664: }
 2665: 
 2666: ###############################################################
 2667: ##    Authentication changing form generation subroutines    ##
 2668: ###############################################################
 2669: ##
 2670: ## All of the authform_xxxxxxx subroutines take their inputs in a
 2671: ## hash, and have reasonable default values.
 2672: ##
 2673: ##    formname = the name given in the <form> tag.
 2674: #-------------------------------------------
 2675: 
 2676: =pod
 2677: 
 2678: =head1 Authentication Routines
 2679: 
 2680: =over 4
 2681: 
 2682: =item * &authform_xxxxxx()
 2683: 
 2684: The authform_xxxxxx subroutines provide javascript and html forms which 
 2685: handle some of the conveniences required for authentication forms.  
 2686: This is not an optimal method, but it works.  
 2687: 
 2688: =over 4
 2689: 
 2690: =item * authform_header
 2691: 
 2692: =item * authform_authorwarning
 2693: 
 2694: =item * authform_nochange
 2695: 
 2696: =item * authform_kerberos
 2697: 
 2698: =item * authform_internal
 2699: 
 2700: =item * authform_filesystem
 2701: 
 2702: =back
 2703: 
 2704: See loncreateuser.pm for invocation and use examples.
 2705: 
 2706: =cut
 2707: 
 2708: #-------------------------------------------
 2709: sub authform_header{  
 2710:     my %in = (
 2711:         formname => 'cu',
 2712:         kerb_def_dom => '',
 2713:         @_,
 2714:     );
 2715:     $in{'formname'} = 'document.' . $in{'formname'};
 2716:     my $result='';
 2717: 
 2718: #---------------------------------------------- Code for upper case translation
 2719:     my $Javascript_toUpperCase;
 2720:     unless ($in{kerb_def_dom}) {
 2721:         $Javascript_toUpperCase =<<"END";
 2722:         switch (choice) {
 2723:            case 'krb': currentform.elements[choicearg].value =
 2724:                currentform.elements[choicearg].value.toUpperCase();
 2725:                break;
 2726:            default:
 2727:         }
 2728: END
 2729:     } else {
 2730:         $Javascript_toUpperCase = "";
 2731:     }
 2732: 
 2733:     my $radioval = "'nochange'";
 2734:     if (defined($in{'curr_authtype'})) {
 2735:         if ($in{'curr_authtype'} ne '') {
 2736:             $radioval = "'".$in{'curr_authtype'}."arg'";
 2737:         }
 2738:     }
 2739:     my $argfield = 'null';
 2740:     if (defined($in{'mode'})) {
 2741:         if ($in{'mode'} eq 'modifycourse')  {
 2742:             if (defined($in{'curr_autharg'})) {
 2743:                 if ($in{'curr_autharg'} ne '') {
 2744:                     $argfield = "'$in{'curr_autharg'}'";
 2745:                 }
 2746:             }
 2747:         }
 2748:     }
 2749: 
 2750:     $result.=<<"END";
 2751: var current = new Object();
 2752: current.radiovalue = $radioval;
 2753: current.argfield = $argfield;
 2754: 
 2755: function changed_radio(choice,currentform) {
 2756:     var choicearg = choice + 'arg';
 2757:     // If a radio button in changed, we need to change the argfield
 2758:     if (current.radiovalue != choice) {
 2759:         current.radiovalue = choice;
 2760:         if (current.argfield != null) {
 2761:             currentform.elements[current.argfield].value = '';
 2762:         }
 2763:         if (choice == 'nochange') {
 2764:             current.argfield = null;
 2765:         } else {
 2766:             current.argfield = choicearg;
 2767:             switch(choice) {
 2768:                 case 'krb': 
 2769:                     currentform.elements[current.argfield].value = 
 2770:                         "$in{'kerb_def_dom'}";
 2771:                 break;
 2772:               default:
 2773:                 break;
 2774:             }
 2775:         }
 2776:     }
 2777:     return;
 2778: }
 2779: 
 2780: function changed_text(choice,currentform) {
 2781:     var choicearg = choice + 'arg';
 2782:     if (currentform.elements[choicearg].value !='') {
 2783:         $Javascript_toUpperCase
 2784:         // clear old field
 2785:         if ((current.argfield != choicearg) && (current.argfield != null)) {
 2786:             currentform.elements[current.argfield].value = '';
 2787:         }
 2788:         current.argfield = choicearg;
 2789:     }
 2790:     set_auth_radio_buttons(choice,currentform);
 2791:     return;
 2792: }
 2793: 
 2794: function set_auth_radio_buttons(newvalue,currentform) {
 2795:     var numauthchoices = currentform.login.length;
 2796:     if (typeof numauthchoices  == "undefined") {
 2797:         return;
 2798:     } 
 2799:     var i=0;
 2800:     while (i < numauthchoices) {
 2801:         if (currentform.login[i].value == newvalue) { break; }
 2802:         i++;
 2803:     }
 2804:     if (i == numauthchoices) {
 2805:         return;
 2806:     }
 2807:     current.radiovalue = newvalue;
 2808:     currentform.login[i].checked = true;
 2809:     return;
 2810: }
 2811: END
 2812:     return $result;
 2813: }
 2814: 
 2815: sub authform_authorwarning {
 2816:     my $result='';
 2817:     $result='<i>'.
 2818:         &mt('As a general rule, only authors or co-authors should be '.
 2819:             'filesystem authenticated '.
 2820:             '(which allows access to the server filesystem).')."</i>\n";
 2821:     return $result;
 2822: }
 2823: 
 2824: sub authform_nochange {
 2825:     my %in = (
 2826:               formname => 'document.cu',
 2827:               kerb_def_dom => 'MSU.EDU',
 2828:               @_,
 2829:           );
 2830:     my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'}); 
 2831:     my $result;
 2832:     if (!$authnum) {
 2833:         $result = &mt('Under your current role you are not permitted to change login settings for this user');
 2834:     } else {
 2835:         $result = '<label>'.&mt('[_1] Do not change login data',
 2836:                   '<input type="radio" name="login" value="nochange" '.
 2837:                   'checked="checked" onclick="'.
 2838:             "javascript:changed_radio('nochange',$in{'formname'});".'" />').
 2839: 	    '</label>';
 2840:     }
 2841:     return $result;
 2842: }
 2843: 
 2844: sub authform_kerberos {
 2845:     my %in = (
 2846:               formname => 'document.cu',
 2847:               kerb_def_dom => 'MSU.EDU',
 2848:               kerb_def_auth => 'krb4',
 2849:               @_,
 2850:               );
 2851:     my ($check4,$check5,$krbcheck,$krbarg,$krbver,$result,$authtype,
 2852:         $autharg,$jscall,$disabled);
 2853:     my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
 2854:     if ($in{'kerb_def_auth'} eq 'krb5') {
 2855:        $check5 = ' checked="checked"';
 2856:     } else {
 2857:        $check4 = ' checked="checked"';
 2858:     }
 2859:     if ($in{'readonly'}) {
 2860:         $disabled = ' disabled="disabled"';
 2861:     }
 2862:     $krbarg = $in{'kerb_def_dom'};
 2863:     if (defined($in{'curr_authtype'})) {
 2864:         if ($in{'curr_authtype'} eq 'krb') {
 2865:             $krbcheck = ' checked="checked"';
 2866:             if (defined($in{'mode'})) {
 2867:                 if ($in{'mode'} eq 'modifyuser') {
 2868:                     $krbcheck = '';
 2869:                 }
 2870:             }
 2871:             if (defined($in{'curr_kerb_ver'})) {
 2872:                 if ($in{'curr_krb_ver'} eq '5') {
 2873:                     $check5 = ' checked="checked"';
 2874:                     $check4 = '';
 2875:                 } else {
 2876:                     $check4 = ' checked="checked"';
 2877:                     $check5 = '';
 2878:                 }
 2879:             }
 2880:             if (defined($in{'curr_autharg'})) {
 2881:                 $krbarg = $in{'curr_autharg'};
 2882:             }
 2883:             if (!$can_assign{'krb4'} && !$can_assign{'krb5'}) {
 2884:                 if (defined($in{'curr_autharg'})) {
 2885:                     $result = 
 2886:     &mt('Currently Kerberos authenticated with domain [_1] Version [_2].',
 2887:         $in{'curr_autharg'},$krbver);
 2888:                 } else {
 2889:                     $result =
 2890:     &mt('Currently Kerberos authenticated, Version [_1].',$krbver);
 2891:                 }
 2892:                 return $result; 
 2893:             }
 2894:         }
 2895:     } else {
 2896:         if ($authnum == 1) {
 2897:             $authtype = '<input type="hidden" name="login" value="krb" />';
 2898:         }
 2899:     }
 2900:     if (!$can_assign{'krb4'} && !$can_assign{'krb5'}) {
 2901:         return;
 2902:     } elsif ($authtype eq '') {
 2903:         if (defined($in{'mode'})) {
 2904:             if ($in{'mode'} eq 'modifycourse') {
 2905:                 if ($authnum == 1) {
 2906:                     $authtype = '<input type="radio" name="login" value="krb"'.$disabled.' />';
 2907:                 }
 2908:             }
 2909:         }
 2910:     }
 2911:     $jscall = "javascript:changed_radio('krb',$in{'formname'});";
 2912:     if ($authtype eq '') {
 2913:         $authtype = '<input type="radio" name="login" value="krb" '.
 2914:                     'onclick="'.$jscall.'" onchange="'.$jscall.'"'.
 2915:                     $krbcheck.$disabled.' />';
 2916:     }
 2917:     if (($can_assign{'krb4'} && $can_assign{'krb5'}) ||
 2918:         ($can_assign{'krb4'} && !$can_assign{'krb5'} &&
 2919:          $in{'curr_authtype'} eq 'krb5') ||
 2920:         (!$can_assign{'krb4'} && $can_assign{'krb5'} &&
 2921:          $in{'curr_authtype'} eq 'krb4')) {
 2922:         $result .= &mt
 2923:         ('[_1] Kerberos authenticated with domain [_2] '.
 2924:          '[_3] Version 4 [_4] Version 5 [_5]',
 2925:          '<label>'.$authtype,
 2926:          '</label><input type="text" size="10" name="krbarg" '.
 2927:              'value="'.$krbarg.'" '.
 2928:              'onchange="'.$jscall.'"'.$disabled.' />',
 2929:          '<label><input type="radio" name="krbver" value="4" '.$check4.$disabled.' />',
 2930:          '</label><label><input type="radio" name="krbver" value="5" '.$check5.$disabled.' />',
 2931: 	 '</label>');
 2932:     } elsif ($can_assign{'krb4'}) {
 2933:         $result .= &mt
 2934:         ('[_1] Kerberos authenticated with domain [_2] '.
 2935:          '[_3] Version 4 [_4]',
 2936:          '<label>'.$authtype,
 2937:          '</label><input type="text" size="10" name="krbarg" '.
 2938:              'value="'.$krbarg.'" '.
 2939:              'onchange="'.$jscall.'"'.$disabled.' />',
 2940:          '<label><input type="hidden" name="krbver" value="4" />',
 2941:          '</label>');
 2942:     } elsif ($can_assign{'krb5'}) {
 2943:         $result .= &mt
 2944:         ('[_1] Kerberos authenticated with domain [_2] '.
 2945:          '[_3] Version 5 [_4]',
 2946:          '<label>'.$authtype,
 2947:          '</label><input type="text" size="10" name="krbarg" '.
 2948:              'value="'.$krbarg.'" '.
 2949:              'onchange="'.$jscall.'"'.$disabled.' />',
 2950:          '<label><input type="hidden" name="krbver" value="5" />',
 2951:          '</label>');
 2952:     }
 2953:     return $result;
 2954: }
 2955: 
 2956: sub authform_internal {
 2957:     my %in = (
 2958:                 formname => 'document.cu',
 2959:                 kerb_def_dom => 'MSU.EDU',
 2960:                 @_,
 2961:                 );
 2962:     my ($intcheck,$intarg,$result,$authtype,$autharg,$jscall,$disabled);
 2963:     my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
 2964:     if ($in{'readonly'}) {
 2965:         $disabled = ' disabled="disabled"';
 2966:     }
 2967:     if (defined($in{'curr_authtype'})) {
 2968:         if ($in{'curr_authtype'} eq 'int') {
 2969:             if ($can_assign{'int'}) {
 2970:                 $intcheck = 'checked="checked" ';
 2971:                 if (defined($in{'mode'})) {
 2972:                     if ($in{'mode'} eq 'modifyuser') {
 2973:                         $intcheck = '';
 2974:                     }
 2975:                 }
 2976:                 if (defined($in{'curr_autharg'})) {
 2977:                     $intarg = $in{'curr_autharg'};
 2978:                 }
 2979:             } else {
 2980:                 $result = &mt('Currently internally authenticated.');
 2981:                 return $result;
 2982:             }
 2983:         }
 2984:     } else {
 2985:         if ($authnum == 1) {
 2986:             $authtype = '<input type="hidden" name="login" value="int" />';
 2987:         }
 2988:     }
 2989:     if (!$can_assign{'int'}) {
 2990:         return;
 2991:     } elsif ($authtype eq '') {
 2992:         if (defined($in{'mode'})) {
 2993:             if ($in{'mode'} eq 'modifycourse') {
 2994:                 if ($authnum == 1) {
 2995:                     $authtype = '<input type="radio" name="login" value="int"'.$disabled.' />';
 2996:                 }
 2997:             }
 2998:         }
 2999:     }
 3000:     $jscall = "javascript:changed_radio('int',$in{'formname'});";
 3001:     if ($authtype eq '') {
 3002:         $authtype = '<input type="radio" name="login" value="int" '.$intcheck.
 3003:                     ' onchange="'.$jscall.'" onclick="'.$jscall.'"'.$disabled.' />';
 3004:     }
 3005:     $autharg = '<input type="password" size="10" name="intarg" value="'.
 3006:                $intarg.'" onchange="'.$jscall.'"'.$disabled.' />';
 3007:     $result = &mt
 3008:         ('[_1] Internally authenticated (with initial password [_2])',
 3009:          '<label>'.$authtype,'</label>'.$autharg);
 3010:     $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>';
 3011:     return $result;
 3012: }
 3013: 
 3014: sub authform_local {
 3015:     my %in = (
 3016:               formname => 'document.cu',
 3017:               kerb_def_dom => 'MSU.EDU',
 3018:               @_,
 3019:               );
 3020:     my ($loccheck,$locarg,$result,$authtype,$autharg,$jscall,$disabled);
 3021:     my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
 3022:     if ($in{'readonly'}) {
 3023:         $disabled = ' disabled="disabled"';
 3024:     }
 3025:     if (defined($in{'curr_authtype'})) {
 3026:         if ($in{'curr_authtype'} eq 'loc') {
 3027:             if ($can_assign{'loc'}) {
 3028:                 $loccheck = 'checked="checked" ';
 3029:                 if (defined($in{'mode'})) {
 3030:                     if ($in{'mode'} eq 'modifyuser') {
 3031:                         $loccheck = '';
 3032:                     }
 3033:                 }
 3034:                 if (defined($in{'curr_autharg'})) {
 3035:                     $locarg = $in{'curr_autharg'};
 3036:                 }
 3037:             } else {
 3038:                 $result = &mt('Currently using local (institutional) authentication.');
 3039:                 return $result;
 3040:             }
 3041:         }
 3042:     } else {
 3043:         if ($authnum == 1) {
 3044:             $authtype = '<input type="hidden" name="login" value="loc" />';
 3045:         }
 3046:     }
 3047:     if (!$can_assign{'loc'}) {
 3048:         return;
 3049:     } elsif ($authtype eq '') {
 3050:         if (defined($in{'mode'})) {
 3051:             if ($in{'mode'} eq 'modifycourse') {
 3052:                 if ($authnum == 1) {
 3053:                     $authtype = '<input type="radio" name="login" value="loc"'.$disabled.' />';
 3054:                 }
 3055:             }
 3056:         }
 3057:     }
 3058:     $jscall = "javascript:changed_radio('loc',$in{'formname'});";
 3059:     if ($authtype eq '') {
 3060:         $authtype = '<input type="radio" name="login" value="loc" '.
 3061:                     $loccheck.' onchange="'.$jscall.'" onclick="'.
 3062:                     $jscall.'"'.$disabled.' />';
 3063:     }
 3064:     $autharg = '<input type="text" size="10" name="locarg" value="'.
 3065:                $locarg.'" onchange="'.$jscall.'"'.$disabled.' />';
 3066:     $result = &mt('[_1] Local Authentication with argument [_2]',
 3067:                   '<label>'.$authtype,'</label>'.$autharg);
 3068:     return $result;
 3069: }
 3070: 
 3071: sub authform_filesystem {
 3072:     my %in = (
 3073:               formname => 'document.cu',
 3074:               kerb_def_dom => 'MSU.EDU',
 3075:               @_,
 3076:               );
 3077:     my ($fsyscheck,$result,$authtype,$autharg,$jscall,$disabled);
 3078:     my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
 3079:     if ($in{'readonly'}) {
 3080:         $disabled = ' disabled="disabled"';
 3081:     }
 3082:     if (defined($in{'curr_authtype'})) {
 3083:         if ($in{'curr_authtype'} eq 'fsys') {
 3084:             if ($can_assign{'fsys'}) {
 3085:                 $fsyscheck = 'checked="checked" ';
 3086:                 if (defined($in{'mode'})) {
 3087:                     if ($in{'mode'} eq 'modifyuser') {
 3088:                         $fsyscheck = '';
 3089:                     }
 3090:                 }
 3091:             } else {
 3092:                 $result = &mt('Currently Filesystem Authenticated.');
 3093:                 return $result;
 3094:             }           
 3095:         }
 3096:     } else {
 3097:         if ($authnum == 1) {
 3098:             $authtype = '<input type="hidden" name="login" value="fsys" />';
 3099:         }
 3100:     }
 3101:     if (!$can_assign{'fsys'}) {
 3102:         return;
 3103:     } elsif ($authtype eq '') {
 3104:         if (defined($in{'mode'})) {
 3105:             if ($in{'mode'} eq 'modifycourse') {
 3106:                 if ($authnum == 1) {
 3107:                     $authtype = '<input type="radio" name="login" value="fsys"'.$disabled.' />';
 3108:                 }
 3109:             }
 3110:         }
 3111:     }
 3112:     $jscall = "javascript:changed_radio('fsys',$in{'formname'});";
 3113:     if ($authtype eq '') {
 3114:         $authtype = '<input type="radio" name="login" value="fsys" '.
 3115:                     $fsyscheck.' onchange="'.$jscall.'" onclick="'.
 3116:                     $jscall.'"'.$disabled.' />';
 3117:     }
 3118:     $autharg = '<input type="text" size="10" name="fsysarg" value=""'.
 3119:                ' onchange="'.$jscall.'"'.$disabled.' />';
 3120:     $result = &mt
 3121:         ('[_1] Filesystem Authenticated (with initial password [_2])',
 3122:          '<label><input type="radio" name="login" value="fsys" '.
 3123:          $fsyscheck.'onchange="'.$jscall.'" onclick="'.$jscall.'"'.$disabled.' />',
 3124:          '</label><input type="password" size="10" name="fsysarg" value="" '.
 3125:                   'onchange="'.$jscall.'"'.$disabled.' />');
 3126:     return $result;
 3127: }
 3128: 
 3129: sub get_assignable_auth {
 3130:     my ($dom) = @_;
 3131:     if ($dom eq '') {
 3132:         $dom = $env{'request.role.domain'};
 3133:     }
 3134:     my %can_assign = (
 3135:                           krb4 => 1,
 3136:                           krb5 => 1,
 3137:                           int  => 1,
 3138:                           loc  => 1,
 3139:                      );
 3140:     my %domconfig = &Apache::lonnet::get_dom('configuration',['usercreation'],$dom);
 3141:     if (ref($domconfig{'usercreation'}) eq 'HASH') {
 3142:         if (ref($domconfig{'usercreation'}{'authtypes'}) eq 'HASH') {
 3143:             my $authhash = $domconfig{'usercreation'}{'authtypes'};
 3144:             my $context;
 3145:             if ($env{'request.role'} =~ /^au/) {
 3146:                 $context = 'author';
 3147:             } elsif ($env{'request.role'} =~ /^(dc|dh)/) {
 3148:                 $context = 'domain';
 3149:             } elsif ($env{'request.course.id'}) {
 3150:                 $context = 'course';
 3151:             }
 3152:             if ($context) {
 3153:                 if (ref($authhash->{$context}) eq 'HASH') {
 3154:                    %can_assign = %{$authhash->{$context}}; 
 3155:                 }
 3156:             }
 3157:         }
 3158:     }
 3159:     my $authnum = 0;
 3160:     foreach my $key (keys(%can_assign)) {
 3161:         if ($can_assign{$key}) {
 3162:             $authnum ++;
 3163:         }
 3164:     }
 3165:     if ($can_assign{'krb4'} && $can_assign{'krb5'}) {
 3166:         $authnum --;
 3167:     }
 3168:     return ($authnum,%can_assign);
 3169: }
 3170: 
 3171: ###############################################################
 3172: ##    Get Kerberos Defaults for Domain                 ##
 3173: ###############################################################
 3174: ##
 3175: ## Returns default kerberos version and an associated argument
 3176: ## as listed in file domain.tab. If not listed, provides
 3177: ## appropriate default domain and kerberos version.
 3178: ##
 3179: #-------------------------------------------
 3180: 
 3181: =pod
 3182: 
 3183: =item * &get_kerberos_defaults()
 3184: 
 3185: get_kerberos_defaults($target_domain) returns the default kerberos
 3186: version and domain. If not found, it defaults to version 4 and the 
 3187: domain of the server.
 3188: 
 3189: =over 4
 3190: 
 3191: ($def_version, $def_krb_domain) = &get_kerberos_defaults($target_domain);
 3192: 
 3193: =back
 3194: 
 3195: =back
 3196: 
 3197: =cut
 3198: 
 3199: #-------------------------------------------
 3200: sub get_kerberos_defaults {
 3201:     my $domain=shift;
 3202:     my ($krbdef,$krbdefdom);
 3203:     my %domdefaults = &Apache::lonnet::get_domain_defaults($domain);
 3204:     if (($domdefaults{'auth_def'} =~/^krb(4|5)$/) && ($domdefaults{'auth_arg_def'} ne '')) {
 3205:         $krbdef = $domdefaults{'auth_def'};
 3206:         $krbdefdom = $domdefaults{'auth_arg_def'};
 3207:     } else {
 3208:         $ENV{'SERVER_NAME'}=~/(\w+\.\w+)$/;
 3209:         my $krbdefdom=$1;
 3210:         $krbdefdom=~tr/a-z/A-Z/;
 3211:         $krbdef = "krb4";
 3212:     }
 3213:     return ($krbdef,$krbdefdom);
 3214: }
 3215: 
 3216: 
 3217: ###############################################################
 3218: ##                Thesaurus Functions                        ##
 3219: ###############################################################
 3220: 
 3221: =pod
 3222: 
 3223: =head1 Thesaurus Functions
 3224: 
 3225: =over 4
 3226: 
 3227: =item * &initialize_keywords()
 3228: 
 3229: Initializes the package variable %Keywords if it is empty.  Uses the
 3230: package variable $thesaurus_db_file.
 3231: 
 3232: =cut
 3233: 
 3234: ###################################################
 3235: 
 3236: sub initialize_keywords {
 3237:     return 1 if (scalar keys(%Keywords));
 3238:     # If we are here, %Keywords is empty, so fill it up
 3239:     #   Make sure the file we need exists...
 3240:     if (! -e $thesaurus_db_file) {
 3241:         &Apache::lonnet::logthis("Attempt to access $thesaurus_db_file".
 3242:                                  " failed because it does not exist");
 3243:         return 0;
 3244:     }
 3245:     #   Set up the hash as a database
 3246:     my %thesaurus_db;
 3247:     if (! tie(%thesaurus_db,'GDBM_File',
 3248:               $thesaurus_db_file,&GDBM_READER(),0640)){
 3249:         &Apache::lonnet::logthis("Could not tie \%thesaurus_db to ".
 3250:                                  $thesaurus_db_file);
 3251:         return 0;
 3252:     } 
 3253:     #  Get the average number of appearances of a word.
 3254:     my $avecount = $thesaurus_db{'average.count'};
 3255:     #  Put keywords (those that appear > average) into %Keywords
 3256:     while (my ($word,$data)=each (%thesaurus_db)) {
 3257:         my ($count,undef) = split /:/,$data;
 3258:         $Keywords{$word}++ if ($count > $avecount);
 3259:     }
 3260:     untie %thesaurus_db;
 3261:     # Remove special values from %Keywords.
 3262:     foreach my $value ('total.count','average.count') {
 3263:         delete($Keywords{$value}) if (exists($Keywords{$value}));
 3264:   }
 3265:     return 1;
 3266: }
 3267: 
 3268: ###################################################
 3269: 
 3270: =pod
 3271: 
 3272: =item * &keyword($word)
 3273: 
 3274: Returns true if $word is a keyword.  A keyword is a word that appears more 
 3275: than the average number of times in the thesaurus database.  Calls 
 3276: &initialize_keywords
 3277: 
 3278: =cut
 3279: 
 3280: ###################################################
 3281: 
 3282: sub keyword {
 3283:     return if (!&initialize_keywords());
 3284:     my $word=lc(shift());
 3285:     $word=~s/\W//g;
 3286:     return exists($Keywords{$word});
 3287: }
 3288: 
 3289: ###############################################################
 3290: 
 3291: =pod 
 3292: 
 3293: =item * &get_related_words()
 3294: 
 3295: Look up a word in the thesaurus.  Takes a scalar argument and returns
 3296: an array of words.  If the keyword is not in the thesaurus, an empty array
 3297: will be returned.  The order of the words returned is determined by the
 3298: database which holds them.
 3299: 
 3300: Uses global $thesaurus_db_file.
 3301: 
 3302: 
 3303: =cut
 3304: 
 3305: ###############################################################
 3306: sub get_related_words {
 3307:     my $keyword = shift;
 3308:     my %thesaurus_db;
 3309:     if (! -e $thesaurus_db_file) {
 3310:         &Apache::lonnet::logthis("Attempt to access $thesaurus_db_file ".
 3311:                                  "failed because the file does not exist");
 3312:         return ();
 3313:     }
 3314:     if (! tie(%thesaurus_db,'GDBM_File',
 3315:               $thesaurus_db_file,&GDBM_READER(),0640)){
 3316:         return ();
 3317:     } 
 3318:     my @Words=();
 3319:     my $count=0;
 3320:     if (exists($thesaurus_db{$keyword})) {
 3321: 	# The first element is the number of times
 3322: 	# the word appears.  We do not need it now.
 3323: 	my (undef,@RelatedWords) = (split(/:/,$thesaurus_db{$keyword}));
 3324: 	my (undef,$mostfrequentcount)=split(/\,/,$RelatedWords[0]);
 3325: 	my $threshold=$mostfrequentcount/10;
 3326:         foreach my $possibleword (@RelatedWords) {
 3327:             my ($word,$wordcount)=split(/\,/,$possibleword);
 3328:             if ($wordcount>$threshold) {
 3329: 		push(@Words,$word);
 3330:                 $count++;
 3331:                 if ($count>10) { last; }
 3332: 	    }
 3333:         }
 3334:     }
 3335:     untie %thesaurus_db;
 3336:     return @Words;
 3337: }
 3338: 
 3339: =pod
 3340: 
 3341: =back
 3342: 
 3343: =cut
 3344: 
 3345: # -------------------------------------------------------------- Plaintext name
 3346: =pod
 3347: 
 3348: =head1 User Name Functions
 3349: 
 3350: =over 4
 3351: 
 3352: =item * &plainname($uname,$udom,$first)
 3353: 
 3354: Takes a users logon name and returns it as a string in
 3355: "first middle last generation" form 
 3356: if $first is set to 'lastname' then it returns it as
 3357: 'lastname generation, firstname middlename' if their is a lastname
 3358: 
 3359: =cut
 3360: 
 3361: 
 3362: ###############################################################
 3363: sub plainname {
 3364:     my ($uname,$udom,$first)=@_;
 3365:     return if (!defined($uname) || !defined($udom));
 3366:     my %names=&getnames($uname,$udom);
 3367:     my $name=&Apache::lonnet::format_name($names{'firstname'},
 3368: 					  $names{'middlename'},
 3369: 					  $names{'lastname'},
 3370: 					  $names{'generation'},$first);
 3371:     $name=~s/^\s+//;
 3372:     $name=~s/\s+$//;
 3373:     $name=~s/\s+/ /g;
 3374:     if ($name !~ /\S/) { $name=$uname.':'.$udom; }
 3375:     return $name;
 3376: }
 3377: 
 3378: # -------------------------------------------------------------------- Nickname
 3379: =pod
 3380: 
 3381: =item * &nickname($uname,$udom)
 3382: 
 3383: Gets a users name and returns it as a string as
 3384: 
 3385: "&quot;nickname&quot;"
 3386: 
 3387: if the user has a nickname or
 3388: 
 3389: "first middle last generation"
 3390: 
 3391: if the user does not
 3392: 
 3393: =cut
 3394: 
 3395: sub nickname {
 3396:     my ($uname,$udom)=@_;
 3397:     return if (!defined($uname) || !defined($udom));
 3398:     my %names=&getnames($uname,$udom);
 3399:     my $name=$names{'nickname'};
 3400:     if ($name) {
 3401:        $name='&quot;'.$name.'&quot;'; 
 3402:     } else {
 3403:        $name=$names{'firstname'}.' '.$names{'middlename'}.' '.
 3404: 	     $names{'lastname'}.' '.$names{'generation'};
 3405:        $name=~s/\s+$//;
 3406:        $name=~s/\s+/ /g;
 3407:     }
 3408:     return $name;
 3409: }
 3410: 
 3411: sub getnames {
 3412:     my ($uname,$udom)=@_;
 3413:     return if (!defined($uname) || !defined($udom));
 3414:     if ($udom eq 'public' && $uname eq 'public') {
 3415: 	return ('lastname' => &mt('Public'));
 3416:     }
 3417:     my $id=$uname.':'.$udom;
 3418:     my ($names,$cached)=&Apache::lonnet::is_cached_new('namescache',$id);
 3419:     if ($cached) {
 3420: 	return %{$names};
 3421:     } else {
 3422: 	my %loadnames=&Apache::lonnet::get('environment',
 3423:                     ['firstname','middlename','lastname','generation','nickname'],
 3424: 					 $udom,$uname);
 3425: 	&Apache::lonnet::do_cache_new('namescache',$id,\%loadnames);
 3426: 	return %loadnames;
 3427:     }
 3428: }
 3429: 
 3430: # -------------------------------------------------------------------- getemails
 3431: 
 3432: =pod
 3433: 
 3434: =item * &getemails($uname,$udom)
 3435: 
 3436: Gets a user's email information and returns it as a hash with keys:
 3437: notification, critnotification, permanentemail
 3438: 
 3439: For notification and critnotification, values are comma-separated lists 
 3440: of e-mail addresses; for permanentemail, value is a single e-mail address.
 3441:  
 3442: 
 3443: =cut
 3444: 
 3445: 
 3446: sub getemails {
 3447:     my ($uname,$udom)=@_;
 3448:     if ($udom eq 'public' && $uname eq 'public') {
 3449: 	return;
 3450:     }
 3451:     if (!$udom) { $udom=$env{'user.domain'}; }
 3452:     if (!$uname) { $uname=$env{'user.name'}; }
 3453:     my $id=$uname.':'.$udom;
 3454:     my ($names,$cached)=&Apache::lonnet::is_cached_new('emailscache',$id);
 3455:     if ($cached) {
 3456: 	return %{$names};
 3457:     } else {
 3458: 	my %loadnames=&Apache::lonnet::get('environment',
 3459:                     			   ['notification','critnotification',
 3460: 					    'permanentemail'],
 3461: 					   $udom,$uname);
 3462: 	&Apache::lonnet::do_cache_new('emailscache',$id,\%loadnames);
 3463: 	return %loadnames;
 3464:     }
 3465: }
 3466: 
 3467: sub flush_email_cache {
 3468:     my ($uname,$udom)=@_;
 3469:     if (!$udom)  { $udom =$env{'user.domain'}; }
 3470:     if (!$uname) { $uname=$env{'user.name'};   }
 3471:     return if ($udom eq 'public' && $uname eq 'public');
 3472:     my $id=$uname.':'.$udom;
 3473:     &Apache::lonnet::devalidate_cache_new('emailscache',$id);
 3474: }
 3475: 
 3476: # -------------------------------------------------------------------- getlangs
 3477: 
 3478: =pod
 3479: 
 3480: =item * &getlangs($uname,$udom)
 3481: 
 3482: Gets a user's language preference and returns it as a hash with key:
 3483: language.
 3484: 
 3485: =cut
 3486: 
 3487: 
 3488: sub getlangs {
 3489:     my ($uname,$udom) = @_;
 3490:     if (!$udom)  { $udom =$env{'user.domain'}; }
 3491:     if (!$uname) { $uname=$env{'user.name'};   }
 3492:     my $id=$uname.':'.$udom;
 3493:     my ($langs,$cached)=&Apache::lonnet::is_cached_new('userlangs',$id);
 3494:     if ($cached) {
 3495:         return %{$langs};
 3496:     } else {
 3497:         my %loadlangs=&Apache::lonnet::get('environment',['languages'],
 3498:                                            $udom,$uname);
 3499:         &Apache::lonnet::do_cache_new('userlangs',$id,\%loadlangs);
 3500:         return %loadlangs;
 3501:     }
 3502: }
 3503: 
 3504: sub flush_langs_cache {
 3505:     my ($uname,$udom)=@_;
 3506:     if (!$udom)  { $udom =$env{'user.domain'}; }
 3507:     if (!$uname) { $uname=$env{'user.name'};   }
 3508:     return if ($udom eq 'public' && $uname eq 'public');
 3509:     my $id=$uname.':'.$udom;
 3510:     &Apache::lonnet::devalidate_cache_new('userlangs',$id);
 3511: }
 3512: 
 3513: # ------------------------------------------------------------------ Screenname
 3514: 
 3515: =pod
 3516: 
 3517: =item * &screenname($uname,$udom)
 3518: 
 3519: Gets a users screenname and returns it as a string
 3520: 
 3521: =cut
 3522: 
 3523: sub screenname {
 3524:     my ($uname,$udom)=@_;
 3525:     if ($uname eq $env{'user.name'} &&
 3526: 	$udom eq $env{'user.domain'}) {return $env{'environment.screenname'};}
 3527:     my %names=&Apache::lonnet::get('environment',['screenname'],$udom,$uname);
 3528:     return $names{'screenname'};
 3529: }
 3530: 
 3531: 
 3532: # ------------------------------------------------------------- Confirm Wrapper
 3533: =pod
 3534: 
 3535: =item * &confirmwrapper($message)
 3536: 
 3537: Wrap messages about completion of operation in box
 3538: 
 3539: =cut
 3540: 
 3541: sub confirmwrapper {
 3542:     my ($message)=@_;
 3543:     if ($message) {
 3544:         return "\n".'<div class="LC_confirm_box">'."\n"
 3545:                .$message."\n"
 3546:                .'</div>'."\n";
 3547:     } else {
 3548:         return $message;
 3549:     }
 3550: }
 3551: 
 3552: # ------------------------------------------------------------- Message Wrapper
 3553: 
 3554: sub messagewrapper {
 3555:     my ($link,$username,$domain,$subject,$text)=@_;
 3556:     return 
 3557:         '<a href="/adm/email?compose=individual&amp;'.
 3558:         'recname='.$username.'&amp;recdom='.$domain.
 3559: 	'&amp;subject='.&escape($subject).'&amp;text='.&escape($text).'" '.
 3560:         'title="'.&mt('Send message').'">'.$link.'</a>';
 3561: }
 3562: 
 3563: # --------------------------------------------------------------- Notes Wrapper
 3564: 
 3565: sub noteswrapper {
 3566:     my ($link,$un,$do)=@_;
 3567:     return 
 3568: "<a href='/adm/email?recordftf=retrieve&amp;recname=$un&amp;recdom=$do'>$link</a>";
 3569: }
 3570: 
 3571: # ------------------------------------------------------------- Aboutme Wrapper
 3572: 
 3573: sub aboutmewrapper {
 3574:     my ($link,$username,$domain,$target,$class)=@_;
 3575:     if (!defined($username)  && !defined($domain)) {
 3576:         return;
 3577:     }
 3578:     return '<a href="/adm/'.$domain.'/'.$username.'/aboutme"'.
 3579: 	($target?' target="'.$target.'"':'').($class?' class="'.$class.'"':'').' title="'.&mt("View this user's personal information page").'">'.$link.'</a>';
 3580: }
 3581: 
 3582: # ------------------------------------------------------------ Syllabus Wrapper
 3583: 
 3584: sub syllabuswrapper {
 3585:     my ($linktext,$coursedir,$domain)=@_;
 3586:     return qq{<a href="/public/$domain/$coursedir/syllabus">$linktext</a>};
 3587: }
 3588: 
 3589: # -----------------------------------------------------------------------------
 3590: 
 3591: sub track_student_link {
 3592:     my ($linktext,$sname,$sdom,$target,$start,$only_body) = @_;
 3593:     my $link ="/adm/trackstudent?";
 3594:     my $title = 'View recent activity';
 3595:     if (defined($sname) && $sname !~ /^\s*$/ &&
 3596:         defined($sdom)  && $sdom  !~ /^\s*$/) {
 3597:         $link .= "selected_student=$sname:$sdom";
 3598:         $title .= ' of this student';
 3599:     } 
 3600:     if (defined($target) && $target !~ /^\s*$/) {
 3601:         $target = qq{target="$target"};
 3602:     } else {
 3603:         $target = '';
 3604:     }
 3605:     if ($start) { $link.='&amp;start='.$start; }
 3606:     if ($only_body) { $link .= '&amp;only_body=1'; }
 3607:     $title = &mt($title);
 3608:     $linktext = &mt($linktext);
 3609:     return qq{<a href="$link" title="$title" $target>$linktext</a>}.
 3610: 	&help_open_topic('View_recent_activity');
 3611: }
 3612: 
 3613: sub slot_reservations_link {
 3614:     my ($linktext,$sname,$sdom,$target) = @_;
 3615:     my $link ="/adm/slotrequest?command=showresv&amp;origin=aboutme";
 3616:     my $title = 'View slot reservation history';
 3617:     if (defined($sname) && $sname !~ /^\s*$/ &&
 3618:         defined($sdom)  && $sdom  !~ /^\s*$/) {
 3619:         $link .= "&amp;uname=$sname&amp;udom=$sdom";
 3620:         $title .= ' of this student';
 3621:     }
 3622:     if (defined($target) && $target !~ /^\s*$/) {
 3623:         $target = qq{target="$target"};
 3624:     } else {
 3625:         $target = '';
 3626:     }
 3627:     $title = &mt($title);
 3628:     $linktext = &mt($linktext);
 3629:     return qq{<a href="$link" title="$title" $target>$linktext</a>};
 3630: # FIXME uncomment when help item created: &help_open_topic('Slot_Reservation_History');
 3631: 
 3632: }
 3633: 
 3634: # ===================================================== Display a student photo
 3635: 
 3636: 
 3637: sub student_image_tag {
 3638:     my ($domain,$user)=@_;
 3639:     my $imgsrc=&Apache::lonnet::studentphoto($domain,$user,'jpg');
 3640:     if (($imgsrc) && ($imgsrc ne '/adm/lonKaputt/lonlogo_broken.gif')) {
 3641: 	return '<img src="'.$imgsrc.'" align="right" />';
 3642:     } else {
 3643: 	return '';
 3644:     }
 3645: }
 3646: 
 3647: =pod
 3648: 
 3649: =back
 3650: 
 3651: =head1 Access .tab File Data
 3652: 
 3653: =over 4
 3654: 
 3655: =item * &languageids() 
 3656: 
 3657: returns list of all language ids
 3658: 
 3659: =cut
 3660: 
 3661: sub languageids {
 3662:     return sort(keys(%language));
 3663: }
 3664: 
 3665: =pod
 3666: 
 3667: =item * &languagedescription() 
 3668: 
 3669: returns description of a specified language id
 3670: 
 3671: =cut
 3672: 
 3673: sub languagedescription {
 3674:     my $code=shift;
 3675:     return  ($supported_language{$code}?'* ':'').
 3676:             $language{$code}.
 3677: 	    ($supported_language{$code}?' ('.&mt('interface available').')':'');
 3678: }
 3679: 
 3680: =pod
 3681: 
 3682: =item * &plainlanguagedescription
 3683: 
 3684: Returns both the plain language description (e.g. 'Creoles and Pidgins, English-based (Other)')
 3685: and the language character encoding (e.g. ISO) separated by a ' - ' string.
 3686: 
 3687: =cut
 3688: 
 3689: sub plainlanguagedescription {
 3690:     my $code=shift;
 3691:     return $language{$code};
 3692: }
 3693: 
 3694: =pod
 3695: 
 3696: =item * &supportedlanguagecode
 3697: 
 3698: Returns the supported language code (e.g. sptutf maps to pt) given a language
 3699: code.
 3700: 
 3701: =cut
 3702: 
 3703: sub supportedlanguagecode {
 3704:     my $code=shift;
 3705:     return $supported_language{$code};
 3706: }
 3707: 
 3708: =pod
 3709: 
 3710: =item * &latexlanguage()
 3711: 
 3712: Given a language key code returns the correspondnig language to use
 3713: to select the correct hyphenation on LaTeX printouts.  This is undef if there
 3714: is no supported hyphenation for the language code.
 3715: 
 3716: =cut
 3717: 
 3718: sub latexlanguage {
 3719:     my $code = shift;
 3720:     return $latex_language{$code};
 3721: }
 3722: 
 3723: =pod
 3724: 
 3725: =item * &latexhyphenation()
 3726: 
 3727: Same as above but what's supplied is the language as it might be stored
 3728: in the metadata.
 3729: 
 3730: =cut
 3731: 
 3732: sub latexhyphenation {
 3733:     my $key = shift;
 3734:     return $latex_language_bykey{$key};
 3735: }
 3736: 
 3737: =pod
 3738: 
 3739: =item * &copyrightids() 
 3740: 
 3741: returns list of all copyrights
 3742: 
 3743: =cut
 3744: 
 3745: sub copyrightids {
 3746:     return sort(keys(%cprtag));
 3747: }
 3748: 
 3749: =pod
 3750: 
 3751: =item * &copyrightdescription() 
 3752: 
 3753: returns description of a specified copyright id
 3754: 
 3755: =cut
 3756: 
 3757: sub copyrightdescription {
 3758:     return &mt($cprtag{shift(@_)});
 3759: }
 3760: 
 3761: =pod
 3762: 
 3763: =item * &source_copyrightids() 
 3764: 
 3765: returns list of all source copyrights
 3766: 
 3767: =cut
 3768: 
 3769: sub source_copyrightids {
 3770:     return sort(keys(%scprtag));
 3771: }
 3772: 
 3773: =pod
 3774: 
 3775: =item * &source_copyrightdescription() 
 3776: 
 3777: returns description of a specified source copyright id
 3778: 
 3779: =cut
 3780: 
 3781: sub source_copyrightdescription {
 3782:     return &mt($scprtag{shift(@_)});
 3783: }
 3784: 
 3785: =pod
 3786: 
 3787: =item * &filecategories() 
 3788: 
 3789: returns list of all file categories
 3790: 
 3791: =cut
 3792: 
 3793: sub filecategories {
 3794:     return sort(keys(%category_extensions));
 3795: }
 3796: 
 3797: =pod
 3798: 
 3799: =item * &filecategorytypes() 
 3800: 
 3801: returns list of file types belonging to a given file
 3802: category
 3803: 
 3804: =cut
 3805: 
 3806: sub filecategorytypes {
 3807:     my ($cat) = @_;
 3808:     return @{$category_extensions{lc($cat)}};
 3809: }
 3810: 
 3811: =pod
 3812: 
 3813: =item * &fileembstyle() 
 3814: 
 3815: returns embedding style for a specified file type
 3816: 
 3817: =cut
 3818: 
 3819: sub fileembstyle {
 3820:     return $fe{lc(shift(@_))};
 3821: }
 3822: 
 3823: sub filemimetype {
 3824:     return $fm{lc(shift(@_))};
 3825: }
 3826: 
 3827: 
 3828: sub filecategoryselect {
 3829:     my ($name,$value)=@_;
 3830:     return &select_form($value,$name,
 3831:                         {'' => &mt('Any category'), map { $_,$_ } sort(keys(%category_extensions))});
 3832: }
 3833: 
 3834: =pod
 3835: 
 3836: =item * &filedescription() 
 3837: 
 3838: returns description for a specified file type
 3839: 
 3840: =cut
 3841: 
 3842: sub filedescription {
 3843:     my $file_description = $fd{lc(shift())};
 3844:     $file_description =~ s:([\[\]]):~$1:g;
 3845:     return &mt($file_description);
 3846: }
 3847: 
 3848: =pod
 3849: 
 3850: =item * &filedescriptionex() 
 3851: 
 3852: returns description for a specified file type with
 3853: extra formatting
 3854: 
 3855: =cut
 3856: 
 3857: sub filedescriptionex {
 3858:     my $ex=shift;
 3859:     my $file_description = $fd{lc($ex)};
 3860:     $file_description =~ s:([\[\]]):~$1:g;
 3861:     return '.'.$ex.' '.&mt($file_description);
 3862: }
 3863: 
 3864: # End of .tab access
 3865: =pod
 3866: 
 3867: =back
 3868: 
 3869: =cut
 3870: 
 3871: # ------------------------------------------------------------------ File Types
 3872: sub fileextensions {
 3873:     return sort(keys(%fe));
 3874: }
 3875: 
 3876: # ----------------------------------------------------------- Display Languages
 3877: # returns a hash with all desired display languages
 3878: #
 3879: 
 3880: sub display_languages {
 3881:     my %languages=();
 3882:     foreach my $lang (&Apache::lonlocal::preferred_languages()) {
 3883: 	$languages{$lang}=1;
 3884:     }
 3885:     &get_unprocessed_cgi($ENV{'QUERY_STRING'},['displaylanguage']);
 3886:     if ($env{'form.displaylanguage'}) {
 3887: 	foreach my $lang (split(/\s*(\,|\;|\:)\s*/,$env{'form.displaylanguage'})) {
 3888: 	    $languages{$lang}=1;
 3889:         }
 3890:     }
 3891:     return %languages;
 3892: }
 3893: 
 3894: sub languages {
 3895:     my ($possible_langs) = @_;
 3896:     my @preferred_langs = &Apache::lonlocal::preferred_languages();
 3897:     if (!ref($possible_langs)) {
 3898: 	if( wantarray ) {
 3899: 	    return @preferred_langs;
 3900: 	} else {
 3901: 	    return $preferred_langs[0];
 3902: 	}
 3903:     }
 3904:     my %possibilities = map { $_ => 1 } (@$possible_langs);
 3905:     my @preferred_possibilities;
 3906:     foreach my $preferred_lang (@preferred_langs) {
 3907: 	if (exists($possibilities{$preferred_lang})) {
 3908: 	    push(@preferred_possibilities, $preferred_lang);
 3909: 	}
 3910:     }
 3911:     if( wantarray ) {
 3912: 	return @preferred_possibilities;
 3913:     }
 3914:     return $preferred_possibilities[0];
 3915: }
 3916: 
 3917: sub user_lang {
 3918:     my ($touname,$toudom,$fromcid) = @_;
 3919:     my @userlangs;
 3920:     if (($fromcid ne '') && ($env{'course.'.$fromcid.'.languages'} ne '')) {
 3921:         @userlangs=(@userlangs,split(/\s*(\,|\;|\:)\s*/,
 3922:                     $env{'course.'.$fromcid.'.languages'}));
 3923:     } else {
 3924:         my %langhash = &getlangs($touname,$toudom);
 3925:         if ($langhash{'languages'} ne '') {
 3926:             @userlangs = split(/\s*(\,|\;|\:)\s*/,$langhash{'languages'});
 3927:         } else {
 3928:             my %domdefs = &Apache::lonnet::get_domain_defaults($toudom);
 3929:             if ($domdefs{'lang_def'} ne '') {
 3930:                 @userlangs = ($domdefs{'lang_def'});
 3931:             }
 3932:         }
 3933:     }
 3934:     my @languages=&Apache::lonlocal::get_genlanguages(@userlangs);
 3935:     my $user_lh = Apache::localize->get_handle(@languages);
 3936:     return $user_lh;
 3937: }
 3938: 
 3939: 
 3940: ###############################################################
 3941: ##               Student Answer Attempts                     ##
 3942: ###############################################################
 3943: 
 3944: =pod
 3945: 
 3946: =head1 Alternate Problem Views
 3947: 
 3948: =over 4
 3949: 
 3950: =item * &get_previous_attempt($symb, $username, $domain, $course,
 3951:     $getattempt, $regexp, $gradesub, $usec, $identifier)
 3952: 
 3953: Return string with previous attempt on problem. Arguments:
 3954: 
 3955: =over 4
 3956: 
 3957: =item * $symb: Problem, including path
 3958: 
 3959: =item * $username: username of the desired student
 3960: 
 3961: =item * $domain: domain of the desired student
 3962: 
 3963: =item * $course: Course ID
 3964: 
 3965: =item * $getattempt: Leave blank for all attempts, otherwise put
 3966:     something
 3967: 
 3968: =item * $regexp: if string matches this regexp, the string will be
 3969:     sent to $gradesub
 3970: 
 3971: =item * $gradesub: routine that processes the string if it matches $regexp
 3972: 
 3973: =item * $usec: section of the desired student
 3974: 
 3975: =item * $identifier: counter for student (multiple students one problem) or
 3976:     problem (one student; whole sequence).
 3977: 
 3978: =back
 3979: 
 3980: The output string is a table containing all desired attempts, if any.
 3981: 
 3982: =cut
 3983: 
 3984: sub get_previous_attempt {
 3985:   my ($symb,$username,$domain,$course,$getattempt,$regexp,$gradesub,$usec,$identifier)=@_;
 3986:   my $prevattempts='';
 3987:   no strict 'refs';
 3988:   if ($symb) {
 3989:     my (%returnhash)=
 3990:       &Apache::lonnet::restore($symb,$course,$domain,$username);
 3991:     if ($returnhash{'version'}) {
 3992:       my %lasthash=();
 3993:       my $version;
 3994:       for ($version=1;$version<=$returnhash{'version'};$version++) {
 3995:         foreach my $key (reverse(sort(split(/\:/,$returnhash{$version.':keys'})))) {
 3996:             if ($key =~ /\.rawrndseed$/) {
 3997:                 my ($id) = ($key =~ /^(.+)\.rawrndseed$/);
 3998:                 $lasthash{$id.'.rndseed'} = $returnhash{$version.':'.$key};
 3999:             } else {
 4000:                 $lasthash{$key}=$returnhash{$version.':'.$key};
 4001:             }
 4002:         }
 4003:       }
 4004:       $prevattempts=&start_data_table().&start_data_table_header_row();
 4005:       $prevattempts.='<th>'.&mt('History').'</th>';
 4006:       my (%typeparts,%lasthidden,%regraded,%hidestatus);
 4007:       my $showsurv=&Apache::lonnet::allowed('vas',$env{'request.course.id'});
 4008:       foreach my $key (sort(keys(%lasthash))) {
 4009: 	my ($ign,@parts) = split(/\./,$key);
 4010: 	if ($#parts > 0) {
 4011: 	  my $data=$parts[-1];
 4012:           next if ($data eq 'foilorder');
 4013: 	  pop(@parts);
 4014:           $prevattempts.='<th>'.&mt('Part ').join('.',@parts).'<br />'.$data.'&nbsp;</th>';
 4015:           if ($data eq 'type') {
 4016:               unless ($showsurv) {
 4017:                   my $id = join(',',@parts);
 4018:                   $typeparts{$ign.'.'.$id} = $lasthash{$key};
 4019:                   if (($lasthash{$key} eq 'anonsurvey') || ($lasthash{$key} eq 'anonsurveycred')) {
 4020:                       $lasthidden{$ign.'.'.$id} = 1;
 4021:                   }
 4022:               }
 4023:               if ($identifier ne '') {
 4024:                   my $id = join(',',@parts);
 4025:                   if (&Apache::lonnet::EXT("resource.$id.problemstatus",$symb,
 4026:                                                $domain,$username,$usec,undef,$course) =~ /^no/) {
 4027:                       $hidestatus{$ign.'.'.$id} = 1;
 4028:                   }
 4029:               }
 4030:           } elsif ($data eq 'regrader') {
 4031:               if (($identifier ne '') && (@parts)) {
 4032:                   my $id = join(',',@parts);
 4033:                   $regraded{$ign.'.'.$id} = 1;
 4034:               }
 4035:           } 
 4036: 	} else {
 4037: 	  if ($#parts == 0) {
 4038: 	    $prevattempts.='<th>'.$parts[0].'</th>';
 4039: 	  } else {
 4040: 	    $prevattempts.='<th>'.$ign.'</th>';
 4041: 	  }
 4042: 	}
 4043:       }
 4044:       $prevattempts.=&end_data_table_header_row();
 4045:       if ($getattempt eq '') {
 4046:         my (%solved,%resets,%probstatus);
 4047:         if (($identifier ne '') && (keys(%regraded) > 0)) {
 4048:             for ($version=1;$version<=$returnhash{'version'};$version++) {
 4049:                 foreach my $id (keys(%regraded)) {
 4050:                     if (($returnhash{$version.':'.$id.'.regrader'}) &&
 4051:                         ($returnhash{$version.':'.$id.'.tries'} eq '') &&
 4052:                         ($returnhash{$version.':'.$id.'.award'} eq '')) {
 4053:                         push(@{$resets{$id}},$version);
 4054:                     }
 4055:                 }
 4056:             }
 4057:         }
 4058: 	for ($version=1;$version<=$returnhash{'version'};$version++) {
 4059:             my (@hidden,@unsolved);
 4060:             if (%typeparts) {
 4061:                 foreach my $id (keys(%typeparts)) {
 4062:                     if (($returnhash{$version.':'.$id.'.type'} eq 'anonsurvey') ||
 4063:                         ($returnhash{$version.':'.$id.'.type'} eq 'anonsurveycred')) {
 4064:                         push(@hidden,$id);
 4065:                     } elsif ($identifier ne '') {
 4066:                         unless (($returnhash{$version.':'.$id.'.type'} eq 'survey') ||
 4067:                                 ($returnhash{$version.':'.$id.'.type'} eq 'surveycred') ||
 4068:                                 ($hidestatus{$id})) {
 4069:                             next if ((ref($resets{$id}) eq 'ARRAY') && grep(/^\Q$version\E$/,@{$resets{$id}}));
 4070:                             if ($returnhash{$version.':'.$id.'.solved'} eq 'correct_by_student') {
 4071:                                 push(@{$solved{$id}},$version);
 4072:                             } elsif (($returnhash{$version.':'.$id.'.solved'} ne '') &&
 4073:                                      (ref($solved{$id}) eq 'ARRAY')) {
 4074:                                 my $skip;
 4075:                                 if (ref($resets{$id}) eq 'ARRAY') {
 4076:                                     foreach my $reset (@{$resets{$id}}) {
 4077:                                         if ($reset > $solved{$id}[-1]) {
 4078:                                             $skip=1;
 4079:                                             last;
 4080:                                         }
 4081:                                     }
 4082:                                 }
 4083:                                 unless ($skip) {
 4084:                                     my ($ign,$partslist) = split(/\./,$id,2);
 4085:                                     push(@unsolved,$partslist);
 4086:                                 }
 4087:                             }
 4088:                         }
 4089:                     }
 4090:                 }
 4091:             }
 4092:             $prevattempts.=&start_data_table_row().
 4093:                            '<td>'.&mt('Transaction [_1]',$version);
 4094:             if (@unsolved) {
 4095:                 $prevattempts .= '<span class="LC_nobreak"><label>'.
 4096:                                  '<input type="checkbox" name="HIDE'.$identifier.'" value="'.$version.':'.join('_',@unsolved).'" />'.
 4097:                                  &mt('Hide').'</label></span>';
 4098:             }
 4099:             $prevattempts .= '</td>';
 4100:             if (@hidden) {
 4101:                 foreach my $key (sort(keys(%lasthash))) {
 4102:                     next if ($key =~ /\.foilorder$/);
 4103:                     my $hide;
 4104:                     foreach my $id (@hidden) {
 4105:                         if ($key =~ /^\Q$id\E/) {
 4106:                             $hide = 1;
 4107:                             last;
 4108:                         }
 4109:                     }
 4110:                     if ($hide) {
 4111:                         my ($id,$data) = ($key =~ /^(.+)\.([^.]+)$/);
 4112:                         if (($data eq 'award') || ($data eq 'awarddetail')) {
 4113:                             my $value = &format_previous_attempt_value($key,
 4114:                                              $returnhash{$version.':'.$key});
 4115:                             $prevattempts.='<td>'.$value.'&nbsp;</td>';
 4116:                         } else {
 4117:                             $prevattempts.='<td>&nbsp;</td>';
 4118:                         }
 4119:                     } else {
 4120:                         if ($key =~ /\./) {
 4121:                             my $value = $returnhash{$version.':'.$key};
 4122:                             if ($key =~ /\.rndseed$/) {
 4123:                                 my ($id) = ($key =~ /^(.+)\.rndseed$/);
 4124:                                 if (exists($returnhash{$version.':'.$id.'.rawrndseed'})) {
 4125:                                     $value = $returnhash{$version.':'.$id.'.rawrndseed'};
 4126:                                 }
 4127:                             }
 4128:                             $prevattempts.='<td>'.&format_previous_attempt_value($key,$value).
 4129:                                            '&nbsp;</td>';
 4130:                         } else {
 4131:                             $prevattempts.='<td>&nbsp;</td>';
 4132:                         }
 4133:                     }
 4134:                 }
 4135:             } else {
 4136: 	        foreach my $key (sort(keys(%lasthash))) {
 4137:                     next if ($key =~ /\.foilorder$/);
 4138:                     my $value = $returnhash{$version.':'.$key};
 4139:                     if ($key =~ /\.rndseed$/) {
 4140:                         my ($id) = ($key =~ /^(.+)\.rndseed$/);
 4141:                         if (exists($returnhash{$version.':'.$id.'.rawrndseed'})) {
 4142:                             $value = $returnhash{$version.':'.$id.'.rawrndseed'};
 4143:                         }
 4144:                     }
 4145:                     $prevattempts.='<td>'.&format_previous_attempt_value($key,$value).
 4146:                                    '&nbsp;</td>';
 4147: 	        }
 4148:             }
 4149: 	    $prevattempts.=&end_data_table_row();
 4150: 	 }
 4151:       }
 4152:       my @currhidden = keys(%lasthidden);
 4153:       $prevattempts.=&start_data_table_row().'<td>'.&mt('Current').'</td>';
 4154:       foreach my $key (sort(keys(%lasthash))) {
 4155:           next if ($key =~ /\.foilorder$/);
 4156:           if (%typeparts) {
 4157:               my $hidden;
 4158:               foreach my $id (@currhidden) {
 4159:                   if ($key =~ /^\Q$id\E/) {
 4160:                       $hidden = 1;
 4161:                       last;
 4162:                   }
 4163:               }
 4164:               if ($hidden) {
 4165:                   my ($id,$data) = ($key =~ /^(.+)\.([^.]+)$/);
 4166:                   if (($data eq 'award') || ($data eq 'awarddetail')) {
 4167:                       my $value = &format_previous_attempt_value($key,$lasthash{$key});
 4168:                       if ($key =~/$regexp$/ && (defined &$gradesub)) {
 4169:                           $value = &$gradesub($value);
 4170:                       }
 4171:                       $prevattempts.='<td>'.$value.'&nbsp;</td>';
 4172:                   } else {
 4173:                       $prevattempts.='<td>&nbsp;</td>';
 4174:                   }
 4175:               } else {
 4176:                   my $value = &format_previous_attempt_value($key,$lasthash{$key});
 4177:                   if ($key =~/$regexp$/ && (defined &$gradesub)) {
 4178:                       $value = &$gradesub($value);
 4179:                   }
 4180:                   $prevattempts.='<td>'.$value.'&nbsp;</td>';
 4181:               }
 4182:           } else {
 4183: 	      my $value = &format_previous_attempt_value($key,$lasthash{$key});
 4184: 	      if ($key =~/$regexp$/ && (defined &$gradesub)) {
 4185:                   $value = &$gradesub($value);
 4186:               }
 4187: 	      $prevattempts.='<td>'.$value.'&nbsp;</td>';
 4188:           }
 4189:       }
 4190:       $prevattempts.= &end_data_table_row().&end_data_table();
 4191:     } else {
 4192:       $prevattempts=
 4193: 	  &start_data_table().&start_data_table_row().
 4194: 	  '<td>'.&mt('Nothing submitted - no attempts.').'</td>'.
 4195: 	  &end_data_table_row().&end_data_table();
 4196:     }
 4197:   } else {
 4198:     $prevattempts=
 4199: 	  &start_data_table().&start_data_table_row().
 4200: 	  '<td>'.&mt('No data.').'</td>'.
 4201: 	  &end_data_table_row().&end_data_table();
 4202:   }
 4203: }
 4204: 
 4205: sub format_previous_attempt_value {
 4206:     my ($key,$value) = @_;
 4207:     if (($key =~ /timestamp/) || ($key=~/duedate/)) {
 4208: 	$value = &Apache::lonlocal::locallocaltime($value);
 4209:     } elsif (ref($value) eq 'ARRAY') {
 4210: 	$value = '('.join(', ', @{ $value }).')';
 4211:     } elsif ($key =~ /answerstring$/) {
 4212:         my %answers = &Apache::lonnet::str2hash($value);
 4213:         my @anskeys = sort(keys(%answers));
 4214:         if (@anskeys == 1) {
 4215:             my $answer = $answers{$anskeys[0]};
 4216:             if ($answer =~ m{\0}) {
 4217:                 $answer =~ s{\0}{,}g;
 4218:             }
 4219:             my $tag_internal_answer_name = 'INTERNAL';
 4220:             if ($anskeys[0] eq $tag_internal_answer_name) {
 4221:                 $value = $answer; 
 4222:             } else {
 4223:                 $value = $anskeys[0].'='.$answer;
 4224:             }
 4225:         } else {
 4226:             foreach my $ans (@anskeys) {
 4227:                 my $answer = $answers{$ans};
 4228:                 if ($answer =~ m{\0}) {
 4229:                     $answer =~ s{\0}{,}g;
 4230:                 }
 4231:                 $value .=  $ans.'='.$answer.'<br />';;
 4232:             } 
 4233:         }
 4234:     } else {
 4235: 	$value = &unescape($value);
 4236:     }
 4237:     return $value;
 4238: }
 4239: 
 4240: 
 4241: sub relative_to_absolute {
 4242:     my ($url,$output)=@_;
 4243:     my $parser=HTML::TokeParser->new(\$output);
 4244:     my $token;
 4245:     my $thisdir=$url;
 4246:     my @rlinks=();
 4247:     while ($token=$parser->get_token) {
 4248: 	if ($token->[0] eq 'S') {
 4249: 	    if ($token->[1] eq 'a') {
 4250: 		if ($token->[2]->{'href'}) {
 4251: 		    $rlinks[$#rlinks+1]=$token->[2]->{'href'};
 4252: 		}
 4253: 	    } elsif ($token->[1] eq 'img' || $token->[1] eq 'embed' ) {
 4254: 		$rlinks[$#rlinks+1]=$token->[2]->{'src'};
 4255: 	    } elsif ($token->[1] eq 'base') {
 4256: 		$thisdir=$token->[2]->{'href'};
 4257: 	    }
 4258: 	}
 4259:     }
 4260:     $thisdir=~s-/[^/]*$--;
 4261:     foreach my $link (@rlinks) {
 4262: 	unless (($link=~/^https?\:\/\//i) ||
 4263: 		($link=~/^\//) ||
 4264: 		($link=~/^javascript:/i) ||
 4265: 		($link=~/^mailto:/i) ||
 4266: 		($link=~/^\#/)) {
 4267: 	    my $newlocation=&Apache::lonnet::hreflocation($thisdir,$link);
 4268: 	    $output=~s/(\"|\'|\=\s*)\Q$link\E(\"|\'|\s|\>)/$1$newlocation$2/;
 4269: 	}
 4270:     }
 4271: # -------------------------------------------------- Deal with Applet codebases
 4272:     $output=~s/(\<applet[^\>]+)(codebase\=[^\S\>]+)*([^\>]*)\>/$1.($2?$2:' codebase="'.$thisdir.'"').$3.'>'/gei;
 4273:     return $output;
 4274: }
 4275: 
 4276: =pod
 4277: 
 4278: =item * &get_student_view()
 4279: 
 4280: show a snapshot of what student was looking at
 4281: 
 4282: =cut
 4283: 
 4284: sub get_student_view {
 4285:   my ($symb,$username,$domain,$courseid,$target,$moreenv) = @_;
 4286:   my ($map,$id,$feedurl) = &Apache::lonnet::decode_symb($symb);
 4287:   my (%form);
 4288:   my @elements=('symb','courseid','domain','username');
 4289:   foreach my $element (@elements) {
 4290:       $form{'grade_'.$element}=eval '$'.$element #'
 4291:   }
 4292:   if (defined($moreenv)) {
 4293:       %form=(%form,%{$moreenv});
 4294:   }
 4295:   if (defined($target)) { $form{'grade_target'} = $target; }
 4296:   $feedurl=&Apache::lonnet::clutter($feedurl);
 4297:   my ($userview,$response)=&Apache::lonnet::ssi_body($feedurl,%form);
 4298:   $userview=~s/\<body[^\>]*\>//gi;
 4299:   $userview=~s/\<\/body\>//gi;
 4300:   $userview=~s/\<html\>//gi;
 4301:   $userview=~s/\<\/html\>//gi;
 4302:   $userview=~s/\<head\>//gi;
 4303:   $userview=~s/\<\/head\>//gi;
 4304:   $userview=~s/action\s*\=/would_be_action\=/gi;
 4305:   $userview=&relative_to_absolute($feedurl,$userview);
 4306:   if (wantarray) {
 4307:      return ($userview,$response);
 4308:   } else {
 4309:      return $userview;
 4310:   }
 4311: }
 4312: 
 4313: sub get_student_view_with_retries {
 4314:   my ($symb,$retries,$username,$domain,$courseid,$target,$moreenv) = @_;
 4315: 
 4316:     my $ok = 0;                 # True if we got a good response.
 4317:     my $content;
 4318:     my $response;
 4319: 
 4320:     # Try to get the student_view done. within the retries count:
 4321:     
 4322:     do {
 4323:          ($content, $response) = &get_student_view($symb,$username,$domain,$courseid,$target,$moreenv);
 4324:          $ok      = $response->is_success;
 4325:          if (!$ok) {
 4326:             &Apache::lonnet::logthis("Failed get_student_view_with_retries on $symb: ".$response->is_success.', '.$response->code.', '.$response->message);
 4327:          }
 4328:          $retries--;
 4329:     } while (!$ok && ($retries > 0));
 4330:     
 4331:     if (!$ok) {
 4332:        $content = '';          # On error return an empty content.
 4333:     }
 4334:     if (wantarray) {
 4335:        return ($content, $response);
 4336:     } else {
 4337:        return $content;
 4338:     }
 4339: }
 4340: 
 4341: =pod
 4342: 
 4343: =item * &get_student_answers() 
 4344: 
 4345: show a snapshot of how student was answering problem
 4346: 
 4347: =cut
 4348: 
 4349: sub get_student_answers {
 4350:   my ($symb,$username,$domain,$courseid,%form) = @_;
 4351:   my ($map,$id,$feedurl) = &Apache::lonnet::decode_symb($symb);
 4352:   my (%moreenv);
 4353:   my @elements=('symb','courseid','domain','username');
 4354:   foreach my $element (@elements) {
 4355:     $moreenv{'grade_'.$element}=eval '$'.$element #'
 4356:   }
 4357:   $moreenv{'grade_target'}='answer';
 4358:   %moreenv=(%form,%moreenv);
 4359:   $feedurl = &Apache::lonnet::clutter($feedurl);
 4360:   my $userview=&Apache::lonnet::ssi($feedurl,%moreenv);
 4361:   return $userview;
 4362: }
 4363: 
 4364: =pod
 4365: 
 4366: =item * &submlink()
 4367: 
 4368: Inputs: $text $uname $udom $symb $target
 4369: 
 4370: Returns: A link to grades.pm such as to see the SUBM view of a student
 4371: 
 4372: =cut
 4373: 
 4374: ###############################################
 4375: sub submlink {
 4376:     my ($text,$uname,$udom,$symb,$target)=@_;
 4377:     if (!($uname && $udom)) {
 4378: 	(my $cursymb, my $courseid,$udom,$uname)=
 4379: 	    &Apache::lonnet::whichuser($symb);
 4380: 	if (!$symb) { $symb=$cursymb; }
 4381:     }
 4382:     if (!$symb) { $symb=&Apache::lonnet::symbread(); }
 4383:     $symb=&escape($symb);
 4384:     if ($target) { $target=" target=\"$target\""; }
 4385:     return
 4386:         '<a href="/adm/grades?command=submission'.
 4387:         '&amp;symb='.$symb.
 4388:         '&amp;student='.$uname.
 4389:         '&amp;userdom='.$udom.'"'.
 4390:         $target.'>'.$text.'</a>';
 4391: }
 4392: ##############################################
 4393: 
 4394: =pod
 4395: 
 4396: =item * &pgrdlink()
 4397: 
 4398: Inputs: $text $uname $udom $symb $target
 4399: 
 4400: Returns: A link to grades.pm such as to see the PGRD view of a student
 4401: 
 4402: =cut
 4403: 
 4404: ###############################################
 4405: sub pgrdlink {
 4406:     my $link=&submlink(@_);
 4407:     $link=~s/(&command=submission)/$1&showgrading=yes/;
 4408:     return $link;
 4409: }
 4410: ##############################################
 4411: 
 4412: =pod
 4413: 
 4414: =item * &pprmlink()
 4415: 
 4416: Inputs: $text $uname $udom $symb $target
 4417: 
 4418: Returns: A link to parmset.pm such as to see the PPRM view of a
 4419: student and a specific resource
 4420: 
 4421: =cut
 4422: 
 4423: ###############################################
 4424: sub pprmlink {
 4425:     my ($text,$uname,$udom,$symb,$target)=@_;
 4426:     if (!($uname && $udom)) {
 4427: 	(my $cursymb, my $courseid,$udom,$uname)=
 4428: 	    &Apache::lonnet::whichuser($symb);
 4429: 	if (!$symb) { $symb=$cursymb; }
 4430:     }
 4431:     if (!$symb) { $symb=&Apache::lonnet::symbread(); }
 4432:     $symb=&escape($symb);
 4433:     if ($target) { $target="target=\"$target\""; }
 4434:     return '<a href="/adm/parmset?command=set&amp;'.
 4435: 	'symb='.$symb.'&amp;uname='.$uname.
 4436: 	'&amp;udom='.$udom.'" '.$target.'>'.$text.'</a>';
 4437: }
 4438: ##############################################
 4439: 
 4440: =pod
 4441: 
 4442: =back
 4443: 
 4444: =cut
 4445: 
 4446: ###############################################
 4447: 
 4448: 
 4449: sub timehash {
 4450:     my ($thistime) = @_;
 4451:     my $timezone = &Apache::lonlocal::gettimezone();
 4452:     my $dt = DateTime->from_epoch(epoch => $thistime)
 4453:                      ->set_time_zone($timezone);
 4454:     my $wday = $dt->day_of_week();
 4455:     if ($wday == 7) { $wday = 0; }
 4456:     return ( 'second' => $dt->second(),
 4457:              'minute' => $dt->minute(),
 4458:              'hour'   => $dt->hour(),
 4459:              'day'     => $dt->day_of_month(),
 4460:              'month'   => $dt->month(),
 4461:              'year'    => $dt->year(),
 4462:              'weekday' => $wday,
 4463:              'dayyear' => $dt->day_of_year(),
 4464:              'dlsav'   => $dt->is_dst() );
 4465: }
 4466: 
 4467: sub utc_string {
 4468:     my ($date)=@_;
 4469:     return strftime("%Y%m%dT%H%M%SZ",gmtime($date));
 4470: }
 4471: 
 4472: sub maketime {
 4473:     my %th=@_;
 4474:     my ($epoch_time,$timezone,$dt);
 4475:     $timezone = &Apache::lonlocal::gettimezone();
 4476:     eval {
 4477:         $dt = DateTime->new( year   => $th{'year'},
 4478:                              month  => $th{'month'},
 4479:                              day    => $th{'day'},
 4480:                              hour   => $th{'hour'},
 4481:                              minute => $th{'minute'},
 4482:                              second => $th{'second'},
 4483:                              time_zone => $timezone,
 4484:                          );
 4485:     };
 4486:     if (!$@) {
 4487:         $epoch_time = $dt->epoch;
 4488:         if ($epoch_time) {
 4489:             return $epoch_time;
 4490:         }
 4491:     }
 4492:     return POSIX::mktime(
 4493:         ($th{'seconds'},$th{'minutes'},$th{'hours'},
 4494:          $th{'day'},$th{'month'}-1,$th{'year'}-1900,0,0,-1));
 4495: }
 4496: 
 4497: #########################################
 4498: 
 4499: sub findallcourses {
 4500:     my ($roles,$uname,$udom) = @_;
 4501:     my %roles;
 4502:     if (ref($roles)) { %roles = map { $_ => 1 } @{$roles}; }
 4503:     my %courses;
 4504:     my $now=time;
 4505:     if (!defined($uname)) {
 4506:         $uname = $env{'user.name'};
 4507:     }
 4508:     if (!defined($udom)) {
 4509:         $udom = $env{'user.domain'};
 4510:     }
 4511:     if (($uname ne $env{'user.name'}) || ($udom ne $env{'user.domain'})) {
 4512:         my %roleshash = &Apache::lonnet::dump('roles',$udom,$uname);
 4513:         if (!%roles) {
 4514:             %roles = (
 4515:                        cc => 1,
 4516:                        co => 1,
 4517:                        in => 1,
 4518:                        ep => 1,
 4519:                        ta => 1,
 4520:                        cr => 1,
 4521:                        st => 1,
 4522:              );
 4523:         }
 4524:         foreach my $entry (keys(%roleshash)) {
 4525:             my ($trole,$tend,$tstart) = split(/_/,$roleshash{$entry});
 4526:             if ($trole =~ /^cr/) { 
 4527:                 next if (!exists($roles{$trole}) && !exists($roles{'cr'}));
 4528:             } else {
 4529:                 next if (!exists($roles{$trole}));
 4530:             }
 4531:             if ($tend) {
 4532:                 next if ($tend < $now);
 4533:             }
 4534:             if ($tstart) {
 4535:                 next if ($tstart > $now);
 4536:             }
 4537:             my ($cdom,$cnum,$sec,$cnumpart,$secpart,$role);
 4538:             (undef,$cdom,$cnumpart,$secpart) = split(/\//,$entry);
 4539:             my $value = $trole.'/'.$cdom.'/';
 4540:             if ($secpart eq '') {
 4541:                 ($cnum,$role) = split(/_/,$cnumpart); 
 4542:                 $sec = 'none';
 4543:                 $value .= $cnum.'/';
 4544:             } else {
 4545:                 $cnum = $cnumpart;
 4546:                 ($sec,$role) = split(/_/,$secpart);
 4547:                 $value .= $cnum.'/'.$sec;
 4548:             }
 4549:             if (ref($courses{$cdom.'_'.$cnum}{$sec}) eq 'ARRAY') {
 4550:                 unless (grep(/^\Q$value\E$/,@{$courses{$cdom.'_'.$cnum}{$sec}})) {
 4551:                     push(@{$courses{$cdom.'_'.$cnum}{$sec}},$value);
 4552:                 }
 4553:             } else {
 4554:                 @{$courses{$cdom.'_'.$cnum}{$sec}} = ($value);
 4555:             }
 4556:         }
 4557:     } else {
 4558:         foreach my $key (keys(%env)) {
 4559: 	    if ( $key=~m{^user\.role\.(\w+)\./($match_domain)/($match_courseid)/?(\w*)$} ||
 4560:                  $key=~m{^user\.role\.(cr/$match_domain/$match_username/\w+)\./($match_domain)/($match_courseid)/?(\w*)$}) {
 4561: 	        my ($role,$cdom,$cnum,$sec) = ($1,$2,$3,$4);
 4562: 	        next if ($role eq 'ca' || $role eq 'aa');
 4563: 	        next if (%roles && !exists($roles{$role}));
 4564: 	        my ($starttime,$endtime)=split(/\./,$env{$key});
 4565:                 my $active=1;
 4566:                 if ($starttime) {
 4567: 		    if ($now<$starttime) { $active=0; }
 4568:                 }
 4569:                 if ($endtime) {
 4570:                     if ($now>$endtime) { $active=0; }
 4571:                 }
 4572:                 if ($active) {
 4573:                     my $value = $role.'/'.$cdom.'/'.$cnum.'/';
 4574:                     if ($sec eq '') {
 4575:                         $sec = 'none';
 4576:                     } else {
 4577:                         $value .= $sec;
 4578:                     }
 4579:                     if (ref($courses{$cdom.'_'.$cnum}{$sec}) eq 'ARRAY') {
 4580:                         unless (grep(/^\Q$value\E$/,@{$courses{$cdom.'_'.$cnum}{$sec}})) {
 4581:                             push(@{$courses{$cdom.'_'.$cnum}{$sec}},$value);
 4582:                         }
 4583:                     } else {
 4584:                         @{$courses{$cdom.'_'.$cnum}{$sec}} = ($value);
 4585:                     }
 4586:                 }
 4587:             }
 4588:         }
 4589:     }
 4590:     return %courses;
 4591: }
 4592: 
 4593: ###############################################
 4594: 
 4595: sub blockcheck {
 4596:     my ($setters,$activity,$uname,$udom,$url,$is_course) = @_;
 4597: 
 4598:     if (defined($udom) && defined($uname)) {
 4599:         # If uname and udom are for a course, check for blocks in the course.
 4600:         if (($is_course) || (&Apache::lonnet::is_course($udom,$uname))) {
 4601:             my ($startblock,$endblock,$triggerblock) =
 4602:                 &get_blocks($setters,$activity,$udom,$uname,$url);
 4603:             return ($startblock,$endblock,$triggerblock);
 4604:         }
 4605:     } else {
 4606:         $udom = $env{'user.domain'};
 4607:         $uname = $env{'user.name'};
 4608:     }
 4609: 
 4610:     my $startblock = 0;
 4611:     my $endblock = 0;
 4612:     my $triggerblock = '';
 4613:     my %live_courses = &findallcourses(undef,$uname,$udom);
 4614: 
 4615:     # If uname is for a user, and activity is course-specific, i.e.,
 4616:     # boards, chat or groups, check for blocking in current course only.
 4617: 
 4618:     if (($activity eq 'boards' || $activity eq 'chat' ||
 4619:          $activity eq 'groups' || $activity eq 'printout' ||
 4620:          $activity eq 'reinit' || $activity eq 'alert') &&
 4621:         ($env{'request.course.id'})) {
 4622:         foreach my $key (keys(%live_courses)) {
 4623:             if ($key ne $env{'request.course.id'}) {
 4624:                 delete($live_courses{$key});
 4625:             }
 4626:         }
 4627:     }
 4628: 
 4629:     my $otheruser = 0;
 4630:     my %own_courses;
 4631:     if ((($uname ne $env{'user.name'})) || ($udom ne $env{'user.domain'})) {
 4632:         # Resource belongs to user other than current user.
 4633:         $otheruser = 1;
 4634:         # Gather courses for current user
 4635:         %own_courses = 
 4636:             &findallcourses(undef,$env{'user.name'},$env{'user.domain'});
 4637:     }
 4638: 
 4639:     # Gather active course roles - course coordinator, instructor, 
 4640:     # exam proctor, ta, student, or custom role.
 4641: 
 4642:     foreach my $course (keys(%live_courses)) {
 4643:         my ($cdom,$cnum);
 4644:         if ((defined($env{'course.'.$course.'.domain'})) && (defined($env{'course.'.$course.'.num'}))) {
 4645:             $cdom = $env{'course.'.$course.'.domain'};
 4646:             $cnum = $env{'course.'.$course.'.num'};
 4647:         } else {
 4648:             ($cdom,$cnum) = split(/_/,$course); 
 4649:         }
 4650:         my $no_ownblock = 0;
 4651:         my $no_userblock = 0;
 4652:         if ($otheruser && $activity ne 'com') {
 4653:             # Check if current user has 'evb' priv for this
 4654:             if (defined($own_courses{$course})) {
 4655:                 foreach my $sec (keys(%{$own_courses{$course}})) {
 4656:                     my $checkrole = 'cm./'.$cdom.'/'.$cnum;
 4657:                     if ($sec ne 'none') {
 4658:                         $checkrole .= '/'.$sec;
 4659:                     }
 4660:                     if (&Apache::lonnet::allowed('evb',undef,undef,$checkrole)) {
 4661:                         $no_ownblock = 1;
 4662:                         last;
 4663:                     }
 4664:                 }
 4665:             }
 4666:             # if they have 'evb' priv and are currently not playing student
 4667:             next if (($no_ownblock) &&
 4668:                  ($env{'request.role'} !~ m{^st\./$cdom/$cnum}));
 4669:         }
 4670:         foreach my $sec (keys(%{$live_courses{$course}})) {
 4671:             my $checkrole = 'cm./'.$cdom.'/'.$cnum;
 4672:             if ($sec ne 'none') {
 4673:                 $checkrole .= '/'.$sec;
 4674:             }
 4675:             if ($otheruser) {
 4676:                 # Resource belongs to user other than current user.
 4677:                 # Assemble privs for that user, and check for 'evb' priv.
 4678:                 my (%allroles,%userroles);
 4679:                 if (ref($live_courses{$course}{$sec}) eq 'ARRAY') {
 4680:                     foreach my $entry (@{$live_courses{$course}{$sec}}) { 
 4681:                         my ($trole,$tdom,$tnum,$tsec);
 4682:                         if ($entry =~ /^cr/) {
 4683:                             ($trole,$tdom,$tnum,$tsec) = 
 4684:                                 ($entry =~ m|^(cr/$match_domain/$match_username/\w+)\./($match_domain)/($match_username)/?(\w*)$|);
 4685:                         } else {
 4686:                            ($trole,$tdom,$tnum,$tsec) = split(/\//,$entry);
 4687:                         }
 4688:                         my ($spec,$area,$trest);
 4689:                         $area = '/'.$tdom.'/'.$tnum;
 4690:                         $trest = $tnum;
 4691:                         if ($tsec ne '') {
 4692:                             $area .= '/'.$tsec;
 4693:                             $trest .= '/'.$tsec;
 4694:                         }
 4695:                         $spec = $trole.'.'.$area;
 4696:                         if ($trole =~ /^cr/) {
 4697:                             &Apache::lonnet::custom_roleprivs(\%allroles,$trole,
 4698:                                                               $tdom,$spec,$trest,$area);
 4699:                         } else {
 4700:                             &Apache::lonnet::standard_roleprivs(\%allroles,$trole,
 4701:                                                                 $tdom,$spec,$trest,$area);
 4702:                         }
 4703:                     }
 4704:                     my ($author,$adv,$rar) = &Apache::lonnet::set_userprivs(\%userroles,\%allroles);
 4705:                     if ($userroles{'user.priv.'.$checkrole} =~ /evb\&([^\:]*)/) {
 4706:                         if ($1) {
 4707:                             $no_userblock = 1;
 4708:                             last;
 4709:                         }
 4710:                     }
 4711:                 }
 4712:             } else {
 4713:                 # Resource belongs to current user
 4714:                 # Check for 'evb' priv via lonnet::allowed().
 4715:                 if (&Apache::lonnet::allowed('evb',undef,undef,$checkrole)) {
 4716:                     $no_ownblock = 1;
 4717:                     last;
 4718:                 }
 4719:             }
 4720:         }
 4721:         # if they have the evb priv and are currently not playing student
 4722:         next if (($no_ownblock) &&
 4723:                  ($env{'request.role'} !~ m{^st\./\Q$cdom\E/\Q$cnum\E}));
 4724:         next if ($no_userblock);
 4725: 
 4726:         # Retrieve blocking times and identity of locker for course
 4727:         # of specified user, unless user has 'evb' privilege.
 4728:         
 4729:         my ($start,$end,$trigger) = 
 4730:             &get_blocks($setters,$activity,$cdom,$cnum,$url);
 4731:         if (($start != 0) && 
 4732:             (($startblock == 0) || ($startblock > $start))) {
 4733:             $startblock = $start;
 4734:             if ($trigger ne '') {
 4735:                 $triggerblock = $trigger;
 4736:             }
 4737:         }
 4738:         if (($end != 0)  &&
 4739:             (($endblock == 0) || ($endblock < $end))) {
 4740:             $endblock = $end;
 4741:             if ($trigger ne '') {
 4742:                 $triggerblock = $trigger;
 4743:             }
 4744:         }
 4745:     }
 4746:     return ($startblock,$endblock,$triggerblock);
 4747: }
 4748: 
 4749: sub get_blocks {
 4750:     my ($setters,$activity,$cdom,$cnum,$url) = @_;
 4751:     my $startblock = 0;
 4752:     my $endblock = 0;
 4753:     my $triggerblock = '';
 4754:     my $course = $cdom.'_'.$cnum;
 4755:     $setters->{$course} = {};
 4756:     $setters->{$course}{'staff'} = [];
 4757:     $setters->{$course}{'times'} = [];
 4758:     $setters->{$course}{'triggers'} = [];
 4759:     my (@blockers,%triggered);
 4760:     my $now = time;
 4761:     my %commblocks = &Apache::lonnet::get_comm_blocks($cdom,$cnum);
 4762:     if ($activity eq 'docs') {
 4763:         @blockers = &Apache::lonnet::has_comm_blocking('bre',undef,$url,\%commblocks);
 4764:         foreach my $block (@blockers) {
 4765:             if ($block =~ /^firstaccess____(.+)$/) {
 4766:                 my $item = $1;
 4767:                 my $type = 'map';
 4768:                 my $timersymb = $item;
 4769:                 if ($item eq 'course') {
 4770:                     $type = 'course';
 4771:                 } elsif ($item =~ /___\d+___/) {
 4772:                     $type = 'resource';
 4773:                 } else {
 4774:                     $timersymb = &Apache::lonnet::symbread($item);
 4775:                 }
 4776:                 my $start = $env{'course.'.$cdom.'_'.$cnum.'.firstaccess.'.$timersymb};
 4777:                 my $end = $start + $env{'course.'.$cdom.'_'.$cnum.'.timerinterval.'.$timersymb};
 4778:                 $triggered{$block} = {
 4779:                                        start => $start,
 4780:                                        end   => $end,
 4781:                                        type  => $type,
 4782:                                      };
 4783:             }
 4784:         }
 4785:     } else {
 4786:         foreach my $block (keys(%commblocks)) {
 4787:             if ($block =~ m/^(\d+)____(\d+)$/) { 
 4788:                 my ($start,$end) = ($1,$2);
 4789:                 if ($start <= time && $end >= time) {
 4790:                     if (ref($commblocks{$block}) eq 'HASH') {
 4791:                         if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
 4792:                             if ($commblocks{$block}{'blocks'}{$activity} eq 'on') {
 4793:                                 unless(grep(/^\Q$block\E$/,@blockers)) {
 4794:                                     push(@blockers,$block);
 4795:                                 }
 4796:                             }
 4797:                         }
 4798:                     }
 4799:                 }
 4800:             } elsif ($block =~ /^firstaccess____(.+)$/) {
 4801:                 my $item = $1;
 4802:                 my $timersymb = $item; 
 4803:                 my $type = 'map';
 4804:                 if ($item eq 'course') {
 4805:                     $type = 'course';
 4806:                 } elsif ($item =~ /___\d+___/) {
 4807:                     $type = 'resource';
 4808:                 } else {
 4809:                     $timersymb = &Apache::lonnet::symbread($item);
 4810:                 }
 4811:                 my $start = $env{'course.'.$cdom.'_'.$cnum.'.firstaccess.'.$timersymb};
 4812:                 my $end = $start + $env{'course.'.$cdom.'_'.$cnum.'.timerinterval.'.$timersymb}; 
 4813:                 if ($start && $end) {
 4814:                     if (($start <= time) && ($end >= time)) {
 4815:                         unless (grep(/^\Q$block\E$/,@blockers)) {
 4816:                             push(@blockers,$block);
 4817:                             $triggered{$block} = {
 4818:                                                    start => $start,
 4819:                                                    end   => $end,
 4820:                                                    type  => $type,
 4821:                                                  };
 4822:                         }
 4823:                     }
 4824:                 }
 4825:             }
 4826:         }
 4827:     }
 4828:     foreach my $blocker (@blockers) {
 4829:         my ($staff_name,$staff_dom,$title,$blocks) =
 4830:             &parse_block_record($commblocks{$blocker});
 4831:         push(@{$$setters{$course}{'staff'}},[$staff_name,$staff_dom]);
 4832:         my ($start,$end,$triggertype);
 4833:         if ($blocker =~ m/^(\d+)____(\d+)$/) {
 4834:             ($start,$end) = ($1,$2);
 4835:         } elsif (ref($triggered{$blocker}) eq 'HASH') {
 4836:             $start = $triggered{$blocker}{'start'};
 4837:             $end = $triggered{$blocker}{'end'};
 4838:             $triggertype = $triggered{$blocker}{'type'};
 4839:         }
 4840:         if ($start) {
 4841:             push(@{$$setters{$course}{'times'}}, [$start,$end]);
 4842:             if ($triggertype) {
 4843:                 push(@{$$setters{$course}{'triggers'}},$triggertype);
 4844:             } else {
 4845:                 push(@{$$setters{$course}{'triggers'}},0);
 4846:             }
 4847:             if ( ($startblock == 0) || ($startblock > $start) ) {
 4848:                 $startblock = $start;
 4849:                 if ($triggertype) {
 4850:                     $triggerblock = $blocker;
 4851:                 }
 4852:             }
 4853:             if ( ($endblock == 0) || ($endblock < $end) ) {
 4854:                $endblock = $end;
 4855:                if ($triggertype) {
 4856:                    $triggerblock = $blocker;
 4857:                }
 4858:             }
 4859:         }
 4860:     }
 4861:     return ($startblock,$endblock,$triggerblock);
 4862: }
 4863: 
 4864: sub parse_block_record {
 4865:     my ($record) = @_;
 4866:     my ($setuname,$setudom,$title,$blocks);
 4867:     if (ref($record) eq 'HASH') {
 4868:         ($setuname,$setudom) = split(/:/,$record->{'setter'});
 4869:         $title = &unescape($record->{'event'});
 4870:         $blocks = $record->{'blocks'};
 4871:     } else {
 4872:         my @data = split(/:/,$record,3);
 4873:         if (scalar(@data) eq 2) {
 4874:             $title = $data[1];
 4875:             ($setuname,$setudom) = split(/@/,$data[0]);
 4876:         } else {
 4877:             ($setuname,$setudom,$title) = @data;
 4878:         }
 4879:         $blocks = { 'com' => 'on' };
 4880:     }
 4881:     return ($setuname,$setudom,$title,$blocks);
 4882: }
 4883: 
 4884: sub blocking_status {
 4885:     my ($activity,$uname,$udom,$url,$is_course) = @_;
 4886:     my %setters;
 4887: 
 4888: # check for active blocking
 4889:     my ($startblock,$endblock,$triggerblock) = 
 4890:         &blockcheck(\%setters,$activity,$uname,$udom,$url,$is_course);
 4891:     my $blocked = 0;
 4892:     if ($startblock && $endblock) {
 4893:         $blocked = 1;
 4894:     }
 4895: 
 4896: # caller just wants to know whether a block is active
 4897:     if (!wantarray) { return $blocked; }
 4898: 
 4899: # build a link to a popup window containing the details
 4900:     my $querystring  = "?activity=$activity";
 4901: # $uname and $udom decide whose portfolio the user is trying to look at
 4902:     if (($activity eq 'port') || ($activity eq 'passwd')) {
 4903:         $querystring .= "&amp;udom=$udom"      if ($udom =~ /^$match_domain$/);
 4904:         $querystring .= "&amp;uname=$uname"    if ($uname =~ /^$match_username$/);
 4905:     } elsif ($activity eq 'docs') {
 4906:         $querystring .= '&amp;url='.&HTML::Entities::encode($url,'&"');
 4907:     }
 4908: 
 4909:     my $output .= <<'END_MYBLOCK';
 4910: function openWindow(url, wdwName, w, h, toolbar,scrollbar) {
 4911:     var options = "width=" + w + ",height=" + h + ",";
 4912:     options += "resizable=yes,scrollbars="+scrollbar+",status=no,";
 4913:     options += "menubar=no,toolbar="+toolbar+",location=no,directories=no";
 4914:     var newWin = window.open(url, wdwName, options);
 4915:     newWin.focus();
 4916: }
 4917: END_MYBLOCK
 4918: 
 4919:     $output = Apache::lonhtmlcommon::scripttag($output);
 4920:   
 4921:     my $popupUrl = "/adm/blockingstatus/$querystring";
 4922:     my $text = &mt('Communication Blocked');
 4923:     my $class = 'LC_comblock';
 4924:     if ($activity eq 'docs') {
 4925:         $text = &mt('Content Access Blocked');
 4926:         $class = '';
 4927:     } elsif ($activity eq 'printout') {
 4928:         $text = &mt('Printing Blocked');
 4929:     } elsif ($activity eq 'passwd') {
 4930:         $text = &mt('Password Changing Blocked');
 4931:     } elsif ($activity eq 'alert') {
 4932:         $text = &mt('Checking Critical Messages Blocked');
 4933:     } elsif ($activity eq 'reinit') {
 4934:         $text = &mt('Checking Course Update Blocked');
 4935:     }
 4936:     $output .= <<"END_BLOCK";
 4937: <div class='$class'>
 4938:   <a onclick='openWindow("$popupUrl","Blocking Table",600,300,"no","no");return false;' href='/adm/blockingstatus/$querystring'
 4939:   title='$text'>
 4940:   <img class='LC_noBorder LC_middle' title='$text' src='/res/adm/pages/comblock.png' alt='$text'/></a>
 4941:   <a onclick='openWindow("$popupUrl","Blocking Table",600,300,"no","no");return false;' href='/adm/blockingstatus/$querystring' 
 4942:   title='$text'>$text</a>
 4943: </div>
 4944: 
 4945: END_BLOCK
 4946: 
 4947:     return ($blocked, $output);
 4948: }
 4949: 
 4950: ###############################################
 4951: 
 4952: sub check_ip_acc {
 4953:     my ($acc,$clientip)=@_;
 4954:     &Apache::lonxml::debug("acc is $acc");
 4955:     if (!defined($acc) || $acc =~ /^\s*$/ || $acc =~/^\s*no\s*$/i) {
 4956:         return 1;
 4957:     }
 4958:     my $allowed=0;
 4959:     my $ip=$ENV{'REMOTE_ADDR'} || $clientip || $env{'request.host'};
 4960: 
 4961:     my $name;
 4962:     foreach my $pattern (split(',',$acc)) {
 4963:         $pattern =~ s/^\s*//;
 4964:         $pattern =~ s/\s*$//;
 4965:         if ($pattern =~ /\*$/) {
 4966:             #35.8.*
 4967:             $pattern=~s/\*//;
 4968:             if ($ip =~ /^\Q$pattern\E/) { $allowed=1; }
 4969:         } elsif ($pattern =~ /(\d+\.\d+\.\d+)\.\[(\d+)-(\d+)\]$/) {
 4970:             #35.8.3.[34-56]
 4971:             my $low=$2;
 4972:             my $high=$3;
 4973:             $pattern=$1;
 4974:             if ($ip =~ /^\Q$pattern\E/) {
 4975:                 my $last=(split(/\./,$ip))[3];
 4976:                 if ($last <=$high && $last >=$low) { $allowed=1; }
 4977:             }
 4978:         } elsif ($pattern =~ /^\*/) {
 4979:             #*.msu.edu
 4980:             $pattern=~s/\*//;
 4981:             if (!defined($name)) {
 4982:                 use Socket;
 4983:                 my $netaddr=inet_aton($ip);
 4984:                 ($name)=gethostbyaddr($netaddr,AF_INET);
 4985:             }
 4986:             if ($name =~ /\Q$pattern\E$/i) { $allowed=1; }
 4987:         } elsif ($pattern =~ /\d+\.\d+\.\d+\.\d+/) {
 4988:             #127.0.0.1
 4989:             if ($ip =~ /^\Q$pattern\E/) { $allowed=1; }
 4990:         } else {
 4991:             #some.name.com
 4992:             if (!defined($name)) {
 4993:                 use Socket;
 4994:                 my $netaddr=inet_aton($ip);
 4995:                 ($name)=gethostbyaddr($netaddr,AF_INET);
 4996:             }
 4997:             if ($name =~ /\Q$pattern\E$/i) { $allowed=1; }
 4998:         }
 4999:         if ($allowed) { last; }
 5000:     }
 5001:     return $allowed;
 5002: }
 5003: 
 5004: sub check_slotip_acc {
 5005:     my ($acc,$clientip)=@_;
 5006:     &Apache::lonxml::debug("acc is $acc");
 5007:     if (!defined($acc) || $acc =~ /^\s*$/ || $acc =~/^\s*no\s*$/i) {
 5008:         return 1;
 5009:     }
 5010:     my $allowed;
 5011:     my $ip=$ENV{'REMOTE_ADDR'} || $clientip || $env{'request.host'};
 5012: 
 5013:     my $name;
 5014:     my %access = (
 5015:                      allowfrom => 1,
 5016:                      denyfrom  => 0,
 5017:                  );
 5018:     my @allows;
 5019:     my @denies;
 5020:     foreach my $item (split(',',$acc)) {
 5021:         $item =~ s/^\s*//;
 5022:         $item =~ s/\s*$//;
 5023:         my $pattern;
 5024:         if ($item =~ /^\!(.+)$/) {
 5025:             push(@denies,$1);
 5026:         } else {
 5027:             push(@allows,$item);
 5028:         }
 5029:    }
 5030:    my $numdenies = scalar(@denies);
 5031:    my $numallows = scalar(@allows);
 5032:    my $count = 0;
 5033:    foreach my $pattern (@denies,@allows) {
 5034:         $count ++;
 5035:         my $acctype = 'allowfrom';
 5036:         if ($count <= $numdenies) {
 5037:             $acctype = 'denyfrom';
 5038:         }
 5039:         if ($pattern =~ /\*$/) {
 5040:             #35.8.*
 5041:             $pattern=~s/\*//;
 5042:             if ($ip =~ /^\Q$pattern\E/) { $allowed=$access{$acctype}; }
 5043:         } elsif ($pattern =~ /(\d+\.\d+\.\d+)\.\[(\d+)-(\d+)\]$/) {
 5044:             #35.8.3.[34-56]
 5045:             my $low=$2;
 5046:             my $high=$3;
 5047:             $pattern=$1;
 5048:             if ($ip =~ /^\Q$pattern\E/) {
 5049:                 my $last=(split(/\./,$ip))[3];
 5050:                 if ($last <=$high && $last >=$low) { $allowed=$access{$acctype}; }
 5051:             }
 5052:         } elsif ($pattern =~ /^\*/) {
 5053:             #*.msu.edu
 5054:             $pattern=~s/\*//;
 5055:             if (!defined($name)) {
 5056:                 use Socket;
 5057:                 my $netaddr=inet_aton($ip);
 5058:                 ($name)=gethostbyaddr($netaddr,AF_INET);
 5059:             }
 5060:             if ($name =~ /\Q$pattern\E$/i) { $allowed=$access{$acctype}; }
 5061:         } elsif ($pattern =~ /\d+\.\d+\.\d+\.\d+/) {
 5062:             #127.0.0.1
 5063:             if ($ip =~ /^\Q$pattern\E/) { $allowed=$access{$acctype}; }
 5064:         } else {
 5065:             #some.name.com
 5066:             if (!defined($name)) {
 5067:                 use Socket;
 5068:                 my $netaddr=inet_aton($ip);
 5069:                 ($name)=gethostbyaddr($netaddr,AF_INET);
 5070:             }
 5071:             if ($name =~ /\Q$pattern\E$/i) { $allowed=$access{$acctype}; }
 5072:         }
 5073:         if ($allowed =~ /^(0|1)$/) { last; }
 5074:     }
 5075:     if ($allowed eq '') {
 5076:         if ($numdenies && !$numallows) {
 5077:             $allowed = 1;
 5078:         } else {
 5079:             $allowed = 0;
 5080:         }
 5081:     }
 5082:     return $allowed;
 5083: }
 5084: 
 5085: ###############################################
 5086: 
 5087: =pod
 5088: 
 5089: =head1 Domain Template Functions
 5090: 
 5091: =over 4
 5092: 
 5093: =item * &determinedomain()
 5094: 
 5095: Inputs: $domain (usually will be undef)
 5096: 
 5097: Returns: Determines which domain should be used for designs
 5098: 
 5099: =cut
 5100: 
 5101: ###############################################
 5102: sub determinedomain {
 5103:     my $domain=shift;
 5104:     if (! $domain) {
 5105:         # Determine domain if we have not been given one
 5106:         $domain = &Apache::lonnet::default_login_domain();
 5107:         if ($env{'user.domain'}) { $domain=$env{'user.domain'}; }
 5108:         if ($env{'request.role.domain'}) { 
 5109:             $domain=$env{'request.role.domain'}; 
 5110:         }
 5111:     }
 5112:     return $domain;
 5113: }
 5114: ###############################################
 5115: 
 5116: sub devalidate_domconfig_cache {
 5117:     my ($udom)=@_;
 5118:     &Apache::lonnet::devalidate_cache_new('domainconfig',$udom);
 5119: }
 5120: 
 5121: # ---------------------- Get domain configuration for a domain
 5122: sub get_domainconf {
 5123:     my ($udom) = @_;
 5124:     my $cachetime=1800;
 5125:     my ($result,$cached)=&Apache::lonnet::is_cached_new('domainconfig',$udom);
 5126:     if (defined($cached)) { return %{$result}; }
 5127: 
 5128:     my %domconfig = &Apache::lonnet::get_dom('configuration',
 5129: 					     ['login','rolecolors','autoenroll'],$udom);
 5130:     my (%designhash,%legacy);
 5131:     if (keys(%domconfig) > 0) {
 5132:         if (ref($domconfig{'login'}) eq 'HASH') {
 5133:             if (keys(%{$domconfig{'login'}})) {
 5134:                 foreach my $key (keys(%{$domconfig{'login'}})) {
 5135:                     if (ref($domconfig{'login'}{$key}) eq 'HASH') {
 5136:                         if (($key eq 'loginvia') || ($key eq 'headtag')) {
 5137:                             if (ref($domconfig{'login'}{$key}) eq 'HASH') {
 5138:                                 foreach my $hostname (keys(%{$domconfig{'login'}{$key}})) {
 5139:                                     if (ref($domconfig{'login'}{$key}{$hostname}) eq 'HASH') {
 5140:                                         if ($key eq 'loginvia') {
 5141:                                             if ($domconfig{'login'}{'loginvia'}{$hostname}{'server'}) {
 5142:                                                 my $server = $domconfig{'login'}{'loginvia'}{$hostname}{'server'};
 5143:                                                 $designhash{$udom.'.login.loginvia'} = $server;
 5144:                                                 if ($domconfig{'login'}{'loginvia'}{$hostname}{'serverpath'} eq 'custom') {
 5145:                                                     $designhash{$udom.'.login.loginvia_'.$hostname} = $server.':'.$domconfig{'login'}{'loginvia'}{$hostname}{'custompath'};
 5146:                                                 } else {
 5147:                                                     $designhash{$udom.'.login.loginvia_'.$hostname} = $server.':'.$domconfig{'login'}{'loginvia'}{$hostname}{'serverpath'};
 5148:                                                 }
 5149:                                             }
 5150:                                         } elsif ($key eq 'headtag') {
 5151:                                             if ($domconfig{'login'}{'headtag'}{$hostname}{'url'}) {
 5152:                                                 $designhash{$udom.'.login.headtag_'.$hostname} = $domconfig{'login'}{'headtag'}{$hostname}{'url'};
 5153:                                             }
 5154:                                         }
 5155:                                         if ($domconfig{'login'}{$key}{$hostname}{'exempt'}) {
 5156:                                             $designhash{$udom.'.login.'.$key.'_exempt_'.$hostname} = $domconfig{'login'}{$key}{$hostname}{'exempt'};
 5157:                                         }
 5158:                                     }
 5159:                                 }
 5160:                             }
 5161:                         } else {
 5162:                             foreach my $img (keys(%{$domconfig{'login'}{$key}})) {
 5163:                                 $designhash{$udom.'.login.'.$key.'_'.$img} = 
 5164:                                     $domconfig{'login'}{$key}{$img};
 5165:                             }
 5166:                         }
 5167:                     } else {
 5168:                         $designhash{$udom.'.login.'.$key}=$domconfig{'login'}{$key};
 5169:                     }
 5170:                 }
 5171:             } else {
 5172:                 $legacy{'login'} = 1;
 5173:             }
 5174:         } else {
 5175:             $legacy{'login'} = 1;
 5176:         }
 5177:         if (ref($domconfig{'rolecolors'}) eq 'HASH') {
 5178:             if (keys(%{$domconfig{'rolecolors'}})) {
 5179:                 foreach my $role (keys(%{$domconfig{'rolecolors'}})) {
 5180:                     if (ref($domconfig{'rolecolors'}{$role}) eq 'HASH') {
 5181:                         foreach my $item (keys(%{$domconfig{'rolecolors'}{$role}})) {
 5182:                             $designhash{$udom.'.'.$role.'.'.$item}=$domconfig{'rolecolors'}{$role}{$item};
 5183:                         }
 5184:                     }
 5185:                 }
 5186:             } else {
 5187:                 $legacy{'rolecolors'} = 1;
 5188:             }
 5189:         } else {
 5190:             $legacy{'rolecolors'} = 1;
 5191:         }
 5192:         if (ref($domconfig{'autoenroll'}) eq 'HASH') {
 5193:             if ($domconfig{'autoenroll'}{'co-owners'}) {
 5194:                 $designhash{$udom.'.autoassign.co-owners'}=$domconfig{'autoenroll'}{'co-owners'};
 5195:             }
 5196:         }
 5197:         if (keys(%legacy) > 0) {
 5198:             my %legacyhash = &get_legacy_domconf($udom);
 5199:             foreach my $item (keys(%legacyhash)) {
 5200:                 if ($item =~ /^\Q$udom\E\.login/) {
 5201:                     if ($legacy{'login'}) { 
 5202:                         $designhash{$item} = $legacyhash{$item};
 5203:                     }
 5204:                 } else {
 5205:                     if ($legacy{'rolecolors'}) {
 5206:                         $designhash{$item} = $legacyhash{$item};
 5207:                     }
 5208:                 }
 5209:             }
 5210:         }
 5211:     } else {
 5212:         %designhash = &get_legacy_domconf($udom); 
 5213:     }
 5214:     &Apache::lonnet::do_cache_new('domainconfig',$udom,\%designhash,
 5215: 				  $cachetime);
 5216:     return %designhash;
 5217: }
 5218: 
 5219: sub get_legacy_domconf {
 5220:     my ($udom) = @_;
 5221:     my %legacyhash;
 5222:     my $designdir=$Apache::lonnet::perlvar{'lonTabDir'}.'/lonDomColors';
 5223:     my $designfile =  $designdir.'/'.$udom.'.tab';
 5224:     if (-e $designfile) {
 5225:         if ( open (my $fh,'<',$designfile) ) {
 5226:             while (my $line = <$fh>) {
 5227:                 next if ($line =~ /^\#/);
 5228:                 chomp($line);
 5229:                 my ($key,$val)=(split(/\=/,$line));
 5230:                 if ($val) { $legacyhash{$udom.'.'.$key}=$val; }
 5231:             }
 5232:             close($fh);
 5233:         }
 5234:     }
 5235:     if (-e $Apache::lonnet::perlvar{'lonDocRoot'}.'/adm/lonDomLogos/'.$udom.'.gif') {
 5236:         $legacyhash{$udom.'.login.domlogo'} = "/adm/lonDomLogos/$udom.gif";
 5237:     }
 5238:     return %legacyhash;
 5239: }
 5240: 
 5241: =pod
 5242: 
 5243: =item * &domainlogo()
 5244: 
 5245: Inputs: $domain (usually will be undef)
 5246: 
 5247: Returns: A link to a domain logo, if the domain logo exists.
 5248: If the domain logo does not exist, a description of the domain.
 5249: 
 5250: =cut
 5251: 
 5252: ###############################################
 5253: sub domainlogo {
 5254:     my $domain = &determinedomain(shift);
 5255:     my %designhash = &get_domainconf($domain);    
 5256:     # See if there is a logo
 5257:     if ($designhash{$domain.'.login.domlogo'} ne '') {
 5258:         my $imgsrc = $designhash{$domain.'.login.domlogo'};
 5259:         if ($imgsrc =~ m{^/(adm|res)/}) {
 5260: 	    if ($imgsrc =~ m{^/res/}) {
 5261: 		my $local_name = &Apache::lonnet::filelocation('',$imgsrc);
 5262: 		&Apache::lonnet::repcopy($local_name);
 5263: 	    }
 5264: 	   $imgsrc = &lonhttpdurl($imgsrc);
 5265:         } 
 5266:         return '<img src="'.$imgsrc.'" alt="'.$domain.'" />';
 5267:     } elsif (defined(&Apache::lonnet::domain($domain,'description'))) {
 5268:         return &Apache::lonnet::domain($domain,'description');
 5269:     } else {
 5270:         return '';
 5271:     }
 5272: }
 5273: ##############################################
 5274: 
 5275: =pod
 5276: 
 5277: =item * &designparm()
 5278: 
 5279: Inputs: $which parameter; $domain (usually will be undef)
 5280: 
 5281: Returns: value of designparamter $which
 5282: 
 5283: =cut
 5284: 
 5285: 
 5286: ##############################################
 5287: sub designparm {
 5288:     my ($which,$domain)=@_;
 5289:     if (exists($env{'environment.color.'.$which})) {
 5290:         return $env{'environment.color.'.$which};
 5291:     }
 5292:     $domain=&determinedomain($domain);
 5293:     my %domdesign;
 5294:     unless ($domain eq 'public') {
 5295:         %domdesign = &get_domainconf($domain);
 5296:     }
 5297:     my $output;
 5298:     if ($domdesign{$domain.'.'.$which} ne '') {
 5299:         $output = $domdesign{$domain.'.'.$which};
 5300:     } else {
 5301:         $output = $defaultdesign{$which};
 5302:     }
 5303:     if (($which =~ /^(student|coordinator|author|admin)\.img$/) ||
 5304:         ($which =~ /login\.(img|logo|domlogo|login)/)) {
 5305:         if ($output =~ m{^/(adm|res)/}) {
 5306:             if ($output =~ m{^/res/}) {
 5307:                 my $local_name = &Apache::lonnet::filelocation('',$output);
 5308:                 &Apache::lonnet::repcopy($local_name);
 5309:             }
 5310:             $output = &lonhttpdurl($output);
 5311:         }
 5312:     }
 5313:     return $output;
 5314: }
 5315: 
 5316: ##############################################
 5317: =pod
 5318: 
 5319: =item * &authorspace()
 5320: 
 5321: Inputs: $url (usually will be undef).
 5322: 
 5323: Returns: Path to Authoring Space containing the resource or 
 5324:          directory being viewed (or for which action is being taken). 
 5325:          If $url is provided, and begins /priv/<domain>/<uname>
 5326:          the path will be that portion of the $context argument.
 5327:          Otherwise the path will be for the author space of the current
 5328:          user when the current role is author, or for that of the 
 5329:          co-author/assistant co-author space when the current role 
 5330:          is co-author or assistant co-author.
 5331: 
 5332: =cut
 5333: 
 5334: sub authorspace {
 5335:     my ($url) = @_;
 5336:     if ($url ne '') {
 5337:         if ($url =~ m{^(/priv/$match_domain/$match_username/)}) {
 5338:            return $1;
 5339:         }
 5340:     }
 5341:     my $caname = '';
 5342:     my $cadom = '';
 5343:     if ($env{'request.role'} =~ /^(?:ca|aa)/) {
 5344:         ($cadom,$caname) =
 5345:             ($env{'request.role'}=~/($match_domain)\/($match_username)$/);
 5346:     } elsif ($env{'request.role'} =~ m{^au\./($match_domain)/}) {
 5347:         $caname = $env{'user.name'};
 5348:         $cadom = $env{'user.domain'};
 5349:     }
 5350:     if (($caname ne '') && ($cadom ne '')) {
 5351:         return "/priv/$cadom/$caname/";
 5352:     }
 5353:     return;
 5354: }
 5355: 
 5356: ##############################################
 5357: =pod
 5358: 
 5359: =item * &head_subbox()
 5360: 
 5361: Inputs: $content (contains HTML code with page functions, etc.)
 5362: 
 5363: Returns: HTML div with $content
 5364:          To be included in page header
 5365: 
 5366: =cut
 5367: 
 5368: sub head_subbox {
 5369:     my ($content)=@_;
 5370:     my $output =
 5371:         '<div class="LC_head_subbox">'
 5372:        .$content
 5373:        .'</div>'
 5374: }
 5375: 
 5376: ##############################################
 5377: =pod
 5378: 
 5379: =item * &CSTR_pageheader()
 5380: 
 5381: Input: (optional) filename from which breadcrumb trail is built.
 5382:        In most cases no input as needed, as $env{'request.filename'}
 5383:        is appropriate for use in building the breadcrumb trail.
 5384: 
 5385: Returns: HTML div with CSTR path and recent box
 5386:          To be included on Authoring Space pages
 5387: 
 5388: =cut
 5389: 
 5390: sub CSTR_pageheader {
 5391:     my ($trailfile) = @_;
 5392:     if ($trailfile eq '') {
 5393:         $trailfile = $env{'request.filename'};
 5394:     }
 5395: 
 5396: # this is for resources; directories have customtitle, and crumbs
 5397: # and select recent are created in lonpubdir.pm
 5398: 
 5399:     my $londocroot = $Apache::lonnet::perlvar{'lonDocRoot'};
 5400:     my ($udom,$uname,$thisdisfn)=
 5401:         ($trailfile =~ m{^\Q$londocroot\E/priv/([^/]+)/([^/]+)(?:|/(.*))$});
 5402:     my $formaction = "/priv/$udom/$uname/$thisdisfn";
 5403:     $formaction =~ s{/+}{/}g;
 5404: 
 5405:     my $parentpath = '';
 5406:     my $lastitem = '';
 5407:     if ($thisdisfn =~ m-(.+/)([^/]*)$-) {
 5408:         $parentpath = $1;
 5409:         $lastitem = $2;
 5410:     } else {
 5411:         $lastitem = $thisdisfn;
 5412:     }
 5413: 
 5414:     my $output =
 5415:          '<div>'
 5416:         .&Apache::loncommon::help_open_menu('','',3,'Authoring') #FIXME: Broken? Where is it?
 5417:         .'<b>'.&mt('Authoring Space:').'</b> '
 5418:         .'<form name="dirs" method="post" action="'.$formaction
 5419:         .'" target="_top">' #FIXME lonpubdir: target="_parent"
 5420:         .&Apache::lonhtmlcommon::crumbs($uname.'/'.$parentpath,'_top','/priv/'.$udom,undef,undef);
 5421: 
 5422:     if ($lastitem) {
 5423:         $output .=
 5424:              '<span class="LC_filename">'
 5425:             .$lastitem
 5426:             .'</span>';
 5427:     }
 5428:     $output .=
 5429:          '<br />'
 5430:         #FIXME lonpubdir: &Apache::lonhtmlcommon::crumbs($uname.$thisdisfn.'/','_top','/priv','','+1',1)."</b></tt><br />"
 5431:         .&Apache::lonhtmlcommon::select_recent('construct','recent','this.form.action=this.form.recent.value;this.form.submit()')
 5432:         .'</form>'
 5433:         .&Apache::lonmenu::constspaceform()
 5434:         .'</div>';
 5435: 
 5436:     return $output;
 5437: }
 5438: 
 5439: ###############################################
 5440: ###############################################
 5441: 
 5442: =pod
 5443: 
 5444: =back
 5445: 
 5446: =head1 HTML Helpers
 5447: 
 5448: =over 4
 5449: 
 5450: =item * &bodytag()
 5451: 
 5452: Returns a uniform header for LON-CAPA web pages.
 5453: 
 5454: Inputs: 
 5455: 
 5456: =over 4
 5457: 
 5458: =item * $title, A title to be displayed on the page.
 5459: 
 5460: =item * $function, the current role (can be undef).
 5461: 
 5462: =item * $addentries, extra parameters for the <body> tag.
 5463: 
 5464: =item * $bodyonly, if defined, only return the <body> tag.
 5465: 
 5466: =item * $domain, if defined, force a given domain.
 5467: 
 5468: =item * $forcereg, if page should register as content page (relevant for 
 5469:             text interface only)
 5470: 
 5471: =item * $no_nav_bar, if true, keep the 'what is this' info but remove the
 5472:                      navigational links
 5473: 
 5474: =item * $bgcolor, used to override the bgcolor on a webpage to a specific value
 5475: 
 5476: =item * $no_inline_link, if true and in remote mode, don't show the
 5477:          'Switch To Inline Menu' link
 5478: 
 5479: =item * $args, optional argument valid values are
 5480:             no_auto_mt_title -> prevents &mt()ing the title arg
 5481: 
 5482: =item * $advtoolsref, optional argument, ref to an array containing
 5483:             inlineremote items to be added in "Functions" menu below
 5484:             breadcrumbs.
 5485: 
 5486: =back
 5487: 
 5488: Returns: A uniform header for LON-CAPA web pages.  
 5489: If $bodyonly is nonzero, a string containing a <body> tag will be returned.
 5490: If $bodyonly is undef or zero, an html string containing a <body> tag and 
 5491: other decorations will be returned.
 5492: 
 5493: =cut
 5494: 
 5495: sub bodytag {
 5496:     my ($title,$function,$addentries,$bodyonly,$domain,$forcereg,
 5497:         $no_nav_bar,$bgcolor,$no_inline_link,$args,$advtoolsref)=@_;
 5498: 
 5499:     my $public;
 5500:     if ((($env{'user.name'} eq 'public') && ($env{'user.domain'} eq 'public'))
 5501:         || ($env{'user.name'} eq '') && ($env{'user.domain'} eq '')) {
 5502:         $public = 1;
 5503:     }
 5504:     if (!$args->{'no_auto_mt_title'}) { $title = &mt($title); }
 5505:     my $httphost = $args->{'use_absolute'};
 5506: 
 5507:     $function = &get_users_function() if (!$function);
 5508:     my $img =    &designparm($function.'.img',$domain);
 5509:     my $font =   &designparm($function.'.font',$domain);
 5510:     my $pgbg   = $bgcolor || &designparm($function.'.pgbg',$domain);
 5511: 
 5512:     my %design = ( 'style'   => 'margin-top: 0',
 5513: 		   'bgcolor' => $pgbg,
 5514: 		   'text'    => $font,
 5515:                    'alink'   => &designparm($function.'.alink',$domain),
 5516: 		   'vlink'   => &designparm($function.'.vlink',$domain),
 5517: 		   'link'    => &designparm($function.'.link',$domain),);
 5518:     @design{keys(%$addentries)} = @$addentries{keys(%$addentries)}; 
 5519: 
 5520:  # role and realm
 5521:     my ($role,$realm) = split(m{\./},$env{'request.role'},2);
 5522:     if ($realm) {
 5523:         $realm = '/'.$realm;
 5524:     }
 5525:     if ($role  eq 'ca') {
 5526:         my ($rdom,$rname) = ($realm =~ m{^/($match_domain)/($match_username)$});
 5527:         $realm = &plainname($rname,$rdom);
 5528:     } 
 5529: # realm
 5530:     if ($env{'request.course.id'}) {
 5531:         if ($env{'request.role'} !~ /^cr/) {
 5532:             $role = &Apache::lonnet::plaintext($role,&course_type());
 5533:         } elsif ($role =~ m{^cr/($match_domain)/\1-domainconfig/(\w+)$}) {
 5534:             if ($env{'request.role.desc'}) {
 5535:                 $role = $env{'request.role.desc'};
 5536:             } else {
 5537:                 $role = &mt('Helpdesk[_1]','&nbsp;'.$2);
 5538:             }
 5539:         } else {
 5540:             $role = (split(/\//,$role,4))[-1];
 5541:         }
 5542:         if ($env{'request.course.sec'}) {
 5543:             $role .= ('&nbsp;'x2).'-&nbsp;'.&mt('section:').'&nbsp;'.$env{'request.course.sec'};
 5544:         }   
 5545: 	$realm = $env{'course.'.$env{'request.course.id'}.'.description'};
 5546:     } else {
 5547:         $role = &Apache::lonnet::plaintext($role);
 5548:     }
 5549: 
 5550:     if (!$realm) { $realm='&nbsp;'; }
 5551: 
 5552:     my $extra_body_attr = &make_attr_string($forcereg,\%design);
 5553: 
 5554: # construct main body tag
 5555:     my $bodytag = "<body $extra_body_attr>".
 5556: 	&Apache::lontexconvert::init_math_support();
 5557: 
 5558:     &get_unprocessed_cgi($ENV{'QUERY_STRING'}, ['inhibitmenu']);
 5559: 
 5560:     if (($bodyonly) || ($no_nav_bar) || ($env{'form.inhibitmenu'} eq 'yes')) {
 5561:         return $bodytag;
 5562:     }
 5563: 
 5564:     if ($public) {
 5565: 	undef($role);
 5566:     }
 5567:     
 5568:     my $titleinfo = '<h1>'.$title.'</h1>';
 5569:     #
 5570:     # Extra info if you are the DC
 5571:     my $dc_info = '';
 5572:     if ($env{'user.adv'} && exists($env{'user.role.dc./'.
 5573:                         $env{'course.'.$env{'request.course.id'}.
 5574:                                  '.domain'}.'/'})) {
 5575:         my $cid = $env{'request.course.id'};
 5576:         $dc_info = $cid.' '.$env{'course.'.$cid.'.internal.coursecode'};
 5577:         $dc_info =~ s/\s+$//;
 5578:     }
 5579: 
 5580:     $role = '<span class="LC_nobreak">('.$role.')</span>' if ($role && !$env{'browser.mobile'});
 5581: 
 5582:     if ($env{'request.state'} eq 'construct') { $forcereg=1; }
 5583: 
 5584: 
 5585: 
 5586:     my $funclist;
 5587:     if (($env{'environment.remote'} eq 'on') && ($env{'request.state'} ne 'construct')) {
 5588:         $bodytag .= Apache::lonhtmlcommon::scripttag(Apache::lonmenu::utilityfunctions($httphost), 'start')."\n".
 5589:                     Apache::lonmenu::serverform();
 5590:         my $forbodytag;
 5591:         &Apache::lonmenu::prepare_functions($env{'request.noversionuri'},
 5592:                                             $forcereg,$args->{'group'},
 5593:                                             $args->{'bread_crumbs'},
 5594:                                             $advtoolsref,'',\$forbodytag);
 5595:         unless (ref($args->{'bread_crumbs'}) eq 'ARRAY') {
 5596:             $funclist = $forbodytag;
 5597:         }
 5598:     } else {
 5599: 
 5600:         #    if ($env{'request.state'} eq 'construct') {
 5601:         #        $titleinfo = &CSTR_pageheader(); #FIXME: Will be removed once all scripts have their own calls
 5602:         #    }
 5603: 
 5604:         $bodytag .= Apache::lonhtmlcommon::scripttag(
 5605:             Apache::lonmenu::utilityfunctions($httphost), 'start');
 5606: 
 5607:         my ($left,$right) = Apache::lonmenu::primary_menu();
 5608: 
 5609:         if ($env{'request.noversionuri'} =~ m{^/res/adm/pages/}) {
 5610:             if ($dc_info) {
 5611:                  $dc_info = qq|<span class="LC_cusr_subheading">$dc_info</span>|;
 5612:             }
 5613:             $bodytag .= qq|<div id="LC_nav_bar">$left $role<br />
 5614:                            <em>$realm</em> $dc_info</div>|;
 5615:             return $bodytag;
 5616:         }
 5617: 
 5618:         unless ($env{'request.symb'} =~ m/\.page___\d+___/) {
 5619:             $bodytag .= qq|<div id="LC_nav_bar">$left $role</div>|;
 5620:         }
 5621: 
 5622:         $bodytag .= $right;
 5623: 
 5624:         if ($dc_info) {
 5625:             $dc_info = &dc_courseid_toggle($dc_info);
 5626:         }
 5627:         $bodytag .= qq|<div id="LC_realm">$realm $dc_info</div>|;
 5628: 
 5629:         #if directed to not display the secondary menu, don't.
 5630:         if ($args->{'no_secondary_menu'}) {
 5631:             return $bodytag;
 5632:         }
 5633:         #don't show menus for public users
 5634:         if (!$public){
 5635:             $bodytag .= Apache::lonmenu::secondary_menu($httphost);
 5636:             $bodytag .= Apache::lonmenu::serverform();
 5637:             $bodytag .= Apache::lonhtmlcommon::scripttag('', 'end');
 5638:             if ($env{'request.state'} eq 'construct') {
 5639:                 $bodytag .= &Apache::lonmenu::innerregister($forcereg,
 5640:                                 $args->{'bread_crumbs'});
 5641:             } elsif ($forcereg) {
 5642:                 $bodytag .= &Apache::lonmenu::innerregister($forcereg,undef,
 5643:                                                             $args->{'group'},
 5644:                                                             $args->{'hide_buttons'});
 5645:             } else {
 5646:                 my $forbodytag;
 5647:                 &Apache::lonmenu::prepare_functions($env{'request.noversionuri'},
 5648:                                                     $forcereg,$args->{'group'},
 5649:                                                     $args->{'bread_crumbs'},
 5650:                                                     $advtoolsref,'',\$forbodytag);
 5651:                 unless (ref($args->{'bread_crumbs'}) eq 'ARRAY') {
 5652:                     $bodytag .= $forbodytag;
 5653:                 }
 5654:             }
 5655:         }else{
 5656:             # this is to seperate menu from content when there's no secondary
 5657:             # menu. Especially needed for public accessible ressources.
 5658:             $bodytag .= '<hr style="clear:both" />';
 5659:             $bodytag .= Apache::lonhtmlcommon::scripttag('', 'end'); 
 5660:         }
 5661: 
 5662:         return $bodytag;
 5663:     }
 5664: 
 5665: #
 5666: # Top frame rendering, Remote is up
 5667: #
 5668: 
 5669:     my $imgsrc = $img;
 5670:     if ($img =~ /^\/adm/) {
 5671:         $imgsrc = &lonhttpdurl($img);
 5672:     }
 5673:     my $upperleft='<img src="'.$imgsrc.'" alt="'.$function.'" />';
 5674: 
 5675:     my $help=($no_inline_link?''
 5676:               :&Apache::loncommon::top_nav_help('Help'));
 5677: 
 5678:     # Explicit link to get inline menu
 5679:     my $menu= ($no_inline_link?''
 5680:                :'<a href="/adm/remote?action=collapse" target="_top">'.&mt('Switch to Inline Menu Mode').'</a>');
 5681: 
 5682:     if ($dc_info) {
 5683:         $dc_info = qq|<span class="LC_cusr_subheading">($dc_info)</span>|;
 5684:     }
 5685: 
 5686:     my $name = &plainname($env{'user.name'},$env{'user.domain'});
 5687:     unless ($public) {
 5688:         $name = &aboutmewrapper($name,$env{'user.name'},$env{'user.domain'},
 5689:                                 undef,'LC_menubuttons_link');
 5690:     }
 5691: 
 5692:     unless ($env{'form.inhibitmenu'}) {
 5693:         $bodytag .= qq|<div id="LC_nav_bar">$name $role</div>
 5694:                        <ol class="LC_primary_menu LC_floatright LC_right">
 5695:                        <li>$help</li>
 5696:                        <li>$menu</li>
 5697:                        </ol><div id="LC_realm"> $realm $dc_info</div>|;
 5698:     }
 5699:     if ($env{'request.state'} eq 'construct') {
 5700:         if (!$public){
 5701:             if ($env{'request.state'} eq 'construct') {
 5702:                 $funclist = &Apache::lonhtmlcommon::scripttag(
 5703:                                 &Apache::lonmenu::utilityfunctions($httphost), 'start').
 5704:                             &Apache::lonhtmlcommon::scripttag('','end').
 5705:                             &Apache::lonmenu::innerregister($forcereg,
 5706:                                                             $args->{'bread_crumbs'});
 5707:             }
 5708:         }
 5709:     }
 5710:     return $bodytag."\n".$funclist;
 5711: }
 5712: 
 5713: sub dc_courseid_toggle {
 5714:     my ($dc_info) = @_;
 5715:     return ' <span id="dccidtext" class="LC_cusr_subheading LC_nobreak">'.
 5716:            '<a href="javascript:showCourseID();" class="LC_menubuttons_link">'.
 5717:            &mt('(More ...)').'</a></span>'.
 5718:            '<div id="dccid" class="LC_dccid">'.$dc_info.'</div>';
 5719: }
 5720: 
 5721: sub make_attr_string {
 5722:     my ($register,$attr_ref) = @_;
 5723: 
 5724:     if ($attr_ref && !ref($attr_ref)) {
 5725: 	die("addentries Must be a hash ref ".
 5726: 	    join(':',caller(1))." ".
 5727: 	    join(':',caller(0))." ");
 5728:     }
 5729: 
 5730:     if ($register) {
 5731: 	my ($on_load,$on_unload);
 5732: 	foreach my $key (keys(%{$attr_ref})) {
 5733: 	    if      (lc($key) eq 'onload') {
 5734: 		$on_load.=$attr_ref->{$key}.';';
 5735: 		delete($attr_ref->{$key});
 5736: 
 5737: 	    } elsif (lc($key) eq 'onunload') {
 5738: 		$on_unload.=$attr_ref->{$key}.';';
 5739: 		delete($attr_ref->{$key});
 5740: 	    }
 5741: 	}
 5742:         if ($env{'environment.remote'} eq 'on') {
 5743:             $attr_ref->{'onload'}  =
 5744:                 &Apache::lonmenu::loadevents().  $on_load;
 5745:             $attr_ref->{'onunload'}=
 5746:                 &Apache::lonmenu::unloadevents().$on_unload;
 5747:         } else {  
 5748: 	    $attr_ref->{'onload'}  = $on_load;
 5749: 	    $attr_ref->{'onunload'}= $on_unload;
 5750:         }
 5751:     }
 5752: 
 5753:     my $attr_string;
 5754:     foreach my $attr (sort(keys(%$attr_ref))) {
 5755: 	$attr_string .= " $attr=\"".$attr_ref->{$attr}.'" ';
 5756:     }
 5757:     return $attr_string;
 5758: }
 5759: 
 5760: 
 5761: ###############################################
 5762: ###############################################
 5763: 
 5764: =pod
 5765: 
 5766: =item * &endbodytag()
 5767: 
 5768: Returns a uniform footer for LON-CAPA web pages.
 5769: 
 5770: Inputs: 1 - optional reference to an args hash
 5771: If in the hash, key for noredirectlink has a value which evaluates to true,
 5772: a 'Continue' link is not displayed if the page contains an
 5773: internal redirect in the <head></head> section,
 5774: i.e., $env{'internal.head.redirect'} exists   
 5775: 
 5776: =cut
 5777: 
 5778: sub endbodytag {
 5779:     my ($args) = @_;
 5780:     my $endbodytag;
 5781:     unless ((ref($args) eq 'HASH') && ($args->{'notbody'})) {
 5782:         $endbodytag='</body>';
 5783:     }
 5784:     if ( exists( $env{'internal.head.redirect'} ) ) {
 5785:         if (!(ref($args) eq 'HASH' && $args->{'noredirectlink'})) {
 5786: 	    $endbodytag=
 5787: 	        "<br /><a href=\"$env{'internal.head.redirect'}\">".
 5788: 	        &mt('Continue').'</a>'.
 5789: 	        $endbodytag;
 5790:         }
 5791:     }
 5792:     return $endbodytag;
 5793: }
 5794: 
 5795: =pod
 5796: 
 5797: =item * &standard_css()
 5798: 
 5799: Returns a style sheet
 5800: 
 5801: Inputs: (all optional)
 5802:             domain         -> force to color decorate a page for a specific
 5803:                                domain
 5804:             function       -> force usage of a specific rolish color scheme
 5805:             bgcolor        -> override the default page bgcolor
 5806: 
 5807: =cut
 5808: 
 5809: sub standard_css {
 5810:     my ($function,$domain,$bgcolor) = @_;
 5811:     $function  = &get_users_function() if (!$function);
 5812:     my $img    = &designparm($function.'.img',   $domain);
 5813:     my $tabbg  = &designparm($function.'.tabbg', $domain);
 5814:     my $font   = &designparm($function.'.font',  $domain);
 5815:     my $fontmenu = &designparm($function.'.fontmenu', $domain);
 5816: #second colour for later usage
 5817:     my $sidebg = &designparm($function.'.sidebg',$domain);
 5818:     my $pgbg_or_bgcolor =
 5819: 	         $bgcolor ||
 5820: 	         &designparm($function.'.pgbg',  $domain);
 5821:     my $pgbg   = &designparm($function.'.pgbg',  $domain);
 5822:     my $alink  = &designparm($function.'.alink', $domain);
 5823:     my $vlink  = &designparm($function.'.vlink', $domain);
 5824:     my $link   = &designparm($function.'.link',  $domain);
 5825: 
 5826:     my $sans                 = 'Verdana,Arial,Helvetica,sans-serif';
 5827:     my $mono                 = 'monospace';
 5828:     my $data_table_head      = $sidebg;
 5829:     my $data_table_light     = '#FAFAFA';
 5830:     my $data_table_dark      = '#E0E0E0';
 5831:     my $data_table_darker    = '#CCCCCC';
 5832:     my $data_table_highlight = '#FFFF00';
 5833:     my $mail_new             = '#FFBB77';
 5834:     my $mail_new_hover       = '#DD9955';
 5835:     my $mail_read            = '#BBBB77';
 5836:     my $mail_read_hover      = '#999944';
 5837:     my $mail_replied         = '#AAAA88';
 5838:     my $mail_replied_hover   = '#888855';
 5839:     my $mail_other           = '#99BBBB';
 5840:     my $mail_other_hover     = '#669999';
 5841:     my $table_header         = '#DDDDDD';
 5842:     my $feedback_link_bg     = '#BBBBBB';
 5843:     my $lg_border_color      = '#C8C8C8';
 5844:     my $button_hover         = '#BF2317';
 5845: 
 5846:     my $border = ($env{'browser.type'} eq 'explorer' ||
 5847:       $env{'browser.type'} eq 'safari'     ) ? '0 2px 0 2px'
 5848:                                              : '0 3px 0 4px';
 5849: 
 5850: 
 5851:     return <<END;
 5852: 
 5853: /* needed for iframe to allow 100% height in FF */
 5854: body, html { 
 5855:     margin: 0;
 5856:     padding: 0 0.5%;
 5857:     height: 99%; /* to avoid scrollbars */
 5858: }
 5859: 
 5860: body {
 5861:   font-family: $sans;
 5862:   line-height:130%;
 5863:   font-size:0.83em;
 5864:   color:$font;
 5865: }
 5866: 
 5867: a:focus,
 5868: a:focus img {
 5869:   color: red;
 5870: }
 5871: 
 5872: form, .inline {
 5873:   display: inline;
 5874: }
 5875: 
 5876: .LC_right {
 5877:   text-align:right;
 5878: }
 5879: 
 5880: .LC_middle {
 5881:   vertical-align:middle;
 5882: }
 5883: 
 5884: .LC_floatleft {
 5885:   float: left;
 5886: }
 5887: 
 5888: .LC_floatright {
 5889:   float: right;
 5890: }
 5891: 
 5892: .LC_400Box {
 5893:   width:400px;
 5894: }
 5895: 
 5896: .LC_iframecontainer {
 5897:     width: 98%;
 5898:     margin: 0;
 5899:     position: fixed;
 5900:     top: 8.5em;
 5901:     bottom: 0;
 5902: }
 5903: 
 5904: .LC_iframecontainer iframe{
 5905:     border: none;
 5906:     width: 100%;
 5907:     height: 100%;
 5908: }
 5909: 
 5910: .LC_filename {
 5911:   font-family: $mono;
 5912:   white-space:pre;
 5913:   font-size: 120%;
 5914: }
 5915: 
 5916: .LC_fileicon {
 5917:   border: none;
 5918:   height: 1.3em;
 5919:   vertical-align: text-bottom;
 5920:   margin-right: 0.3em;
 5921:   text-decoration:none;
 5922: }
 5923: 
 5924: .LC_setting {
 5925:   text-decoration:underline;
 5926: }
 5927: 
 5928: .LC_error {
 5929:   color: red;
 5930: }
 5931: 
 5932: .LC_warning {
 5933:   color: darkorange;
 5934: }
 5935: 
 5936: .LC_diff_removed {
 5937:   color: red;
 5938: }
 5939: 
 5940: .LC_info,
 5941: .LC_success,
 5942: .LC_diff_added {
 5943:   color: green;
 5944: }
 5945: 
 5946: div.LC_confirm_box {
 5947:   background-color: #FAFAFA;
 5948:   border: 1px solid $lg_border_color;
 5949:   margin-right: 0;
 5950:   padding: 5px;
 5951: }
 5952: 
 5953: div.LC_confirm_box .LC_error img,
 5954: div.LC_confirm_box .LC_success img {
 5955:   vertical-align: middle;
 5956: }
 5957: 
 5958: .LC_maxwidth {
 5959:   max-width: 100%;
 5960:   height: auto;
 5961: }
 5962: 
 5963: .LC_textsize_mobile {
 5964:   \@media only screen and (max-device-width: 480px) {
 5965:       -webkit-text-size-adjust:100%; -moz-text-size-adjust:100%; -ms-text-size-adjust:100%;
 5966:   }
 5967: }
 5968: 
 5969: .LC_icon {
 5970:   border: none;
 5971:   vertical-align: middle;
 5972: }
 5973: 
 5974: .LC_docs_spacer {
 5975:   width: 25px;
 5976:   height: 1px;
 5977:   border: none;
 5978: }
 5979: 
 5980: .LC_internal_info {
 5981:   color: #999999;
 5982: }
 5983: 
 5984: .LC_discussion {
 5985:   background: $data_table_dark;
 5986:   border: 1px solid black;
 5987:   margin: 2px;
 5988: }
 5989: 
 5990: .LC_disc_action_left {
 5991:   background: $sidebg;
 5992:   text-align: left;
 5993:   padding: 4px;
 5994:   margin: 2px;
 5995: }
 5996: 
 5997: .LC_disc_action_right {
 5998:   background: $sidebg;
 5999:   text-align: right;
 6000:   padding: 4px;
 6001:   margin: 2px;
 6002: }
 6003: 
 6004: .LC_disc_new_item {
 6005:   background: white;
 6006:   border: 2px solid red;
 6007:   margin: 4px;
 6008:   padding: 4px;
 6009: }
 6010: 
 6011: .LC_disc_old_item {
 6012:   background: white;
 6013:   margin: 4px;
 6014:   padding: 4px;
 6015: }
 6016: 
 6017: table.LC_pastsubmission {
 6018:   border: 1px solid black;
 6019:   margin: 2px;
 6020: }
 6021: 
 6022: table#LC_menubuttons {
 6023:   width: 100%;
 6024:   background: $pgbg;
 6025:   border: 2px;
 6026:   border-collapse: separate;
 6027:   padding: 0;
 6028: }
 6029: 
 6030: table#LC_title_bar a {
 6031:   color: $fontmenu;
 6032: }
 6033: 
 6034: table#LC_title_bar {
 6035:   clear: both;
 6036:   display: none;
 6037: }
 6038: 
 6039: table#LC_title_bar,
 6040: table.LC_breadcrumbs, /* obsolete? */
 6041: table#LC_title_bar.LC_with_remote {
 6042:   width: 100%;
 6043:   border-color: $pgbg;
 6044:   border-style: solid;
 6045:   border-width: $border;
 6046:   background: $pgbg;
 6047:   color: $fontmenu;
 6048:   border-collapse: collapse;
 6049:   padding: 0;
 6050:   margin: 0;
 6051: }
 6052: 
 6053: ul.LC_breadcrumb_tools_outerlist {
 6054:     margin: 0;
 6055:     padding: 0;
 6056:     position: relative;
 6057:     list-style: none;
 6058: }
 6059: ul.LC_breadcrumb_tools_outerlist li {
 6060:     display: inline;
 6061: }
 6062: 
 6063: .LC_breadcrumb_tools_navigation {
 6064:     padding: 0;
 6065:     margin: 0;
 6066:     float: left;
 6067: }
 6068: .LC_breadcrumb_tools_tools {
 6069:     padding: 0;
 6070:     margin: 0;
 6071:     float: right;
 6072: }
 6073: 
 6074: table#LC_title_bar td {
 6075:   background: $tabbg;
 6076: }
 6077: 
 6078: table#LC_menubuttons img {
 6079:   border: none;
 6080: }
 6081: 
 6082: .LC_breadcrumbs_component {
 6083:   float: right;
 6084:   margin: 0 1em;
 6085: }
 6086: .LC_breadcrumbs_component img {
 6087:   vertical-align: middle;
 6088: }
 6089: 
 6090: .LC_breadcrumbs_hoverable {
 6091:   background: $sidebg;
 6092: }
 6093: 
 6094: td.LC_table_cell_checkbox {
 6095:   text-align: center;
 6096: }
 6097: 
 6098: .LC_fontsize_small {
 6099:   font-size: 70%;
 6100: }
 6101: 
 6102: #LC_breadcrumbs {
 6103:   clear:both;
 6104:   background: $sidebg;
 6105:   border-bottom: 1px solid $lg_border_color;
 6106:   line-height: 2.5em;
 6107:   overflow: hidden;
 6108:   margin: 0;
 6109:   padding: 0;
 6110:   text-align: left;
 6111: }
 6112: 
 6113: .LC_head_subbox, .LC_actionbox {
 6114:   clear:both;
 6115:   background: #F8F8F8; /* $sidebg; */
 6116:   border: 1px solid $sidebg;
 6117:   margin: 0 0 10px 0;
 6118:   padding: 3px;
 6119:   text-align: left;
 6120: }
 6121: 
 6122: .LC_fontsize_medium {
 6123:   font-size: 85%;
 6124: }
 6125: 
 6126: .LC_fontsize_large {
 6127:   font-size: 120%;
 6128: }
 6129: 
 6130: .LC_menubuttons_inline_text {
 6131:   color: $font;
 6132:   font-size: 90%;
 6133:   padding-left:3px;
 6134: }
 6135: 
 6136: .LC_menubuttons_inline_text img{
 6137:   vertical-align: middle;
 6138: }
 6139: 
 6140: li.LC_menubuttons_inline_text img {
 6141:   cursor:pointer;
 6142:   text-decoration: none;
 6143: }
 6144: 
 6145: .LC_menubuttons_link {
 6146:   text-decoration: none;
 6147: }
 6148: 
 6149: .LC_menubuttons_category {
 6150:   color: $font;
 6151:   background: $pgbg;
 6152:   font-size: larger;
 6153:   font-weight: bold;
 6154: }
 6155: 
 6156: td.LC_menubuttons_text {
 6157:   color: $font;
 6158: }
 6159: 
 6160: .LC_current_location {
 6161:   background: $tabbg;
 6162: }
 6163: 
 6164: table.LC_data_table {
 6165:   border: 1px solid #000000;
 6166:   border-collapse: separate;
 6167:   border-spacing: 1px;
 6168:   background: $pgbg;
 6169: }
 6170: 
 6171: .LC_data_table_dense {
 6172:   font-size: small;
 6173: }
 6174: 
 6175: table.LC_nested_outer {
 6176:   border: 1px solid #000000;
 6177:   border-collapse: collapse;
 6178:   border-spacing: 0;
 6179:   width: 100%;
 6180: }
 6181: 
 6182: table.LC_innerpickbox,
 6183: table.LC_nested {
 6184:   border: none;
 6185:   border-collapse: collapse;
 6186:   border-spacing: 0;
 6187:   width: 100%;
 6188: }
 6189: 
 6190: table.LC_data_table tr th,
 6191: table.LC_calendar tr th,
 6192: table.LC_prior_tries tr th,
 6193: table.LC_innerpickbox tr th {
 6194:   font-weight: bold;
 6195:   background-color: $data_table_head;
 6196:   color:$fontmenu;
 6197:   font-size:90%;
 6198: }
 6199: 
 6200: table.LC_innerpickbox tr th,
 6201: table.LC_innerpickbox tr td {
 6202:   vertical-align: top;
 6203: }
 6204: 
 6205: table.LC_data_table tr.LC_info_row > td {
 6206:   background-color: #CCCCCC;
 6207:   font-weight: bold;
 6208:   text-align: left;
 6209: }
 6210: 
 6211: table.LC_data_table tr.LC_odd_row > td {
 6212:   background-color: $data_table_light;
 6213:   padding: 2px;
 6214:   vertical-align: top;
 6215: }
 6216: 
 6217: table.LC_pick_box tr > td.LC_odd_row {
 6218:   background-color: $data_table_light;
 6219:   vertical-align: top;
 6220: }
 6221: 
 6222: table.LC_data_table tr.LC_even_row > td {
 6223:   background-color: $data_table_dark;
 6224:   padding: 2px;
 6225:   vertical-align: top;
 6226: }
 6227: 
 6228: table.LC_pick_box tr > td.LC_even_row {
 6229:   background-color: $data_table_dark;
 6230:   vertical-align: top;
 6231: }
 6232: 
 6233: table.LC_data_table tr.LC_data_table_highlight td {
 6234:   background-color: $data_table_darker;
 6235: }
 6236: 
 6237: table.LC_data_table tr td.LC_leftcol_header {
 6238:   background-color: $data_table_head;
 6239:   font-weight: bold;
 6240: }
 6241: 
 6242: table.LC_data_table tr.LC_empty_row td,
 6243: table.LC_nested tr.LC_empty_row td {
 6244:   font-weight: bold;
 6245:   font-style: italic;
 6246:   text-align: center;
 6247:   padding: 8px;
 6248: }
 6249: 
 6250: table.LC_data_table tr.LC_empty_row td,
 6251: table.LC_data_table tr.LC_footer_row td {
 6252:   background-color: $sidebg;
 6253: }
 6254: 
 6255: table.LC_nested tr.LC_empty_row td {
 6256:   background-color: #FFFFFF;
 6257: }
 6258: 
 6259: table.LC_caption {
 6260: }
 6261: 
 6262: table.LC_nested tr.LC_empty_row td {
 6263:   padding: 4ex
 6264: }
 6265: 
 6266: table.LC_nested_outer tr th {
 6267:   font-weight: bold;
 6268:   color:$fontmenu;
 6269:   background-color: $data_table_head;
 6270:   font-size: small;
 6271:   border-bottom: 1px solid #000000;
 6272: }
 6273: 
 6274: table.LC_nested_outer tr td.LC_subheader {
 6275:   background-color: $data_table_head;
 6276:   font-weight: bold;
 6277:   font-size: small;
 6278:   border-bottom: 1px solid #000000;
 6279:   text-align: right;
 6280: }
 6281: 
 6282: table.LC_nested tr.LC_info_row td {
 6283:   background-color: #CCCCCC;
 6284:   font-weight: bold;
 6285:   font-size: small;
 6286:   text-align: center;
 6287: }
 6288: 
 6289: table.LC_nested tr.LC_info_row td.LC_left_item,
 6290: table.LC_nested_outer tr th.LC_left_item {
 6291:   text-align: left;
 6292: }
 6293: 
 6294: table.LC_nested td {
 6295:   background-color: #FFFFFF;
 6296:   font-size: small;
 6297: }
 6298: 
 6299: table.LC_nested_outer tr th.LC_right_item,
 6300: table.LC_nested tr.LC_info_row td.LC_right_item,
 6301: table.LC_nested tr.LC_odd_row td.LC_right_item,
 6302: table.LC_nested tr td.LC_right_item {
 6303:   text-align: right;
 6304: }
 6305: 
 6306: table.LC_nested tr.LC_odd_row td {
 6307:   background-color: #EEEEEE;
 6308: }
 6309: 
 6310: table.LC_createuser {
 6311: }
 6312: 
 6313: table.LC_createuser tr.LC_section_row td {
 6314:   font-size: small;
 6315: }
 6316: 
 6317: table.LC_createuser tr.LC_info_row td  {
 6318:   background-color: #CCCCCC;
 6319:   font-weight: bold;
 6320:   text-align: center;
 6321: }
 6322: 
 6323: table.LC_calendar {
 6324:   border: 1px solid #000000;
 6325:   border-collapse: collapse;
 6326:   width: 98%;
 6327: }
 6328: 
 6329: table.LC_calendar_pickdate {
 6330:   font-size: xx-small;
 6331: }
 6332: 
 6333: table.LC_calendar tr td {
 6334:   border: 1px solid #000000;
 6335:   vertical-align: top;
 6336:   width: 14%;
 6337: }
 6338: 
 6339: table.LC_calendar tr td.LC_calendar_day_empty {
 6340:   background-color: $data_table_dark;
 6341: }
 6342: 
 6343: table.LC_calendar tr td.LC_calendar_day_current {
 6344:   background-color: $data_table_highlight;
 6345: }
 6346: 
 6347: table.LC_data_table tr td.LC_mail_new {
 6348:   background-color: $mail_new;
 6349: }
 6350: 
 6351: table.LC_data_table tr.LC_mail_new:hover {
 6352:   background-color: $mail_new_hover;
 6353: }
 6354: 
 6355: table.LC_data_table tr td.LC_mail_read {
 6356:   background-color: $mail_read;
 6357: }
 6358: 
 6359: /*
 6360: table.LC_data_table tr.LC_mail_read:hover {
 6361:   background-color: $mail_read_hover;
 6362: }
 6363: */
 6364: 
 6365: table.LC_data_table tr td.LC_mail_replied {
 6366:   background-color: $mail_replied;
 6367: }
 6368: 
 6369: /*
 6370: table.LC_data_table tr.LC_mail_replied:hover {
 6371:   background-color: $mail_replied_hover;
 6372: }
 6373: */
 6374: 
 6375: table.LC_data_table tr td.LC_mail_other {
 6376:   background-color: $mail_other;
 6377: }
 6378: 
 6379: /*
 6380: table.LC_data_table tr.LC_mail_other:hover {
 6381:   background-color: $mail_other_hover;
 6382: }
 6383: */
 6384: 
 6385: table.LC_data_table tr > td.LC_browser_file,
 6386: table.LC_data_table tr > td.LC_browser_file_published {
 6387:   background: #AAEE77;
 6388: }
 6389: 
 6390: table.LC_data_table tr > td.LC_browser_file_locked,
 6391: table.LC_data_table tr > td.LC_browser_file_unpublished {
 6392:   background: #FFAA99;
 6393: }
 6394: 
 6395: table.LC_data_table tr > td.LC_browser_file_obsolete {
 6396:   background: #888888;
 6397: }
 6398: 
 6399: table.LC_data_table tr > td.LC_browser_file_modified,
 6400: table.LC_data_table tr > td.LC_browser_file_metamodified {
 6401:   background: #F8F866;
 6402: }
 6403: 
 6404: table.LC_data_table tr.LC_browser_folder > td {
 6405:   background: #E0E8FF;
 6406: }
 6407: 
 6408: table.LC_data_table tr > td.LC_roles_is {
 6409:   /* background: #77FF77; */
 6410: }
 6411: 
 6412: table.LC_data_table tr > td.LC_roles_future {
 6413:   border-right: 8px solid #FFFF77;
 6414: }
 6415: 
 6416: table.LC_data_table tr > td.LC_roles_will {
 6417:   border-right: 8px solid #FFAA77;
 6418: }
 6419: 
 6420: table.LC_data_table tr > td.LC_roles_expired {
 6421:   border-right: 8px solid #FF7777;
 6422: }
 6423: 
 6424: table.LC_data_table tr > td.LC_roles_will_not {
 6425:   border-right: 8px solid #AAFF77;
 6426: }
 6427: 
 6428: table.LC_data_table tr > td.LC_roles_selected {
 6429:   border-right: 8px solid #11CC55;
 6430: }
 6431: 
 6432: span.LC_current_location {
 6433:   font-size:larger;
 6434:   background: $pgbg;
 6435: }
 6436: 
 6437: span.LC_current_nav_location {
 6438:   font-weight:bold;
 6439:   background: $sidebg;
 6440: }
 6441: 
 6442: span.LC_parm_menu_item {
 6443:   font-size: larger;
 6444: }
 6445: 
 6446: span.LC_parm_scope_all {
 6447:   color: red;
 6448: }
 6449: 
 6450: span.LC_parm_scope_folder {
 6451:   color: green;
 6452: }
 6453: 
 6454: span.LC_parm_scope_resource {
 6455:   color: orange;
 6456: }
 6457: 
 6458: span.LC_parm_part {
 6459:   color: blue;
 6460: }
 6461: 
 6462: span.LC_parm_folder,
 6463: span.LC_parm_symb {
 6464:   font-size: x-small;
 6465:   font-family: $mono;
 6466:   color: #AAAAAA;
 6467: }
 6468: 
 6469: ul.LC_parm_parmlist li {
 6470:   display: inline-block;
 6471:   padding: 0.3em 0.8em;
 6472:   vertical-align: top;
 6473:   width: 150px;
 6474:   border-top:1px solid $lg_border_color;
 6475: }
 6476: 
 6477: td.LC_parm_overview_level_menu,
 6478: td.LC_parm_overview_map_menu,
 6479: td.LC_parm_overview_parm_selectors,
 6480: td.LC_parm_overview_restrictions  {
 6481:   border: 1px solid black;
 6482:   border-collapse: collapse;
 6483: }
 6484: 
 6485: table.LC_parm_overview_restrictions td {
 6486:   border-width: 1px 4px 1px 4px;
 6487:   border-style: solid;
 6488:   border-color: $pgbg;
 6489:   text-align: center;
 6490: }
 6491: 
 6492: table.LC_parm_overview_restrictions th {
 6493:   background: $tabbg;
 6494:   border-width: 1px 4px 1px 4px;
 6495:   border-style: solid;
 6496:   border-color: $pgbg;
 6497: }
 6498: 
 6499: table#LC_helpmenu {
 6500:   border: none;
 6501:   height: 55px;
 6502:   border-spacing: 0;
 6503: }
 6504: 
 6505: table#LC_helpmenu fieldset legend {
 6506:   font-size: larger;
 6507: }
 6508: 
 6509: table#LC_helpmenu_links {
 6510:   width: 100%;
 6511:   border: 1px solid black;
 6512:   background: $pgbg;
 6513:   padding: 0;
 6514:   border-spacing: 1px;
 6515: }
 6516: 
 6517: table#LC_helpmenu_links tr td {
 6518:   padding: 1px;
 6519:   background: $tabbg;
 6520:   text-align: center;
 6521:   font-weight: bold;
 6522: }
 6523: 
 6524: table#LC_helpmenu_links a:link,
 6525: table#LC_helpmenu_links a:visited,
 6526: table#LC_helpmenu_links a:active {
 6527:   text-decoration: none;
 6528:   color: $font;
 6529: }
 6530: 
 6531: table#LC_helpmenu_links a:hover {
 6532:   text-decoration: underline;
 6533:   color: $vlink;
 6534: }
 6535: 
 6536: .LC_chrt_popup_exists {
 6537:   border: 1px solid #339933;
 6538:   margin: -1px;
 6539: }
 6540: 
 6541: .LC_chrt_popup_up {
 6542:   border: 1px solid yellow;
 6543:   margin: -1px;
 6544: }
 6545: 
 6546: .LC_chrt_popup {
 6547:   border: 1px solid #8888FF;
 6548:   background: #CCCCFF;
 6549: }
 6550: 
 6551: table.LC_pick_box {
 6552:   border-collapse: separate;
 6553:   background: white;
 6554:   border: 1px solid black;
 6555:   border-spacing: 1px;
 6556: }
 6557: 
 6558: table.LC_pick_box td.LC_pick_box_title {
 6559:   background: $sidebg;
 6560:   font-weight: bold;
 6561:   text-align: left;
 6562:   vertical-align: top;
 6563:   width: 184px;
 6564:   padding: 8px;
 6565: }
 6566: 
 6567: table.LC_pick_box td.LC_pick_box_value {
 6568:   text-align: left;
 6569:   padding: 8px;
 6570: }
 6571: 
 6572: table.LC_pick_box td.LC_pick_box_select {
 6573:   text-align: left;
 6574:   padding: 8px;
 6575: }
 6576: 
 6577: table.LC_pick_box td.LC_pick_box_separator {
 6578:   padding: 0;
 6579:   height: 1px;
 6580:   background: black;
 6581: }
 6582: 
 6583: table.LC_pick_box td.LC_pick_box_submit {
 6584:   text-align: right;
 6585: }
 6586: 
 6587: table.LC_pick_box td.LC_evenrow_value {
 6588:   text-align: left;
 6589:   padding: 8px;
 6590:   background-color: $data_table_light;
 6591: }
 6592: 
 6593: table.LC_pick_box td.LC_oddrow_value {
 6594:   text-align: left;
 6595:   padding: 8px;
 6596:   background-color: $data_table_light;
 6597: }
 6598: 
 6599: span.LC_helpform_receipt_cat {
 6600:   font-weight: bold;
 6601: }
 6602: 
 6603: table.LC_group_priv_box {
 6604:   background: white;
 6605:   border: 1px solid black;
 6606:   border-spacing: 1px;
 6607: }
 6608: 
 6609: table.LC_group_priv_box td.LC_pick_box_title {
 6610:   background: $tabbg;
 6611:   font-weight: bold;
 6612:   text-align: right;
 6613:   width: 184px;
 6614: }
 6615: 
 6616: table.LC_group_priv_box td.LC_groups_fixed {
 6617:   background: $data_table_light;
 6618:   text-align: center;
 6619: }
 6620: 
 6621: table.LC_group_priv_box td.LC_groups_optional {
 6622:   background: $data_table_dark;
 6623:   text-align: center;
 6624: }
 6625: 
 6626: table.LC_group_priv_box td.LC_groups_functionality {
 6627:   background: $data_table_darker;
 6628:   text-align: center;
 6629:   font-weight: bold;
 6630: }
 6631: 
 6632: table.LC_group_priv td {
 6633:   text-align: left;
 6634:   padding: 0;
 6635: }
 6636: 
 6637: .LC_navbuttons {
 6638:   margin: 2ex 0ex 2ex 0ex;
 6639: }
 6640: 
 6641: .LC_topic_bar {
 6642:   font-weight: bold;
 6643:   background: $tabbg;
 6644:   margin: 1em 0em 1em 2em;
 6645:   padding: 3px;
 6646:   font-size: 1.2em;
 6647: }
 6648: 
 6649: .LC_topic_bar span {
 6650:   left: 0.5em;
 6651:   position: absolute;
 6652:   vertical-align: middle;
 6653:   font-size: 1.2em;
 6654: }
 6655: 
 6656: table.LC_course_group_status {
 6657:   margin: 20px;
 6658: }
 6659: 
 6660: table.LC_status_selector td {
 6661:   vertical-align: top;
 6662:   text-align: center;
 6663:   padding: 4px;
 6664: }
 6665: 
 6666: div.LC_feedback_link {
 6667:   clear: both;
 6668:   background: $sidebg;
 6669:   width: 100%;
 6670:   padding-bottom: 10px;
 6671:   border: 1px $tabbg solid;
 6672:   height: 22px;
 6673:   line-height: 22px;
 6674:   padding-top: 5px;
 6675: }
 6676: 
 6677: div.LC_feedback_link img {
 6678:   height: 22px;
 6679:   vertical-align:middle;
 6680: }
 6681: 
 6682: div.LC_feedback_link a {
 6683:   text-decoration: none;
 6684: }
 6685: 
 6686: div.LC_comblock {
 6687:   display:inline;
 6688:   color:$font;
 6689:   font-size:90%;
 6690: }
 6691: 
 6692: div.LC_feedback_link div.LC_comblock {
 6693:   padding-left:5px;
 6694: }
 6695: 
 6696: div.LC_feedback_link div.LC_comblock a {
 6697:   color:$font;
 6698: }
 6699: 
 6700: span.LC_feedback_link {
 6701:   /* background: $feedback_link_bg; */
 6702:   font-size: larger;
 6703: }
 6704: 
 6705: span.LC_message_link {
 6706:   /* background: $feedback_link_bg; */
 6707:   font-size: larger;
 6708:   position: absolute;
 6709:   right: 1em;
 6710: }
 6711: 
 6712: table.LC_prior_tries {
 6713:   border: 1px solid #000000;
 6714:   border-collapse: separate;
 6715:   border-spacing: 1px;
 6716: }
 6717: 
 6718: table.LC_prior_tries td {
 6719:   padding: 2px;
 6720: }
 6721: 
 6722: .LC_answer_correct {
 6723:   background: lightgreen;
 6724:   color: darkgreen;
 6725:   padding: 6px;
 6726: }
 6727: 
 6728: .LC_answer_charged_try {
 6729:   background: #FFAAAA;
 6730:   color: darkred;
 6731:   padding: 6px;
 6732: }
 6733: 
 6734: .LC_answer_not_charged_try,
 6735: .LC_answer_no_grade,
 6736: .LC_answer_late {
 6737:   background: lightyellow;
 6738:   color: black;
 6739:   padding: 6px;
 6740: }
 6741: 
 6742: .LC_answer_previous {
 6743:   background: lightblue;
 6744:   color: darkblue;
 6745:   padding: 6px;
 6746: }
 6747: 
 6748: .LC_answer_no_message {
 6749:   background: #FFFFFF;
 6750:   color: black;
 6751:   padding: 6px;
 6752: }
 6753: 
 6754: .LC_answer_unknown {
 6755:   background: orange;
 6756:   color: black;
 6757:   padding: 6px;
 6758: }
 6759: 
 6760: span.LC_prior_numerical,
 6761: span.LC_prior_string,
 6762: span.LC_prior_custom,
 6763: span.LC_prior_reaction,
 6764: span.LC_prior_math {
 6765:   font-family: $mono;
 6766:   white-space: pre;
 6767: }
 6768: 
 6769: span.LC_prior_string {
 6770:   font-family: $mono;
 6771:   white-space: pre;
 6772: }
 6773: 
 6774: table.LC_prior_option {
 6775:   width: 100%;
 6776:   border-collapse: collapse;
 6777: }
 6778: 
 6779: table.LC_prior_rank,
 6780: table.LC_prior_match {
 6781:   border-collapse: collapse;
 6782: }
 6783: 
 6784: table.LC_prior_option tr td,
 6785: table.LC_prior_rank tr td,
 6786: table.LC_prior_match tr td {
 6787:   border: 1px solid #000000;
 6788: }
 6789: 
 6790: .LC_nobreak {
 6791:   white-space: nowrap;
 6792: }
 6793: 
 6794: span.LC_cusr_emph {
 6795:   font-style: italic;
 6796: }
 6797: 
 6798: span.LC_cusr_subheading {
 6799:   font-weight: normal;
 6800:   font-size: 85%;
 6801: }
 6802: 
 6803: div.LC_docs_entry_move {
 6804:   border: 1px solid #BBBBBB;
 6805:   background: #DDDDDD;
 6806:   width: 22px;
 6807:   padding: 1px;
 6808:   margin: 0;
 6809: }
 6810: 
 6811: table.LC_data_table tr > td.LC_docs_entry_commands,
 6812: table.LC_data_table tr > td.LC_docs_entry_parameter {
 6813:   font-size: x-small;
 6814: }
 6815: 
 6816: .LC_docs_entry_parameter {
 6817:   white-space: nowrap;
 6818: }
 6819: 
 6820: .LC_docs_copy {
 6821:   color: #000099;
 6822: }
 6823: 
 6824: .LC_docs_cut {
 6825:   color: #550044;
 6826: }
 6827: 
 6828: .LC_docs_rename {
 6829:   color: #009900;
 6830: }
 6831: 
 6832: .LC_docs_remove {
 6833:   color: #990000;
 6834: }
 6835: 
 6836: .LC_docs_reinit_warn,
 6837: .LC_docs_ext_edit {
 6838:   font-size: x-small;
 6839: }
 6840: 
 6841: table.LC_docs_adddocs td,
 6842: table.LC_docs_adddocs th {
 6843:   border: 1px solid #BBBBBB;
 6844:   padding: 4px;
 6845:   background: #DDDDDD;
 6846: }
 6847: 
 6848: table.LC_sty_begin {
 6849:   background: #BBFFBB;
 6850: }
 6851: 
 6852: table.LC_sty_end {
 6853:   background: #FFBBBB;
 6854: }
 6855: 
 6856: table.LC_double_column {
 6857:   border-width: 0;
 6858:   border-collapse: collapse;
 6859:   width: 100%;
 6860:   padding: 2px;
 6861: }
 6862: 
 6863: table.LC_double_column tr td.LC_left_col {
 6864:   top: 2px;
 6865:   left: 2px;
 6866:   width: 47%;
 6867:   vertical-align: top;
 6868: }
 6869: 
 6870: table.LC_double_column tr td.LC_right_col {
 6871:   top: 2px;
 6872:   right: 2px;
 6873:   width: 47%;
 6874:   vertical-align: top;
 6875: }
 6876: 
 6877: div.LC_left_float {
 6878:   float: left;
 6879:   padding-right: 5%;
 6880:   padding-bottom: 4px;
 6881: }
 6882: 
 6883: div.LC_clear_float_header {
 6884:   padding-bottom: 2px;
 6885: }
 6886: 
 6887: div.LC_clear_float_footer {
 6888:   padding-top: 10px;
 6889:   clear: both;
 6890: }
 6891: 
 6892: div.LC_grade_show_user {
 6893: /*  border-left: 5px solid $sidebg; */
 6894:   border-top: 5px solid #000000;
 6895:   margin: 50px 0 0 0;
 6896:   padding: 15px 0 5px 10px;
 6897: }
 6898: 
 6899: div.LC_grade_show_user_odd_row {
 6900: /*  border-left: 5px solid #000000; */
 6901: }
 6902: 
 6903: div.LC_grade_show_user div.LC_Box {
 6904:   margin-right: 50px;
 6905: }
 6906: 
 6907: div.LC_grade_submissions,
 6908: div.LC_grade_message_center,
 6909: div.LC_grade_info_links {
 6910:   margin: 5px;
 6911:   width: 99%;
 6912:   background: #FFFFFF;
 6913: }
 6914: 
 6915: div.LC_grade_submissions_header,
 6916: div.LC_grade_message_center_header {
 6917:   font-weight: bold;
 6918:   font-size: large;
 6919: }
 6920: 
 6921: div.LC_grade_submissions_body,
 6922: div.LC_grade_message_center_body {
 6923:   border: 1px solid black;
 6924:   width: 99%;
 6925:   background: #FFFFFF;
 6926: }
 6927: 
 6928: table.LC_scantron_action {
 6929:   width: 100%;
 6930: }
 6931: 
 6932: table.LC_scantron_action tr th {
 6933:   font-weight:bold;
 6934:   font-style:normal;
 6935: }
 6936: 
 6937: .LC_edit_problem_header,
 6938: div.LC_edit_problem_footer {
 6939:   font-weight: normal;
 6940:   font-size:  medium;
 6941:   margin: 2px;
 6942:   background-color: $sidebg;
 6943: }
 6944: 
 6945: div.LC_edit_problem_header,
 6946: div.LC_edit_problem_header div,
 6947: div.LC_edit_problem_footer,
 6948: div.LC_edit_problem_footer div,
 6949: div.LC_edit_problem_editxml_header,
 6950: div.LC_edit_problem_editxml_header div {
 6951:   z-index: 100;
 6952: }
 6953: 
 6954: div.LC_edit_problem_header_title {
 6955:   font-weight: bold;
 6956:   font-size: larger;
 6957:   background: $tabbg;
 6958:   padding: 3px;
 6959:   margin: 0 0 5px 0;
 6960: }
 6961: 
 6962: table.LC_edit_problem_header_title {
 6963:   width: 100%;
 6964:   background: $tabbg;
 6965: }
 6966: 
 6967: div.LC_edit_actionbar {
 6968:     background-color: $sidebg;
 6969:     margin: 0;
 6970:     padding: 0;
 6971:     line-height: 200%;
 6972: }
 6973: 
 6974: div.LC_edit_actionbar div{
 6975:     padding: 0;
 6976:     margin: 0;
 6977:     display: inline-block;
 6978: }
 6979: 
 6980: .LC_edit_opt {
 6981:   padding-left: 1em;
 6982:   white-space: nowrap;
 6983: }
 6984: 
 6985: .LC_edit_problem_latexhelper{
 6986:     text-align: right;
 6987: }
 6988: 
 6989: #LC_edit_problem_colorful div{
 6990:     margin-left: 40px;
 6991: }
 6992: 
 6993: #LC_edit_problem_codemirror div{
 6994:     margin-left: 0px;
 6995: }
 6996: 
 6997: img.stift {
 6998:   border-width: 0;
 6999:   vertical-align: middle;
 7000: }
 7001: 
 7002: table td.LC_mainmenu_col_fieldset {
 7003:   vertical-align: top;
 7004: }
 7005: 
 7006: div.LC_createcourse {
 7007:   margin: 10px 10px 10px 10px;
 7008: }
 7009: 
 7010: .LC_dccid {
 7011:   float: right;
 7012:   margin: 0.2em 0 0 0;
 7013:   padding: 0;
 7014:   font-size: 90%;
 7015:   display:none;
 7016: }
 7017: 
 7018: ol.LC_primary_menu a:hover,
 7019: ol#LC_MenuBreadcrumbs a:hover,
 7020: ol#LC_PathBreadcrumbs a:hover,
 7021: ul#LC_secondary_menu a:hover,
 7022: .LC_FormSectionClearButton input:hover
 7023: ul.LC_TabContent   li:hover a {
 7024:   color:$button_hover;
 7025:   text-decoration:none;
 7026: }
 7027: 
 7028: h1 {
 7029:   padding: 0;
 7030:   line-height:130%;
 7031: }
 7032: 
 7033: h2,
 7034: h3,
 7035: h4,
 7036: h5,
 7037: h6 {
 7038:   margin: 5px 0 5px 0;
 7039:   padding: 0;
 7040:   line-height:130%;
 7041: }
 7042: 
 7043: .LC_hcell {
 7044:   padding:3px 15px 3px 15px;
 7045:   margin: 0;
 7046:   background-color:$tabbg;
 7047:   color:$fontmenu;
 7048:   border-bottom:solid 1px $lg_border_color;
 7049: }
 7050: 
 7051: .LC_Box > .LC_hcell {
 7052:   margin: 0 -10px 10px -10px;
 7053: }
 7054: 
 7055: .LC_noBorder {
 7056:   border: 0;
 7057: }
 7058: 
 7059: .LC_FormSectionClearButton input {
 7060:   background-color:transparent;
 7061:   border: none;
 7062:   cursor:pointer;
 7063:   text-decoration:underline;
 7064: }
 7065: 
 7066: .LC_help_open_topic {
 7067:   color: #FFFFFF;
 7068:   background-color: #EEEEFF;
 7069:   margin: 1px;
 7070:   padding: 4px;
 7071:   border: 1px solid #000033;
 7072:   white-space: nowrap;
 7073:   /* vertical-align: middle; */
 7074: }
 7075: 
 7076: dl,
 7077: ul,
 7078: div,
 7079: fieldset {
 7080:   margin: 10px 10px 10px 0;
 7081:   /* overflow: hidden; */
 7082: }
 7083: 
 7084: article.geogebraweb div {
 7085:     margin: 0;
 7086: }
 7087: 
 7088: fieldset > legend {
 7089:   font-weight: bold;
 7090:   padding: 0 5px 0 5px;
 7091: }
 7092: 
 7093: #LC_nav_bar {
 7094:   float: left;
 7095:   background-color: $pgbg_or_bgcolor;
 7096:   margin: 0 0 2px 0;
 7097: }
 7098: 
 7099: #LC_realm {
 7100:   margin: 0.2em 0 0 0;
 7101:   padding: 0;
 7102:   font-weight: bold;
 7103:   text-align: center;
 7104:   background-color: $pgbg_or_bgcolor;
 7105: }
 7106: 
 7107: #LC_nav_bar em {
 7108:   font-weight: bold;
 7109:   font-style: normal;
 7110: }
 7111: 
 7112: ol.LC_primary_menu {
 7113:   margin: 0;
 7114:   padding: 0;
 7115: }
 7116: 
 7117: ol#LC_PathBreadcrumbs {
 7118:   margin: 0;
 7119: }
 7120: 
 7121: ol.LC_primary_menu li {
 7122:   color: RGB(80, 80, 80);
 7123:   vertical-align: middle;
 7124:   text-align: left;
 7125:   list-style: none;
 7126:   position: relative;
 7127:   float: left;
 7128:   z-index: 100; /* will be displayed above codemirror and underneath the help-layer */
 7129:   line-height: 1.5em;
 7130: }
 7131: 
 7132: ol.LC_primary_menu li a, 
 7133: ol.LC_primary_menu li p {
 7134:   display: block;
 7135:   margin: 0;
 7136:   padding: 0 5px 0 10px;
 7137:   text-decoration: none;
 7138: }
 7139: 
 7140: ol.LC_primary_menu li p span.LC_primary_menu_innertitle {
 7141:   display: inline-block;
 7142:   width: 95%;
 7143:   text-align: left;
 7144: }
 7145: 
 7146: ol.LC_primary_menu li p span.LC_primary_menu_innerarrow {
 7147:   display: inline-block;
 7148:   width: 5%;
 7149:   float: right;
 7150:   text-align: right;
 7151:   font-size: 70%;
 7152: }
 7153: 
 7154: ol.LC_primary_menu ul {
 7155:   display: none;
 7156:   width: 15em;
 7157:   background-color: $data_table_light;
 7158:   position: absolute;
 7159:   top: 100%;
 7160: }
 7161: 
 7162: ol.LC_primary_menu ul ul {
 7163:   left: 100%;
 7164:   top: 0;
 7165: }
 7166: 
 7167: ol.LC_primary_menu li:hover > ul, ol.LC_primary_menu li.hover > ul {
 7168:   display: block;
 7169:   position: absolute;
 7170:   margin: 0;
 7171:   padding: 0;
 7172:   z-index: 2;
 7173: }
 7174: 
 7175: ol.LC_primary_menu li:hover li, ol.LC_primary_menu li.hover li {
 7176: /* First Submenu -> size should be smaller than the menu title of the whole menu */
 7177:   font-size: 90%;
 7178:   vertical-align: top;
 7179:   float: none;
 7180:   border-left: 1px solid black;
 7181:   border-right: 1px solid black;
 7182: /* A dark bottom border to visualize different menu options;
 7183: overwritten in the create_submenu routine for the last border-bottom of the menu */
 7184:   border-bottom: 1px solid $data_table_dark;
 7185: }
 7186: 
 7187: ol.LC_primary_menu li li p:hover {
 7188:   color:$button_hover;
 7189:   text-decoration:none;
 7190:   background-color:$data_table_dark;
 7191: }
 7192: 
 7193: ol.LC_primary_menu li li a:hover {
 7194:    color:$button_hover;
 7195:    background-color:$data_table_dark;
 7196: }
 7197: 
 7198: /* Font-size equal to the size of the predecessors*/
 7199: ol.LC_primary_menu li:hover li li {
 7200:   font-size: 100%;
 7201: }
 7202: 
 7203: ol.LC_primary_menu li img {
 7204:   vertical-align: bottom;
 7205:   height: 1.1em;
 7206:   margin: 0.2em 0 0 0;
 7207: }
 7208: 
 7209: ol.LC_primary_menu a {
 7210:   color: RGB(80, 80, 80);
 7211:   text-decoration: none;
 7212: }
 7213: 
 7214: ol.LC_primary_menu a.LC_new_message {
 7215:   font-weight:bold;
 7216:   color: darkred;
 7217: }
 7218: 
 7219: ol.LC_docs_parameters {
 7220:   margin-left: 0;
 7221:   padding: 0;
 7222:   list-style: none;
 7223: }
 7224: 
 7225: ol.LC_docs_parameters li {
 7226:   margin: 0;
 7227:   padding-right: 20px;
 7228:   display: inline;
 7229: }
 7230: 
 7231: ol.LC_docs_parameters li:before {
 7232:   content: "\\002022 \\0020";
 7233: }
 7234: 
 7235: li.LC_docs_parameters_title {
 7236:   font-weight: bold;
 7237: }
 7238: 
 7239: ol.LC_docs_parameters li.LC_docs_parameters_title:before {
 7240:   content: "";
 7241: }
 7242: 
 7243: ul#LC_secondary_menu {
 7244:   clear: right;
 7245:   color: $fontmenu;
 7246:   background: $tabbg;
 7247:   list-style: none;
 7248:   padding: 0;
 7249:   margin: 0;
 7250:   width: 100%;
 7251:   text-align: left;
 7252:   float: left;
 7253: }
 7254: 
 7255: ul#LC_secondary_menu li {
 7256:   font-weight: bold;
 7257:   line-height: 1.8em;
 7258:   border-right: 1px solid black;
 7259:   float: left;
 7260: }
 7261: 
 7262: ul#LC_secondary_menu li.LC_hoverable:hover, ul#LC_secondary_menu li.hover {
 7263:   background-color: $data_table_light;
 7264: }
 7265: 
 7266: ul#LC_secondary_menu li a {
 7267:   padding: 0 0.8em;
 7268: }
 7269: 
 7270: ul#LC_secondary_menu li ul {
 7271:   display: none;
 7272: }
 7273: 
 7274: ul#LC_secondary_menu li:hover ul, ul#LC_secondary_menu li.hover ul {
 7275:   display: block;
 7276:   position: absolute;
 7277:   margin: 0;
 7278:   padding: 0;
 7279:   list-style:none;
 7280:   float: none;
 7281:   background-color: $data_table_light;
 7282:   z-index: 2;
 7283:   margin-left: -1px;
 7284: }
 7285: 
 7286: ul#LC_secondary_menu li ul li {
 7287:   font-size: 90%;
 7288:   vertical-align: top;
 7289:   border-left: 1px solid black;
 7290:   border-right: 1px solid black;
 7291:   background-color: $data_table_light;
 7292:   list-style:none;
 7293:   float: none;
 7294: }
 7295: 
 7296: ul#LC_secondary_menu li ul li:hover, ul#LC_secondary_menu li ul li.hover {
 7297:   background-color: $data_table_dark;
 7298: }
 7299: 
 7300: ul.LC_TabContent {
 7301:   display:block;
 7302:   background: $sidebg;
 7303:   border-bottom: solid 1px $lg_border_color;
 7304:   list-style:none;
 7305:   margin: -1px -10px 0 -10px;
 7306:   padding: 0;
 7307: }
 7308: 
 7309: ul.LC_TabContent li,
 7310: ul.LC_TabContentBigger li {
 7311:   float:left;
 7312: }
 7313: 
 7314: ul#LC_secondary_menu li a {
 7315:   color: $fontmenu;
 7316:   text-decoration: none;
 7317: }
 7318: 
 7319: ul.LC_TabContent {
 7320:   min-height:20px;
 7321: }
 7322: 
 7323: ul.LC_TabContent li {
 7324:   vertical-align:middle;
 7325:   padding: 0 16px 0 10px;
 7326:   background-color:$tabbg;
 7327:   border-bottom:solid 1px $lg_border_color;
 7328:   border-left: solid 1px $font;
 7329: }
 7330: 
 7331: ul.LC_TabContent .right {
 7332:   float:right;
 7333: }
 7334: 
 7335: ul.LC_TabContent li a,
 7336: ul.LC_TabContent li {
 7337:   color:rgb(47,47,47);
 7338:   text-decoration:none;
 7339:   font-size:95%;
 7340:   font-weight:bold;
 7341:   min-height:20px;
 7342: }
 7343: 
 7344: ul.LC_TabContent li a:hover,
 7345: ul.LC_TabContent li a:focus {
 7346:   color: $button_hover;
 7347:   background:none;
 7348:   outline:none;
 7349: }
 7350: 
 7351: ul.LC_TabContent li:hover {
 7352:   color: $button_hover;
 7353:   cursor:pointer;
 7354: }
 7355: 
 7356: ul.LC_TabContent li.active {
 7357:   color: $font;
 7358:   background:#FFFFFF url(/adm/lonIcons/open.gif) no-repeat scroll right center;
 7359:   border-bottom:solid 1px #FFFFFF;
 7360:   cursor: default;
 7361: }
 7362: 
 7363: ul.LC_TabContent li.active a {
 7364:   color:$font;
 7365:   background:#FFFFFF;
 7366:   outline: none;
 7367: }
 7368: 
 7369: ul.LC_TabContent li.goback {
 7370:   float: left;
 7371:   border-left: none;
 7372: }
 7373: 
 7374: #maincoursedoc {
 7375:   clear:both;
 7376: }
 7377: 
 7378: ul.LC_TabContentBigger {
 7379:   display:block;
 7380:   list-style:none;
 7381:   padding: 0;
 7382: }
 7383: 
 7384: ul.LC_TabContentBigger li {
 7385:   vertical-align:bottom;
 7386:   height: 30px;
 7387:   font-size:110%;
 7388:   font-weight:bold;
 7389:   color: #737373;
 7390: }
 7391: 
 7392: ul.LC_TabContentBigger li.active {
 7393:   position: relative;
 7394:   top: 1px;
 7395: }
 7396: 
 7397: ul.LC_TabContentBigger li a {
 7398:   background:url('/adm/lonIcons/tabbgleft.gif') left bottom no-repeat;
 7399:   height: 30px;
 7400:   line-height: 30px;
 7401:   text-align: center;
 7402:   display: block;
 7403:   text-decoration: none;
 7404:   outline: none;  
 7405: }
 7406: 
 7407: ul.LC_TabContentBigger li.active a {
 7408:   background:url('/adm/lonIcons/tabbgleft.gif') left top no-repeat;
 7409:   color:$font;
 7410: }
 7411: 
 7412: ul.LC_TabContentBigger li b {
 7413:   background: url('/adm/lonIcons/tabbgright.gif') no-repeat right bottom;
 7414:   display: block;
 7415:   float: left;
 7416:   padding: 0 30px;
 7417:   border-bottom: 1px solid $lg_border_color;
 7418: }
 7419: 
 7420: ul.LC_TabContentBigger li:hover b {
 7421:   color:$button_hover;
 7422: }
 7423: 
 7424: ul.LC_TabContentBigger li.active b {
 7425:   background:url('/adm/lonIcons/tabbgright.gif') right top no-repeat;
 7426:   color:$font;
 7427:   border: 0;
 7428: }
 7429: 
 7430: 
 7431: ul.LC_CourseBreadcrumbs {
 7432:   background: $sidebg;
 7433:   height: 2em;
 7434:   padding-left: 10px;
 7435:   margin: 0;
 7436:   list-style-position: inside;
 7437: }
 7438: 
 7439: ol#LC_MenuBreadcrumbs,
 7440: ol#LC_PathBreadcrumbs {
 7441:   padding-left: 10px;
 7442:   margin: 0;
 7443:   height: 2.5em;  /* equal to #LC_breadcrumbs line-height */
 7444: }
 7445: 
 7446: ol#LC_MenuBreadcrumbs li,
 7447: ol#LC_PathBreadcrumbs li,
 7448: ul.LC_CourseBreadcrumbs li {
 7449:   display: inline;
 7450:   white-space: normal;  
 7451: }
 7452: 
 7453: ol#LC_MenuBreadcrumbs li a,
 7454: ul.LC_CourseBreadcrumbs li a {
 7455:   text-decoration: none;
 7456:   font-size:90%;
 7457: }
 7458: 
 7459: ol#LC_MenuBreadcrumbs h1 {
 7460:   display: inline;
 7461:   font-size: 90%;
 7462:   line-height: 2.5em;
 7463:   margin: 0;
 7464:   padding: 0;
 7465: }
 7466: 
 7467: ol#LC_PathBreadcrumbs li a {
 7468:   text-decoration:none;
 7469:   font-size:100%;
 7470:   font-weight:bold;
 7471: }
 7472: 
 7473: .LC_Box {
 7474:   border: solid 1px $lg_border_color;
 7475:   padding: 0 10px 10px 10px;
 7476: }
 7477: 
 7478: .LC_DocsBox {
 7479:   border: solid 1px $lg_border_color;
 7480:   padding: 0 0 10px 10px;
 7481: }
 7482: 
 7483: .LC_AboutMe_Image {
 7484:   float:left;
 7485:   margin-right:10px;
 7486: }
 7487: 
 7488: .LC_Clear_AboutMe_Image {
 7489:   clear:left;
 7490: }
 7491: 
 7492: dl.LC_ListStyleClean dt {
 7493:   padding-right: 5px;
 7494:   display: table-header-group;
 7495: }
 7496: 
 7497: dl.LC_ListStyleClean dd {
 7498:   display: table-row;
 7499: }
 7500: 
 7501: .LC_ListStyleClean,
 7502: .LC_ListStyleSimple,
 7503: .LC_ListStyleNormal,
 7504: .LC_ListStyleSpecial {
 7505:   /* display:block; */
 7506:   list-style-position: inside;
 7507:   list-style-type: none;
 7508:   overflow: hidden;
 7509:   padding: 0;
 7510: }
 7511: 
 7512: .LC_ListStyleSimple li,
 7513: .LC_ListStyleSimple dd,
 7514: .LC_ListStyleNormal li,
 7515: .LC_ListStyleNormal dd,
 7516: .LC_ListStyleSpecial li,
 7517: .LC_ListStyleSpecial dd {
 7518:   margin: 0;
 7519:   padding: 5px 5px 5px 10px;
 7520:   clear: both;
 7521: }
 7522: 
 7523: .LC_ListStyleClean li,
 7524: .LC_ListStyleClean dd {
 7525:   padding-top: 0;
 7526:   padding-bottom: 0;
 7527: }
 7528: 
 7529: .LC_ListStyleSimple dd,
 7530: .LC_ListStyleSimple li {
 7531:   border-bottom: solid 1px $lg_border_color;
 7532: }
 7533: 
 7534: .LC_ListStyleSpecial li,
 7535: .LC_ListStyleSpecial dd {
 7536:   list-style-type: none;
 7537:   background-color: RGB(220, 220, 220);
 7538:   margin-bottom: 4px;
 7539: }
 7540: 
 7541: table.LC_SimpleTable {
 7542:   margin:5px;
 7543:   border:solid 1px $lg_border_color;
 7544: }
 7545: 
 7546: table.LC_SimpleTable tr {
 7547:   padding: 0;
 7548:   border:solid 1px $lg_border_color;
 7549: }
 7550: 
 7551: table.LC_SimpleTable thead {
 7552:   background:rgb(220,220,220);
 7553: }
 7554: 
 7555: div.LC_columnSection {
 7556:   display: block;
 7557:   clear: both;
 7558:   overflow: hidden;
 7559:   margin: 0;
 7560: }
 7561: 
 7562: div.LC_columnSection>* {
 7563:   float: left;
 7564:   margin: 10px 20px 10px 0;
 7565:   overflow:hidden;
 7566: }
 7567: 
 7568: table em {
 7569:   font-weight: bold;
 7570:   font-style: normal;
 7571: }
 7572: 
 7573: table.LC_tableBrowseRes,
 7574: table.LC_tableOfContent {
 7575:   border:none;
 7576:   border-spacing: 1px;
 7577:   padding: 3px;
 7578:   background-color: #FFFFFF;
 7579:   font-size: 90%;
 7580: }
 7581: 
 7582: table.LC_tableOfContent {
 7583:   border-collapse: collapse;
 7584: }
 7585: 
 7586: table.LC_tableBrowseRes a,
 7587: table.LC_tableOfContent a {
 7588:   background-color: transparent;
 7589:   text-decoration: none;
 7590: }
 7591: 
 7592: table.LC_tableOfContent img {
 7593:   border: none;
 7594:   height: 1.3em;
 7595:   vertical-align: text-bottom;
 7596:   margin-right: 0.3em;
 7597: }
 7598: 
 7599: a#LC_content_toolbar_firsthomework {
 7600:   background-image:url(/res/adm/pages/open-first-problem.gif);
 7601: }
 7602: 
 7603: a#LC_content_toolbar_everything {
 7604:   background-image:url(/res/adm/pages/show-all.gif);
 7605: }
 7606: 
 7607: a#LC_content_toolbar_uncompleted {
 7608:   background-image:url(/res/adm/pages/show-incomplete-problems.gif);
 7609: }
 7610: 
 7611: #LC_content_toolbar_clearbubbles {
 7612:   background-image:url(/res/adm/pages/mark-discussionentries-read.gif);
 7613: }
 7614: 
 7615: a#LC_content_toolbar_changefolder {
 7616:   background : url(/res/adm/pages/close-all-folders.gif) top center ;
 7617: }
 7618: 
 7619: a#LC_content_toolbar_changefolder_toggled {
 7620:   background-image:url(/res/adm/pages/open-all-folders.gif);
 7621: }
 7622: 
 7623: a#LC_content_toolbar_edittoplevel {
 7624:   background-image:url(/res/adm/pages/edittoplevel.gif);
 7625: }
 7626: 
 7627: ul#LC_toolbar li a:hover {
 7628:   background-position: bottom center;
 7629: }
 7630: 
 7631: ul#LC_toolbar {
 7632:   padding: 0;
 7633:   margin: 2px;
 7634:   list-style:none;
 7635:   position:relative;
 7636:   background-color:white;
 7637:   overflow: auto;
 7638: }
 7639: 
 7640: ul#LC_toolbar li {
 7641:   border:1px solid white;
 7642:   padding: 0;
 7643:   margin: 0;
 7644:   float: left;
 7645:   display:inline;
 7646:   vertical-align:middle;
 7647:   white-space: nowrap;
 7648: }
 7649: 
 7650: 
 7651: a.LC_toolbarItem {
 7652:   display:block;
 7653:   padding: 0;
 7654:   margin: 0;
 7655:   height: 32px;
 7656:   width: 32px;
 7657:   color:white;
 7658:   border: none;
 7659:   background-repeat:no-repeat;
 7660:   background-color:transparent;
 7661: }
 7662: 
 7663: ul.LC_funclist {
 7664:     margin: 0;
 7665:     padding: 0.5em 1em 0.5em 0;
 7666: }
 7667: 
 7668: ul.LC_funclist > li:first-child {
 7669:     font-weight:bold; 
 7670:     margin-left:0.8em;
 7671: }
 7672: 
 7673: ul.LC_funclist + ul.LC_funclist {
 7674:     /* 
 7675:        left border as a seperator if we have more than
 7676:        one list 
 7677:     */
 7678:     border-left: 1px solid $sidebg;
 7679:     /* 
 7680:        this hides the left border behind the border of the 
 7681:        outer box if element is wrapped to the next 'line' 
 7682:     */
 7683:     margin-left: -1px;
 7684: }
 7685: 
 7686: ul.LC_funclist li {
 7687:   display: inline;
 7688:   white-space: nowrap;
 7689:   margin: 0 0 0 25px;
 7690:   line-height: 150%;
 7691: }
 7692: 
 7693: .LC_hidden {
 7694:   display: none;
 7695: }
 7696: 
 7697: .LCmodal-overlay {
 7698: 		position:fixed;
 7699: 		top:0;
 7700: 		right:0;
 7701: 		bottom:0;
 7702: 		left:0;
 7703: 		height:100%;
 7704: 		width:100%;
 7705: 		margin:0;
 7706: 		padding:0;
 7707: 		background:#999;
 7708: 		opacity:.75;
 7709: 		filter: alpha(opacity=75);
 7710: 		-moz-opacity: 0.75;
 7711: 		z-index:101;
 7712: }
 7713: 
 7714: * html .LCmodal-overlay {   
 7715: 		position: absolute;
 7716: 		height: expression(document.body.scrollHeight > document.body.offsetHeight ? document.body.scrollHeight : document.body.offsetHeight + 'px');
 7717: }
 7718: 
 7719: .LCmodal-window {
 7720: 		position:fixed;
 7721: 		top:50%;
 7722: 		left:50%;
 7723: 		margin:0;
 7724: 		padding:0;
 7725: 		z-index:102;
 7726: 	}
 7727: 
 7728: * html .LCmodal-window {
 7729: 		position:absolute;
 7730: }
 7731: 
 7732: .LCclose-window {
 7733: 		position:absolute;
 7734: 		width:32px;
 7735: 		height:32px;
 7736: 		right:8px;
 7737: 		top:8px;
 7738: 		background:transparent url('/res/adm/pages/process-stop.png') no-repeat scroll right top;
 7739: 		text-indent:-99999px;
 7740: 		overflow:hidden;
 7741: 		cursor:pointer;
 7742: }
 7743: 
 7744: /*
 7745:   styles used by TTH when "Default set of options to pass to tth/m
 7746:   when converting TeX" in course settings has been set
 7747: 
 7748:   option passed: -t
 7749: 
 7750: */
 7751: 
 7752: td div.comp { margin-top: -0.6ex; margin-bottom: -1ex;}
 7753: td div.comb { margin-top: -0.6ex; margin-bottom: -.6ex;}
 7754: td div.hrcomp { line-height: 0.9; margin-top: -0.8ex; margin-bottom: -1ex;}
 7755: td div.norm {line-height:normal;}
 7756: 
 7757: /*
 7758:   option passed -y3
 7759: */
 7760: 
 7761: span.roman {font-family: serif; font-style: normal; font-weight: normal;}
 7762: span.overacc2 {position: relative;  left: .8em; top: -1.2ex;}
 7763: span.overacc1 {position: relative;  left: .6em; top: -1.2ex;}
 7764: 
 7765: #LC_minitab_header {
 7766:   float:left;
 7767:   width:100%;
 7768:   background:#DAE0D2 url("/res/adm/pages/minitabmenu_bg.gif") repeat-x bottom;
 7769:   font-size:93%;
 7770:   line-height:normal;
 7771:   margin: 0.5em 0 0.5em 0;
 7772: }
 7773: #LC_minitab_header ul {
 7774:   margin:0;
 7775:   padding:10px 10px 0;
 7776:   list-style:none;
 7777: }
 7778: #LC_minitab_header li {
 7779:   float:left;
 7780:   background:url("/res/adm/pages/minitabmenu_left.gif") no-repeat left top;
 7781:   margin:0;
 7782:   padding:0 0 0 9px;
 7783: }
 7784: #LC_minitab_header a {
 7785:   display:block;
 7786:   background:url("/res/adm/pages/minitabmenu_right.gif") no-repeat right top;
 7787:   padding:5px 15px 4px 6px;
 7788: }
 7789: #LC_minitab_header #LC_current_minitab {
 7790:   background-image:url("/res/adm/pages/minitabmenu_left_on.gif");
 7791: }
 7792: #LC_minitab_header #LC_current_minitab a {
 7793:   background-image:url("/res/adm/pages/minitabmenu_right_on.gif");
 7794:   padding-bottom:5px;
 7795: }
 7796: 
 7797: 
 7798: END
 7799: }
 7800: 
 7801: =pod
 7802: 
 7803: =item * &headtag()
 7804: 
 7805: Returns a uniform footer for LON-CAPA web pages.
 7806: 
 7807: Inputs: $title - optional title for the head
 7808:         $head_extra - optional extra HTML to put inside the <head>
 7809:         $args - optional arguments
 7810:             force_register - if is true call registerurl so the remote is 
 7811:                              informed
 7812:             redirect       -> array ref of
 7813:                                    1- seconds before redirect occurs
 7814:                                    2- url to redirect to
 7815:                                    3- whether the side effect should occur
 7816:                            (side effect of setting 
 7817:                                $env{'internal.head.redirect'} to the url 
 7818:                                redirected too)
 7819:             domain         -> force to color decorate a page for a specific
 7820:                                domain
 7821:             function       -> force usage of a specific rolish color scheme
 7822:             bgcolor        -> override the default page bgcolor
 7823:             no_auto_mt_title
 7824:                            -> prevent &mt()ing the title arg
 7825: 
 7826: =cut
 7827: 
 7828: sub headtag {
 7829:     my ($title,$head_extra,$args) = @_;
 7830:     
 7831:     my $function = $args->{'function'} || &get_users_function();
 7832:     my $domain   = $args->{'domain'}   || &determinedomain();
 7833:     my $bgcolor  = $args->{'bgcolor'}  || &designparm($function.'.pgbg',$domain);
 7834:     my $httphost = $args->{'use_absolute'};
 7835:     my $url = join(':',$env{'user.name'},$env{'user.domain'},
 7836: 		   $Apache::lonnet::perlvar{'lonVersion'},
 7837: 		   #time(),
 7838: 		   $env{'environment.color.timestamp'},
 7839: 		   $function,$domain,$bgcolor);
 7840: 
 7841:     $url = '/adm/css/'.&escape($url).'.css';
 7842: 
 7843:     my $result =
 7844: 	'<head>'.
 7845: 	&font_settings($args);
 7846: 
 7847:     my $inhibitprint;
 7848:     if ($args->{'print_suppress'}) {
 7849:         $inhibitprint = &print_suppression();
 7850:     }
 7851: 
 7852:     if (!$args->{'frameset'}) {
 7853: 	$result .= &Apache::lonhtmlcommon::htmlareaheaders();
 7854:     }
 7855:     if ($args->{'force_register'}) {
 7856:         $result .= &Apache::lonmenu::registerurl(1);
 7857:     }
 7858:     if (!$args->{'no_nav_bar'} 
 7859: 	&& !$args->{'only_body'}
 7860: 	&& !$args->{'frameset'}) {
 7861: 	$result .= &help_menu_js($httphost);
 7862:         $result.=&modal_window();
 7863:         $result.=&togglebox_script();
 7864:         $result.=&wishlist_window();
 7865:         $result.=&LCprogressbarUpdate_script();
 7866:     } else {
 7867:         if ($args->{'add_modal'}) {
 7868:            $result.=&modal_window();
 7869:         }
 7870:         if ($args->{'add_wishlist'}) {
 7871:            $result.=&wishlist_window();
 7872:         }
 7873:         if ($args->{'add_togglebox'}) {
 7874:            $result.=&togglebox_script();
 7875:         }
 7876:         if ($args->{'add_progressbar'}) {
 7877:            $result.=&LCprogressbarUpdate_script();
 7878:         }
 7879:     }
 7880:     if (ref($args->{'redirect'})) {
 7881: 	my ($time,$url,$inhibit_continue) = @{$args->{'redirect'}};
 7882: 	$url = &Apache::lonenc::check_encrypt($url);
 7883: 	if (!$inhibit_continue) {
 7884: 	    $env{'internal.head.redirect'} = $url;
 7885: 	}
 7886: 	$result.=<<ADDMETA
 7887: <meta http-equiv="pragma" content="no-cache" />
 7888: <meta http-equiv="Refresh" content="$time; url=$url" />
 7889: ADDMETA
 7890:     } else {
 7891:         unless (($args->{'frameset'}) || ($args->{'js_ready'}) || ($args->{'only_body'}) || ($args->{'no_nav_bar'})) {
 7892:             my $requrl = $env{'request.uri'};
 7893:             if ($requrl eq '') {
 7894:                 $requrl = $ENV{'REQUEST_URI'};
 7895:                 $requrl =~ s/\?.+$//;
 7896:             }
 7897:             unless (($requrl =~ m{^/adm/(?:switchserver|login|authenticate|logout|groupsort|cleanup|helper|slotrequest|grades)(\?|$)}) ||
 7898:                     (($requrl =~ m{^/res/}) && (($env{'form.submitted'} eq 'scantron') ||
 7899:                      ($env{'form.grade_symb'}) || ($Apache::lonhomework::scantronmode)))) {
 7900:                 my $dom_in_use = $Apache::lonnet::perlvar{'lonDefDomain'};
 7901:                 unless (&Apache::lonnet::allowed('mau',$dom_in_use)) {
 7902:                     my %domdefs = &Apache::lonnet::get_domain_defaults($dom_in_use);
 7903:                     if (ref($domdefs{'offloadnow'}) eq 'HASH') {
 7904:                         my $lonhost = $Apache::lonnet::perlvar{'lonHostID'};
 7905:                         if ($domdefs{'offloadnow'}{$lonhost}) {
 7906:                             my $newserver = &Apache::lonnet::spareserver(30000,undef,1,$dom_in_use);
 7907:                             if (($newserver) && ($newserver ne $lonhost)) {
 7908:                                 my $numsec = 5;
 7909:                                 my $timeout = $numsec * 1000;
 7910:                                 my ($newurl,$locknum,%locks,$msg);
 7911:                                 if ($env{'request.role.adv'}) {
 7912:                                     ($locknum,%locks) = &Apache::lonnet::get_locks();
 7913:                                 }
 7914:                                 my $disable_submit = 0;
 7915:                                 if ($requrl =~ /$LONCAPA::assess_re/) {
 7916:                                     $disable_submit = 1;
 7917:                                 }
 7918:                                 if ($locknum) {
 7919:                                     my @lockinfo = sort(values(%locks));
 7920:                                     $msg = &mt('Once the following tasks are complete: ')."\\n".
 7921:                                            join(", ",sort(values(%locks)))."\\n".
 7922:                                            &mt('your session will be transferred to a different server, after you click "Roles".');
 7923:                                 } else {
 7924:                                     if (($requrl =~ m{^/res/}) && ($env{'form.submitted'} =~ /^part_/)) {
 7925:                                         $msg = &mt('Your LON-CAPA submission has been recorded')."\\n";
 7926:                                     }
 7927:                                     $msg .= &mt('Your current LON-CAPA session will be transferred to a different server in [quant,_1,second].',$numsec);
 7928:                                     $newurl = '/adm/switchserver?otherserver='.$newserver;
 7929:                                     if (($env{'request.role'}) && ($env{'request.role'} ne 'cm')) {
 7930:                                         $newurl .= '&role='.$env{'request.role'};
 7931:                                     }
 7932:                                     if ($env{'request.symb'}) {
 7933:                                         $newurl .= '&symb='.$env{'request.symb'};
 7934:                                     } else {
 7935:                                         $newurl .= '&origurl='.$requrl;
 7936:                                     }
 7937:                                 }
 7938:                                 &js_escape(\$msg);
 7939:                                 $result.=<<OFFLOAD
 7940: <meta http-equiv="pragma" content="no-cache" />
 7941: <script type="text/javascript">
 7942: // <![CDATA[
 7943: function LC_Offload_Now() {
 7944:     var dest = "$newurl";
 7945:     if (dest != '') {
 7946:         window.location.href="$newurl";
 7947:     }
 7948: }
 7949: \$(document).ready(function () {
 7950:     window.alert('$msg');
 7951:     if ($disable_submit) {
 7952:         \$(".LC_hwk_submit").prop("disabled", true);
 7953:         \$( ".LC_textline" ).prop( "readonly", "readonly");
 7954:     }
 7955:     setTimeout('LC_Offload_Now()', $timeout);
 7956: });
 7957: // ]]>
 7958: </script>
 7959: OFFLOAD
 7960:                             }
 7961:                         }
 7962:                     }
 7963:                 }
 7964:             }
 7965:         }
 7966:     }
 7967:     if (!defined($title)) {
 7968: 	$title = 'The LearningOnline Network with CAPA';
 7969:     }
 7970:     if (!$args->{'no_auto_mt_title'}) { $title = &mt($title); }
 7971:     $result .= '<title> LON-CAPA '.$title.'</title>'
 7972: 	.'<link rel="stylesheet" type="text/css" href="'.$url.'"';
 7973:     if (!$args->{'frameset'}) {
 7974:         $result .= ' /';
 7975:     }
 7976:     $result .= '>'
 7977:         .$inhibitprint
 7978: 	.$head_extra;
 7979:     my $clientmobile;
 7980:     if (($env{'user.name'} eq '') && ($env{'user.domain'} eq '')) {
 7981:         (undef,undef,undef,undef,undef,undef,$clientmobile) = &decode_user_agent();
 7982:     } else {
 7983:         $clientmobile = $env{'browser.mobile'};
 7984:     }
 7985:     if ($clientmobile) {
 7986:         $result .= '
 7987: <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=0, minimum-scale=1.0, maximum-scale=1.0">
 7988: <meta name="apple-mobile-web-app-capable" content="yes" />';
 7989:     }
 7990:     $result .= '<meta name="google" content="notranslate" />'."\n";
 7991:     return $result.'</head>';
 7992: }
 7993: 
 7994: =pod
 7995: 
 7996: =item * &font_settings()
 7997: 
 7998: Returns neccessary <meta> to set the proper encoding
 7999: 
 8000: Inputs: optional reference to HASH -- $args passed to &headtag()
 8001: 
 8002: =cut
 8003: 
 8004: sub font_settings {
 8005:     my ($args) = @_;
 8006:     my $headerstring='';
 8007:     if ((!$env{'browser.mathml'} && $env{'browser.unicode'}) ||
 8008:         ((ref($args) eq 'HASH') && ($args->{'browser.unicode'}))) {
 8009: 	$headerstring.=
 8010: 	    '<meta http-equiv="Content-Type" content="text/html; charset=utf-8"';
 8011:         if (!$args->{'frameset'}) {
 8012:             $headerstring.= ' /';
 8013:         }
 8014:         $headerstring .= '>'."\n";
 8015:     }
 8016:     return $headerstring;
 8017: }
 8018: 
 8019: =pod
 8020: 
 8021: =item * &print_suppression()
 8022: 
 8023: In course context returns css which causes the body to be blank when media="print",
 8024: if printout generation is unavailable for the current resource.
 8025: 
 8026: This could be because:
 8027: 
 8028: (a) printstartdate is in the future
 8029: 
 8030: (b) printenddate is in the past
 8031: 
 8032: (c) there is an active exam block with "printout"
 8033: functionality blocked
 8034: 
 8035: Users with pav, pfo or evb privileges are exempt.
 8036: 
 8037: Inputs: none
 8038: 
 8039: =cut
 8040: 
 8041: 
 8042: sub print_suppression {
 8043:     my $noprint;
 8044:     if ($env{'request.course.id'}) {
 8045:         my $scope = $env{'request.course.id'};
 8046:         if ((&Apache::lonnet::allowed('pav',$scope)) ||
 8047:             (&Apache::lonnet::allowed('pfo',$scope))) {
 8048:             return;
 8049:         }
 8050:         if ($env{'request.course.sec'} ne '') {
 8051:             $scope .= "/$env{'request.course.sec'}";
 8052:             if ((&Apache::lonnet::allowed('pav',$scope)) ||
 8053:                 (&Apache::lonnet::allowed('pfo',$scope))) {
 8054:                 return;
 8055:             }
 8056:         }
 8057:         my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 8058:         my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 8059:         my $blocked = &blocking_status('printout',$cnum,$cdom,undef,1);
 8060:         if ($blocked) {
 8061:             my $checkrole = "cm./$cdom/$cnum";
 8062:             if ($env{'request.course.sec'} ne '') {
 8063:                 $checkrole .= "/$env{'request.course.sec'}";
 8064:             }
 8065:             unless ((&Apache::lonnet::allowed('evb',undef,undef,$checkrole)) &&
 8066:                     ($env{'request.role'} !~ m{^st\./$cdom/$cnum})) {
 8067:                 $noprint = 1;
 8068:             }
 8069:         }
 8070:         unless ($noprint) {
 8071:             my $symb = &Apache::lonnet::symbread();
 8072:             if ($symb ne '') {
 8073:                 my $navmap = Apache::lonnavmaps::navmap->new();
 8074:                 if (ref($navmap)) {
 8075:                     my $res = $navmap->getBySymb($symb);
 8076:                     if (ref($res)) {
 8077:                         if (!$res->resprintable()) {
 8078:                             $noprint = 1;
 8079:                         }
 8080:                     }
 8081:                 }
 8082:             }
 8083:         }
 8084:         if ($noprint) {
 8085:             return <<"ENDSTYLE";
 8086: <style type="text/css" media="print">
 8087:     body { display:none }
 8088: </style>
 8089: ENDSTYLE
 8090:         }
 8091:     }
 8092:     return;
 8093: }
 8094: 
 8095: =pod
 8096: 
 8097: =item * &xml_begin()
 8098: 
 8099: Returns the needed doctype and <html>
 8100: 
 8101: Inputs: none
 8102: 
 8103: =cut
 8104: 
 8105: sub xml_begin {
 8106:     my ($is_frameset) = @_;
 8107:     my $output='';
 8108: 
 8109:     if ($env{'browser.mathml'}) {
 8110: 	$output='<?xml version="1.0"?>'
 8111:             #.'<?xml-stylesheet type="text/css" href="/adm/MathML/mathml.css"?>'."\n"
 8112: #            .'<!DOCTYPE html SYSTEM "/adm/MathML/mathml.dtd" '
 8113:             
 8114: #	    .'<!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">] >'
 8115: 	    .'<!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">'
 8116:             .'<html xmlns:math="http://www.w3.org/1998/Math/MathML" ' 
 8117: 	    .'xmlns="http://www.w3.org/1999/xhtml">';
 8118:     } elsif ($is_frameset) {
 8119:         $output='<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Frameset//EN" "http://www.w3.org/TR/html4/frameset.dtd">'."\n".
 8120:                 '<html>'."\n";
 8121:     } else {
 8122: 	$output='<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">'."\n".
 8123:                 '<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">'."\n";
 8124:     }
 8125:     return $output;
 8126: }
 8127: 
 8128: =pod
 8129: 
 8130: =item * &start_page()
 8131: 
 8132: Returns a complete <html> .. <body> section for LON-CAPA web pages.
 8133: 
 8134: Inputs:
 8135: 
 8136: =over 4
 8137: 
 8138: $title - optional title for the page
 8139: 
 8140: $head_extra - optional extra HTML to incude inside the <head>
 8141: 
 8142: $args - additional optional args supported are:
 8143: 
 8144: =over 8
 8145: 
 8146:              only_body      -> is true will set &bodytag() onlybodytag
 8147:                                     arg on
 8148:              no_nav_bar     -> is true will set &bodytag() no_nav_bar arg on
 8149:              add_entries    -> additional attributes to add to the  <body>
 8150:              domain         -> force to color decorate a page for a 
 8151:                                     specific domain
 8152:              function       -> force usage of a specific rolish color
 8153:                                     scheme
 8154:              redirect       -> see &headtag()
 8155:              bgcolor        -> override the default page bg color
 8156:              js_ready       -> return a string ready for being used in 
 8157:                                     a javascript writeln
 8158:              html_encode    -> return a string ready for being used in 
 8159:                                     a html attribute
 8160:              force_register -> if is true will turn on the &bodytag()
 8161:                                     $forcereg arg
 8162:              frameset       -> if true will start with a <frameset>
 8163:                                     rather than <body>
 8164:              skip_phases    -> hash ref of 
 8165:                                     head -> skip the <html><head> generation
 8166:                                     body -> skip all <body> generation
 8167:              no_inline_link -> if true and in remote mode, don't show the
 8168:                                     'Switch To Inline Menu' link
 8169:              no_auto_mt_title -> prevent &mt()ing the title arg
 8170:              bread_crumbs ->             Array containing breadcrumbs
 8171:              bread_crumbs_component ->  if exists show it as headline else show only the breadcrumbs
 8172:              bread_crumbs_nomenu -> if true will pass false as the value of $menulink
 8173:                                     to lonhtmlcommon::breadcrumbs
 8174:              group          -> includes the current group, if page is for a
 8175:                                specific group
 8176: 
 8177: =back
 8178: 
 8179: =back
 8180: 
 8181: =cut
 8182: 
 8183: sub start_page {
 8184:     my ($title,$head_extra,$args) = @_;
 8185:     #&Apache::lonnet::logthis("start_page ".join(':',caller(0)));
 8186: 
 8187:     $env{'internal.start_page'}++;
 8188:     my ($result,@advtools);
 8189: 
 8190:     if (! exists($args->{'skip_phases'}{'head'}) ) {
 8191:         $result .= &xml_begin($args->{'frameset'}) . &headtag($title, $head_extra, $args);
 8192:     }
 8193:     
 8194:     if (! exists($args->{'skip_phases'}{'body'}) ) {
 8195: 	if ($args->{'frameset'}) {
 8196: 	    my $attr_string = &make_attr_string($args->{'force_register'},
 8197: 						$args->{'add_entries'});
 8198: 	    $result .= "\n<frameset $attr_string>\n";
 8199:         } else {
 8200:             $result .=
 8201:                 &bodytag($title, 
 8202:                          $args->{'function'},       $args->{'add_entries'},
 8203:                          $args->{'only_body'},      $args->{'domain'},
 8204:                          $args->{'force_register'}, $args->{'no_nav_bar'},
 8205:                          $args->{'bgcolor'},        $args->{'no_inline_link'},
 8206:                          $args,                     \@advtools);
 8207:         }
 8208:     }
 8209: 
 8210:     if ($args->{'js_ready'}) {
 8211: 		$result = &js_ready($result);
 8212:     }
 8213:     if ($args->{'html_encode'}) {
 8214: 		$result = &html_encode($result);
 8215:     }
 8216: 
 8217:     # Preparation for new and consistent functionlist at top of screen
 8218:     # if ($args->{'functionlist'}) {
 8219:     #            $result .= &build_functionlist();
 8220:     #}
 8221: 
 8222:     # Don't add anything more if only_body wanted or in const space
 8223:     return $result if    $args->{'only_body'} 
 8224:                       || $env{'request.state'} eq 'construct';
 8225: 
 8226:     #Breadcrumbs
 8227:     if (exists($args->{'bread_crumbs'}) or exists($args->{'bread_crumbs_component'})) {
 8228: 		&Apache::lonhtmlcommon::clear_breadcrumbs();
 8229: 		#if any br links exists, add them to the breadcrumbs
 8230: 		if (exists($args->{'bread_crumbs'}) and ref($args->{'bread_crumbs'}) eq 'ARRAY') {         
 8231: 			foreach my $crumb (@{$args->{'bread_crumbs'}}){
 8232: 				&Apache::lonhtmlcommon::add_breadcrumb($crumb);
 8233: 			}
 8234: 		}
 8235:                 # if @advtools array contains items add then to the breadcrumbs
 8236:                 if (@advtools > 0) {
 8237:                     &Apache::lonmenu::advtools_crumbs(@advtools);
 8238:                 }
 8239:                 my $menulink;
 8240:                 # if arg: bread_crumbs_nomenu is true pass 0 as $menulink item.
 8241:                 if (exists($args->{'bread_crumbs_nomenu'})) {
 8242:                     $menulink = 0;
 8243:                 } else {
 8244:                     undef($menulink);
 8245:                 }
 8246: 		#if bread_crumbs_component exists show it as headline else show only the breadcrumbs
 8247: 		if(exists($args->{'bread_crumbs_component'})){
 8248: 			$result .= &Apache::lonhtmlcommon::breadcrumbs($args->{'bread_crumbs_component'},'',$menulink);
 8249: 		}else{
 8250: 			$result .= &Apache::lonhtmlcommon::breadcrumbs('','',$menulink);
 8251: 		}
 8252:     } elsif (($env{'environment.remote'} eq 'on') &&
 8253:              ($env{'form.inhibitmenu'} ne 'yes') &&
 8254:              ($env{'request.noversionuri'} =~ m{^/res/}) &&
 8255:              ($env{'request.noversionuri'} !~ m{^/res/adm/pages/})) {
 8256:         $result .= '<div style="padding:0;margin:0;clear:both"><hr /></div>';
 8257:     }
 8258:     return $result;
 8259: }
 8260: 
 8261: sub end_page {
 8262:     my ($args) = @_;
 8263:     $env{'internal.end_page'}++;
 8264:     my $result;
 8265:     if ($args->{'discussion'}) {
 8266: 	my ($target,$parser);
 8267: 	if (ref($args->{'discussion'})) {
 8268: 	    ($target,$parser) =($args->{'discussion'}{'target'},
 8269: 				$args->{'discussion'}{'parser'});
 8270: 	}
 8271: 	$result .= &Apache::lonxml::xmlend($target,$parser);
 8272:     }
 8273:     if ($args->{'frameset'}) {
 8274: 	$result .= '</frameset>';
 8275:     } else {
 8276: 	$result .= &endbodytag($args);
 8277:     }
 8278:     unless ($args->{'notbody'}) {
 8279:         $result .= "\n</html>";
 8280:     }
 8281: 
 8282:     if ($args->{'js_ready'}) {
 8283: 	$result = &js_ready($result);
 8284:     }
 8285: 
 8286:     if ($args->{'html_encode'}) {
 8287: 	$result = &html_encode($result);
 8288:     }
 8289: 
 8290:     return $result;
 8291: }
 8292: 
 8293: sub wishlist_window {
 8294:     return(<<'ENDWISHLIST');
 8295: <script type="text/javascript">
 8296: // <![CDATA[
 8297: // <!-- BEGIN LON-CAPA Internal
 8298: function set_wishlistlink(title, path) {
 8299:     if (!title) {
 8300:         title = document.title;
 8301:         title = title.replace(/^LON-CAPA /,'');
 8302:     }
 8303:     title = encodeURIComponent(title);
 8304:     title = title.replace("'","\\\'");
 8305:     if (!path) {
 8306:         path = location.pathname;
 8307:     }
 8308:     path = encodeURIComponent(path);
 8309:     path = path.replace("'","\\\'");
 8310:     Win = window.open('/adm/wishlist?mode=newLink&setTitle='+title+'&setPath='+path,
 8311:                       'wishlistNewLink','width=560,height=350,scrollbars=0');
 8312: }
 8313: // END LON-CAPA Internal -->
 8314: // ]]>
 8315: </script>
 8316: ENDWISHLIST
 8317: }
 8318: 
 8319: sub modal_window {
 8320:     return(<<'ENDMODAL');
 8321: <script type="text/javascript">
 8322: // <![CDATA[
 8323: // <!-- BEGIN LON-CAPA Internal
 8324: var modalWindow = {
 8325: 	parent:"body",
 8326: 	windowId:null,
 8327: 	content:null,
 8328: 	width:null,
 8329: 	height:null,
 8330: 	close:function()
 8331: 	{
 8332: 	        $(".LCmodal-window").remove();
 8333: 	        $(".LCmodal-overlay").remove();
 8334: 	},
 8335: 	open:function()
 8336: 	{
 8337: 		var modal = "";
 8338: 		modal += "<div class=\"LCmodal-overlay\"></div>";
 8339: 		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;\">";
 8340: 		modal += this.content;
 8341: 		modal += "</div>";	
 8342: 
 8343: 		$(this.parent).append(modal);
 8344: 
 8345: 		$(".LCmodal-window").append("<a class=\"LCclose-window\"></a>");
 8346: 		$(".LCclose-window").click(function(){modalWindow.close();});
 8347: 		$(".LCmodal-overlay").click(function(){modalWindow.close();});
 8348: 	}
 8349: };
 8350: 	var openMyModal = function(source,width,height,scrolling,transparency,style)
 8351: 	{
 8352:                 source = source.replace(/'/g,"&#39;");
 8353: 		modalWindow.windowId = "myModal";
 8354: 		modalWindow.width = width;
 8355: 		modalWindow.height = height;
 8356: 		modalWindow.content = "<iframe width='"+width+"' height='"+height+"' frameborder='0' scrolling='"+scrolling+"' allowtransparency='"+transparency+"' src='" + source + "' style='"+style+"'></iframe>";
 8357: 		modalWindow.open();
 8358: 	};
 8359: // END LON-CAPA Internal -->
 8360: // ]]>
 8361: </script>
 8362: ENDMODAL
 8363: }
 8364: 
 8365: sub modal_link {
 8366:     my ($link,$linktext,$width,$height,$target,$scrolling,$title,$transparency,$style)=@_;
 8367:     unless ($width) { $width=480; }
 8368:     unless ($height) { $height=400; }
 8369:     unless ($scrolling) { $scrolling='yes'; }
 8370:     unless ($transparency) { $transparency='true'; }
 8371: 
 8372:     my $target_attr;
 8373:     if (defined($target)) {
 8374:         $target_attr = 'target="'.$target.'"';
 8375:     }
 8376:     return <<"ENDLINK";
 8377: <a href="$link" $target_attr title="$title" onclick="javascript:openMyModal('$link',$width,$height,'$scrolling','$transparency','$style'); return false;">
 8378:            $linktext</a>
 8379: ENDLINK
 8380: }
 8381: 
 8382: sub modal_adhoc_script {
 8383:     my ($funcname,$width,$height,$content)=@_;
 8384:     return (<<ENDADHOC);
 8385: <script type="text/javascript">
 8386: // <![CDATA[
 8387:         var $funcname = function()
 8388:         {
 8389:                 modalWindow.windowId = "myModal";
 8390:                 modalWindow.width = $width;
 8391:                 modalWindow.height = $height;
 8392:                 modalWindow.content = '$content';
 8393:                 modalWindow.open();
 8394:         };  
 8395: // ]]>
 8396: </script>
 8397: ENDADHOC
 8398: }
 8399: 
 8400: sub modal_adhoc_inner {
 8401:     my ($funcname,$width,$height,$content)=@_;
 8402:     my $innerwidth=$width-20;
 8403:     $content=&js_ready(
 8404:                &start_page('Dialog',undef,{'only_body'=>1,'bgcolor'=>'#FFFFFF'}).
 8405:                  &start_scrollbox($width.'px',$innerwidth.'px',$height.'px','myModal','#FFFFFF',undef,1).
 8406:                  $content.
 8407:                  &end_scrollbox().
 8408:                  &end_page()
 8409:              );
 8410:     return &modal_adhoc_script($funcname,$width,$height,$content);
 8411: }
 8412: 
 8413: sub modal_adhoc_window {
 8414:     my ($funcname,$width,$height,$content,$linktext)=@_;
 8415:     return &modal_adhoc_inner($funcname,$width,$height,$content).
 8416:            "<a href=\"javascript:$funcname();void(0);\">".$linktext."</a>";
 8417: }
 8418: 
 8419: sub modal_adhoc_launch {
 8420:     my ($funcname,$width,$height,$content)=@_;
 8421:     return &modal_adhoc_inner($funcname,$width,$height,$content).(<<ENDLAUNCH);
 8422: <script type="text/javascript">
 8423: // <![CDATA[
 8424: $funcname();
 8425: // ]]>
 8426: </script>
 8427: ENDLAUNCH
 8428: }
 8429: 
 8430: sub modal_adhoc_close {
 8431:     return (<<ENDCLOSE);
 8432: <script type="text/javascript">
 8433: // <![CDATA[
 8434: modalWindow.close();
 8435: // ]]>
 8436: </script>
 8437: ENDCLOSE
 8438: }
 8439: 
 8440: sub togglebox_script {
 8441:    return(<<ENDTOGGLE);
 8442: <script type="text/javascript"> 
 8443: // <![CDATA[
 8444: function LCtoggleDisplay(id,hidetext,showtext) {
 8445:    link = document.getElementById(id + "link").childNodes[0];
 8446:    with (document.getElementById(id).style) {
 8447:       if (display == "none" ) {
 8448:           display = "inline";
 8449:           link.nodeValue = hidetext;
 8450:         } else {
 8451:           display = "none";
 8452:           link.nodeValue = showtext;
 8453:        }
 8454:    }
 8455: }
 8456: // ]]>
 8457: </script>
 8458: ENDTOGGLE
 8459: }
 8460: 
 8461: sub start_togglebox {
 8462:     my ($id,$heading,$headerbg,$hidetext,$showtext)=@_;
 8463:     unless ($heading) { $heading=''; } else { $heading.=' '; }
 8464:     unless ($showtext) { $showtext=&mt('show'); }
 8465:     unless ($hidetext) { $hidetext=&mt('hide'); }
 8466:     unless ($headerbg) { $headerbg='#FFFFFF'; }
 8467:     return &start_data_table().
 8468:            &start_data_table_header_row().
 8469:            '<td bgcolor="'.$headerbg.'">'.$heading.
 8470:            '[<a id="'.$id.'link" href="javascript:LCtoggleDisplay(\''.$id.'\',\''.$hidetext.'\',\''.
 8471:            $showtext.'\')">'.$showtext.'</a>]</td>'.
 8472:            &end_data_table_header_row().
 8473:            '<tr id="'.$id.'" style="display:none""><td>';
 8474: }
 8475: 
 8476: sub end_togglebox {
 8477:     return '</td></tr>'.&end_data_table();
 8478: }
 8479: 
 8480: sub LCprogressbar_script {
 8481:    my ($id)=@_;
 8482:    return(<<ENDPROGRESS);
 8483: <script type="text/javascript">
 8484: // <![CDATA[
 8485: \$('#progressbar$id').progressbar({
 8486:   value: 0,
 8487:   change: function(event, ui) {
 8488:     var newVal = \$(this).progressbar('option', 'value');
 8489:     \$('.pblabel', this).text(LCprogressTxt);
 8490:   }
 8491: });
 8492: // ]]>
 8493: </script>
 8494: ENDPROGRESS
 8495: }
 8496: 
 8497: sub LCprogressbarUpdate_script {
 8498:    return(<<ENDPROGRESSUPDATE);
 8499: <style type="text/css">
 8500: .ui-progressbar { position:relative; }
 8501: .pblabel { position: absolute; width: 100%; text-align: center; line-height: 1.9em; }
 8502: </style>
 8503: <script type="text/javascript">
 8504: // <![CDATA[
 8505: var LCprogressTxt='---';
 8506: 
 8507: function LCupdateProgress(percent,progresstext,id) {
 8508:    LCprogressTxt=progresstext;
 8509:    \$('#progressbar'+id).progressbar('value',percent);
 8510: }
 8511: // ]]>
 8512: </script>
 8513: ENDPROGRESSUPDATE
 8514: }
 8515: 
 8516: my $LClastpercent;
 8517: my $LCidcnt;
 8518: my $LCcurrentid;
 8519: 
 8520: sub LCprogressbar {
 8521:     my ($r)=(@_);
 8522:     $LClastpercent=0;
 8523:     $LCidcnt++;
 8524:     $LCcurrentid=$$.'_'.$LCidcnt;
 8525:     my $starting=&mt('Starting');
 8526:     my $content=(<<ENDPROGBAR);
 8527:   <div id="progressbar$LCcurrentid">
 8528:     <span class="pblabel">$starting</span>
 8529:   </div>
 8530: ENDPROGBAR
 8531:     &r_print($r,$content.&LCprogressbar_script($LCcurrentid));
 8532: }
 8533: 
 8534: sub LCprogressbarUpdate {
 8535:     my ($r,$val,$text)=@_;
 8536:     unless ($val) { 
 8537:        if ($LClastpercent) {
 8538:            $val=$LClastpercent;
 8539:        } else {
 8540:            $val=0;
 8541:        }
 8542:     }
 8543:     if ($val<0) { $val=0; }
 8544:     if ($val>100) { $val=0; }
 8545:     $LClastpercent=$val;
 8546:     unless ($text) { $text=$val.'%'; }
 8547:     $text=&js_ready($text);
 8548:     &r_print($r,<<ENDUPDATE);
 8549: <script type="text/javascript">
 8550: // <![CDATA[
 8551: LCupdateProgress($val,'$text','$LCcurrentid');
 8552: // ]]>
 8553: </script>
 8554: ENDUPDATE
 8555: }
 8556: 
 8557: sub LCprogressbarClose {
 8558:     my ($r)=@_;
 8559:     $LClastpercent=0;
 8560:     &r_print($r,<<ENDCLOSE);
 8561: <script type="text/javascript">
 8562: // <![CDATA[
 8563: \$("#progressbar$LCcurrentid").hide('slow'); 
 8564: // ]]>
 8565: </script>
 8566: ENDCLOSE
 8567: }
 8568: 
 8569: sub r_print {
 8570:     my ($r,$to_print)=@_;
 8571:     if ($r) {
 8572:       $r->print($to_print);
 8573:       $r->rflush();
 8574:     } else {
 8575:       print($to_print);
 8576:     }
 8577: }
 8578: 
 8579: sub html_encode {
 8580:     my ($result) = @_;
 8581: 
 8582:     $result = &HTML::Entities::encode($result,'<>&"');
 8583:     
 8584:     return $result;
 8585: }
 8586: 
 8587: sub js_ready {
 8588:     my ($result) = @_;
 8589: 
 8590:     $result =~ s/[\n\r]/ /xmsg;
 8591:     $result =~ s/\\/\\\\/xmsg;
 8592:     $result =~ s/'/\\'/xmsg;
 8593:     $result =~ s{</}{<\\/}xmsg;
 8594:     
 8595:     return $result;
 8596: }
 8597: 
 8598: sub validate_page {
 8599:     if (  exists($env{'internal.start_page'})
 8600: 	  &&     $env{'internal.start_page'} > 1) {
 8601: 	&Apache::lonnet::logthis('start_page called multiple times '.
 8602: 				 $env{'internal.start_page'}.' '.
 8603: 				 $ENV{'request.filename'});
 8604:     }
 8605:     if (  exists($env{'internal.end_page'})
 8606: 	  &&     $env{'internal.end_page'} > 1) {
 8607: 	&Apache::lonnet::logthis('end_page called multiple times '.
 8608: 				 $env{'internal.end_page'}.' '.
 8609: 				 $env{'request.filename'});
 8610:     }
 8611:     if (     exists($env{'internal.start_page'})
 8612: 	&& ! exists($env{'internal.end_page'})) {
 8613: 	&Apache::lonnet::logthis('start_page called without end_page '.
 8614: 				 $env{'request.filename'});
 8615:     }
 8616:     if (   ! exists($env{'internal.start_page'})
 8617: 	&&   exists($env{'internal.end_page'})) {
 8618: 	&Apache::lonnet::logthis('end_page called without start_page'.
 8619: 				 $env{'request.filename'});
 8620:     }
 8621: }
 8622: 
 8623: 
 8624: sub start_scrollbox {
 8625:     my ($outerwidth,$width,$height,$id,$bgcolor,$cursor,$needjsready) = @_;
 8626:     unless ($outerwidth) { $outerwidth='520px'; }
 8627:     unless ($width) { $width='500px'; }
 8628:     unless ($height) { $height='200px'; }
 8629:     my ($table_id,$div_id,$tdcol);
 8630:     if ($id ne '') {
 8631:         $table_id = ' id="table_'.$id.'"';
 8632:         $div_id = ' id="div_'.$id.'"';
 8633:     }
 8634:     if ($bgcolor ne '') {
 8635:         $tdcol = "background-color: $bgcolor;";
 8636:     }
 8637:     my $nicescroll_js;
 8638:     if ($env{'browser.mobile'}) {
 8639:         $nicescroll_js = &nicescroll_javascript('div_'.$id,$cursor,$needjsready);
 8640:     }
 8641:     return <<"END";
 8642: $nicescroll_js
 8643: 
 8644: <table style="width: $outerwidth; border: 1px solid none;"$table_id><tr><td style="width: $width;$tdcol">
 8645: <div style="overflow:auto; width:$width; height:$height;"$div_id>
 8646: END
 8647: }
 8648: 
 8649: sub end_scrollbox {
 8650:     return '</div></td></tr></table>';
 8651: }
 8652: 
 8653: sub nicescroll_javascript {
 8654:     my ($id,$cursor,$needjsready,$framecheck,$location) = @_;
 8655:     my %options;
 8656:     if (ref($cursor) eq 'HASH') {
 8657:         %options = %{$cursor};
 8658:     }
 8659:     unless ($options{'railalign'} =~ /^left|right$/) {
 8660:         $options{'railalign'} = 'left';
 8661:     }
 8662:     unless ($options{'cursorcolor'} =~ /^\#\w+$/) {
 8663:         my $function  = &get_users_function();
 8664:         $options{'cursorcolor'} = &designparm($function.'.sidebg',$env{'request.role.domain'});
 8665:         unless ($options{'cursorcolor'} =~ /^\#\w+$/) {
 8666:             $options{'cursorcolor'} = '#00F';
 8667:         }
 8668:     }
 8669:     if ($options{'cursoropacity'} =~ /^[\d.]+$/) {
 8670:         unless ($options{'cursoropacity'} >= 0.0 && $options{'cursoropacity'} <=1.0) {
 8671:             $options{'cursoropacity'}='1.0';
 8672:         }
 8673:     } else {
 8674:         $options{'cursoropacity'}='1.0';
 8675:     }
 8676:     if ($options{'cursorfixedheight'} eq 'none') {
 8677:         delete($options{'cursorfixedheight'});
 8678:     } else {
 8679:         unless ($options{'cursorfixedheight'} =~ /^\d+$/) { $options{'cursorfixedheight'}='50'; }
 8680:     }
 8681:     unless ($options{'railoffset'} =~ /^{[\w\:\d\-,]+}$/) {
 8682:         delete($options{'railoffset'});
 8683:     }
 8684:     my @niceoptions;
 8685:     while (my($key,$value) = each(%options)) {
 8686:         if ($value =~ /^\{.+\}$/) {
 8687:             push(@niceoptions,$key.':'.$value);
 8688:         } else {
 8689:             push(@niceoptions,$key.':"'.$value.'"');
 8690:         }
 8691:     }
 8692:     my $nicescroll_js = '
 8693: $(document).ready(
 8694:       function() {
 8695:           $("#'.$id.'").niceScroll({'.join(',',@niceoptions).'});
 8696:       }
 8697: );
 8698: ';
 8699:     if ($framecheck) {
 8700:         $nicescroll_js .= '
 8701: function expand_div(caller) {
 8702:     if (top === self) {
 8703:         document.getElementById("'.$id.'").style.width = "auto";
 8704:         document.getElementById("'.$id.'").style.height = "auto";
 8705:     } else {
 8706:         try {
 8707:             if (parent.frames) {
 8708:                 if (parent.frames.length > 1) {
 8709:                     var framesrc = parent.frames[1].location.href;
 8710:                     var currsrc = framesrc.replace(/\#.*$/,"");
 8711:                     if ((caller == "search") || (currsrc == "'.$location.'")) {
 8712:                         document.getElementById("'.$id.'").style.width = "auto";
 8713:                         document.getElementById("'.$id.'").style.height = "auto";
 8714:                     }
 8715:                 }
 8716:             }
 8717:         } catch (e) {
 8718:             return;
 8719:         }
 8720:     }
 8721:     return;
 8722: }
 8723: ';
 8724:     }
 8725:     if ($needjsready) {
 8726:         $nicescroll_js = '
 8727: <script type="text/javascript">'."\n".$nicescroll_js."\n</script>\n";
 8728:     } else {
 8729:         $nicescroll_js = &Apache::lonhtmlcommon::scripttag($nicescroll_js);
 8730:     }
 8731:     return $nicescroll_js;
 8732: }
 8733: 
 8734: sub simple_error_page {
 8735:     my ($r,$title,$msg,$args) = @_;
 8736:     if (ref($args) eq 'HASH') {
 8737:         if (!$args->{'no_auto_mt_msg'}) { $msg = &mt($msg); }
 8738:     } else {
 8739:         $msg = &mt($msg);
 8740:     }
 8741: 
 8742:     my $page =
 8743: 	&Apache::loncommon::start_page($title).
 8744: 	'<p class="LC_error">'.$msg.'</p>'.
 8745: 	&Apache::loncommon::end_page();
 8746:     if (ref($r)) {
 8747: 	$r->print($page);
 8748: 	return;
 8749:     }
 8750:     return $page;
 8751: }
 8752: 
 8753: {
 8754:     my @row_count;
 8755: 
 8756:     sub start_data_table_count {
 8757:         unshift(@row_count, 0);
 8758:         return;
 8759:     }
 8760: 
 8761:     sub end_data_table_count {
 8762:         shift(@row_count);
 8763:         return;
 8764:     }
 8765: 
 8766:     sub start_data_table {
 8767: 	my ($add_class,$id) = @_;
 8768: 	my $css_class = (join(' ','LC_data_table',$add_class));
 8769:         my $table_id;
 8770:         if (defined($id)) {
 8771:             $table_id = ' id="'.$id.'"';
 8772:         }
 8773: 	&start_data_table_count();
 8774: 	return '<table class="'.$css_class.'"'.$table_id.'>'."\n";
 8775:     }
 8776: 
 8777:     sub end_data_table {
 8778: 	&end_data_table_count();
 8779: 	return '</table>'."\n";;
 8780:     }
 8781: 
 8782:     sub start_data_table_row {
 8783: 	my ($add_class, $id) = @_;
 8784: 	$row_count[0]++;
 8785: 	my $css_class = ($row_count[0] % 2)?'LC_odd_row':'LC_even_row';
 8786: 	$css_class = (join(' ',$css_class,$add_class)) unless ($add_class eq '');
 8787:         $id = (' id="'.$id.'"') unless ($id eq '');
 8788:         return  '<tr class="'.$css_class.'"'.$id.'>'."\n";
 8789:     }
 8790:     
 8791:     sub continue_data_table_row {
 8792: 	my ($add_class, $id) = @_;
 8793: 	my $css_class = ($row_count[0] % 2)?'LC_odd_row':'LC_even_row';
 8794: 	$css_class = (join(' ',$css_class,$add_class)) unless ($add_class eq '');
 8795:         $id = (' id="'.$id.'"') unless ($id eq '');
 8796:         return  '<tr class="'.$css_class.'"'.$id.'>'."\n";
 8797:     }
 8798: 
 8799:     sub end_data_table_row {
 8800: 	return '</tr>'."\n";;
 8801:     }
 8802: 
 8803:     sub start_data_table_empty_row {
 8804: #	$row_count[0]++;
 8805: 	return  '<tr class="LC_empty_row" >'."\n";;
 8806:     }
 8807: 
 8808:     sub end_data_table_empty_row {
 8809: 	return '</tr>'."\n";;
 8810:     }
 8811: 
 8812:     sub start_data_table_header_row {
 8813: 	return  '<tr class="LC_header_row">'."\n";;
 8814:     }
 8815: 
 8816:     sub end_data_table_header_row {
 8817: 	return '</tr>'."\n";;
 8818:     }
 8819: 
 8820:     sub data_table_caption {
 8821:         my $caption = shift;
 8822:         return "<caption class=\"LC_caption\">$caption</caption>";
 8823:     }
 8824: }
 8825: 
 8826: =pod
 8827: 
 8828: =item * &inhibit_menu_check($arg)
 8829: 
 8830: Checks for a inhibitmenu state and generates output to preserve it
 8831: 
 8832: Inputs:         $arg - can be any of
 8833:                      - undef - in which case the return value is a string 
 8834:                                to add  into arguments list of a uri
 8835:                      - 'input' - in which case the return value is a HTML
 8836:                                  <form> <input> field of type hidden to
 8837:                                  preserve the value
 8838:                      - a url - in which case the return value is the url with
 8839:                                the neccesary cgi args added to preserve the
 8840:                                inhibitmenu state
 8841:                      - a ref to a url - no return value, but the string is
 8842:                                         updated to include the neccessary cgi
 8843:                                         args to preserve the inhibitmenu state
 8844: 
 8845: =cut
 8846: 
 8847: sub inhibit_menu_check {
 8848:     my ($arg) = @_;
 8849:     &get_unprocessed_cgi($ENV{'QUERY_STRING'}, ['inhibitmenu']);
 8850:     if ($arg eq 'input') {
 8851: 	if ($env{'form.inhibitmenu'}) {
 8852: 	    return '<input type="hidden" name="inhibitmenu" value="'.$env{'form.inhibitmenu'}.'" />';
 8853: 	} else {
 8854: 	    return
 8855: 	}
 8856:     }
 8857:     if ($env{'form.inhibitmenu'}) {
 8858: 	if (ref($arg)) {
 8859: 	    $$arg .= '?inhibitmenu='.$env{'form.inhibitmenu'};
 8860: 	} elsif ($arg eq '') {
 8861: 	    $arg .= 'inhibitmenu='.$env{'form.inhibitmenu'};
 8862: 	} else {
 8863: 	    $arg .= '?inhibitmenu='.$env{'form.inhibitmenu'};
 8864: 	}
 8865:     }
 8866:     if (!ref($arg)) {
 8867: 	return $arg;
 8868:     }
 8869: }
 8870: 
 8871: ###############################################
 8872: 
 8873: =pod
 8874: 
 8875: =back
 8876: 
 8877: =head1 User Information Routines
 8878: 
 8879: =over 4
 8880: 
 8881: =item * &get_users_function()
 8882: 
 8883: Used by &bodytag to determine the current users primary role.
 8884: Returns either 'student','coordinator','admin', or 'author'.
 8885: 
 8886: =cut
 8887: 
 8888: ###############################################
 8889: sub get_users_function {
 8890:     my $function = 'norole';
 8891:     if ($env{'request.role'}=~/^(st)/) {
 8892:         $function='student';
 8893:     }
 8894:     if ($env{'request.role'}=~/^(cc|co|in|ta|ep)/) {
 8895:         $function='coordinator';
 8896:     }
 8897:     if ($env{'request.role'}=~/^(su|dc|ad|li)/) {
 8898:         $function='admin';
 8899:     }
 8900:     if (($env{'request.role'}=~/^(au|ca|aa)/) ||
 8901:         ($ENV{'REQUEST_URI'}=~ m{/^(/priv)})) {
 8902:         $function='author';
 8903:     }
 8904:     return $function;
 8905: }
 8906: 
 8907: ###############################################
 8908: 
 8909: =pod
 8910: 
 8911: =item * &show_course()
 8912: 
 8913: Used by lonmenu.pm and lonroles.pm to determine whether to use the word
 8914: 'Courses' or 'Roles' in inline navigation and on screen displaying user's roles.
 8915: 
 8916: Inputs:
 8917: None
 8918: 
 8919: Outputs:
 8920: Scalar: 1 if 'Course' to be used, 0 otherwise.
 8921: 
 8922: =cut
 8923: 
 8924: ###############################################
 8925: sub show_course {
 8926:     my $course = !$env{'user.adv'};
 8927:     if (!$env{'user.adv'}) {
 8928:         foreach my $env (keys(%env)) {
 8929:             next if ($env !~ m/^user\.priv\./);
 8930:             if ($env !~ m/^user\.priv\.(?:st|cm)/) {
 8931:                 $course = 0;
 8932:                 last;
 8933:             }
 8934:         }
 8935:     }
 8936:     return $course;
 8937: }
 8938: 
 8939: ###############################################
 8940: 
 8941: =pod
 8942: 
 8943: =item * &check_user_status()
 8944: 
 8945: Determines current status of supplied role for a
 8946: specific user. Roles can be active, previous or future.
 8947: 
 8948: Inputs: 
 8949: user's domain, user's username, course's domain,
 8950: course's number, optional section ID.
 8951: 
 8952: Outputs:
 8953: role status: active, previous or future. 
 8954: 
 8955: =cut
 8956: 
 8957: sub check_user_status {
 8958:     my ($udom,$uname,$cdom,$crs,$role,$sec) = @_;
 8959:     my %userinfo = &Apache::lonnet::dump('roles',$udom,$uname);
 8960:     my @uroles = keys(%userinfo);
 8961:     my $srchstr;
 8962:     my $active_chk = 'none';
 8963:     my $now = time;
 8964:     if (@uroles > 0) {
 8965:         if (($role eq 'cc') || ($role eq 'co') || ($sec eq '') || (!defined($sec))) {
 8966:             $srchstr = '/'.$cdom.'/'.$crs.'_'.$role;
 8967:         } else {
 8968:             $srchstr = '/'.$cdom.'/'.$crs.'/'.$sec.'_'.$role;
 8969:         }
 8970:         if (grep/^\Q$srchstr\E$/,@uroles) {
 8971:             my $role_end = 0;
 8972:             my $role_start = 0;
 8973:             $active_chk = 'active';
 8974:             if ($userinfo{$srchstr} =~ m/^\Q$role\E_(\d+)/) {
 8975:                 $role_end = $1;
 8976:                 if ($userinfo{$srchstr} =~ m/^\Q$role\E_\Q$role_end\E_(\d+)$/) {
 8977:                     $role_start = $1;
 8978:                 }
 8979:             }
 8980:             if ($role_start > 0) {
 8981:                 if ($now < $role_start) {
 8982:                     $active_chk = 'future';
 8983:                 }
 8984:             }
 8985:             if ($role_end > 0) {
 8986:                 if ($now > $role_end) {
 8987:                     $active_chk = 'previous';
 8988:                 }
 8989:             }
 8990:         }
 8991:     }
 8992:     return $active_chk;
 8993: }
 8994: 
 8995: ###############################################
 8996: 
 8997: =pod
 8998: 
 8999: =item * &get_sections()
 9000: 
 9001: Determines all the sections for a course including
 9002: sections with students and sections containing other roles.
 9003: Incoming parameters: 
 9004: 
 9005: 1. domain
 9006: 2. course number 
 9007: 3. reference to array containing roles for which sections should 
 9008: be gathered (optional).
 9009: 4. reference to array containing status types for which sections 
 9010: should be gathered (optional).
 9011: 
 9012: If the third argument is undefined, sections are gathered for any role. 
 9013: If the fourth argument is undefined, sections are gathered for any status.
 9014: Permissible values are 'active' or 'future' or 'previous'.
 9015:  
 9016: Returns section hash (keys are section IDs, values are
 9017: number of users in each section), subject to the
 9018: optional roles filter, optional status filter 
 9019: 
 9020: =cut
 9021: 
 9022: ###############################################
 9023: sub get_sections {
 9024:     my ($cdom,$cnum,$possible_roles,$possible_status) = @_;
 9025:     if (!defined($cdom) || !defined($cnum)) {
 9026:         my $cid =  $env{'request.course.id'};
 9027: 
 9028: 	return if (!defined($cid));
 9029: 
 9030:         $cdom = $env{'course.'.$cid.'.domain'};
 9031:         $cnum = $env{'course.'.$cid.'.num'};
 9032:     }
 9033: 
 9034:     my %sectioncount;
 9035:     my $now = time;
 9036: 
 9037:     my $check_students = 1;
 9038:     my $only_students = 0;
 9039:     if (ref($possible_roles) eq 'ARRAY') {
 9040:         if (grep(/^st$/,@{$possible_roles})) {
 9041:             if (@{$possible_roles} == 1) {
 9042:                 $only_students = 1;
 9043:             }
 9044:         } else {
 9045:             $check_students = 0;
 9046:         }
 9047:     }
 9048: 
 9049:     if ($check_students) {
 9050: 	my ($classlist) = &Apache::loncoursedata::get_classlist($cdom,$cnum);
 9051: 	my $sec_index = &Apache::loncoursedata::CL_SECTION();
 9052: 	my $status_index = &Apache::loncoursedata::CL_STATUS();
 9053:         my $start_index = &Apache::loncoursedata::CL_START();
 9054:         my $end_index = &Apache::loncoursedata::CL_END();
 9055:         my $status;
 9056: 	while (my ($student,$data) = each(%$classlist)) {
 9057: 	    my ($section,$stu_status,$start,$end) = ($data->[$sec_index],
 9058: 				                     $data->[$status_index],
 9059:                                                      $data->[$start_index],
 9060:                                                      $data->[$end_index]);
 9061:             if ($stu_status eq 'Active') {
 9062:                 $status = 'active';
 9063:             } elsif ($end < $now) {
 9064:                 $status = 'previous';
 9065:             } elsif ($start > $now) {
 9066:                 $status = 'future';
 9067:             } 
 9068: 	    if ($section ne '-1' && $section !~ /^\s*$/) {
 9069:                 if ((!defined($possible_status)) || (($status ne '') && 
 9070:                     (grep/^\Q$status\E$/,@{$possible_status}))) { 
 9071: 		    $sectioncount{$section}++;
 9072:                 }
 9073: 	    }
 9074: 	}
 9075:     }
 9076:     if ($only_students) {
 9077:         return %sectioncount;
 9078:     }
 9079:     my %courseroles = &Apache::lonnet::dump('nohist_userroles',$cdom,$cnum);
 9080:     foreach my $user (sort(keys(%courseroles))) {
 9081: 	if ($user !~ /^(\w{2})/) { next; }
 9082: 	my ($role) = ($user =~ /^(\w{2})/);
 9083: 	if ($possible_roles && !(grep(/^$role$/,@$possible_roles))) { next; }
 9084: 	my ($section,$status);
 9085: 	if ($role eq 'cr' &&
 9086: 	    $user =~ m-^$role/[^/]*/[^/]*/[^/]*:[^:]*:[^:]*:(\w+)-) {
 9087: 	    $section=$1;
 9088: 	}
 9089: 	if ($user =~ /^$role:[^:]*:[^:]*:(\w+)/) { $section=$1; }
 9090: 	if (!defined($section) || $section eq '-1') { next; }
 9091:         my ($end,$start) = ($courseroles{$user} =~ /^([^:]*):([^:]*)$/);
 9092:         if ($end == -1 && $start == -1) {
 9093:             next; #deleted role
 9094:         }
 9095:         if (!defined($possible_status)) { 
 9096:             $sectioncount{$section}++;
 9097:         } else {
 9098:             if ((!$end || $end >= $now) && (!$start || $start <= $now)) {
 9099:                 $status = 'active';
 9100:             } elsif ($end < $now) {
 9101:                 $status = 'future';
 9102:             } elsif ($start > $now) {
 9103:                 $status = 'previous';
 9104:             }
 9105:             if (($status ne '') && (grep/^\Q$status\E$/,@{$possible_status})) {
 9106:                 $sectioncount{$section}++;
 9107:             }
 9108:         }
 9109:     }
 9110:     return %sectioncount;
 9111: }
 9112: 
 9113: ###############################################
 9114: 
 9115: =pod
 9116: 
 9117: =item * &get_course_users()
 9118: 
 9119: Retrieves usernames:domains for users in the specified course
 9120: with specific role(s), and access status. 
 9121: 
 9122: Incoming parameters:
 9123: 1. course domain
 9124: 2. course number
 9125: 3. access status: users must have - either active, 
 9126: previous, future, or all.
 9127: 4. reference to array of permissible roles
 9128: 5. reference to array of section restrictions (optional)
 9129: 6. reference to results object (hash of hashes).
 9130: 7. reference to optional userdata hash
 9131: 8. reference to optional statushash
 9132: 9. flag if privileged users (except those set to unhide in
 9133:    course settings) should be excluded    
 9134: Keys of top level results hash are roles.
 9135: Keys of inner hashes are username:domain, with 
 9136: values set to access type.
 9137: Optional userdata hash returns an array with arguments in the 
 9138: same order as loncoursedata::get_classlist() for student data.
 9139: 
 9140: Optional statushash returns
 9141: 
 9142: Entries for end, start, section and status are blank because
 9143: of the possibility of multiple values for non-student roles.
 9144: 
 9145: =cut
 9146: 
 9147: ###############################################
 9148: 
 9149: sub get_course_users {
 9150:     my ($cdom,$cnum,$types,$roles,$sections,$users,$userdata,$statushash,$hidepriv) = @_;
 9151:     my %idx = ();
 9152:     my %seclists;
 9153: 
 9154:     $idx{udom} = &Apache::loncoursedata::CL_SDOM();
 9155:     $idx{uname} =  &Apache::loncoursedata::CL_SNAME();
 9156:     $idx{end} = &Apache::loncoursedata::CL_END();
 9157:     $idx{start} = &Apache::loncoursedata::CL_START();
 9158:     $idx{id} = &Apache::loncoursedata::CL_ID();
 9159:     $idx{section} = &Apache::loncoursedata::CL_SECTION();
 9160:     $idx{fullname} = &Apache::loncoursedata::CL_FULLNAME();
 9161:     $idx{status} = &Apache::loncoursedata::CL_STATUS();
 9162: 
 9163:     if (grep(/^st$/,@{$roles})) {
 9164:         my ($classlist,$keylist)=&Apache::loncoursedata::get_classlist($cdom,$cnum);
 9165:         my $now = time;
 9166:         foreach my $student (keys(%{$classlist})) {
 9167:             my $match = 0;
 9168:             my $secmatch = 0;
 9169:             my $section = $$classlist{$student}[$idx{section}];
 9170:             my $status = $$classlist{$student}[$idx{status}];
 9171:             if ($section eq '') {
 9172:                 $section = 'none';
 9173:             }
 9174:             if ((ref($sections) eq 'ARRAY') && (@{$sections} > 0)) {
 9175:                 if (grep(/^all$/,@{$sections})) {
 9176:                     $secmatch = 1;
 9177:                 } elsif ($$classlist{$student}[$idx{section}] eq '') {
 9178:                     if (grep(/^none$/,@{$sections})) {
 9179:                         $secmatch = 1;
 9180:                     }
 9181:                 } else {  
 9182: 		    if (grep(/^\Q$section\E$/,@{$sections})) {
 9183: 		        $secmatch = 1;
 9184:                     }
 9185: 		}
 9186:                 if (!$secmatch) {
 9187:                     next;
 9188:                 }
 9189:             }
 9190:             if (defined($$types{'active'})) {
 9191:                 if ($$classlist{$student}[$idx{status}] eq 'Active') {
 9192:                     push(@{$$users{st}{$student}},'active');
 9193:                     $match = 1;
 9194:                 }
 9195:             }
 9196:             if (defined($$types{'previous'})) {
 9197:                 if ($$classlist{$student}[$idx{status}] eq 'Expired') {
 9198:                     push(@{$$users{st}{$student}},'previous');
 9199:                     $match = 1;
 9200:                 }
 9201:             }
 9202:             if (defined($$types{'future'})) {
 9203:                 if ($$classlist{$student}[$idx{status}] eq 'Future') {
 9204:                     push(@{$$users{st}{$student}},'future');
 9205:                     $match = 1;
 9206:                 }
 9207:             }
 9208:             if ($match) {
 9209:                 push(@{$seclists{$student}},$section);
 9210:                 if (ref($userdata) eq 'HASH') {
 9211:                     $$userdata{$student} = $$classlist{$student};
 9212:                 }
 9213:                 if (ref($statushash) eq 'HASH') {
 9214:                     $statushash->{$student}{'st'}{$section} = $status;
 9215:                 }
 9216:             }
 9217:         }
 9218:     }
 9219:     if ((@{$roles} > 1) || ((@{$roles} == 1) && ($$roles[0] ne "st"))) {
 9220:         my %coursepersonnel = &Apache::lonnet::dump('nohist_userroles',$cdom,$cnum);
 9221:         my $now = time;
 9222:         my %displaystatus = ( previous => 'Expired',
 9223:                               active   => 'Active',
 9224:                               future   => 'Future',
 9225:                             );
 9226:         my (%nothide,@possdoms);
 9227:         if ($hidepriv) {
 9228:             my %coursehash=&Apache::lonnet::coursedescription($cdom.'_'.$cnum);
 9229:             foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
 9230:                 if ($user !~ /:/) {
 9231:                     $nothide{join(':',split(/[\@]/,$user))}=1;
 9232:                 } else {
 9233:                     $nothide{$user} = 1;
 9234:                 }
 9235:             }
 9236:             my @possdoms = ($cdom);
 9237:             if ($coursehash{'checkforpriv'}) {
 9238:                 push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
 9239:             }
 9240:         }
 9241:         foreach my $person (sort(keys(%coursepersonnel))) {
 9242:             my $match = 0;
 9243:             my $secmatch = 0;
 9244:             my $status;
 9245:             my ($role,$user,$usec) = ($person =~ /^([^:]*):([^:]+:[^:]+):([^:]*)/);
 9246:             $user =~ s/:$//;
 9247:             my ($end,$start) = split(/:/,$coursepersonnel{$person});
 9248:             if ($end == -1 || $start == -1) {
 9249:                 next;
 9250:             }
 9251:             if (($role) && ((grep(/^\Q$role\E$/,@{$roles})) ||
 9252:                 (grep(/^cr$/,@{$roles}) && $role =~ /^cr\//))) {
 9253:                 my ($uname,$udom) = split(/:/,$user);
 9254:                 if ((ref($sections) eq 'ARRAY') && (@{$sections} > 0)) {
 9255:                     if (grep(/^all$/,@{$sections})) {
 9256:                         $secmatch = 1;
 9257:                     } elsif ($usec eq '') {
 9258:                         if (grep(/^none$/,@{$sections})) {
 9259:                             $secmatch = 1;
 9260:                         }
 9261:                     } else {
 9262:                         if (grep(/^\Q$usec\E$/,@{$sections})) {
 9263:                             $secmatch = 1;
 9264:                         }
 9265:                     }
 9266:                     if (!$secmatch) {
 9267:                         next;
 9268:                     }
 9269:                 }
 9270:                 if ($usec eq '') {
 9271:                     $usec = 'none';
 9272:                 }
 9273:                 if ($uname ne '' && $udom ne '') {
 9274:                     if ($hidepriv) {
 9275:                         if ((&Apache::lonnet::privileged($uname,$udom,\@possdoms)) &&
 9276:                             (!$nothide{$uname.':'.$udom})) {
 9277:                             next;
 9278:                         }
 9279:                     }
 9280:                     if ($end > 0 && $end < $now) {
 9281:                         $status = 'previous';
 9282:                     } elsif ($start > $now) {
 9283:                         $status = 'future';
 9284:                     } else {
 9285:                         $status = 'active';
 9286:                     }
 9287:                     foreach my $type (keys(%{$types})) { 
 9288:                         if ($status eq $type) {
 9289:                             if (!grep(/^\Q$type\E$/,@{$$users{$role}{$user}})) {
 9290:                                 push(@{$$users{$role}{$user}},$type);
 9291:                             }
 9292:                             $match = 1;
 9293:                         }
 9294:                     }
 9295:                     if (($match) && (ref($userdata) eq 'HASH')) {
 9296:                         if (!exists($$userdata{$uname.':'.$udom})) {
 9297: 			    &get_user_info($udom,$uname,\%idx,$userdata);
 9298:                         }
 9299:                         if (!grep(/^\Q$usec\E$/,@{$seclists{$uname.':'.$udom}})) {
 9300:                             push(@{$seclists{$uname.':'.$udom}},$usec);
 9301:                         }
 9302:                         if (ref($statushash) eq 'HASH') {
 9303:                             $statushash->{$uname.':'.$udom}{$role}{$usec} = $displaystatus{$status};
 9304:                         }
 9305:                     }
 9306:                 }
 9307:             }
 9308:         }
 9309:         if (grep(/^ow$/,@{$roles})) {
 9310:             if ((defined($cdom)) && (defined($cnum))) {
 9311:                 my %csettings = &Apache::lonnet::get('environment',['internal.courseowner'],$cdom,$cnum);
 9312:                 if ( defined($csettings{'internal.courseowner'}) ) {
 9313:                     my $owner = $csettings{'internal.courseowner'};
 9314:                     next if ($owner eq '');
 9315:                     my ($ownername,$ownerdom);
 9316:                     if ($owner =~ /^([^:]+):([^:]+)$/) {
 9317:                         $ownername = $1;
 9318:                         $ownerdom = $2;
 9319:                     } else {
 9320:                         $ownername = $owner;
 9321:                         $ownerdom = $cdom;
 9322:                         $owner = $ownername.':'.$ownerdom;
 9323:                     }
 9324:                     @{$$users{'ow'}{$owner}} = 'any';
 9325:                     if (defined($userdata) && 
 9326: 			!exists($$userdata{$owner})) {
 9327: 			&get_user_info($ownerdom,$ownername,\%idx,$userdata);
 9328:                         if (!grep(/^none$/,@{$seclists{$owner}})) {
 9329:                             push(@{$seclists{$owner}},'none');
 9330:                         }
 9331:                         if (ref($statushash) eq 'HASH') {
 9332:                             $statushash->{$owner}{'ow'}{'none'} = 'Any';
 9333:                         }
 9334: 		    }
 9335:                 }
 9336:             }
 9337:         }
 9338:         foreach my $user (keys(%seclists)) {
 9339:             @{$seclists{$user}} = (sort {$a <=> $b} @{$seclists{$user}});
 9340:             $$userdata{$user}[$idx{section}] = join(',',@{$seclists{$user}});
 9341:         }
 9342:     }
 9343:     return;
 9344: }
 9345: 
 9346: sub get_user_info {
 9347:     my ($udom,$uname,$idx,$userdata) = @_;
 9348:     $$userdata{$uname.':'.$udom}[$$idx{fullname}] = 
 9349: 	&plainname($uname,$udom,'lastname');
 9350:     $$userdata{$uname.':'.$udom}[$$idx{uname}] = $uname;
 9351:     $$userdata{$uname.':'.$udom}[$$idx{udom}] = $udom;
 9352:     my %idhash =  &Apache::lonnet::idrget($udom,($uname));
 9353:     $$userdata{$uname.':'.$udom}[$$idx{id}] = $idhash{$uname}; 
 9354:     return;
 9355: }
 9356: 
 9357: ###############################################
 9358: 
 9359: =pod
 9360: 
 9361: =item * &get_user_quota()
 9362: 
 9363: Retrieves quota assigned for storage of user files.
 9364: Default is to report quota for portfolio files.
 9365: 
 9366: Incoming parameters:
 9367: 1. user's username
 9368: 2. user's domain
 9369: 3. quota name - portfolio, author, or course
 9370:    (if no quota name provided, defaults to portfolio).
 9371: 4. crstype - official, unofficial, textbook or community, if quota name is
 9372:    course
 9373: 
 9374: Returns:
 9375: 1. Disk quota (in MB) assigned to student.
 9376: 2. (Optional) Type of setting: custom or default
 9377:    (individually assigned or default for user's 
 9378:    institutional status).
 9379: 3. (Optional) - User's institutional status (e.g., faculty, staff
 9380:    or student - types as defined in localenroll::inst_usertypes 
 9381:    for user's domain, which determines default quota for user.
 9382: 4. (Optional) - Default quota which would apply to the user.
 9383: 
 9384: If a value has been stored in the user's environment, 
 9385: it will return that, otherwise it returns the maximal default
 9386: defined for the user's institutional status(es) in the domain.
 9387: 
 9388: =cut
 9389: 
 9390: ###############################################
 9391: 
 9392: 
 9393: sub get_user_quota {
 9394:     my ($uname,$udom,$quotaname,$crstype) = @_;
 9395:     my ($quota,$quotatype,$settingstatus,$defquota);
 9396:     if (!defined($udom)) {
 9397:         $udom = $env{'user.domain'};
 9398:     }
 9399:     if (!defined($uname)) {
 9400:         $uname = $env{'user.name'};
 9401:     }
 9402:     if (($udom eq '' || $uname eq '') ||
 9403:         ($udom eq 'public') && ($uname eq 'public')) {
 9404:         $quota = 0;
 9405:         $quotatype = 'default';
 9406:         $defquota = 0; 
 9407:     } else {
 9408:         my $inststatus;
 9409:         if ($quotaname eq 'course') {
 9410:             if (($env{'course.'.$udom.'_'.$uname.'.num'} eq $uname) &&
 9411:                 ($env{'course.'.$udom.'_'.$uname.'.domain'} eq $udom)) {
 9412:                 $quota = $env{'course.'.$udom.'_'.$uname.'.internal.uploadquota'};
 9413:             } else {
 9414:                 my %cenv = &Apache::lonnet::coursedescription("$udom/$uname");
 9415:                 $quota = $cenv{'internal.uploadquota'};
 9416:             }
 9417:         } else {
 9418:             if ($udom eq $env{'user.domain'} && $uname eq $env{'user.name'}) {
 9419:                 if ($quotaname eq 'author') {
 9420:                     $quota = $env{'environment.authorquota'};
 9421:                 } else {
 9422:                     $quota = $env{'environment.portfolioquota'};
 9423:                 }
 9424:                 $inststatus = $env{'environment.inststatus'};
 9425:             } else {
 9426:                 my %userenv = 
 9427:                     &Apache::lonnet::get('environment',['portfolioquota',
 9428:                                          'authorquota','inststatus'],$udom,$uname);
 9429:                 my ($tmp) = keys(%userenv);
 9430:                 if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
 9431:                     if ($quotaname eq 'author') {
 9432:                         $quota = $userenv{'authorquota'};
 9433:                     } else {
 9434:                         $quota = $userenv{'portfolioquota'};
 9435:                     }
 9436:                     $inststatus = $userenv{'inststatus'};
 9437:                 } else {
 9438:                     undef(%userenv);
 9439:                 }
 9440:             }
 9441:         }
 9442:         if ($quota eq '' || wantarray) {
 9443:             if ($quotaname eq 'course') {
 9444:                 my %domdefs = &Apache::lonnet::get_domain_defaults($udom);
 9445:                 if (($crstype eq 'official') || ($crstype eq 'unofficial') ||
 9446:                     ($crstype eq 'community') || ($crstype eq 'textbook')) {
 9447:                     $defquota = $domdefs{$crstype.'quota'};
 9448:                 }
 9449:                 if ($defquota eq '') {
 9450:                     $defquota = 500;
 9451:                 }
 9452:             } else {
 9453:                 ($defquota,$settingstatus) = &default_quota($udom,$inststatus,$quotaname);
 9454:             }
 9455:             if ($quota eq '') {
 9456:                 $quota = $defquota;
 9457:                 $quotatype = 'default';
 9458:             } else {
 9459:                 $quotatype = 'custom';
 9460:             }
 9461:         }
 9462:     }
 9463:     if (wantarray) {
 9464:         return ($quota,$quotatype,$settingstatus,$defquota);
 9465:     } else {
 9466:         return $quota;
 9467:     }
 9468: }
 9469: 
 9470: ###############################################
 9471: 
 9472: =pod
 9473: 
 9474: =item * &default_quota()
 9475: 
 9476: Retrieves default quota assigned for storage of user portfolio files,
 9477: given an (optional) user's institutional status.
 9478: 
 9479: Incoming parameters:
 9480: 
 9481: 1. domain
 9482: 2. (Optional) institutional status(es).  This is a : separated list of 
 9483:    status types (e.g., faculty, staff, student etc.)
 9484:    which apply to the user for whom the default is being retrieved.
 9485:    If the institutional status string in undefined, the domain
 9486:    default quota will be returned.
 9487: 3.  quota name - portfolio, author, or course
 9488:    (if no quota name provided, defaults to portfolio).
 9489: 
 9490: Returns:
 9491: 
 9492: 1. Default disk quota (in MB) for user portfolios in the domain.
 9493: 2. (Optional) institutional type which determined the value of the
 9494:    default quota.
 9495: 
 9496: If a value has been stored in the domain's configuration db,
 9497: it will return that, otherwise it returns 20 (for backwards 
 9498: compatibility with domains which have not set up a configuration
 9499: db file; the original statically defined portfolio quota was 20 MB). 
 9500: 
 9501: If the user's status includes multiple types (e.g., staff and student),
 9502: the largest default quota which applies to the user determines the
 9503: default quota returned.
 9504: 
 9505: =cut
 9506: 
 9507: ###############################################
 9508: 
 9509: 
 9510: sub default_quota {
 9511:     my ($udom,$inststatus,$quotaname) = @_;
 9512:     my ($defquota,$settingstatus);
 9513:     my %quotahash = &Apache::lonnet::get_dom('configuration',
 9514:                                             ['quotas'],$udom);
 9515:     my $key = 'defaultquota';
 9516:     if ($quotaname eq 'author') {
 9517:         $key = 'authorquota';
 9518:     }
 9519:     if (ref($quotahash{'quotas'}) eq 'HASH') {
 9520:         if ($inststatus ne '') {
 9521:             my @statuses = map { &unescape($_); } split(/:/,$inststatus);
 9522:             foreach my $item (@statuses) {
 9523:                 if (ref($quotahash{'quotas'}{$key}) eq 'HASH') {
 9524:                     if ($quotahash{'quotas'}{$key}{$item} ne '') {
 9525:                         if ($defquota eq '') {
 9526:                             $defquota = $quotahash{'quotas'}{$key}{$item};
 9527:                             $settingstatus = $item;
 9528:                         } elsif ($quotahash{'quotas'}{$key}{$item} > $defquota) {
 9529:                             $defquota = $quotahash{'quotas'}{$key}{$item};
 9530:                             $settingstatus = $item;
 9531:                         }
 9532:                     }
 9533:                 } elsif ($key eq 'defaultquota') {
 9534:                     if ($quotahash{'quotas'}{$item} ne '') {
 9535:                         if ($defquota eq '') {
 9536:                             $defquota = $quotahash{'quotas'}{$item};
 9537:                             $settingstatus = $item;
 9538:                         } elsif ($quotahash{'quotas'}{$item} > $defquota) {
 9539:                             $defquota = $quotahash{'quotas'}{$item};
 9540:                             $settingstatus = $item;
 9541:                         }
 9542:                     }
 9543:                 }
 9544:             }
 9545:         }
 9546:         if ($defquota eq '') {
 9547:             if (ref($quotahash{'quotas'}{$key}) eq 'HASH') {
 9548:                 $defquota = $quotahash{'quotas'}{$key}{'default'};
 9549:             } elsif ($key eq 'defaultquota') {
 9550:                 $defquota = $quotahash{'quotas'}{'default'};
 9551:             }
 9552:             $settingstatus = 'default';
 9553:             if ($defquota eq '') {
 9554:                 if ($quotaname eq 'author') {
 9555:                     $defquota = 500;
 9556:                 }
 9557:             }
 9558:         }
 9559:     } else {
 9560:         $settingstatus = 'default';
 9561:         if ($quotaname eq 'author') {
 9562:             $defquota = 500;
 9563:         } else {
 9564:             $defquota = 20;
 9565:         }
 9566:     }
 9567:     if (wantarray) {
 9568:         return ($defquota,$settingstatus);
 9569:     } else {
 9570:         return $defquota;
 9571:     }
 9572: }
 9573: 
 9574: ###############################################
 9575: 
 9576: =pod
 9577: 
 9578: =item * &excess_filesize_warning()
 9579: 
 9580: Returns warning message if upload of file to authoring space, or copying
 9581: of existing file within authoring space will cause quota for the authoring
 9582: space to be exceeded.
 9583: 
 9584: Same, if upload of a file directly to a course/community via Course Editor
 9585: will cause quota for uploaded content for the course to be exceeded.
 9586: 
 9587: Inputs: 7 
 9588: 1. username or coursenum
 9589: 2. domain
 9590: 3. context ('author' or 'course')
 9591: 4. filename of file for which action is being requested
 9592: 5. filesize (kB) of file
 9593: 6. action being taken: copy or upload.
 9594: 7. quotatype (in course context -- official, unofficial, community or textbook).
 9595: 
 9596: Returns: 1 scalar: HTML to display containing warning if quota would be exceeded,
 9597:          otherwise return null.
 9598: 
 9599: =back
 9600: 
 9601: =cut
 9602: 
 9603: sub excess_filesize_warning {
 9604:     my ($uname,$udom,$context,$filename,$filesize,$action,$quotatype) = @_;
 9605:     my $current_disk_usage = 0;
 9606:     my $disk_quota = &get_user_quota($uname,$udom,$context,$quotatype); #expressed in MB
 9607:     if ($context eq 'author') {
 9608:         my $authorspace = $Apache::lonnet::perlvar{'lonDocRoot'}."/priv/$udom/$uname";
 9609:         $current_disk_usage = &Apache::lonnet::diskusage($udom,$uname,$authorspace);
 9610:     } else {
 9611:         foreach my $subdir ('docs','supplemental') {
 9612:             $current_disk_usage += &Apache::lonnet::diskusage($udom,$uname,"userfiles/$subdir",1);
 9613:         }
 9614:     }
 9615:     $disk_quota = int($disk_quota * 1000);
 9616:     if (($current_disk_usage + $filesize) > $disk_quota) {
 9617:         return '<p class="LC_warning">'.
 9618:                 &mt("Unable to $action [_1]. (size = [_2] kilobytes). Disk quota will be exceeded.",
 9619:                     '<span class="LC_filename">'.$filename.'</span>',$filesize).'</p>'.
 9620:                '<p>'.&mt('Disk quota is [_1] kilobytes. Your current disk usage is [_2] kilobytes.',
 9621:                             $disk_quota,$current_disk_usage).
 9622:                '</p>';
 9623:     }
 9624:     return;
 9625: }
 9626: 
 9627: ###############################################
 9628: 
 9629: 
 9630: sub get_secgrprole_info {
 9631:     my ($cdom,$cnum,$needroles,$type)  = @_;
 9632:     my %sections_count = &get_sections($cdom,$cnum);
 9633:     my @sections =  (sort {$a <=> $b} keys(%sections_count));
 9634:     my %curr_groups = &Apache::longroup::coursegroups($cdom,$cnum);
 9635:     my @groups = sort(keys(%curr_groups));
 9636:     my $allroles = [];
 9637:     my $rolehash;
 9638:     my $accesshash = {
 9639:                      active => 'Currently has access',
 9640:                      future => 'Will have future access',
 9641:                      previous => 'Previously had access',
 9642:                   };
 9643:     if ($needroles) {
 9644:         $rolehash = {'all' => 'all'};
 9645:         my %user_roles = &Apache::lonnet::dump('nohist_userroles',$cdom,$cnum);
 9646: 	if (&Apache::lonnet::error(%user_roles)) {
 9647: 	    undef(%user_roles);
 9648: 	}
 9649:         foreach my $item (keys(%user_roles)) {
 9650:             my ($role)=split(/\:/,$item,2);
 9651:             if ($role eq 'cr') { next; }
 9652:             if ($role =~ /^cr/) {
 9653:                 $$rolehash{$role} = (split('/',$role))[3];
 9654:             } else {
 9655:                 $$rolehash{$role} = &Apache::lonnet::plaintext($role,$type);
 9656:             }
 9657:         }
 9658:         foreach my $key (sort(keys(%{$rolehash}))) {
 9659:             push(@{$allroles},$key);
 9660:         }
 9661:         push (@{$allroles},'st');
 9662:         $$rolehash{'st'} = &Apache::lonnet::plaintext('st',$type);
 9663:     }
 9664:     return (\@sections,\@groups,$allroles,$rolehash,$accesshash);
 9665: }
 9666: 
 9667: sub user_picker {
 9668:     my ($dom,$srch,$forcenewuser,$caller,$cancreate,$usertype,$context,$fixeddom,$noinstd) = @_;
 9669:     my $currdom = $dom;
 9670:     my @alldoms = &Apache::lonnet::all_domains();
 9671:     if (@alldoms == 1) {
 9672:         my %domsrch = &Apache::lonnet::get_dom('configuration',
 9673:                                                ['directorysrch'],$alldoms[0]);
 9674:         my $domdesc = &Apache::lonnet::domain($alldoms[0],'description');
 9675:         my $showdom = $domdesc;
 9676:         if ($showdom eq '') {
 9677:             $showdom = $dom;
 9678:         }
 9679:         if (ref($domsrch{'directorysrch'}) eq 'HASH') {
 9680:             if ((!$domsrch{'directorysrch'}{'available'}) &&
 9681:                 ($domsrch{'directorysrch'}{'lcavailable'} eq '0')) {
 9682:                 return (&mt('LON-CAPA directory search is not available in domain: [_1]',$showdom),0);
 9683:             }
 9684:         }
 9685:     }
 9686:     my %curr_selected = (
 9687:                         srchin => 'dom',
 9688:                         srchby => 'lastname',
 9689:                       );
 9690:     my $srchterm;
 9691:     if ((ref($srch) eq 'HASH') && ($env{'form.origform'} ne 'crtusername')) {
 9692:         if ($srch->{'srchby'} ne '') {
 9693:             $curr_selected{'srchby'} = $srch->{'srchby'};
 9694:         }
 9695:         if ($srch->{'srchin'} ne '') {
 9696:             $curr_selected{'srchin'} = $srch->{'srchin'};
 9697:         }
 9698:         if ($srch->{'srchtype'} ne '') {
 9699:             $curr_selected{'srchtype'} = $srch->{'srchtype'};
 9700:         }
 9701:         if ($srch->{'srchdomain'} ne '') {
 9702:             $currdom = $srch->{'srchdomain'};
 9703:         }
 9704:         $srchterm = $srch->{'srchterm'};
 9705:     }
 9706:     my %html_lt=&Apache::lonlocal::texthash(
 9707:                     'usr'       => 'Search criteria',
 9708:                     'doma'      => 'Domain/institution to search',
 9709:                     'uname'     => 'username',
 9710:                     'lastname'  => 'last name',
 9711:                     'lastfirst' => 'last name, first name',
 9712:                     'crs'       => 'in this course',
 9713:                     'dom'       => 'in selected LON-CAPA domain', 
 9714:                     'alc'       => 'all LON-CAPA',
 9715:                     'instd'     => 'in institutional directory for selected domain',
 9716:                     'exact'     => 'is',
 9717:                     'contains'  => 'contains',
 9718:                     'begins'    => 'begins with',
 9719:                                        );
 9720:     my %js_lt=&Apache::lonlocal::texthash(
 9721:                     'youm'      => "You must include some text to search for.",
 9722:                     'thte'      => "The text you are searching for must contain at least two characters when using a 'begins' type search.",
 9723:                     'thet'      => "The text you are searching for must contain at least three characters when using a 'contains' type search.",
 9724:                     'yomc'      => "You must choose a domain when using an institutional directory search.",
 9725:                     'ymcd'      => "You must choose a domain when using a domain search.",
 9726:                     'whus'      => "When using searching by last,first you must include a comma as separator between last name and first name.",
 9727:                     'whse'      => "When searching by last,first you must include at least one character in the first name.",
 9728:                      'thfo'     => "The following need to be corrected before the search can be run:",
 9729:                                        );
 9730:     &html_escape(\%html_lt);
 9731:     &js_escape(\%js_lt);
 9732:     my $domform;
 9733:     my $allow_blank = 1;
 9734:     if ($fixeddom) {
 9735:         $allow_blank = 0;
 9736:         $domform = &select_dom_form($currdom,'srchdomain',$allow_blank,1,undef,[$currdom]);
 9737:     } else {
 9738:         $domform = &select_dom_form($currdom,'srchdomain',$allow_blank,1);
 9739:     }
 9740:     my $srchinsel = ' <select name="srchin">';
 9741: 
 9742:     my @srchins = ('crs','dom','alc','instd');
 9743: 
 9744:     foreach my $option (@srchins) {
 9745:         # FIXME 'alc' option unavailable until 
 9746:         #       loncreateuser::print_user_query_page()
 9747:         #       has been completed.
 9748:         next if ($option eq 'alc');
 9749:         next if (($option eq 'crs') && ($env{'form.form'} eq 'requestcrs'));  
 9750:         next if ($option eq 'crs' && !$env{'request.course.id'});
 9751:         next if (($option eq 'instd') && ($noinstd));
 9752:         if ($curr_selected{'srchin'} eq $option) {
 9753:             $srchinsel .= ' 
 9754:    <option value="'.$option.'" selected="selected">'.$html_lt{$option}.'</option>';
 9755:         } else {
 9756:             $srchinsel .= '
 9757:    <option value="'.$option.'">'.$html_lt{$option}.'</option>';
 9758:         }
 9759:     }
 9760:     $srchinsel .= "\n  </select>\n";
 9761: 
 9762:     my $srchbysel =  ' <select name="srchby">';
 9763:     foreach my $option ('lastname','lastfirst','uname') {
 9764:         if ($curr_selected{'srchby'} eq $option) {
 9765:             $srchbysel .= '
 9766:    <option value="'.$option.'" selected="selected">'.$html_lt{$option}.'</option>';
 9767:         } else {
 9768:             $srchbysel .= '
 9769:    <option value="'.$option.'">'.$html_lt{$option}.'</option>';
 9770:          }
 9771:     }
 9772:     $srchbysel .= "\n  </select>\n";
 9773: 
 9774:     my $srchtypesel = ' <select name="srchtype">';
 9775:     foreach my $option ('begins','contains','exact') {
 9776:         if ($curr_selected{'srchtype'} eq $option) {
 9777:             $srchtypesel .= '
 9778:    <option value="'.$option.'" selected="selected">'.$html_lt{$option}.'</option>';
 9779:         } else {
 9780:             $srchtypesel .= '
 9781:    <option value="'.$option.'">'.$html_lt{$option}.'</option>';
 9782:         }
 9783:     }
 9784:     $srchtypesel .= "\n  </select>\n";
 9785: 
 9786:     my ($newuserscript,$new_user_create);
 9787:     my $context_dom = $env{'request.role.domain'};
 9788:     if ($context eq 'requestcrs') {
 9789:         if ($env{'form.coursedom'} ne '') { 
 9790:             $context_dom = $env{'form.coursedom'};
 9791:         }
 9792:     }
 9793:     if ($forcenewuser) {
 9794:         if (ref($srch) eq 'HASH') {
 9795:             if ($srch->{'srchby'} eq 'uname' && $srch->{'srchtype'} eq 'exact' && $srch->{'srchin'} eq 'dom' && $srch->{'srchdomain'} eq $context_dom) {
 9796:                 if ($cancreate) {
 9797:                     $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>';
 9798:                 } else {
 9799:                     my $helplink = 'javascript:helpMenu('."'display'".')';
 9800:                     my %usertypetext = (
 9801:                         official   => 'institutional',
 9802:                         unofficial => 'non-institutional',
 9803:                     );
 9804:                     $new_user_create = '<p class="LC_warning">'
 9805:                                       .&mt("You are not authorized to create new $usertypetext{$usertype} users in this domain.")
 9806:                                       .' '
 9807:                                       .&mt('Please contact the [_1]helpdesk[_2] for assistance.'
 9808:                                           ,'<a href="'.$helplink.'">','</a>')
 9809:                                       .'</p><br />';
 9810:                 }
 9811:             }
 9812:         }
 9813: 
 9814:         $newuserscript = <<"ENDSCRIPT";
 9815: 
 9816: function setSearch(createnew,callingForm) {
 9817:     if (createnew == 1) {
 9818:         for (var i=0; i<callingForm.srchby.length; i++) {
 9819:             if (callingForm.srchby.options[i].value == 'uname') {
 9820:                 callingForm.srchby.selectedIndex = i;
 9821:             }
 9822:         }
 9823:         for (var i=0; i<callingForm.srchin.length; i++) {
 9824:             if ( callingForm.srchin.options[i].value == 'dom') {
 9825: 		callingForm.srchin.selectedIndex = i;
 9826:             }
 9827:         }
 9828:         for (var i=0; i<callingForm.srchtype.length; i++) {
 9829:             if (callingForm.srchtype.options[i].value == 'exact') {
 9830:                 callingForm.srchtype.selectedIndex = i;
 9831:             }
 9832:         }
 9833:         for (var i=0; i<callingForm.srchdomain.length; i++) {
 9834:             if (callingForm.srchdomain.options[i].value == '$context_dom') {
 9835:                 callingForm.srchdomain.selectedIndex = i;
 9836:             }
 9837:         }
 9838:     }
 9839: }
 9840: ENDSCRIPT
 9841: 
 9842:     }
 9843: 
 9844:     my $output = <<"END_BLOCK";
 9845: <script type="text/javascript">
 9846: // <![CDATA[
 9847: function validateEntry(callingForm) {
 9848: 
 9849:     var checkok = 1;
 9850:     var srchin;
 9851:     for (var i=0; i<callingForm.srchin.length; i++) {
 9852: 	if ( callingForm.srchin[i].checked ) {
 9853: 	    srchin = callingForm.srchin[i].value;
 9854: 	}
 9855:     }
 9856: 
 9857:     var srchtype = callingForm.srchtype.options[callingForm.srchtype.selectedIndex].value;
 9858:     var srchby = callingForm.srchby.options[callingForm.srchby.selectedIndex].value;
 9859:     var srchdomain = callingForm.srchdomain.options[callingForm.srchdomain.selectedIndex].value;
 9860:     var srchterm =  callingForm.srchterm.value;
 9861:     var srchin = callingForm.srchin.options[callingForm.srchin.selectedIndex].value;
 9862:     var msg = "";
 9863: 
 9864:     if (srchterm == "") {
 9865:         checkok = 0;
 9866:         msg += "$js_lt{'youm'}\\n";
 9867:     }
 9868: 
 9869:     if (srchtype== 'begins') {
 9870:         if (srchterm.length < 2) {
 9871:             checkok = 0;
 9872:             msg += "$js_lt{'thte'}\\n";
 9873:         }
 9874:     }
 9875: 
 9876:     if (srchtype== 'contains') {
 9877:         if (srchterm.length < 3) {
 9878:             checkok = 0;
 9879:             msg += "$js_lt{'thet'}\\n";
 9880:         }
 9881:     }
 9882:     if (srchin == 'instd') {
 9883:         if (srchdomain == '') {
 9884:             checkok = 0;
 9885:             msg += "$js_lt{'yomc'}\\n";
 9886:         }
 9887:     }
 9888:     if (srchin == 'dom') {
 9889:         if (srchdomain == '') {
 9890:             checkok = 0;
 9891:             msg += "$js_lt{'ymcd'}\\n";
 9892:         }
 9893:     }
 9894:     if (srchby == 'lastfirst') {
 9895:         if (srchterm.indexOf(",") == -1) {
 9896:             checkok = 0;
 9897:             msg += "$js_lt{'whus'}\\n";
 9898:         }
 9899:         if (srchterm.indexOf(",") == srchterm.length -1) {
 9900:             checkok = 0;
 9901:             msg += "$js_lt{'whse'}\\n";
 9902:         }
 9903:     }
 9904:     if (checkok == 0) {
 9905:         alert("$js_lt{'thfo'}\\n"+msg);
 9906:         return;
 9907:     }
 9908:     if (checkok == 1) {
 9909:         callingForm.submit();
 9910:     }
 9911: }
 9912: 
 9913: $newuserscript
 9914: 
 9915: // ]]>
 9916: </script>
 9917: 
 9918: $new_user_create
 9919: 
 9920: END_BLOCK
 9921: 
 9922:     $output .= &Apache::lonhtmlcommon::start_pick_box().
 9923:                &Apache::lonhtmlcommon::row_title($html_lt{'doma'}).
 9924:                $domform.
 9925:                &Apache::lonhtmlcommon::row_closure().
 9926:                &Apache::lonhtmlcommon::row_title($html_lt{'usr'}).
 9927:                $srchbysel.
 9928:                $srchtypesel. 
 9929:                '<input type="text" size="15" name="srchterm" value="'.$srchterm.'" />'.
 9930:                $srchinsel.
 9931:                &Apache::lonhtmlcommon::row_closure(1). 
 9932:                &Apache::lonhtmlcommon::end_pick_box().
 9933:                '<br />';
 9934:     return ($output,1);
 9935: }
 9936: 
 9937: sub user_rule_check {
 9938:     my ($usershash,$checks,$alerts,$rulematch,$inst_results,$curr_rules,$got_rules) = @_;
 9939:     my ($response,%inst_response);
 9940:     if (ref($usershash) eq 'HASH') {
 9941:         if (keys(%{$usershash}) > 1) {
 9942:             my (%by_username,%by_id,%userdoms);
 9943:             my $checkid;
 9944:             if (ref($checks) eq 'HASH') {
 9945:                 if ((!defined($checks->{'username'})) && (defined($checks->{'id'}))) {
 9946:                     $checkid = 1;
 9947:                 }
 9948:             }
 9949:             foreach my $user (keys(%{$usershash})) {
 9950:                 my ($uname,$udom) = split(/:/,$user);
 9951:                 if ($checkid) {
 9952:                     if (ref($usershash->{$user}) eq 'HASH') {
 9953:                         if ($usershash->{$user}->{'id'} ne '') {
 9954:                             $by_id{$udom}{$usershash->{$user}->{'id'}} = $uname;
 9955:                             $userdoms{$udom} = 1;
 9956:                             if (ref($inst_results) eq 'HASH') {
 9957:                                 $inst_results->{$uname.':'.$udom} = {};
 9958:                             }
 9959:                         }
 9960:                     }
 9961:                 } else {
 9962:                     $by_username{$udom}{$uname} = 1;
 9963:                     $userdoms{$udom} = 1;
 9964:                     if (ref($inst_results) eq 'HASH') {
 9965:                         $inst_results->{$uname.':'.$udom} = {};
 9966:                     }
 9967:                 }
 9968:             }
 9969:             foreach my $udom (keys(%userdoms)) {
 9970:                 if (!$got_rules->{$udom}) {
 9971:                     my %domconfig = &Apache::lonnet::get_dom('configuration',
 9972:                                                              ['usercreation'],$udom);
 9973:                     if (ref($domconfig{'usercreation'}) eq 'HASH') {
 9974:                         foreach my $item ('username','id') {
 9975:                             if (ref($domconfig{'usercreation'}{$item.'_rule'}) eq 'ARRAY') {
 9976:                                 $$curr_rules{$udom}{$item} =
 9977:                                     $domconfig{'usercreation'}{$item.'_rule'};
 9978:                             }
 9979:                         }
 9980:                     }
 9981:                     $got_rules->{$udom} = 1;
 9982:                 }
 9983:             }
 9984:             if ($checkid) {
 9985:                 foreach my $udom (keys(%by_id)) {
 9986:                     my ($outcome,$results) = &Apache::lonnet::get_multiple_instusers($udom,$by_id{$udom},'id');
 9987:                     if ($outcome eq 'ok') {
 9988:                         foreach my $id (keys(%{$by_id{$udom}})) {
 9989:                             my $uname = $by_id{$udom}{$id};
 9990:                             $inst_response{$uname.':'.$udom} = $outcome;
 9991:                         }
 9992:                         if (ref($results) eq 'HASH') {
 9993:                             foreach my $uname (keys(%{$results})) {
 9994:                                 if (exists($inst_response{$uname.':'.$udom})) {
 9995:                                     $inst_response{$uname.':'.$udom} = $outcome;
 9996:                                     $inst_results->{$uname.':'.$udom} = $results->{$uname};
 9997:                                 }
 9998:                             }
 9999:                         }
10000:                     }
10001:                 }
10002:             } else {
10003:                 foreach my $udom (keys(%by_username)) {
10004:                     my ($outcome,$results) = &Apache::lonnet::get_multiple_instusers($udom,$by_username{$udom});
10005:                     if ($outcome eq 'ok') {
10006:                         foreach my $uname (keys(%{$by_username{$udom}})) {
10007:                             $inst_response{$uname.':'.$udom} = $outcome;
10008:                         }
10009:                         if (ref($results) eq 'HASH') {
10010:                             foreach my $uname (keys(%{$results})) {
10011:                                 $inst_results->{$uname.':'.$udom} = $results->{$uname};
10012:                             }
10013:                         }
10014:                     }
10015:                 }
10016:             }
10017:         } elsif (keys(%{$usershash}) == 1) {
10018:             my $user = (keys(%{$usershash}))[0];
10019:             my ($uname,$udom) = split(/:/,$user);
10020:             if (($udom ne '') && ($uname ne '')) {
10021:                 if (ref($usershash->{$user}) eq 'HASH') {
10022:                     if (ref($checks) eq 'HASH') {
10023:                         if (defined($checks->{'username'})) {
10024:                             ($inst_response{$user},%{$inst_results->{$user}}) =
10025:                                 &Apache::lonnet::get_instuser($udom,$uname);
10026:                         } elsif (defined($checks->{'id'})) {
10027:                             if ($usershash->{$user}->{'id'} ne '') {
10028:                                 ($inst_response{$user},%{$inst_results->{$user}}) =
10029:                                     &Apache::lonnet::get_instuser($udom,undef,
10030:                                                                   $usershash->{$user}->{'id'});
10031:                             } else {
10032:                                 ($inst_response{$user},%{$inst_results->{$user}}) =
10033:                                     &Apache::lonnet::get_instuser($udom,$uname);
10034:                             }
10035:                         }
10036:                     } else {
10037:                        ($inst_response{$user},%{$inst_results->{$user}}) =
10038:                             &Apache::lonnet::get_instuser($udom,$uname);
10039:                        return;
10040:                     }
10041:                     if (!$got_rules->{$udom}) {
10042:                         my %domconfig = &Apache::lonnet::get_dom('configuration',
10043:                                                                  ['usercreation'],$udom);
10044:                         if (ref($domconfig{'usercreation'}) eq 'HASH') {
10045:                             foreach my $item ('username','id') {
10046:                                 if (ref($domconfig{'usercreation'}{$item.'_rule'}) eq 'ARRAY') {
10047:                                    $$curr_rules{$udom}{$item} =
10048:                                        $domconfig{'usercreation'}{$item.'_rule'};
10049:                                 }
10050:                             }
10051:                         }
10052:                         $got_rules->{$udom} = 1;
10053:                     }
10054:                 }
10055:             } else {
10056:                 return;
10057:             }
10058:         } else {
10059:             return;
10060:         }
10061:         foreach my $user (keys(%{$usershash})) {
10062:             my ($uname,$udom) = split(/:/,$user);
10063:             next if (($udom eq '') || ($uname eq ''));
10064:             my $id;
10065:             if (ref($inst_results) eq 'HASH') {
10066:                 if (ref($inst_results->{$user}) eq 'HASH') {
10067:                     $id = $inst_results->{$user}->{'id'};
10068:                 }
10069:             }
10070:             if ($id eq '') {
10071:                 if (ref($usershash->{$user})) {
10072:                     $id = $usershash->{$user}->{'id'};
10073:                 }
10074:             }
10075:             foreach my $item (keys(%{$checks})) {
10076:                 if (ref($$curr_rules{$udom}) eq 'HASH') {
10077:                     if (ref($$curr_rules{$udom}{$item}) eq 'ARRAY') {
10078:                         if (@{$$curr_rules{$udom}{$item}} > 0) {
10079:                             my %rule_check = &Apache::lonnet::inst_rulecheck($udom,$uname,$id,$item,
10080:                                                                              $$curr_rules{$udom}{$item});
10081:                             foreach my $rule (@{$$curr_rules{$udom}{$item}}) {
10082:                                 if ($rule_check{$rule}) {
10083:                                     $$rulematch{$user}{$item} = $rule;
10084:                                     if ($inst_response{$user} eq 'ok') {
10085:                                         if (ref($inst_results) eq 'HASH') {
10086:                                             if (ref($inst_results->{$user}) eq 'HASH') {
10087:                                                 if (keys(%{$inst_results->{$user}}) == 0) {
10088:                                                     $$alerts{$item}{$udom}{$uname} = 1;
10089:                                                 } elsif ($item eq 'id') {
10090:                                                     if ($inst_results->{$user}->{'id'} eq '') {
10091:                                                         $$alerts{$item}{$udom}{$uname} = 1;
10092:                                                     }
10093:                                                 }
10094:                                             }
10095:                                         }
10096:                                     }
10097:                                     last;
10098:                                 }
10099:                             }
10100:                         }
10101:                     }
10102:                 }
10103:             }
10104:         }
10105:     }
10106:     return;
10107: }
10108: 
10109: sub user_rule_formats {
10110:     my ($domain,$domdesc,$curr_rules,$check) = @_;
10111:     my %text = ( 
10112:                  'username' => 'Usernames',
10113:                  'id'       => 'IDs',
10114:                );
10115:     my $output;
10116:     my ($rules,$ruleorder) = &Apache::lonnet::inst_userrules($domain,$check);
10117:     if ((ref($rules) eq 'HASH') && (ref($ruleorder) eq 'ARRAY')) {
10118:         if (@{$ruleorder} > 0) {
10119:             $output = '<br />'.
10120:                       &mt($text{$check}.' with the following format(s) may [_1]only[_2] be used for verified users at [_3]:',
10121:                           '<span class="LC_cusr_emph">','</span>',$domdesc).
10122:                       ' <ul>';
10123:             foreach my $rule (@{$ruleorder}) {
10124:                 if (ref($curr_rules) eq 'ARRAY') {
10125:                     if (grep(/^\Q$rule\E$/,@{$curr_rules})) {
10126:                         if (ref($rules->{$rule}) eq 'HASH') {
10127:                             $output .= '<li>'.$rules->{$rule}{'name'}.': '.
10128:                                         $rules->{$rule}{'desc'}.'</li>';
10129:                         }
10130:                     }
10131:                 }
10132:             }
10133:             $output .= '</ul>';
10134:         }
10135:     }
10136:     return $output;
10137: }
10138: 
10139: sub instrule_disallow_msg {
10140:     my ($checkitem,$domdesc,$count,$mode) = @_;
10141:     my $response;
10142:     my %text = (
10143:                   item   => 'username',
10144:                   items  => 'usernames',
10145:                   match  => 'matches',
10146:                   do     => 'does',
10147:                   action => 'a username',
10148:                   one    => 'one',
10149:                );
10150:     if ($count > 1) {
10151:         $text{'item'} = 'usernames';
10152:         $text{'match'} ='match';
10153:         $text{'do'} = 'do';
10154:         $text{'action'} = 'usernames',
10155:         $text{'one'} = 'ones';
10156:     }
10157:     if ($checkitem eq 'id') {
10158:         $text{'items'} = 'IDs';
10159:         $text{'item'} = 'ID';
10160:         $text{'action'} = 'an ID';
10161:         if ($count > 1) {
10162:             $text{'item'} = 'IDs';
10163:             $text{'action'} = 'IDs';
10164:         }
10165:     }
10166:     $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 />';
10167:     if ($mode eq 'upload') {
10168:         if ($checkitem eq 'username') {
10169:             $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'}.");
10170:         } elsif ($checkitem eq 'id') {
10171:             $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.");
10172:         }
10173:     } elsif ($mode eq 'selfcreate') {
10174:         if ($checkitem eq 'id') {
10175:             $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.");
10176:         }
10177:     } else {
10178:         if ($checkitem eq 'username') {
10179:             $response .= &mt("You must choose $text{'action'} with a different format --  $text{'one'} that will not conflict with 'official' institutional $text{'items'}.");
10180:         } elsif ($checkitem eq 'id') {
10181:             $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.");
10182:         }
10183:     }
10184:     return $response;
10185: }
10186: 
10187: sub personal_data_fieldtitles {
10188:     my %fieldtitles = &Apache::lonlocal::texthash (
10189:                         id => 'Student/Employee ID',
10190:                         permanentemail => 'E-mail address',
10191:                         lastname => 'Last Name',
10192:                         firstname => 'First Name',
10193:                         middlename => 'Middle Name',
10194:                         generation => 'Generation',
10195:                         gen => 'Generation',
10196:                         inststatus => 'Affiliation',
10197:                    );
10198:     return %fieldtitles;
10199: }
10200: 
10201: sub sorted_inst_types {
10202:     my ($dom) = @_;
10203:     my ($usertypes,$order);
10204:     my %domdefaults = &Apache::lonnet::get_domain_defaults($dom);
10205:     if (ref($domdefaults{'inststatus'}) eq 'HASH') {
10206:         $usertypes = $domdefaults{'inststatus'}{'inststatustypes'};
10207:         $order = $domdefaults{'inststatus'}{'inststatusorder'};
10208:     } else {
10209:         ($usertypes,$order) = &Apache::lonnet::retrieve_inst_usertypes($dom);
10210:     }
10211:     my $othertitle = &mt('All users');
10212:     if ($env{'request.course.id'}) {
10213:         $othertitle  = &mt('Any users');
10214:     }
10215:     my @types;
10216:     if (ref($order) eq 'ARRAY') {
10217:         @types = @{$order};
10218:     }
10219:     if (@types == 0) {
10220:         if (ref($usertypes) eq 'HASH') {
10221:             @types = sort(keys(%{$usertypes}));
10222:         }
10223:     }
10224:     if (keys(%{$usertypes}) > 0) {
10225:         $othertitle = &mt('Other users');
10226:     }
10227:     return ($othertitle,$usertypes,\@types);
10228: }
10229: 
10230: sub get_institutional_codes {
10231:     my ($settings,$allcourses,$LC_code) = @_;
10232: # Get complete list of course sections to update
10233:     my @currsections = ();
10234:     my @currxlists = ();
10235:     my $coursecode = $$settings{'internal.coursecode'};
10236: 
10237:     if ($$settings{'internal.sectionnums'} ne '') {
10238:         @currsections = split(/,/,$$settings{'internal.sectionnums'});
10239:     }
10240: 
10241:     if ($$settings{'internal.crosslistings'} ne '') {
10242:         @currxlists = split(/,/,$$settings{'internal.crosslistings'});
10243:     }
10244: 
10245:     if (@currxlists > 0) {
10246:         foreach (@currxlists) {
10247:             if (m/^([^:]+):(\w*)$/) {
10248:                 unless (grep/^$1$/,@{$allcourses}) {
10249:                     push(@{$allcourses},$1);
10250:                     $$LC_code{$1} = $2;
10251:                 }
10252:             }
10253:         }
10254:     }
10255:  
10256:     if (@currsections > 0) {
10257:         foreach (@currsections) {
10258:             if (m/^(\w+):(\w*)$/) {
10259:                 my $sec = $coursecode.$1;
10260:                 my $lc_sec = $2;
10261:                 unless (grep/^$sec$/,@{$allcourses}) {
10262:                     push(@{$allcourses},$sec);
10263:                     $$LC_code{$sec} = $lc_sec;
10264:                 }
10265:             }
10266:         }
10267:     }
10268:     return;
10269: }
10270: 
10271: sub get_standard_codeitems {
10272:     return ('Year','Semester','Department','Number','Section');
10273: }
10274: 
10275: =pod
10276: 
10277: =head1 Slot Helpers
10278: 
10279: =over 4
10280: 
10281: =item * sorted_slots()
10282: 
10283: Sorts an array of slot names in order of an optional sort key,
10284: default sort is by slot start time (earliest first). 
10285: 
10286: Inputs:
10287: 
10288: =over 4
10289: 
10290: slotsarr  - Reference to array of unsorted slot names.
10291: 
10292: slots     - Reference to hash of hash, where outer hash keys are slot names.
10293: 
10294: sortkey   - Name of key in inner hash to be sorted on (e.g., starttime).
10295: 
10296: =back
10297: 
10298: Returns:
10299: 
10300: =over 4
10301: 
10302: sorted   - An array of slot names sorted by a specified sort key 
10303:            (default sort key is start time of the slot).
10304: 
10305: =back
10306: 
10307: =cut
10308: 
10309: 
10310: sub sorted_slots {
10311:     my ($slotsarr,$slots,$sortkey) = @_;
10312:     if ($sortkey eq '') {
10313:         $sortkey = 'starttime';
10314:     }
10315:     my @sorted;
10316:     if ((ref($slotsarr) eq 'ARRAY') && (ref($slots) eq 'HASH')) {
10317:         @sorted =
10318:             sort {
10319:                      if (ref($slots->{$a}) && ref($slots->{$b})) {
10320:                          return $slots->{$a}{$sortkey} <=> $slots->{$b}{$sortkey}
10321:                      }
10322:                      if (ref($slots->{$a})) { return -1;}
10323:                      if (ref($slots->{$b})) { return 1;}
10324:                      return 0;
10325:                  } @{$slotsarr};
10326:     }
10327:     return @sorted;
10328: }
10329: 
10330: =pod
10331: 
10332: =item * get_future_slots()
10333: 
10334: Inputs:
10335: 
10336: =over 4
10337: 
10338: cnum - course number
10339: 
10340: cdom - course domain
10341: 
10342: now - current UNIX time
10343: 
10344: symb - optional symb
10345: 
10346: =back
10347: 
10348: Returns:
10349: 
10350: =over 4
10351: 
10352: sorted_reservable - ref to array of student_schedulable slots currently 
10353:                     reservable, ordered by end date of reservation period.
10354: 
10355: reservable_now - ref to hash of student_schedulable slots currently
10356:                  reservable.
10357: 
10358:     Keys in inner hash are:
10359:     (a) symb: either blank or symb to which slot use is restricted.
10360:     (b) endreserve: end date of reservation period.
10361:     (c) uniqueperiod: start,end dates when slot is to be uniquely
10362:         selected.
10363: 
10364: sorted_future - ref to array of student_schedulable slots reservable in
10365:                 the future, ordered by start date of reservation period.
10366: 
10367: future_reservable - ref to hash of student_schedulable slots reservable
10368:                     in the future.
10369: 
10370:     Keys in inner hash are:
10371:     (a) symb: either blank or symb to which slot use is restricted.
10372:     (b) startreserve:  start date of reservation period.
10373:     (c) uniqueperiod: start,end dates when slot is to be uniquely
10374:         selected.
10375: 
10376: =back
10377: 
10378: =cut
10379: 
10380: sub get_future_slots {
10381:     my ($cnum,$cdom,$now,$symb) = @_;
10382:     my (%reservable_now,%future_reservable,@sorted_reservable,@sorted_future);
10383:     my %slots = &Apache::lonnet::get_course_slots($cnum,$cdom);
10384:     foreach my $slot (keys(%slots)) {
10385:         next unless($slots{$slot}->{'type'} eq 'schedulable_student');
10386:         if ($symb) {
10387:             next if (($slots{$slot}->{'symb'} ne '') && 
10388:                      ($slots{$slot}->{'symb'} ne $symb));
10389:         }
10390:         if (($slots{$slot}->{'starttime'} > $now) &&
10391:             ($slots{$slot}->{'endtime'} > $now)) {
10392:             if (($slots{$slot}->{'allowedsections'}) || ($slots{$slot}->{'allowedusers'})) {
10393:                 my $userallowed = 0;
10394:                 if ($slots{$slot}->{'allowedsections'}) {
10395:                     my @allowed_sec = split(',',$slots{$slot}->{'allowedsections'});
10396:                     if (!defined($env{'request.role.sec'})
10397:                         && grep(/^No section assigned$/,@allowed_sec)) {
10398:                         $userallowed=1;
10399:                     } else {
10400:                         if (grep(/^\Q$env{'request.role.sec'}\E$/,@allowed_sec)) {
10401:                             $userallowed=1;
10402:                         }
10403:                     }
10404:                     unless ($userallowed) {
10405:                         if (defined($env{'request.course.groups'})) {
10406:                             my @groups = split(/:/,$env{'request.course.groups'});
10407:                             foreach my $group (@groups) {
10408:                                 if (grep(/^\Q$group\E$/,@allowed_sec)) {
10409:                                     $userallowed=1;
10410:                                     last;
10411:                                 }
10412:                             }
10413:                         }
10414:                     }
10415:                 }
10416:                 if ($slots{$slot}->{'allowedusers'}) {
10417:                     my @allowed_users = split(',',$slots{$slot}->{'allowedusers'});
10418:                     my $user = $env{'user.name'}.':'.$env{'user.domain'};
10419:                     if (grep(/^\Q$user\E$/,@allowed_users)) {
10420:                         $userallowed = 1;
10421:                     }
10422:                 }
10423:                 next unless($userallowed);
10424:             }
10425:             my $startreserve = $slots{$slot}->{'startreserve'};
10426:             my $endreserve = $slots{$slot}->{'endreserve'};
10427:             my $symb = $slots{$slot}->{'symb'};
10428:             my $uniqueperiod;
10429:             if (ref($slots{$slot}->{'uniqueperiod'}) eq 'ARRAY') {
10430:                 $uniqueperiod = join(',',@{$slots{$slot}->{'uniqueperiod'}});
10431:             }
10432:             if (($startreserve < $now) &&
10433:                 (!$endreserve || $endreserve > $now)) {
10434:                 my $lastres = $endreserve;
10435:                 if (!$lastres) {
10436:                     $lastres = $slots{$slot}->{'starttime'};
10437:                 }
10438:                 $reservable_now{$slot} = {
10439:                                            symb       => $symb,
10440:                                            endreserve => $lastres,
10441:                                            uniqueperiod => $uniqueperiod,   
10442:                                          };
10443:             } elsif (($startreserve > $now) &&
10444:                      (!$endreserve || $endreserve > $startreserve)) {
10445:                 $future_reservable{$slot} = {
10446:                                               symb         => $symb,
10447:                                               startreserve => $startreserve,
10448:                                               uniqueperiod => $uniqueperiod,
10449:                                             };
10450:             }
10451:         }
10452:     }
10453:     my @unsorted_reservable = keys(%reservable_now);
10454:     if (@unsorted_reservable > 0) {
10455:         @sorted_reservable = 
10456:             &sorted_slots(\@unsorted_reservable,\%reservable_now,'endreserve');
10457:     }
10458:     my @unsorted_future = keys(%future_reservable);
10459:     if (@unsorted_future > 0) {
10460:         @sorted_future =
10461:             &sorted_slots(\@unsorted_future,\%future_reservable,'startreserve');
10462:     }
10463:     return (\@sorted_reservable,\%reservable_now,\@sorted_future,\%future_reservable);
10464: }
10465: 
10466: =pod
10467: 
10468: =back
10469: 
10470: =head1 HTTP Helpers
10471: 
10472: =over 4
10473: 
10474: =item * &get_unprocessed_cgi($query,$possible_names)
10475: 
10476: Modify the %env hash to contain unprocessed CGI form parameters held in
10477: $query.  The parameters listed in $possible_names (an array reference),
10478: will be set in $env{'form.name'} if they do not already exist.
10479: 
10480: Typically called with $ENV{'QUERY_STRING'} as the first parameter.  
10481: $possible_names is an ref to an array of form element names.  As an example:
10482: get_unprocessed_cgi($ENV{'QUERY_STRING'},['uname','udom']);
10483: will result in $env{'form.uname'} and $env{'form.udom'} being set.
10484: 
10485: =cut
10486: 
10487: sub get_unprocessed_cgi {
10488:   my ($query,$possible_names)= @_;
10489:   # $Apache::lonxml::debug=1;
10490:   foreach my $pair (split(/&/,$query)) {
10491:     my ($name, $value) = split(/=/,$pair);
10492:     $name = &unescape($name);
10493:     if (!defined($possible_names) || (grep {$_ eq $name} @$possible_names)) {
10494:       $value =~ tr/+/ /;
10495:       $value =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack("C",hex($1))/eg;
10496:       unless (defined($env{'form.'.$name})) { &add_to_env('form.'.$name,$value) };
10497:     }
10498:   }
10499: }
10500: 
10501: =pod
10502: 
10503: =item * &cacheheader() 
10504: 
10505: returns cache-controlling header code
10506: 
10507: =cut
10508: 
10509: sub cacheheader {
10510:     unless ($env{'request.method'} eq 'GET') { return ''; }
10511:     my $date=strftime("%a, %d %b %Y %H:%M:%S GMT",gmtime);
10512:     my $output .='<meta HTTP-EQUIV="Expires" CONTENT="'.$date.'" />
10513:                 <meta HTTP-EQUIV="Cache-control" CONTENT="no-cache" />
10514:                 <meta HTTP-EQUIV="Pragma" CONTENT="no-cache" />';
10515:     return $output;
10516: }
10517: 
10518: =pod
10519: 
10520: =item * &no_cache($r) 
10521: 
10522: specifies header code to not have cache
10523: 
10524: =cut
10525: 
10526: sub no_cache {
10527:     my ($r) = @_;
10528:     if ($ENV{'REQUEST_METHOD'} ne 'GET' &&
10529: 	$env{'request.method'} ne 'GET') { return ''; }
10530:     my $date=strftime("%a, %d %b %Y %H:%M:%S GMT",gmtime(time));
10531:     $r->no_cache(1);
10532:     $r->header_out("Expires" => $date);
10533:     $r->header_out("Pragma" => "no-cache");
10534: }
10535: 
10536: sub content_type {
10537:     my ($r,$type,$charset) = @_;
10538:     if ($r) {
10539: 	#  Note that printout.pl calls this with undef for $r.
10540: 	&no_cache($r);
10541:     }
10542:     if ($env{'browser.mathml'} && $type eq 'text/html') { $type='text/xml'; }
10543:     unless ($charset) {
10544: 	$charset=&Apache::lonlocal::current_encoding;
10545:     }
10546:     if ($charset) { $type.='; charset='.$charset; }
10547:     if ($r) {
10548: 	$r->content_type($type);
10549:     } else {
10550: 	print("Content-type: $type\n\n");
10551:     }
10552: }
10553: 
10554: =pod
10555: 
10556: =item * &add_to_env($name,$value) 
10557: 
10558: adds $name to the %env hash with value
10559: $value, if $name already exists, the entry is converted to an array
10560: reference and $value is added to the array.
10561: 
10562: =cut
10563: 
10564: sub add_to_env {
10565:   my ($name,$value)=@_;
10566:   if (defined($env{$name})) {
10567:     if (ref($env{$name})) {
10568:       #already have multiple values
10569:       push(@{ $env{$name} },$value);
10570:     } else {
10571:       #first time seeing multiple values, convert hash entry to an arrayref
10572:       my $first=$env{$name};
10573:       undef($env{$name});
10574:       push(@{ $env{$name} },$first,$value);
10575:     }
10576:   } else {
10577:     $env{$name}=$value;
10578:   }
10579: }
10580: 
10581: =pod
10582: 
10583: =item * &get_env_multiple($name) 
10584: 
10585: gets $name from the %env hash, it seemlessly handles the cases where multiple
10586: values may be defined and end up as an array ref.
10587: 
10588: returns an array of values
10589: 
10590: =cut
10591: 
10592: sub get_env_multiple {
10593:     my ($name) = @_;
10594:     my @values;
10595:     if (defined($env{$name})) {
10596:         # exists is it an array
10597:         if (ref($env{$name})) {
10598:             @values=@{ $env{$name} };
10599:         } else {
10600:             $values[0]=$env{$name};
10601:         }
10602:     }
10603:     return(@values);
10604: }
10605: 
10606: sub ask_for_embedded_content {
10607:     my ($actionurl,$state,$allfiles,$codebase,$args)=@_;
10608:     my (%subdependencies,%dependencies,%mapping,%existing,%newfiles,%pathchanges,
10609:         %currsubfile,%unused,$rem);
10610:     my $counter = 0;
10611:     my $numnew = 0;
10612:     my $numremref = 0;
10613:     my $numinvalid = 0;
10614:     my $numpathchg = 0;
10615:     my $numexisting = 0;
10616:     my $numunused = 0;
10617:     my ($output,$upload_output,$toplevel,$url,$udom,$uname,$getpropath,$cdom,$cnum,
10618:         $fileloc,$filename,$delete_output,$modify_output,$title,$symb,$path,$navmap);
10619:     my $heading = &mt('Upload embedded files');
10620:     my $buttontext = &mt('Upload');
10621: 
10622:     if ($env{'request.course.id'}) {
10623:         if ($actionurl eq '/adm/dependencies') {
10624:             $navmap = Apache::lonnavmaps::navmap->new();
10625:         }
10626:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
10627:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
10628:     }
10629:     if (($actionurl eq '/adm/portfolio') ||
10630:         ($actionurl eq '/adm/coursegrp_portfolio')) {
10631:         my $current_path='/';
10632:         if ($env{'form.currentpath'}) {
10633:             $current_path = $env{'form.currentpath'};
10634:         }
10635:         if ($actionurl eq '/adm/coursegrp_portfolio') {
10636:             $udom = $cdom;
10637:             $uname = $cnum;
10638:             $url = '/userfiles/groups/'.$env{'form.group'}.'/portfolio';
10639:         } else {
10640:             $udom = $env{'user.domain'};
10641:             $uname = $env{'user.name'};
10642:             $url = '/userfiles/portfolio';
10643:         }
10644:         $toplevel = $url.'/';
10645:         $url .= $current_path;
10646:         $getpropath = 1;
10647:     } elsif (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank') ||
10648:              ($actionurl eq '/adm/imsimport')) { 
10649:         my ($udom,$uname,$rest) = ($args->{'current_path'} =~ m{/priv/($match_domain)/($match_username)/?(.*)$});
10650:         $url = $Apache::lonnet::perlvar{'lonDocRoot'}."/priv/$udom/$uname/";
10651:         $toplevel = $url;
10652:         if ($rest ne '') {
10653:             $url .= $rest;
10654:         }
10655:     } elsif ($actionurl eq '/adm/coursedocs') {
10656:         if (ref($args) eq 'HASH') {
10657:             $url = $args->{'docs_url'};
10658:             $toplevel = $url;
10659:             if ($args->{'context'} eq 'paste') {
10660:                 ($cdom,$cnum) = ($url =~ m{^\Q/uploaded/\E($match_domain)/($match_courseid)/});
10661:                 ($path) =
10662:                     ($toplevel =~ m{^(\Q/uploaded/$cdom/$cnum/\E(?:docs|supplemental)/(?:default|\d+)/\d+)/});
10663:                 $fileloc = &Apache::lonnet::filelocation('',$toplevel);
10664:                 $fileloc =~ s{^/}{};
10665:             }
10666:         }
10667:     } elsif ($actionurl eq '/adm/dependencies') {
10668:         if ($env{'request.course.id'} ne '') {
10669:             if (ref($args) eq 'HASH') {
10670:                 $url = $args->{'docs_url'};
10671:                 $title = $args->{'docs_title'};
10672:                 $toplevel = $url;
10673:                 unless ($toplevel =~ m{^/}) {
10674:                     $toplevel = "/$url";
10675:                 }
10676:                 ($rem) = ($toplevel =~ m{^(.+/)[^/]+$});
10677:                 if ($toplevel =~ m{^(\Q/uploaded/$cdom/$cnum/portfolio/syllabus\E)}) {
10678:                     $path = $1;
10679:                 } else {
10680:                     ($path) =
10681:                         ($toplevel =~ m{^(\Q/uploaded/$cdom/$cnum/\E(?:docs|supplemental)/(?:default|\d+)/\d+)/});
10682:                 }
10683:                 if ($toplevel=~/^\/*(uploaded|editupload)/) {
10684:                     $fileloc = $toplevel;
10685:                     $fileloc=~ s/^\s*(\S+)\s*$/$1/;
10686:                     my ($udom,$uname,$fname) =
10687:                         ($fileloc=~ m{^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$});
10688:                     $fileloc = propath($udom,$uname).'/userfiles/'.$fname;
10689:                 } else {
10690:                     $fileloc = &Apache::lonnet::filelocation('',$toplevel);
10691:                 }
10692:                 $fileloc =~ s{^/}{};
10693:                 ($filename) = ($fileloc =~ m{.+/([^/]+)$});
10694:                 $heading = &mt('Status of dependencies in [_1]',"$title ($filename)");
10695:             }
10696:         }
10697:     } elsif ($actionurl eq "/public/$cdom/$cnum/syllabus") {
10698:         $udom = $cdom;
10699:         $uname = $cnum;
10700:         $url = "/uploaded/$cdom/$cnum/portfolio/syllabus";
10701:         $toplevel = $url;
10702:         $path = $url;
10703:         $fileloc = &Apache::lonnet::filelocation('',$toplevel).'/';
10704:         $fileloc =~ s{^/}{};
10705:     }
10706:     foreach my $file (keys(%{$allfiles})) {
10707:         my $embed_file;
10708:         if (($path eq "/uploaded/$cdom/$cnum/portfolio/syllabus") && ($file =~ m{^\Q$path/\E(.+)$})) {
10709:             $embed_file = $1;
10710:         } else {
10711:             $embed_file = $file;
10712:         }
10713:         my ($absolutepath,$cleaned_file);
10714:         if ($embed_file =~ m{^\w+://}) {
10715:             $cleaned_file = $embed_file;
10716:             $newfiles{$cleaned_file} = 1;
10717:             $mapping{$cleaned_file} = $embed_file;
10718:         } else {
10719:             $cleaned_file = &clean_path($embed_file);
10720:             if ($embed_file =~ m{^/}) {
10721:                 $absolutepath = $embed_file;
10722:             }
10723:             if ($cleaned_file =~ m{/}) {
10724:                 my ($path,$fname) = ($cleaned_file =~ m{^(.+)/([^/]*)$});
10725:                 $path = &check_for_traversal($path,$url,$toplevel);
10726:                 my $item = $fname;
10727:                 if ($path ne '') {
10728:                     $item = $path.'/'.$fname;
10729:                     $subdependencies{$path}{$fname} = 1;
10730:                 } else {
10731:                     $dependencies{$item} = 1;
10732:                 }
10733:                 if ($absolutepath) {
10734:                     $mapping{$item} = $absolutepath;
10735:                 } else {
10736:                     $mapping{$item} = $embed_file;
10737:                 }
10738:             } else {
10739:                 $dependencies{$embed_file} = 1;
10740:                 if ($absolutepath) {
10741:                     $mapping{$cleaned_file} = $absolutepath;
10742:                 } else {
10743:                     $mapping{$cleaned_file} = $embed_file;
10744:                 }
10745:             }
10746:         }
10747:     }
10748:     my $dirptr = 16384;
10749:     foreach my $path (keys(%subdependencies)) {
10750:         $currsubfile{$path} = {};
10751:         if (($actionurl eq '/adm/portfolio') ||
10752:             ($actionurl eq '/adm/coursegrp_portfolio')) { 
10753:             my ($sublistref,$listerror) =
10754:                 &Apache::lonnet::dirlist($url.$path,$udom,$uname,$getpropath);
10755:             if (ref($sublistref) eq 'ARRAY') {
10756:                 foreach my $line (@{$sublistref}) {
10757:                     my ($file_name,$rest) = split(/\&/,$line,2);
10758:                     $currsubfile{$path}{$file_name} = 1;
10759:                 }
10760:             }
10761:         } elsif (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank')) {
10762:             if (opendir(my $dir,$url.'/'.$path)) {
10763:                 my @subdir_list = grep(!/^\./,readdir($dir));
10764:                 map {$currsubfile{$path}{$_} = 1;} @subdir_list;
10765:             }
10766:         } elsif (($actionurl eq '/adm/dependencies') ||
10767:                  (($actionurl eq '/adm/coursedocs') && (ref($args) eq 'HASH') &&
10768:                   ($args->{'context'} eq 'paste')) ||
10769:                  ($actionurl eq "/public/$cdom/$cnum/syllabus")) {
10770:             if ($env{'request.course.id'} ne '') {
10771:                 my $dir;
10772:                 if ($actionurl eq "/public/$cdom/$cnum/syllabus") {
10773:                     $dir = $fileloc;
10774:                 } else {
10775:                     ($dir) = ($fileloc =~ m{^(.+/)[^/]+$});
10776:                 }
10777:                 if ($dir ne '') {
10778:                     my ($sublistref,$listerror) =
10779:                         &Apache::lonnet::dirlist($dir.$path,$cdom,$cnum,$getpropath,undef,'/');
10780:                     if (ref($sublistref) eq 'ARRAY') {
10781:                         foreach my $line (@{$sublistref}) {
10782:                             my ($file_name,$dom,undef,$testdir,undef,undef,undef,undef,$size,
10783:                                 undef,$mtime)=split(/\&/,$line,12);
10784:                             unless (($testdir&$dirptr) ||
10785:                                     ($file_name =~ /^\.\.?$/)) {
10786:                                 $currsubfile{$path}{$file_name} = [$size,$mtime];
10787:                             }
10788:                         }
10789:                     }
10790:                 }
10791:             }
10792:         }
10793:         foreach my $file (keys(%{$subdependencies{$path}})) {
10794:             if (exists($currsubfile{$path}{$file})) {
10795:                 my $item = $path.'/'.$file;
10796:                 unless ($mapping{$item} eq $item) {
10797:                     $pathchanges{$item} = 1;
10798:                 }
10799:                 $existing{$item} = 1;
10800:                 $numexisting ++;
10801:             } else {
10802:                 $newfiles{$path.'/'.$file} = 1;
10803:             }
10804:         }
10805:         if ($actionurl eq '/adm/dependencies') {
10806:             foreach my $path (keys(%currsubfile)) {
10807:                 if (ref($currsubfile{$path}) eq 'HASH') {
10808:                     foreach my $file (keys(%{$currsubfile{$path}})) {
10809:                          unless ($subdependencies{$path}{$file}) {
10810:                              next if (($rem ne '') &&
10811:                                       (($env{"httpref.$rem"."$path/$file"} ne '') ||
10812:                                        (ref($navmap) &&
10813:                                        (($navmap->getResourceByUrl($rem."$path/$file") ne '') ||
10814:                                         (($file =~ /^(.*\.s?html?)\.bak$/i) &&
10815:                                          ($navmap->getResourceByUrl($rem."$path/$1")))))));
10816:                              $unused{$path.'/'.$file} = 1; 
10817:                          }
10818:                     }
10819:                 }
10820:             }
10821:         }
10822:     }
10823:     my %currfile;
10824:     if (($actionurl eq '/adm/portfolio') ||
10825:         ($actionurl eq '/adm/coursegrp_portfolio')) {
10826:         my ($dirlistref,$listerror) =
10827:             &Apache::lonnet::dirlist($url,$udom,$uname,$getpropath);
10828:         if (ref($dirlistref) eq 'ARRAY') {
10829:             foreach my $line (@{$dirlistref}) {
10830:                 my ($file_name,$rest) = split(/\&/,$line,2);
10831:                 $currfile{$file_name} = 1;
10832:             }
10833:         }
10834:     } elsif (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank')) {
10835:         if (opendir(my $dir,$url)) {
10836:             my @dir_list = grep(!/^\./,readdir($dir));
10837:             map {$currfile{$_} = 1;} @dir_list;
10838:         }
10839:     } elsif (($actionurl eq '/adm/dependencies') ||
10840:              (($actionurl eq '/adm/coursedocs') && (ref($args) eq 'HASH') &&
10841:               ($args->{'context'} eq 'paste')) ||
10842:              ($actionurl eq "/public/$cdom/$cnum/syllabus")) {
10843:         if ($env{'request.course.id'} ne '') {
10844:             my ($dir) = ($fileloc =~ m{^(.+/)[^/]+$});
10845:             if ($dir ne '') {
10846:                 my ($dirlistref,$listerror) =
10847:                     &Apache::lonnet::dirlist($dir,$cdom,$cnum,$getpropath,undef,'/');
10848:                 if (ref($dirlistref) eq 'ARRAY') {
10849:                     foreach my $line (@{$dirlistref}) {
10850:                         my ($file_name,$dom,undef,$testdir,undef,undef,undef,undef,
10851:                             $size,undef,$mtime)=split(/\&/,$line,12);
10852:                         unless (($testdir&$dirptr) ||
10853:                                 ($file_name =~ /^\.\.?$/)) {
10854:                             $currfile{$file_name} = [$size,$mtime];
10855:                         }
10856:                     }
10857:                 }
10858:             }
10859:         }
10860:     }
10861:     foreach my $file (keys(%dependencies)) {
10862:         if (exists($currfile{$file})) {
10863:             unless ($mapping{$file} eq $file) {
10864:                 $pathchanges{$file} = 1;
10865:             }
10866:             $existing{$file} = 1;
10867:             $numexisting ++;
10868:         } else {
10869:             $newfiles{$file} = 1;
10870:         }
10871:     }
10872:     foreach my $file (keys(%currfile)) {
10873:         unless (($file eq $filename) ||
10874:                 ($file eq $filename.'.bak') ||
10875:                 ($dependencies{$file})) {
10876:             if ($actionurl eq '/adm/dependencies') {
10877:                 unless ($toplevel =~ m{^\Q/uploaded/$cdom/$cnum/portfolio/syllabus\E}) {
10878:                     next if (($rem ne '') &&
10879:                              (($env{"httpref.$rem".$file} ne '') ||
10880:                               (ref($navmap) &&
10881:                               (($navmap->getResourceByUrl($rem.$file) ne '') ||
10882:                                (($file =~ /^(.*\.s?html?)\.bak$/i) &&
10883:                                 ($navmap->getResourceByUrl($rem.$1)))))));
10884:                 }
10885:             }
10886:             $unused{$file} = 1;
10887:         }
10888:     }
10889:     if (($actionurl eq '/adm/coursedocs') && (ref($args) eq 'HASH') &&
10890:         ($args->{'context'} eq 'paste')) {
10891:         $counter = scalar(keys(%existing));
10892:         $numpathchg = scalar(keys(%pathchanges));
10893:         return ($output,$counter,$numpathchg,\%existing);
10894:     } elsif (($actionurl eq "/public/$cdom/$cnum/syllabus") &&
10895:              (ref($args) eq 'HASH') && ($args->{'context'} eq 'rewrites')) {
10896:         $counter = scalar(keys(%existing));
10897:         $numpathchg = scalar(keys(%pathchanges));
10898:         return ($output,$counter,$numpathchg,\%existing,\%mapping);
10899:     }
10900:     foreach my $embed_file (sort {lc($a) cmp lc($b)} keys(%newfiles)) {
10901:         if ($actionurl eq '/adm/dependencies') {
10902:             next if ($embed_file =~ m{^\w+://});
10903:         }
10904:         $upload_output .= &start_data_table_row().
10905:                           '<td valign="top"><img src="'.&icon($embed_file).'" />&nbsp;'.
10906:                           '<span class="LC_filename">'.$embed_file.'</span>';
10907:         unless ($mapping{$embed_file} eq $embed_file) {
10908:             $upload_output .= '<br /><span class="LC_info" style="font-size:smaller;">'.
10909:                               &mt('changed from: [_1]',$mapping{$embed_file}).'</span>';
10910:         }
10911:         $upload_output .= '</td>';
10912:         if ($args->{'ignore_remote_references'} && $embed_file =~ m{^\w+://}) { 
10913:             $upload_output.='<td align="right">'.
10914:                             '<span class="LC_info LC_fontsize_medium">'.
10915:                             &mt("URL points to web address").'</span>';
10916:             $numremref++;
10917:         } elsif ($args->{'error_on_invalid_names'}
10918:             && $embed_file ne &Apache::lonnet::clean_filename($embed_file,{'keep_path' => 1,})) {
10919:             $upload_output.='<td align="right"><span class="LC_warning">'.
10920:                             &mt('Invalid characters').'</span>';
10921:             $numinvalid++;
10922:         } else {
10923:             $upload_output .= '<td>'.
10924:                               &embedded_file_element('upload_embedded',$counter,
10925:                                                      $embed_file,\%mapping,
10926:                                                      $allfiles,$codebase,'upload');
10927:             $counter ++;
10928:             $numnew ++;
10929:         }
10930:         $upload_output .= '</td>'.&Apache::loncommon::end_data_table_row()."\n";
10931:     }
10932:     foreach my $embed_file (sort {lc($a) cmp lc($b)} keys(%existing)) {
10933:         if ($actionurl eq '/adm/dependencies') {
10934:             my ($size,$mtime) = &get_dependency_details(\%currfile,\%currsubfile,$embed_file);
10935:             $modify_output .= &start_data_table_row().
10936:                               '<td><a href="'.$path.'/'.$embed_file.'" style="text-decoration:none;">'.
10937:                               '<img src="'.&icon($embed_file).'" border="0" />'.
10938:                               '&nbsp;<span class="LC_filename">'.$embed_file.'</span></a></td>'.
10939:                               '<td>'.$size.'</td>'.
10940:                               '<td>'.$mtime.'</td>'.
10941:                               '<td><label><input type="checkbox" name="mod_upload_dep" '.
10942:                               'onclick="toggleBrowse('."'$counter'".')" id="mod_upload_dep_'.
10943:                               $counter.'" value="'.$counter.'" />'.&mt('Yes').'</label>'.
10944:                               '<div id="moduploaddep_'.$counter.'" style="display:none;">'.
10945:                               &embedded_file_element('upload_embedded',$counter,
10946:                                                      $embed_file,\%mapping,
10947:                                                      $allfiles,$codebase,'modify').
10948:                               '</div></td>'.
10949:                               &end_data_table_row()."\n";
10950:             $counter ++;
10951:         } else {
10952:             $upload_output .= &start_data_table_row().
10953:                               '<td valign="top"><img src="'.&icon($embed_file).'" />&nbsp;'.
10954:                               '<span class="LC_filename">'.$embed_file.'</span></td>'.
10955:                               '<td align="right"><span class="LC_info LC_fontsize_medium">'.&mt('Already exists').'</span></td>'.
10956:                               &Apache::loncommon::end_data_table_row()."\n";
10957:         }
10958:     }
10959:     my $delidx = $counter;
10960:     foreach my $oldfile (sort {lc($a) cmp lc($b)} keys(%unused)) {
10961:         my ($size,$mtime) = &get_dependency_details(\%currfile,\%currsubfile,$oldfile);
10962:         $delete_output .= &start_data_table_row().
10963:                           '<td><img src="'.&icon($oldfile).'" />'.
10964:                           '&nbsp;<span class="LC_filename">'.$oldfile.'</span></td>'.
10965:                           '<td>'.$size.'</td>'.
10966:                           '<td>'.$mtime.'</td>'.
10967:                           '<td><label><input type="checkbox" name="del_upload_dep" '.
10968:                           ' value="'.$delidx.'" />'.&mt('Yes').'</label>'.
10969:                           &embedded_file_element('upload_embedded',$delidx,
10970:                                                  $oldfile,\%mapping,$allfiles,
10971:                                                  $codebase,'delete').'</td>'.
10972:                           &end_data_table_row()."\n"; 
10973:         $numunused ++;
10974:         $delidx ++;
10975:     }
10976:     if ($upload_output) {
10977:         $upload_output = &start_data_table().
10978:                          $upload_output.
10979:                          &end_data_table()."\n";
10980:     }
10981:     if ($modify_output) {
10982:         $modify_output = &start_data_table().
10983:                          &start_data_table_header_row().
10984:                          '<th>'.&mt('File').'</th>'.
10985:                          '<th>'.&mt('Size (KB)').'</th>'.
10986:                          '<th>'.&mt('Modified').'</th>'.
10987:                          '<th>'.&mt('Upload replacement?').'</th>'.
10988:                          &end_data_table_header_row().
10989:                          $modify_output.
10990:                          &end_data_table()."\n";
10991:     }
10992:     if ($delete_output) {
10993:         $delete_output = &start_data_table().
10994:                          &start_data_table_header_row().
10995:                          '<th>'.&mt('File').'</th>'.
10996:                          '<th>'.&mt('Size (KB)').'</th>'.
10997:                          '<th>'.&mt('Modified').'</th>'.
10998:                          '<th>'.&mt('Delete?').'</th>'.
10999:                          &end_data_table_header_row().
11000:                          $delete_output.
11001:                          &end_data_table()."\n";
11002:     }
11003:     my $applies = 0;
11004:     if ($numremref) {
11005:         $applies ++;
11006:     }
11007:     if ($numinvalid) {
11008:         $applies ++;
11009:     }
11010:     if ($numexisting) {
11011:         $applies ++;
11012:     }
11013:     if ($counter || $numunused) {
11014:         $output = '<form name="upload_embedded" action="'.$actionurl.'"'.
11015:                   ' method="post" enctype="multipart/form-data">'."\n".
11016:                   $state.'<h3>'.$heading.'</h3>'; 
11017:         if ($actionurl eq '/adm/dependencies') {
11018:             if ($numnew) {
11019:                 $output .= '<h4>'.&mt('Missing dependencies').'</h4>'.
11020:                            '<p>'.&mt('The following files need to be uploaded.').'</p>'."\n".
11021:                            $upload_output.'<br />'."\n";
11022:             }
11023:             if ($numexisting) {
11024:                 $output .= '<h4>'.&mt('Uploaded dependencies (in use)').'</h4>'.
11025:                            '<p>'.&mt('Upload a new file to replace the one currently in use.').'</p>'."\n".
11026:                            $modify_output.'<br />'."\n";
11027:                            $buttontext = &mt('Save changes');
11028:             }
11029:             if ($numunused) {
11030:                 $output .= '<h4>'.&mt('Unused files').'</h4>'.
11031:                            '<p>'.&mt('The following uploaded files are no longer used.').'</p>'."\n".
11032:                            $delete_output.'<br />'."\n";
11033:                            $buttontext = &mt('Save changes');
11034:             }
11035:         } else {
11036:             $output .= $upload_output.'<br />'."\n";
11037:         }
11038:         $output .= '<input type ="hidden" name="number_embedded_items" value="'.
11039:                    $counter.'" />'."\n";
11040:         if ($actionurl eq '/adm/dependencies') { 
11041:             $output .= '<input type ="hidden" name="number_newemb_items" value="'.
11042:                        $numnew.'" />'."\n";
11043:         } elsif ($actionurl eq '') {
11044:             $output .=  '<input type="hidden" name="phase" value="three" />';
11045:         }
11046:     } elsif ($applies) {
11047:         $output = '<b>'.&mt('Referenced files').'</b>:<br />';
11048:         if ($applies > 1) {
11049:             $output .=  
11050:                 &mt('No dependencies need to be uploaded, as one of the following applies to each reference:').'<ul>';
11051:             if ($numremref) {
11052:                 $output .= '<li>'.&mt('reference is to a URL which points to another server').'</li>'."\n";
11053:             }
11054:             if ($numinvalid) {
11055:                 $output .= '<li>'.&mt('reference is to file with a name containing invalid characters').'</li>'."\n";
11056:             }
11057:             if ($numexisting) {
11058:                 $output .= '<li>'.&mt('reference is to an existing file at the specified location').'</li>'."\n";
11059:             }
11060:             $output .= '</ul><br />';
11061:         } elsif ($numremref) {
11062:             $output .= '<p>'.&mt('None to upload, as all references are to URLs pointing to another server.').'</p>';
11063:         } elsif ($numinvalid) {
11064:             $output .= '<p>'.&mt('None to upload, as all references are to files with names containing invalid characters.').'</p>';
11065:         } elsif ($numexisting) {
11066:             $output .= '<p>'.&mt('None to upload, as all references are to existing files.').'</p>';
11067:         }
11068:         $output .= $upload_output.'<br />';
11069:     }
11070:     my ($pathchange_output,$chgcount);
11071:     $chgcount = $counter;
11072:     if (keys(%pathchanges) > 0) {
11073:         foreach my $embed_file (sort {lc($a) cmp lc($b)} keys(%pathchanges)) {
11074:             if ($counter) {
11075:                 $output .= &embedded_file_element('pathchange',$chgcount,
11076:                                                   $embed_file,\%mapping,
11077:                                                   $allfiles,$codebase,'change');
11078:             } else {
11079:                 $pathchange_output .= 
11080:                     &start_data_table_row().
11081:                     '<td><input type ="checkbox" name="namechange" value="'.
11082:                     $chgcount.'" checked="checked" /></td>'.
11083:                     '<td>'.$mapping{$embed_file}.'</td>'.
11084:                     '<td>'.$embed_file.
11085:                     &embedded_file_element('pathchange',$numpathchg,$embed_file,
11086:                                            \%mapping,$allfiles,$codebase,'change').
11087:                     '</td>'.&end_data_table_row();
11088:             }
11089:             $numpathchg ++;
11090:             $chgcount ++;
11091:         }
11092:     }
11093:     if (($counter) || ($numunused)) {
11094:         if ($numpathchg) {
11095:             $output .= '<input type ="hidden" name="number_pathchange_items" value="'.
11096:                        $numpathchg.'" />'."\n";
11097:         }
11098:         if (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank') || 
11099:             ($actionurl eq '/adm/imsimport')) {
11100:             $output .= '<input type="hidden" name="phase" value="three" />'."\n";
11101:         } elsif ($actionurl eq '/adm/portfolio' || $actionurl eq '/adm/coursegrp_portfolio') {
11102:             $output .= '<input type="hidden" name="action" value="upload_embedded" />';
11103:         } elsif ($actionurl eq '/adm/dependencies') {
11104:             $output .= '<input type="hidden" name="action" value="process_changes" />';
11105:         }
11106:         $output .= '<input type ="submit" value="'.$buttontext.'" />'."\n".'</form>'."\n";
11107:     } elsif ($numpathchg) {
11108:         my %pathchange = ();
11109:         $output .= &modify_html_form('pathchange',$actionurl,$state,\%pathchange,$pathchange_output);
11110:         if (($actionurl eq '/adm/portfolio') || ($actionurl eq '/adm/coursegrp_portfolio')) {
11111:             $output .= '<p>'.&mt('or').'</p>'; 
11112:         }
11113:     }
11114:     return ($output,$counter,$numpathchg);
11115: }
11116: 
11117: =pod
11118: 
11119: =item * clean_path($name)
11120: 
11121: Performs clean-up of directories, subdirectories and filename in an
11122: embedded object, referenced in an HTML file which is being uploaded
11123: to a course or portfolio, where
11124: "Upload embedded images/multimedia files if HTML file" checkbox was
11125: checked.
11126: 
11127: Clean-up is similar to replacements in lonnet::clean_filename()
11128: except each / between sub-directory and next level is preserved.
11129: 
11130: =cut
11131: 
11132: sub clean_path {
11133:     my ($embed_file) = @_;
11134:     $embed_file =~s{^/+}{};
11135:     my @contents;
11136:     if ($embed_file =~ m{/}) {
11137:         @contents = split(/\//,$embed_file);
11138:     } else {
11139:         @contents = ($embed_file);
11140:     }
11141:     my $lastidx = scalar(@contents)-1;
11142:     for (my $i=0; $i<=$lastidx; $i++) {
11143:         $contents[$i]=~s{\\}{/}g;
11144:         $contents[$i]=~s/\s+/\_/g;
11145:         $contents[$i]=~s{[^/\w\.\-]}{}g;
11146:         if ($i == $lastidx) {
11147:             $contents[$i]=~s/\.(\d+)(?=\.)/_$1/g;
11148:         }
11149:     }
11150:     if ($lastidx > 0) {
11151:         return join('/',@contents);
11152:     } else {
11153:         return $contents[0];
11154:     }
11155: }
11156: 
11157: sub embedded_file_element {
11158:     my ($context,$num,$embed_file,$mapping,$allfiles,$codebase,$type) = @_;
11159:     return unless ((ref($mapping) eq 'HASH') && (ref($allfiles) eq 'HASH') &&
11160:                    (ref($codebase) eq 'HASH'));
11161:     my $output;
11162:     if (($context eq 'upload_embedded') && ($type ne 'delete')) {
11163:        $output = '<input name="embedded_item_'.$num.'" type="file" value="" />'."\n";
11164:     }
11165:     $output .= '<input name="embedded_orig_'.$num.'" type="hidden" value="'.
11166:                &escape($embed_file).'" />';
11167:     unless (($context eq 'upload_embedded') && 
11168:             ($mapping->{$embed_file} eq $embed_file)) {
11169:         $output .='
11170:         <input name="embedded_ref_'.$num.'" type="hidden" value="'.&escape($mapping->{$embed_file}).'" />';
11171:     }
11172:     my $attrib;
11173:     if (ref($allfiles->{$mapping->{$embed_file}}) eq 'ARRAY') {
11174:         $attrib = &escape(join(':',@{$allfiles->{$mapping->{$embed_file}}}));
11175:     }
11176:     $output .=
11177:         "\n\t\t".
11178:         '<input name="embedded_attrib_'.$num.'" type="hidden" value="'.
11179:         $attrib.'" />';
11180:     if (exists($codebase->{$mapping->{$embed_file}})) {
11181:         $output .=
11182:             "\n\t\t".
11183:             '<input name="codebase_'.$num.'" type="hidden" value="'.
11184:             &escape($codebase->{$mapping->{$embed_file}}).'" />';
11185:     }
11186:     return $output;
11187: }
11188: 
11189: sub get_dependency_details {
11190:     my ($currfile,$currsubfile,$embed_file) = @_;
11191:     my ($size,$mtime,$showsize,$showmtime);
11192:     if ((ref($currfile) eq 'HASH') && (ref($currsubfile))) {
11193:         if ($embed_file =~ m{/}) {
11194:             my ($path,$fname) = split(/\//,$embed_file);
11195:             if (ref($currsubfile->{$path}{$fname}) eq 'ARRAY') {
11196:                 ($size,$mtime) = @{$currsubfile->{$path}{$fname}};
11197:             }
11198:         } else {
11199:             if (ref($currfile->{$embed_file}) eq 'ARRAY') {
11200:                 ($size,$mtime) = @{$currfile->{$embed_file}};
11201:             }
11202:         }
11203:         $showsize = $size/1024.0;
11204:         $showsize = sprintf("%.1f",$showsize);
11205:         if ($mtime > 0) {
11206:             $showmtime = &Apache::lonlocal::locallocaltime($mtime);
11207:         }
11208:     }
11209:     return ($showsize,$showmtime);
11210: }
11211: 
11212: sub ask_embedded_js {
11213:     return <<"END";
11214: <script type="text/javascript"">
11215: // <![CDATA[
11216: function toggleBrowse(counter) {
11217:     var chkboxid = document.getElementById('mod_upload_dep_'+counter);
11218:     var fileid = document.getElementById('embedded_item_'+counter);
11219:     var uploaddivid = document.getElementById('moduploaddep_'+counter);
11220:     if (chkboxid.checked == true) {
11221:         uploaddivid.style.display='block';
11222:     } else {
11223:         uploaddivid.style.display='none';
11224:         fileid.value = '';
11225:     }
11226: }
11227: // ]]>
11228: </script>
11229: 
11230: END
11231: }
11232: 
11233: sub upload_embedded {
11234:     my ($context,$dirpath,$uname,$udom,$dir_root,$url_root,$group,$disk_quota,
11235:         $current_disk_usage,$hiddenstate,$actionurl) = @_;
11236:     my (%pathchange,$output,$modifyform,$footer,$returnflag);
11237:     for (my $i=0; $i<$env{'form.number_embedded_items'}; $i++) {
11238:         next if (!exists($env{'form.embedded_item_'.$i.'.filename'}));
11239:         my $orig_uploaded_filename =
11240:             $env{'form.embedded_item_'.$i.'.filename'};
11241:         foreach my $type ('orig','ref','attrib','codebase') {
11242:             if ($env{'form.embedded_'.$type.'_'.$i} ne '') {
11243:                 $env{'form.embedded_'.$type.'_'.$i} =
11244:                     &unescape($env{'form.embedded_'.$type.'_'.$i});
11245:             }
11246:         }
11247:         my ($path,$fname) =
11248:             ($env{'form.embedded_orig_'.$i} =~ m{(.*/)([^/]*)});
11249:         # no path, whole string is fname
11250:         if (!$fname) { $fname = $env{'form.embedded_orig_'.$i} };
11251:         $fname = &Apache::lonnet::clean_filename($fname);
11252:         # See if there is anything left
11253:         next if ($fname eq '');
11254: 
11255:         # Check if file already exists as a file or directory.
11256:         my ($state,$msg);
11257:         if ($context eq 'portfolio') {
11258:             my $port_path = $dirpath;
11259:             if ($group ne '') {
11260:                 $port_path = "groups/$group/$port_path";
11261:             }
11262:             ($state,$msg) = &check_for_upload($env{'form.currentpath'}.$path,
11263:                                               $fname,$group,'embedded_item_'.$i,
11264:                                               $dir_root,$port_path,$disk_quota,
11265:                                               $current_disk_usage,$uname,$udom);
11266:             if ($state eq 'will_exceed_quota'
11267:                 || $state eq 'file_locked') {
11268:                 $output .= $msg;
11269:                 next;
11270:             }
11271:         } elsif (($context eq 'author') || ($context eq 'testbank')) {
11272:             ($state,$msg) = &check_for_existing($path,$fname,'embedded_item_'.$i);
11273:             if ($state eq 'exists') {
11274:                 $output .= $msg;
11275:                 next;
11276:             }
11277:         }
11278:         # Check if extension is valid
11279:         if (($fname =~ /\.(\w+)$/) &&
11280:             (&Apache::loncommon::fileembstyle($1) eq 'hdn')) {
11281:             $output .= &mt('Invalid file extension ([_1]) - reserved for internal use.',$1)
11282:                       .' '.&mt('Rename the file with a different extension and re-upload.').'<br />';
11283:             next;
11284:         } elsif (($fname =~ /\.(\w+)$/) &&
11285:                  (!defined(&Apache::loncommon::fileembstyle($1)))) {
11286:             $output .= &mt('Unrecognized file extension ([_1]) - rename the file with a proper extension and re-upload.',$1).'<br />';
11287:             next;
11288:         } elsif ($fname=~/\.(\d+)\.(\w+)$/) {
11289:             $output .= &mt('Filename not allowed - rename the file to remove the number immediately before the file extension([_1]) and re-upload.',$2).'<br />';
11290:             next;
11291:         }
11292:         $env{'form.embedded_item_'.$i.'.filename'}=$fname;
11293:         my $subdir = $path;
11294:         $subdir =~ s{/+$}{};
11295:         if ($context eq 'portfolio') {
11296:             my $result;
11297:             if ($state eq 'existingfile') {
11298:                 $result=
11299:                     &Apache::lonnet::userfileupload('embedded_item_'.$i,'existingfile',
11300:                                                     $dirpath.$env{'form.currentpath'}.$subdir);
11301:             } else {
11302:                 $result=
11303:                     &Apache::lonnet::userfileupload('embedded_item_'.$i,'',
11304:                                                     $dirpath.
11305:                                                     $env{'form.currentpath'}.$subdir);
11306:                 if ($result !~ m|^/uploaded/|) {
11307:                     $output .= '<span class="LC_error">'
11308:                                .&mt('An error occurred ([_1]) while trying to upload [_2] for embedded element [_3].'
11309:                                ,$result,$orig_uploaded_filename,$env{'form.embedded_orig_'.$i})
11310:                                .'</span><br />';
11311:                     next;
11312:                 } else {
11313:                     $output .= &mt('Uploaded [_1]','<span class="LC_filename">'.
11314:                                $path.$fname.'</span>').'<br />';     
11315:                 }
11316:             }
11317:         } elsif (($context eq 'coursedoc') || ($context eq 'syllabus')) {
11318:             my $extendedsubdir = $dirpath.'/'.$subdir;
11319:             $extendedsubdir =~ s{/+$}{};
11320:             my $result =
11321:                 &Apache::lonnet::userfileupload('embedded_item_'.$i,$context,$extendedsubdir);
11322:             if ($result !~ m|^/uploaded/|) {
11323:                 $output .= '<span class="LC_error">'
11324:                            .&mt('An error occurred ([_1]) while trying to upload [_2] for embedded element [_3].'
11325:                            ,$result,$orig_uploaded_filename,$env{'form.embedded_orig_'.$i})
11326:                            .'</span><br />';
11327:                     next;
11328:             } else {
11329:                 $output .= &mt('Uploaded [_1]','<span class="LC_filename">'.
11330:                            $path.$fname.'</span>').'<br />';
11331:                 if ($context eq 'syllabus') {
11332:                     &Apache::lonnet::make_public_indefinitely($result);
11333:                 }
11334:             }
11335:         } else {
11336: # Save the file
11337:             my $target = $env{'form.embedded_item_'.$i};
11338:             my $fullpath = $dir_root.$dirpath.'/'.$path;
11339:             my $dest = $fullpath.$fname;
11340:             my $url = $url_root.$dirpath.'/'.$path.$fname;
11341:             my @parts=split(/\//,"$dirpath/$path");
11342:             my $count;
11343:             my $filepath = $dir_root;
11344:             foreach my $subdir (@parts) {
11345:                 $filepath .= "/$subdir";
11346:                 if (!-e $filepath) {
11347:                     mkdir($filepath,0770);
11348:                 }
11349:             }
11350:             my $fh;
11351:             if (!open($fh,'>'.$dest)) {
11352:                 &Apache::lonnet::logthis('Failed to create '.$dest);
11353:                 $output .= '<span class="LC_error">'.
11354:                            &mt('An error occurred while trying to upload [_1] for embedded element [_2].',
11355:                                $orig_uploaded_filename,$env{'form.embedded_orig_'.$i}).
11356:                            '</span><br />';
11357:             } else {
11358:                 if (!print $fh $env{'form.embedded_item_'.$i}) {
11359:                     &Apache::lonnet::logthis('Failed to write to '.$dest);
11360:                     $output .= '<span class="LC_error">'.
11361:                               &mt('An error occurred while writing the file [_1] for embedded element [_2].',
11362:                                   $orig_uploaded_filename,$env{'form.embedded_orig_'.$i}).
11363:                               '</span><br />';
11364:                 } else {
11365:                     $output .= &mt('Uploaded [_1]','<span class="LC_filename">'.
11366:                                $url.'</span>').'<br />';
11367:                     unless ($context eq 'testbank') {
11368:                         $footer .= &mt('View embedded file: [_1]',
11369:                                        '<a href="'.$url.'">'.$fname.'</a>').'<br />';
11370:                     }
11371:                 }
11372:                 close($fh);
11373:             }
11374:         }
11375:         if ($env{'form.embedded_ref_'.$i}) {
11376:             $pathchange{$i} = 1;
11377:         }
11378:     }
11379:     if ($output) {
11380:         $output = '<p>'.$output.'</p>';
11381:     }
11382:     $output .= &modify_html_form('upload_embedded',$actionurl,$hiddenstate,\%pathchange);
11383:     $returnflag = 'ok';
11384:     my $numpathchgs = scalar(keys(%pathchange));
11385:     if ($numpathchgs > 0) {
11386:         if ($context eq 'portfolio') {
11387:             $output .= '<p>'.&mt('or').'</p>';
11388:         } elsif ($context eq 'testbank') {
11389:             $output .=  '<p>'.&mt('Or [_1]continue[_2] the testbank import without modifying the reference(s).',
11390:                                   '<a href="javascript:document.testbankForm.submit();">','</a>').'</p>';
11391:             $returnflag = 'modify_orightml';
11392:         }
11393:     }
11394:     return ($output.$footer,$returnflag,$numpathchgs);
11395: }
11396: 
11397: sub modify_html_form {
11398:     my ($context,$actionurl,$hiddenstate,$pathchange,$pathchgtable) = @_;
11399:     my $end = 0;
11400:     my $modifyform;
11401:     if ($context eq 'upload_embedded') {
11402:         return unless (ref($pathchange) eq 'HASH');
11403:         if ($env{'form.number_embedded_items'}) {
11404:             $end += $env{'form.number_embedded_items'};
11405:         }
11406:         if ($env{'form.number_pathchange_items'}) {
11407:             $end += $env{'form.number_pathchange_items'};
11408:         }
11409:         if ($end) {
11410:             for (my $i=0; $i<$end; $i++) {
11411:                 if ($i < $env{'form.number_embedded_items'}) {
11412:                     next unless($pathchange->{$i});
11413:                 }
11414:                 $modifyform .=
11415:                     &start_data_table_row().
11416:                     '<td><input type ="checkbox" name="namechange" value="'.$i.'" '.
11417:                     'checked="checked" /></td>'.
11418:                     '<td>'.$env{'form.embedded_ref_'.$i}.
11419:                     '<input type="hidden" name="embedded_ref_'.$i.'" value="'.
11420:                     &escape($env{'form.embedded_ref_'.$i}).'" />'.
11421:                     '<input type="hidden" name="embedded_codebase_'.$i.'" value="'.
11422:                     &escape($env{'form.embedded_codebase_'.$i}).'" />'.
11423:                     '<input type="hidden" name="embedded_attrib_'.$i.'" value="'.
11424:                     &escape($env{'form.embedded_attrib_'.$i}).'" /></td>'.
11425:                     '<td>'.$env{'form.embedded_orig_'.$i}.
11426:                     '<input type="hidden" name="embedded_orig_'.$i.'" value="'.
11427:                     &escape($env{'form.embedded_orig_'.$i}).'" /></td>'.
11428:                     &end_data_table_row();
11429:             }
11430:         }
11431:     } else {
11432:         $modifyform = $pathchgtable;
11433:         if (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank')) {
11434:             $hiddenstate .= '<input type="hidden" name="phase" value="four" />';
11435:         } elsif (($actionurl eq '/adm/portfolio') || ($actionurl eq '/adm/coursegrp_portfolio')) {
11436:             $hiddenstate .= '<input type="hidden" name="action" value="modify_orightml" />';
11437:         }
11438:     }
11439:     if ($modifyform) {
11440:         if ($actionurl eq '/adm/dependencies') {
11441:             $hiddenstate .= '<input type="hidden" name="action" value="modifyhrefs" />';
11442:         }
11443:         return '<h3>'.&mt('Changes in content of HTML file required').'</h3>'."\n".
11444:                '<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".
11445:                '<li>'.&mt('For consistency between the reference(s) and the location of the corresponding stored file within LON-CAPA.').'</li>'."\n".
11446:                '<li>'.&mt('To change absolute paths to relative paths, or replace directory traversal via "../" within the original reference.').'</li>'."\n".
11447:                '</ol></p>'."\n".'<p>'.
11448:                &mt('LON-CAPA can make the required changes to your HTML file.').'</p>'."\n".
11449:                '<form method="post" name="refchanger" action="'.$actionurl.'">'.
11450:                &start_data_table()."\n".
11451:                &start_data_table_header_row().
11452:                '<th>'.&mt('Change?').'</th>'.
11453:                '<th>'.&mt('Current reference').'</th>'.
11454:                '<th>'.&mt('Required reference').'</th>'.
11455:                &end_data_table_header_row()."\n".
11456:                $modifyform.
11457:                &end_data_table().'<br />'."\n".$hiddenstate.
11458:                '<input type="submit" name="pathchanges" value="'.&mt('Modify HTML file').'" />'.
11459:                '</form>'."\n";
11460:     }
11461:     return;
11462: }
11463: 
11464: sub modify_html_refs {
11465:     my ($context,$dirpath,$uname,$udom,$dir_root,$url) = @_;
11466:     my $container;
11467:     if ($context eq 'portfolio') {
11468:         $container = $env{'form.container'};
11469:     } elsif ($context eq 'coursedoc') {
11470:         $container = $env{'form.primaryurl'};
11471:     } elsif ($context eq 'manage_dependencies') {
11472:         (undef,undef,$container) = &Apache::lonnet::decode_symb($env{'form.symb'});
11473:         $container = "/$container";
11474:     } elsif ($context eq 'syllabus') {
11475:         $container = $url;
11476:     } else {
11477:         $container = $Apache::lonnet::perlvar{'lonDocRoot'}.$env{'form.filename'};
11478:     }
11479:     my (%allfiles,%codebase,$output,$content);
11480:     my @changes = &get_env_multiple('form.namechange');
11481:     unless ((@changes > 0)  || ($context eq 'syllabus')) {
11482:         if (wantarray) {
11483:             return ('',0,0); 
11484:         } else {
11485:             return;
11486:         }
11487:     }
11488:     if (($context eq 'portfolio') || ($context eq 'coursedoc') || 
11489:         ($context eq 'manage_dependencies') || ($context eq 'syllabus')) {
11490:         unless ($container =~ m{^/uploaded/\Q$udom\E/\Q$uname\E/}) {
11491:             if (wantarray) {
11492:                 return ('',0,0);
11493:             } else {
11494:                 return;
11495:             }
11496:         } 
11497:         $content = &Apache::lonnet::getfile($container);
11498:         if ($content eq '-1') {
11499:             if (wantarray) {
11500:                 return ('',0,0);
11501:             } else {
11502:                 return;
11503:             }
11504:         }
11505:     } else {
11506:         unless ($container =~ /^\Q$dir_root\E/) {
11507:             if (wantarray) {
11508:                 return ('',0,0);
11509:             } else {
11510:                 return;
11511:             }
11512:         } 
11513:         if (open(my $fh,'<',$container)) {
11514:             $content = join('', <$fh>);
11515:             close($fh);
11516:         } else {
11517:             if (wantarray) {
11518:                 return ('',0,0);
11519:             } else {
11520:                 return;
11521:             }
11522:         }
11523:     }
11524:     my ($count,$codebasecount) = (0,0);
11525:     my $mm = new File::MMagic;
11526:     my $mime_type = $mm->checktype_contents($content);
11527:     if ($mime_type eq 'text/html') {
11528:         my $parse_result = 
11529:             &Apache::lonnet::extract_embedded_items($container,\%allfiles,
11530:                                                     \%codebase,\$content);
11531:         if ($parse_result eq 'ok') {
11532:             foreach my $i (@changes) {
11533:                 my $orig = &unescape($env{'form.embedded_orig_'.$i});
11534:                 my $ref = &unescape($env{'form.embedded_ref_'.$i});
11535:                 if ($allfiles{$ref}) {
11536:                     my $newname =  $orig;
11537:                     my ($attrib_regexp,$codebase);
11538:                     $attrib_regexp = &unescape($env{'form.embedded_attrib_'.$i});
11539:                     if ($attrib_regexp =~ /:/) {
11540:                         $attrib_regexp =~ s/\:/|/g;
11541:                     }
11542:                     if ($content =~ m{($attrib_regexp\s*=\s*['"]?)\Q$ref\E(['"]?)}) {
11543:                         my $numchg = ($content =~ s{($attrib_regexp\s*=\s*['"]?)\Q$ref\E(['"]?)}{$1$newname$2}gi);
11544:                         $count += $numchg;
11545:                         $allfiles{$newname} = $allfiles{$ref};
11546:                         delete($allfiles{$ref});
11547:                     }
11548:                     if ($env{'form.embedded_codebase_'.$i} ne '') {
11549:                         $codebase = &unescape($env{'form.embedded_codebase_'.$i});
11550:                         my $numchg = ($content =~ s/(codebase\s*=\s*["']?)\Q$codebase\E(["']?)/$1.$2/i); #' stupid emacs
11551:                         $codebasecount ++;
11552:                     }
11553:                 }
11554:             }
11555:             my $skiprewrites;
11556:             if ($count || $codebasecount) {
11557:                 my $saveresult;
11558:                 if (($context eq 'portfolio') || ($context eq 'coursedoc') || 
11559:                     ($context eq 'manage_dependencies') || ($context eq 'syllabus')) {
11560:                     my $url = &Apache::lonnet::store_edited_file($container,$content,$udom,$uname,\$saveresult);
11561:                     if ($url eq $container) {
11562:                         my ($fname) = ($container =~ m{/([^/]+)$});
11563:                         $output = '<p>'.&mt('Updated [quant,_1,reference] in [_2].',
11564:                                             $count,'<span class="LC_filename">'.
11565:                                             $fname.'</span>').'</p>';
11566:                     } else {
11567:                          $output = '<p class="LC_error">'.
11568:                                    &mt('Error: update failed for: [_1].',
11569:                                    '<span class="LC_filename">'.
11570:                                    $container.'</span>').'</p>';
11571:                     }
11572:                     if ($context eq 'syllabus') {
11573:                         unless ($saveresult eq 'ok') {
11574:                             $skiprewrites = 1;
11575:                         }
11576:                     }
11577:                 } else {
11578:                     if (open(my $fh,'>',$container)) {
11579:                         print $fh $content;
11580:                         close($fh);
11581:                         $output = '<p>'.&mt('Updated [quant,_1,reference] in [_2].',
11582:                                   $count,'<span class="LC_filename">'.
11583:                                   $container.'</span>').'</p>';
11584:                     } else {
11585:                          $output = '<p class="LC_error">'.
11586:                                    &mt('Error: could not update [_1].',
11587:                                    '<span class="LC_filename">'.
11588:                                    $container.'</span>').'</p>';
11589:                     }
11590:                 }
11591:             }
11592:             if (($context eq 'syllabus') && (!$skiprewrites)) {
11593:                 my ($actionurl,$state);
11594:                 $actionurl = "/public/$udom/$uname/syllabus";
11595:                 my ($ignore,$num,$numpathchanges,$existing,$mapping) =
11596:                     &ask_for_embedded_content($actionurl,$state,\%allfiles,
11597:                                               \%codebase,
11598:                                               {'context' => 'rewrites',
11599:                                                'ignore_remote_references' => 1,});
11600:                 if (ref($mapping) eq 'HASH') {
11601:                     my $rewrites = 0;
11602:                     foreach my $key (keys(%{$mapping})) {
11603:                         next if ($key =~ m{^https?://});
11604:                         my $ref = $mapping->{$key};
11605:                         my $newname = "/uploaded/$udom/$uname/portfolio/syllabus/$key";
11606:                         my $attrib;
11607:                         if (ref($allfiles{$mapping->{$key}}) eq 'ARRAY') {
11608:                             $attrib = join('|',@{$allfiles{$mapping->{$key}}});
11609:                         }
11610:                         if ($content =~ m{($attrib\s*=\s*['"]?)\Q$ref\E(['"]?)}) {
11611:                             my $numchg = ($content =~ s{($attrib\s*=\s*['"]?)\Q$ref\E(['"]?)}{$1$newname$2}gi);
11612:                             $rewrites += $numchg;
11613:                         }
11614:                     }
11615:                     if ($rewrites) {
11616:                         my $saveresult;
11617:                         my $url = &Apache::lonnet::store_edited_file($container,$content,$udom,$uname,\$saveresult);
11618:                         if ($url eq $container) {
11619:                             my ($fname) = ($container =~ m{/([^/]+)$});
11620:                             $output .= '<p>'.&mt('Rewrote [quant,_1,link] as [quant,_1,absolute link] in [_2].',
11621:                                             $count,'<span class="LC_filename">'.
11622:                                             $fname.'</span>').'</p>';
11623:                         } else {
11624:                             $output .= '<p class="LC_error">'.
11625:                                        &mt('Error: could not update links in [_1].',
11626:                                        '<span class="LC_filename">'.
11627:                                        $container.'</span>').'</p>';
11628: 
11629:                         }
11630:                     }
11631:                 }
11632:             }
11633:         } else {
11634:             &logthis('Failed to parse '.$container.
11635:                      ' to modify references: '.$parse_result);
11636:         }
11637:     }
11638:     if (wantarray) {
11639:         return ($output,$count,$codebasecount);
11640:     } else {
11641:         return $output;
11642:     }
11643: }
11644: 
11645: sub check_for_existing {
11646:     my ($path,$fname,$element) = @_;
11647:     my ($state,$msg);
11648:     if (-d $path.'/'.$fname) {
11649:         $state = 'exists';
11650:         $msg = &mt('Unable to upload [_1]. A directory by that name was found in [_2].','<span class="LC_filename">'.$fname.'</span>',$path);
11651:     } elsif (-e $path.'/'.$fname) {
11652:         $state = 'exists';
11653:         $msg = &mt('Unable to upload [_1]. A file by that name was found in [_2].','<span class="LC_filename">'.$fname.'</span>',$path);
11654:     }
11655:     if ($state eq 'exists') {
11656:         $msg = '<span class="LC_error">'.$msg.'</span><br />';
11657:     }
11658:     return ($state,$msg);
11659: }
11660: 
11661: sub check_for_upload {
11662:     my ($path,$fname,$group,$element,$portfolio_root,$port_path,
11663:         $disk_quota,$current_disk_usage,$uname,$udom) = @_;
11664:     my $filesize = length($env{'form.'.$element});
11665:     if (!$filesize) {
11666:         my $msg = '<span class="LC_error">'.
11667:                   &mt('Unable to upload [_1]. (size = [_2] bytes)', 
11668:                       '<span class="LC_filename">'.$fname.'</span>',
11669:                       $filesize).'<br />'.
11670:                   &mt('Either the file you attempted to upload was empty, or your web browser was unable to read its contents.').'<br />'.
11671:                   '</span>';
11672:         return ('zero_bytes',$msg);
11673:     }
11674:     $filesize =  $filesize/1000; #express in k (1024?)
11675:     my $getpropath = 1;
11676:     my ($dirlistref,$listerror) =
11677:          &Apache::lonnet::dirlist($portfolio_root.$path,$udom,$uname,$getpropath);
11678:     my $found_file = 0;
11679:     my $locked_file = 0;
11680:     my @lockers;
11681:     my $navmap;
11682:     if ($env{'request.course.id'}) {
11683:         $navmap = Apache::lonnavmaps::navmap->new();
11684:     }
11685:     if (ref($dirlistref) eq 'ARRAY') {
11686:         foreach my $line (@{$dirlistref}) {
11687:             my ($file_name,$rest)=split(/\&/,$line,2);
11688:             if ($file_name eq $fname){
11689:                 $file_name = $path.$file_name;
11690:                 if ($group ne '') {
11691:                     $file_name = $group.$file_name;
11692:                 }
11693:                 $found_file = 1;
11694:                 if (&Apache::lonnet::is_locked($file_name,$udom,$uname,\@lockers) eq 'true') {
11695:                     foreach my $lock (@lockers) {
11696:                         if (ref($lock) eq 'ARRAY') {
11697:                             my ($symb,$crsid) = @{$lock};
11698:                             if ($crsid eq $env{'request.course.id'}) {
11699:                                 if (ref($navmap)) {
11700:                                     my $res = $navmap->getBySymb($symb);
11701:                                     foreach my $part (@{$res->parts()}) { 
11702:                                         my ($slot_status,$slot_time,$slot_name)=$res->check_for_slot($part);
11703:                                         unless (($slot_status == $res->RESERVED) ||
11704:                                                 ($slot_status == $res->RESERVED_LOCATION)) {
11705:                                             $locked_file = 1;
11706:                                         }
11707:                                     }
11708:                                 } else {
11709:                                     $locked_file = 1;
11710:                                 }
11711:                             } else {
11712:                                 $locked_file = 1;
11713:                             }
11714:                         }
11715:                    }
11716:                 } else {
11717:                     my @info = split(/\&/,$rest);
11718:                     my $currsize = $info[6]/1000;
11719:                     if ($currsize < $filesize) {
11720:                         my $extra = $filesize - $currsize;
11721:                         if (($current_disk_usage + $extra) > $disk_quota) {
11722:                             my $msg = '<p class="LC_warning">'.
11723:                                       &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.',
11724:                                           '<span class="LC_filename">'.$fname.'</span>',$filesize,$currsize).'</p>'.
11725:                                       '<p>'.&mt('Disk quota is [_1] kilobytes. Your current disk usage is [_2] kilobytes.',
11726:                                                    $disk_quota,$current_disk_usage).'</p>';
11727:                             return ('will_exceed_quota',$msg);
11728:                         }
11729:                     }
11730:                 }
11731:             }
11732:         }
11733:     }
11734:     if (($current_disk_usage + $filesize) > $disk_quota){
11735:         my $msg = '<p class="LC_warning">'.
11736:                 &mt('Unable to upload [_1]. (size = [_2] kilobytes). Disk quota will be exceeded.','<span class="LC_filename">'.$fname.'</span>',$filesize).'</p>'.
11737:                   '<p>'.&mt('Disk quota is [_1] kilobytes. Your current disk usage is [_2] kilobytes.',$disk_quota,$current_disk_usage).'</p>';
11738:         return ('will_exceed_quota',$msg);
11739:     } elsif ($found_file) {
11740:         if ($locked_file) {
11741:             my $msg = '<p class="LC_warning">';
11742:             $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>');
11743:             $msg .= '</p>';
11744:             $msg .= &mt('You will be able to rename or delete existing [_1] after a grade has been assigned.','<span class="LC_filename">'.$fname.'</span>');
11745:             return ('file_locked',$msg);
11746:         } else {
11747:             my $msg = '<p class="LC_error">';
11748:             $msg .= &mt(' A file by that name: [_1] was found in [_2].','<span class="LC_filename">'.$fname.'</span>',$port_path.$env{'form.currentpath'});
11749:             $msg .= '</p>';
11750:             return ('existingfile',$msg);
11751:         }
11752:     }
11753: }
11754: 
11755: sub check_for_traversal {
11756:     my ($path,$url,$toplevel) = @_;
11757:     my @parts=split(/\//,$path);
11758:     my $cleanpath;
11759:     my $fullpath = $url;
11760:     for (my $i=0;$i<@parts;$i++) {
11761:         next if ($parts[$i] eq '.');
11762:         if ($parts[$i] eq '..') {
11763:             $fullpath =~ s{([^/]+/)$}{};
11764:         } else {
11765:             $fullpath .= $parts[$i].'/';
11766:         }
11767:     }
11768:     if ($fullpath =~ /^\Q$url\E(.*)$/) {
11769:         $cleanpath = $1;
11770:     } elsif ($fullpath =~ /^\Q$toplevel\E(.*)$/) {
11771:         my $curr_toprel = $1;
11772:         my @parts = split(/\//,$curr_toprel);
11773:         my ($url_toprel) = ($url =~ /^\Q$toplevel\E(.*)$/);
11774:         my @urlparts = split(/\//,$url_toprel);
11775:         my $doubledots;
11776:         my $startdiff = -1;
11777:         for (my $i=0; $i<@urlparts; $i++) {
11778:             if ($startdiff == -1) {
11779:                 unless ($urlparts[$i] eq $parts[$i]) {
11780:                     $startdiff = $i;
11781:                     $doubledots .= '../';
11782:                 }
11783:             } else {
11784:                 $doubledots .= '../';
11785:             }
11786:         }
11787:         if ($startdiff > -1) {
11788:             $cleanpath = $doubledots;
11789:             for (my $i=$startdiff; $i<@parts; $i++) {
11790:                 $cleanpath .= $parts[$i].'/';
11791:             }
11792:         }
11793:     }
11794:     $cleanpath =~ s{(/)$}{};
11795:     return $cleanpath;
11796: }
11797: 
11798: sub is_archive_file {
11799:     my ($mimetype) = @_;
11800:     if (($mimetype eq 'application/octet-stream') ||
11801:         ($mimetype eq 'application/x-stuffit') ||
11802:         ($mimetype =~ m{^application/(x\-)?(compressed|tar|zip|tgz|gz|gtar|gzip|gunzip|bz|bz2|bzip2)})) {
11803:         return 1;
11804:     }
11805:     return;
11806: }
11807: 
11808: sub decompress_form {
11809:     my ($mimetype,$archiveurl,$action,$noextract,$hiddenelements,$dirlist) = @_;
11810:     my %lt = &Apache::lonlocal::texthash (
11811:         this => 'This file is an archive file.',
11812:         camt => 'This file is a Camtasia archive file.',
11813:         itsc => 'Its contents are as follows:',
11814:         youm => 'You may wish to extract its contents.',
11815:         extr => 'Extract contents',
11816:         auto => 'LON-CAPA can process the files automatically, or you can decide how each should be handled.',
11817:         proa => 'Process automatically?',
11818:         yes  => 'Yes',
11819:         no   => 'No',
11820:         fold => 'Title for folder containing movie',
11821:         movi => 'Title for page containing embedded movie', 
11822:     );
11823:     my $fileloc = &Apache::lonnet::filelocation(undef,$archiveurl);
11824:     my ($is_camtasia,$topdir,%toplevel,@paths);
11825:     my $info = &list_archive_contents($fileloc,\@paths);
11826:     if (@paths) {
11827:         foreach my $path (@paths) {
11828:             $path =~ s{^/}{};
11829:             if ($path =~ m{^([^/]+)/$}) {
11830:                 $topdir = $1;
11831:             }
11832:             if ($path =~ m{^([^/]+)/}) {
11833:                 $toplevel{$1} = $path;
11834:             } else {
11835:                 $toplevel{$path} = $path;
11836:             }
11837:         }
11838:     }
11839:     if ($mimetype =~ m{^application/(x\-)?(compressed|zip)}) {
11840:         my @camtasia6 = ("$topdir/","$topdir/index.html",
11841:                         "$topdir/media/",
11842:                         "$topdir/media/$topdir.mp4",
11843:                         "$topdir/media/FirstFrame.png",
11844:                         "$topdir/media/player.swf",
11845:                         "$topdir/media/swfobject.js",
11846:                         "$topdir/media/expressInstall.swf");
11847:         my @camtasia8_1 = ("$topdir/","$topdir/$topdir.html",
11848:                          "$topdir/$topdir.mp4",
11849:                          "$topdir/$topdir\_config.xml",
11850:                          "$topdir/$topdir\_controller.swf",
11851:                          "$topdir/$topdir\_embed.css",
11852:                          "$topdir/$topdir\_First_Frame.png",
11853:                          "$topdir/$topdir\_player.html",
11854:                          "$topdir/$topdir\_Thumbnails.png",
11855:                          "$topdir/playerProductInstall.swf",
11856:                          "$topdir/scripts/",
11857:                          "$topdir/scripts/config_xml.js",
11858:                          "$topdir/scripts/handlebars.js",
11859:                          "$topdir/scripts/jquery-1.7.1.min.js",
11860:                          "$topdir/scripts/jquery-ui-1.8.15.custom.min.js",
11861:                          "$topdir/scripts/modernizr.js",
11862:                          "$topdir/scripts/player-min.js",
11863:                          "$topdir/scripts/swfobject.js",
11864:                          "$topdir/skins/",
11865:                          "$topdir/skins/configuration_express.xml",
11866:                          "$topdir/skins/express_show/",
11867:                          "$topdir/skins/express_show/player-min.css",
11868:                          "$topdir/skins/express_show/spritesheet.png");
11869:         my @camtasia8_4 = ("$topdir/","$topdir/$topdir.html",
11870:                          "$topdir/$topdir.mp4",
11871:                          "$topdir/$topdir\_config.xml",
11872:                          "$topdir/$topdir\_controller.swf",
11873:                          "$topdir/$topdir\_embed.css",
11874:                          "$topdir/$topdir\_First_Frame.png",
11875:                          "$topdir/$topdir\_player.html",
11876:                          "$topdir/$topdir\_Thumbnails.png",
11877:                          "$topdir/playerProductInstall.swf",
11878:                          "$topdir/scripts/",
11879:                          "$topdir/scripts/config_xml.js",
11880:                          "$topdir/scripts/techsmith-smart-player.min.js",
11881:                          "$topdir/skins/",
11882:                          "$topdir/skins/configuration_express.xml",
11883:                          "$topdir/skins/express_show/",
11884:                          "$topdir/skins/express_show/spritesheet.min.css",
11885:                          "$topdir/skins/express_show/spritesheet.png",
11886:                          "$topdir/skins/express_show/techsmith-smart-player.min.css");
11887:         my @diffs = &compare_arrays(\@paths,\@camtasia6);
11888:         if (@diffs == 0) {
11889:             $is_camtasia = 6;
11890:         } else {
11891:             @diffs = &compare_arrays(\@paths,\@camtasia8_1);
11892:             if (@diffs == 0) {
11893:                 $is_camtasia = 8;
11894:             } else {
11895:                 @diffs = &compare_arrays(\@paths,\@camtasia8_4);
11896:                 if (@diffs == 0) {
11897:                     $is_camtasia = 8;
11898:                 }
11899:             }
11900:         }
11901:     }
11902:     my $output;
11903:     if ($is_camtasia) {
11904:         $output = <<"ENDCAM";
11905: <script type="text/javascript" language="Javascript">
11906: // <![CDATA[
11907: 
11908: function camtasiaToggle() {
11909:     for (var i=0; i<document.uploaded_decompress.autoextract_camtasia.length; i++) {
11910:         if (document.uploaded_decompress.autoextract_camtasia[i].checked) {
11911:             if (document.uploaded_decompress.autoextract_camtasia[i].value == $is_camtasia) {
11912:                 document.getElementById('camtasia_titles').style.display='block';
11913:             } else {
11914:                 document.getElementById('camtasia_titles').style.display='none';
11915:             }
11916:         }
11917:     }
11918:     return;
11919: }
11920: 
11921: // ]]>
11922: </script>
11923: <p>$lt{'camt'}</p>
11924: ENDCAM
11925:     } else {
11926:         $output = '<p>'.$lt{'this'};
11927:         if ($info eq '') {
11928:             $output .= ' '.$lt{'youm'}.'</p>'."\n";
11929:         } else {
11930:             $output .= ' '.$lt{'itsc'}.'</p>'."\n".
11931:                        '<div><pre>'.$info.'</pre></div>';
11932:         }
11933:     }
11934:     $output .= '<form name="uploaded_decompress" action="'.$action.'" method="post">'."\n";
11935:     my $duplicates;
11936:     my $num = 0;
11937:     if (ref($dirlist) eq 'ARRAY') {
11938:         foreach my $item (@{$dirlist}) {
11939:             if (ref($item) eq 'ARRAY') {
11940:                 if (exists($toplevel{$item->[0]})) {
11941:                     $duplicates .= 
11942:                         &start_data_table_row().
11943:                         '<td><label><input type="radio" name="archive_overwrite_'.$num.'" '.
11944:                         'value="0" checked="checked" />'.&mt('No').'</label>'.
11945:                         '&nbsp;<label><input type="radio" name="archive_overwrite_'.$num.'" '.
11946:                         'value="1" />'.&mt('Yes').'</label>'.
11947:                         '<input type="hidden" name="archive_overwrite_name_'.$num.'" value="'.$item->[0].'" /></td>'."\n".
11948:                         '<td>'.$item->[0].'</td>';
11949:                     if ($item->[2]) {
11950:                         $duplicates .= '<td>'.&mt('Directory').'</td>';
11951:                     } else {
11952:                         $duplicates .= '<td>'.&mt('File').'</td>';
11953:                     }
11954:                     $duplicates .= '<td>'.$item->[3].'</td>'.
11955:                                    '<td>'.
11956:                                    &Apache::lonlocal::locallocaltime($item->[4]).
11957:                                    '</td>'.
11958:                                    &end_data_table_row();
11959:                     $num ++;
11960:                 }
11961:             }
11962:         }
11963:     }
11964:     my $itemcount;
11965:     if (@paths > 0) {
11966:         $itemcount = scalar(@paths);
11967:     } else {
11968:         $itemcount = 1;
11969:     }
11970:     if ($is_camtasia) {
11971:         $output .= $lt{'auto'}.'<br />'.
11972:                    '<span class="LC_nobreak">'.$lt{'proa'}.'<label>'.
11973:                    '<input type="radio" name="autoextract_camtasia" value="'.$is_camtasia.'" onclick="javascript:camtasiaToggle();" checked="checked" />'.
11974:                    $lt{'yes'}.'</label>&nbsp;<label>'.
11975:                    '<input type="radio" name="autoextract_camtasia" value="0" onclick="javascript:camtasiaToggle();" />'.
11976:                    $lt{'no'}.'</label></span><br />'.
11977:                    '<div id="camtasia_titles" style="display:block">'.
11978:                    &Apache::lonhtmlcommon::start_pick_box().
11979:                    &Apache::lonhtmlcommon::row_title($lt{'fold'}).
11980:                    '<input type="textbox" name="camtasia_foldername" value="'.$env{'form.comment'}.'" />'."\n".
11981:                    &Apache::lonhtmlcommon::row_closure().
11982:                    &Apache::lonhtmlcommon::row_title($lt{'movi'}).
11983:                    '<input type="textbox" name="camtasia_moviename" value="" />'."\n".
11984:                    &Apache::lonhtmlcommon::row_closure(1).
11985:                    &Apache::lonhtmlcommon::end_pick_box().
11986:                    '</div>';
11987:     }
11988:     $output .= 
11989:         '<input type="hidden" name="archive_overwrite_total" value="'.$num.'" />'.
11990:         '<input type="hidden" name="archive_itemcount" value="'.$itemcount.'" />'.
11991:         "\n";
11992:     if ($duplicates ne '') {
11993:         $output .= '<p><span class="LC_warning">'.
11994:                    &mt('Warning: decompression of the archive will overwrite the following items which already exist:').'</span><br />'.  
11995:                    &start_data_table().
11996:                    &start_data_table_header_row().
11997:                    '<th>'.&mt('Overwrite?').'</th>'.
11998:                    '<th>'.&mt('Name').'</th>'.
11999:                    '<th>'.&mt('Type').'</th>'.
12000:                    '<th>'.&mt('Size').'</th>'.
12001:                    '<th>'.&mt('Last modified').'</th>'.
12002:                    &end_data_table_header_row().
12003:                    $duplicates.
12004:                    &end_data_table().
12005:                    '</p>';
12006:     }
12007:     $output .= '<input type="hidden" name="archiveurl" value="'.$archiveurl.'" />'."\n";
12008:     if (ref($hiddenelements) eq 'HASH') {
12009:         foreach my $hidden (sort(keys(%{$hiddenelements}))) {
12010:             $output .= '<input type="hidden" name="'.$hidden.'" value="'.$hiddenelements->{$hidden}.'" />'."\n";
12011:         }
12012:     }
12013:     $output .= <<"END";
12014: <br />
12015: <input type="submit" name="decompress" value="$lt{'extr'}" />
12016: </form>
12017: $noextract
12018: END
12019:     return $output;
12020: }
12021: 
12022: sub decompression_utility {
12023:     my ($program) = @_;
12024:     my @utilities = ('tar','gunzip','bunzip2','unzip'); 
12025:     my $location;
12026:     if (grep(/^\Q$program\E$/,@utilities)) { 
12027:         foreach my $dir ('/bin/','/usr/bin/','/usr/local/bin/','/sbin/',
12028:                          '/usr/sbin/') {
12029:             if (-x $dir.$program) {
12030:                 $location = $dir.$program;
12031:                 last;
12032:             }
12033:         }
12034:     }
12035:     return $location;
12036: }
12037: 
12038: sub list_archive_contents {
12039:     my ($file,$pathsref) = @_;
12040:     my (@cmd,$output);
12041:     my $needsregexp;
12042:     if ($file =~ /\.zip$/) {
12043:         @cmd = (&decompression_utility('unzip'),"-l");
12044:         $needsregexp = 1;
12045:     } elsif (($file =~ m/\.tar\.gz$/) ||
12046:              ($file =~ /\.tgz$/)) {
12047:         @cmd = (&decompression_utility('tar'),"-ztf");
12048:     } elsif ($file =~ /\.tar\.bz2$/) {
12049:         @cmd = (&decompression_utility('tar'),"-jtf");
12050:     } elsif ($file =~ m|\.tar$|) {
12051:         @cmd = (&decompression_utility('tar'),"-tf");
12052:     }
12053:     if (@cmd) {
12054:         undef($!);
12055:         undef($@);
12056:         if (open(my $fh,"-|", @cmd, $file)) {
12057:             while (my $line = <$fh>) {
12058:                 $output .= $line;
12059:                 chomp($line);
12060:                 my $item;
12061:                 if ($needsregexp) {
12062:                     ($item) = ($line =~ /^\s*\d+\s+[\d\-]+\s+[\d:]+\s*(.+)$/); 
12063:                 } else {
12064:                     $item = $line;
12065:                 }
12066:                 if ($item ne '') {
12067:                     unless (grep(/^\Q$item\E$/,@{$pathsref})) {
12068:                         push(@{$pathsref},$item);
12069:                     } 
12070:                 }
12071:             }
12072:             close($fh);
12073:         }
12074:     }
12075:     return $output;
12076: }
12077: 
12078: sub decompress_uploaded_file {
12079:     my ($file,$dir) = @_;
12080:     &Apache::lonnet::appenv({'cgi.file' => $file});
12081:     &Apache::lonnet::appenv({'cgi.dir' => $dir});
12082:     my $result = &Apache::lonnet::ssi_body('/cgi-bin/decompress.pl');
12083:     my ($handle) = ($env{'user.environment'} =~m{/([^/]+)\.id$});
12084:     my $lonidsdir = $Apache::lonnet::perlvar{'lonIDsDir'};
12085:     &Apache::lonnet::transfer_profile_to_env($lonidsdir,$handle,1);
12086:     my $decompressed = $env{'cgi.decompressed'};
12087:     &Apache::lonnet::delenv('cgi.file');
12088:     &Apache::lonnet::delenv('cgi.dir');
12089:     &Apache::lonnet::delenv('cgi.decompressed');
12090:     return ($decompressed,$result);
12091: }
12092: 
12093: sub process_decompression {
12094:     my ($docudom,$docuname,$file,$destination,$dir_root,$hiddenelem) = @_;
12095:     unless (($dir_root eq '/userfiles') && ($destination =~ m{^(docs|supplemental)/(default|\d+)/\d+$})) {
12096:         return '<p class="LC_error">'.&mt('Not extracted.').'<br />'.
12097:                &mt('Unexpected file path.').'</p>'."\n";
12098:     }
12099:     unless (($docudom =~ /^$match_domain$/) && ($docuname =~ /^$match_courseid$/)) {
12100:         return '<p class="LC_error">'.&mt('Not extracted.').'<br />'.
12101:                &mt('Unexpected course context.').'</p>'."\n";
12102:     }
12103:     unless ($file eq &Apache::lonnet::clean_filename($file)) {
12104:         return '<p class="LC_error">'.&mt('Not extracted.').'<br />'.
12105:                &mt('Filename contained unexpected characters.').'</p>'."\n";
12106:     }
12107:     my ($dir,$error,$warning,$output);
12108:     if ($file !~ /\.(zip|tar|bz2|gz|tar.gz|tar.bz2|tgz)$/i) {
12109:         $error = &mt('Filename not a supported archive file type.').
12110:                  '<br />'.&mt('Filename should end with one of: [_1].',
12111:                               '.zip, .tar, .bz2, .gz, .tar.gz, .tar.bz2, .tgz');
12112:     } else {
12113:         my $docuhome = &Apache::lonnet::homeserver($docuname,$docudom);
12114:         if ($docuhome eq 'no_host') {
12115:             $error = &mt('Could not determine home server for course.');
12116:         } else {
12117:             my @ids=&Apache::lonnet::current_machine_ids();
12118:             my $currdir = "$dir_root/$destination";
12119:             if (grep(/^\Q$docuhome\E$/,@ids)) {
12120:                 $dir = &LONCAPA::propath($docudom,$docuname).
12121:                        "$dir_root/$destination";
12122:             } else {
12123:                 $dir = $Apache::lonnet::perlvar{'lonDocRoot'}.
12124:                        "$dir_root/$docudom/$docuname/$destination";
12125:                 unless (&Apache::lonnet::repcopy_userfile("$dir/$file") eq 'ok') {
12126:                     $error = &mt('Archive file not found.');
12127:                 }
12128:             }
12129:             my (@to_overwrite,@to_skip);
12130:             if ($env{'form.archive_overwrite_total'} > 0) {
12131:                 my $total = $env{'form.archive_overwrite_total'};
12132:                 for (my $i=0; $i<$total; $i++) {
12133:                     if ($env{'form.archive_overwrite_'.$i} == 1) {
12134:                         push(@to_overwrite,$env{'form.archive_overwrite_name_'.$i});
12135:                     } elsif ($env{'form.archive_overwrite_'.$i} == 0) {
12136:                         push(@to_skip,$env{'form.archive_overwrite_name_'.$i});
12137:                     }
12138:                 }
12139:             }
12140:             my $numskip = scalar(@to_skip);
12141:             my $numoverwrite = scalar(@to_overwrite);
12142:             if (($numskip) && (!$numoverwrite)) {
12143:                 $warning = &mt('All items in the archive file already exist, and no overwriting of existing files has been requested.');         
12144:             } elsif ($dir eq '') {
12145:                 $error = &mt('Directory containing archive file unavailable.');
12146:             } elsif (!$error) {
12147:                 my ($decompressed,$display);
12148:                 if (($numskip) || ($numoverwrite)) {
12149:                     my $tempdir = time.'_'.$$.int(rand(10000));
12150:                     mkdir("$dir/$tempdir",0755);
12151:                     if (&File::Copy::move("$dir/$file","$dir/$tempdir/$file")) {
12152:                         ($decompressed,$display) =
12153:                             &decompress_uploaded_file($file,"$dir/$tempdir");
12154:                         foreach my $item (@to_skip) {
12155:                             if (($item ne '') && ($item !~ /\.\./)) {
12156:                                 if (-f "$dir/$tempdir/$item") {
12157:                                     unlink("$dir/$tempdir/$item");
12158:                                 } elsif (-d "$dir/$tempdir/$item") {
12159:                                     &File::Path::remove_tree("$dir/$tempdir/$item",{ safe => 1 });
12160:                                 }
12161:                             }
12162:                         }
12163:                         foreach my $item (@to_overwrite) {
12164:                             if ((-e "$dir/$tempdir/$item") && (-e "$dir/$item")) {
12165:                                 if (($item ne '') && ($item !~ /\.\./)) {
12166:                                     if (-f "$dir/$item") {
12167:                                         unlink("$dir/$item");
12168:                                     } elsif (-d "$dir/$item") {
12169:                                         &File::Path::remove_tree("$dir/$item",{ safe => 1 });
12170:                                     }
12171:                                     &File::Copy::move("$dir/$tempdir/$item","$dir/$item");
12172:                                 }
12173:                             }
12174:                         }
12175:                         if (&File::Copy::move("$dir/$tempdir/$file","$dir/$file")) {
12176:                             &File::Path::remove_tree("$dir/$tempdir",{ safe => 1 });
12177:                         }
12178:                     }
12179:                 } else {
12180:                     ($decompressed,$display) = 
12181:                         &decompress_uploaded_file($file,$dir);
12182:                 }
12183:                 if ($decompressed eq 'ok') {
12184:                     $output = '<p class="LC_info">'.
12185:                               &mt('Files extracted successfully from archive.').
12186:                               '</p>'."\n";
12187:                     my ($warning,$result,@contents);
12188:                     my ($newdirlistref,$newlisterror) =
12189:                         &Apache::lonnet::dirlist($currdir,$docudom,
12190:                                                  $docuname,1);
12191:                     my (%is_dir,%changes,@newitems);
12192:                     my $dirptr = 16384;
12193:                     if (ref($newdirlistref) eq 'ARRAY') {
12194:                         foreach my $dir_line (@{$newdirlistref}) {
12195:                             my ($item,undef,undef,$testdir)=split(/\&/,$dir_line,5);
12196:                             unless (($item =~ /^\.+$/) || ($item eq $file) || 
12197:                                     ((@to_skip > 0) && (grep(/^\Q$item\E$/,@to_skip)))) {
12198:                                 push(@newitems,$item);
12199:                                 if ($dirptr&$testdir) {
12200:                                     $is_dir{$item} = 1;
12201:                                 }
12202:                                 $changes{$item} = 1;
12203:                             }
12204:                         }
12205:                     }
12206:                     if (keys(%changes) > 0) {
12207:                         foreach my $item (sort(@newitems)) {
12208:                             if ($changes{$item}) {
12209:                                 push(@contents,$item);
12210:                             }
12211:                         }
12212:                     }
12213:                     if (@contents > 0) {
12214:                         my $wantform;
12215:                         unless ($env{'form.autoextract_camtasia'}) {
12216:                             $wantform = 1;
12217:                         }
12218:                         my (%children,%parent,%dirorder,%titles);
12219:                         my ($count,$datatable) = &get_extracted($docudom,$docuname,
12220:                                                                 $currdir,\%is_dir,
12221:                                                                 \%children,\%parent,
12222:                                                                 \@contents,\%dirorder,
12223:                                                                 \%titles,$wantform);
12224:                         if ($datatable ne '') {
12225:                             $output .= &archive_options_form('decompressed',$datatable,
12226:                                                              $count,$hiddenelem);
12227:                             my $startcount = 6;
12228:                             $output .= &archive_javascript($startcount,$count,
12229:                                                            \%titles,\%children);
12230:                         }
12231:                         if ($env{'form.autoextract_camtasia'}) {
12232:                             my $version = $env{'form.autoextract_camtasia'};
12233:                             my %displayed;
12234:                             my $total = 1;
12235:                             $env{'form.archive_directory'} = [];
12236:                             foreach my $i (sort { $a <=> $b } keys(%dirorder)) {
12237:                                 my $path = join('/',map { $titles{$_}; } @{$dirorder{$i}});
12238:                                 $path =~ s{/$}{};
12239:                                 my $item;
12240:                                 if ($path ne '') {
12241:                                     $item = "$path/$titles{$i}";
12242:                                 } else {
12243:                                     $item = $titles{$i};
12244:                                 }
12245:                                 $env{'form.archive_content_'.$i} = "$dir_root/$destination/$item";
12246:                                 if ($item eq $contents[0]) {
12247:                                     push(@{$env{'form.archive_directory'}},$i);
12248:                                     $env{'form.archive_'.$i} = 'display';
12249:                                     $env{'form.archive_title_'.$i} = $env{'form.camtasia_foldername'};
12250:                                     $displayed{'folder'} = $i;
12251:                                 } elsif ((($item eq "$contents[0]/index.html") && ($version == 6)) ||
12252:                                          (($item eq "$contents[0]/$contents[0]".'.html') && ($version == 8))) {
12253:                                     $env{'form.archive_'.$i} = 'display';
12254:                                     $env{'form.archive_title_'.$i} = $env{'form.camtasia_moviename'};
12255:                                     $displayed{'web'} = $i;
12256:                                 } else {
12257:                                     if ((($item eq "$contents[0]/media") && ($version == 6)) ||
12258:                                         ((($item eq "$contents[0]/scripts") || ($item eq "$contents[0]/skins") ||
12259:                                              ($item eq "$contents[0]/skins/express_show")) && ($version == 8))) {
12260:                                         push(@{$env{'form.archive_directory'}},$i);
12261:                                     }
12262:                                     $env{'form.archive_'.$i} = 'dependency';
12263:                                 }
12264:                                 $total ++;
12265:                             }
12266:                             for (my $i=1; $i<$total; $i++) {
12267:                                 next if ($i == $displayed{'web'});
12268:                                 next if ($i == $displayed{'folder'});
12269:                                 $env{'form.archive_dependent_on_'.$i} = $displayed{'web'};
12270:                             }
12271:                             $env{'form.phase'} = 'decompress_cleanup';
12272:                             $env{'form.archivedelete'} = 1;
12273:                             $env{'form.archive_count'} = $total-1;
12274:                             $output .=
12275:                                 &process_extracted_files('coursedocs',$docudom,
12276:                                                          $docuname,$destination,
12277:                                                          $dir_root,$hiddenelem);
12278:                         }
12279:                     } else {
12280:                         $warning = &mt('No new items extracted from archive file.');
12281:                     }
12282:                 } else {
12283:                     $output = $display;
12284:                     $error = &mt('An error occurred during extraction from the archive file.');
12285:                 }
12286:             }
12287:         }
12288:     }
12289:     if ($error) {
12290:         $output .= '<p class="LC_error">'.&mt('Not extracted.').'<br />'.
12291:                    $error.'</p>'."\n";
12292:     }
12293:     if ($warning) {
12294:         $output .= '<p class="LC_warning">'.$warning.'</p>'."\n";
12295:     }
12296:     return $output;
12297: }
12298: 
12299: sub get_extracted {
12300:     my ($docudom,$docuname,$currdir,$is_dir,$children,$parent,$contents,$dirorder,
12301:         $titles,$wantform) = @_;
12302:     my $count = 0;
12303:     my $depth = 0;
12304:     my $datatable;
12305:     my @hierarchy;
12306:     return unless ((ref($is_dir) eq 'HASH') && (ref($children) eq 'HASH') &&
12307:                    (ref($parent) eq 'HASH') && (ref($contents) eq 'ARRAY') &&
12308:                    (ref($dirorder) eq 'HASH') && (ref($titles) eq 'HASH'));
12309:     foreach my $item (@{$contents}) {
12310:         $count ++;
12311:         @{$dirorder->{$count}} = @hierarchy;
12312:         $titles->{$count} = $item;
12313:         &archive_hierarchy($depth,$count,$parent,$children);
12314:         if ($wantform) {
12315:             $datatable .= &archive_row($is_dir->{$item},$item,
12316:                                        $currdir,$depth,$count);
12317:         }
12318:         if ($is_dir->{$item}) {
12319:             $depth ++;
12320:             push(@hierarchy,$count);
12321:             $parent->{$depth} = $count;
12322:             $datatable .=
12323:                 &recurse_extracted_archive("$currdir/$item",$docudom,$docuname,
12324:                                            \$depth,\$count,\@hierarchy,$dirorder,
12325:                                            $children,$parent,$titles,$wantform);
12326:             $depth --;
12327:             pop(@hierarchy);
12328:         }
12329:     }
12330:     return ($count,$datatable);
12331: }
12332: 
12333: sub recurse_extracted_archive {
12334:     my ($currdir,$docudom,$docuname,$depth,$count,$hierarchy,$dirorder,
12335:         $children,$parent,$titles,$wantform) = @_;
12336:     my $result='';
12337:     unless ((ref($depth)) && (ref($count)) && (ref($hierarchy) eq 'ARRAY') &&
12338:             (ref($children) eq 'HASH') && (ref($parent) eq 'HASH') &&
12339:             (ref($dirorder) eq 'HASH')) {
12340:         return $result;
12341:     }
12342:     my $dirptr = 16384;
12343:     my ($newdirlistref,$newlisterror) =
12344:         &Apache::lonnet::dirlist($currdir,$docudom,$docuname,1);
12345:     if (ref($newdirlistref) eq 'ARRAY') {
12346:         foreach my $dir_line (@{$newdirlistref}) {
12347:             my ($item,undef,undef,$testdir)=split(/\&/,$dir_line,5);
12348:             unless ($item =~ /^\.+$/) {
12349:                 $$count ++;
12350:                 @{$dirorder->{$$count}} = @{$hierarchy};
12351:                 $titles->{$$count} = $item;
12352:                 &archive_hierarchy($$depth,$$count,$parent,$children);
12353: 
12354:                 my $is_dir;
12355:                 if ($dirptr&$testdir) {
12356:                     $is_dir = 1;
12357:                 }
12358:                 if ($wantform) {
12359:                     $result .= &archive_row($is_dir,$item,$currdir,$$depth,$$count);
12360:                 }
12361:                 if ($is_dir) {
12362:                     $$depth ++;
12363:                     push(@{$hierarchy},$$count);
12364:                     $parent->{$$depth} = $$count;
12365:                     $result .=
12366:                         &recurse_extracted_archive("$currdir/$item",$docudom,
12367:                                                    $docuname,$depth,$count,
12368:                                                    $hierarchy,$dirorder,$children,
12369:                                                    $parent,$titles,$wantform);
12370:                     $$depth --;
12371:                     pop(@{$hierarchy});
12372:                 }
12373:             }
12374:         }
12375:     }
12376:     return $result;
12377: }
12378: 
12379: sub archive_hierarchy {
12380:     my ($depth,$count,$parent,$children) =@_;
12381:     if ((ref($parent) eq 'HASH') && (ref($children) eq 'HASH')) {
12382:         if (exists($parent->{$depth})) {
12383:              $children->{$parent->{$depth}} .= $count.':';
12384:         }
12385:     }
12386:     return;
12387: }
12388: 
12389: sub archive_row {
12390:     my ($is_dir,$item,$currdir,$depth,$count) = @_;
12391:     my ($name) = ($item =~ m{([^/]+)$});
12392:     my %choices = &Apache::lonlocal::texthash (
12393:                                        'display'    => 'Add as file',
12394:                                        'dependency' => 'Include as dependency',
12395:                                        'discard'    => 'Discard',
12396:                                       );
12397:     if ($is_dir) {
12398:         $choices{'display'} = &mt('Add as folder'); 
12399:     }
12400:     my $output = &start_data_table_row().'<td align="right">'.$count.'</td>'."\n";
12401:     my $offset = 0;
12402:     foreach my $action ('display','dependency','discard') {
12403:         $offset ++;
12404:         if ($action ne 'display') {
12405:             $offset ++;
12406:         }  
12407:         $output .= '<td><span class="LC_nobreak">'.
12408:                    '<label><input type="radio" name="archive_'.$count.
12409:                    '" id="archive_'.$action.'_'.$count.'" value="'.$action.'"';
12410:         my $text = $choices{$action};
12411:         if ($is_dir) {
12412:             $output .= ' onclick="javascript:propagateCheck(this.form,'."'$count'".');"';
12413:             if ($action eq 'display') {
12414:                 $text = &mt('Add as folder');
12415:             }
12416:         } else {
12417:             $output .= ' onclick="javascript:dependencyCheck(this.form,'."$count,$offset".');"';
12418: 
12419:         }
12420:         $output .= ' />&nbsp;'.$choices{$action}.'</label></span>';
12421:         if ($action eq 'dependency') {
12422:             $output .= '<div id="arc_depon_'.$count.'" style="display:none;">'."\n".
12423:                        &mt('Used by:').'&nbsp;<select name="archive_dependent_on_'.$count.'" '.
12424:                        'onchange="propagateSelect(this.form,'."$count,$offset".')">'."\n".
12425:                        '<option value=""></option>'."\n".
12426:                        '</select>'."\n".
12427:                        '</div>';
12428:         } elsif ($action eq 'display') {
12429:             $output .= '<div id="arc_title_'.$count.'" style="display:none;">'."\n".
12430:                        &mt('Title:').'&nbsp;<input type="text" name="archive_title_'.$count.'" id="archive_title_'.$count.'" />'."\n".
12431:                        '</div>';
12432:         }
12433:         $output .= '</td>';
12434:     }
12435:     $output .= '<td><input type="hidden" name="archive_content_'.$count.'" value="'.
12436:                &HTML::Entities::encode("$currdir/$item",'"<>&').'" />'.('&nbsp;' x 2);
12437:     for (my $i=0; $i<$depth; $i++) {
12438:         $output .= ('<img src="/adm/lonIcons/whitespace1.gif" class="LC_docs_spacer" alt="" />' x2)."\n";
12439:     }
12440:     if ($is_dir) {
12441:         $output .= '<img src="/adm/lonIcons/navmap.folder.open.gif" alt="" />&nbsp;'."\n".
12442:                    '<input type="hidden" name="archive_directory" value="'.$count.'" />'."\n";
12443:     } else {
12444:         $output .= '<input type="hidden" name="archive_file" value="'.$count.'" />'."\n";
12445:     }
12446:     $output .= '&nbsp;'.$name.'</td>'."\n".
12447:                &end_data_table_row();
12448:     return $output;
12449: }
12450: 
12451: sub archive_options_form {
12452:     my ($form,$display,$count,$hiddenelem) = @_;
12453:     my %lt = &Apache::lonlocal::texthash(
12454:                perm => 'Permanently remove archive file?',
12455:                hows => 'How should each extracted item be incorporated in the course?',
12456:                cont => 'Content actions for all',
12457:                addf => 'Add as folder/file',
12458:                incd => 'Include as dependency for a displayed file',
12459:                disc => 'Discard',
12460:                no   => 'No',
12461:                yes  => 'Yes',
12462:                save => 'Save',
12463:     );
12464:     my $output = <<"END";
12465: <form name="$form" method="post" action="">
12466: <p><span class="LC_nobreak">$lt{'perm'}&nbsp;
12467: <label>
12468:   <input type="radio" name="archivedelete" value="0" checked="checked" />$lt{'no'}
12469: </label>
12470: &nbsp;
12471: <label>
12472:   <input type="radio" name="archivedelete" value="1" />$lt{'yes'}</label>
12473: </span>
12474: </p>
12475: <input type="hidden" name="phase" value="decompress_cleanup" />
12476: <br />$lt{'hows'}
12477: <div class="LC_columnSection">
12478:   <fieldset>
12479:     <legend>$lt{'cont'}</legend>
12480:     <input type="button" value="$lt{'addf'}" onclick="javascript:checkAll(document.$form,'display');" /> 
12481:     &nbsp;&nbsp;<input type="button" value="$lt{'incd'}" onclick="javascript:checkAll(document.$form,'dependency');" />
12482:     &nbsp;&nbsp;<input type="button" value="$lt{'disc'}" onclick="javascript:checkAll(document.$form,'discard');" />
12483:   </fieldset>
12484: </div>
12485: END
12486:     return $output.
12487:            &start_data_table()."\n".
12488:            $display."\n".
12489:            &end_data_table()."\n".
12490:            '<input type="hidden" name="archive_count" value="'.$count.'" />'.
12491:            $hiddenelem.
12492:            '<br /><input type="submit" name="archive_submit" value="'.$lt{'save'}.'" />'.
12493:            '</form>';
12494: }
12495: 
12496: sub archive_javascript {
12497:     my ($startcount,$numitems,$titles,$children) = @_;
12498:     return unless ((ref($titles) eq 'HASH') && (ref($children) eq 'HASH'));
12499:     my $maintitle = $env{'form.comment'};
12500:     my $scripttag = <<START;
12501: <script type="text/javascript">
12502: // <![CDATA[
12503: 
12504: function checkAll(form,prefix) {
12505:     var idstr =  new RegExp("^archive_"+prefix+"_\\\\d+\$");
12506:     for (var i=0; i < form.elements.length; i++) {
12507:         var id = form.elements[i].id;
12508:         if ((id != '') && (id != undefined)) {
12509:             if (idstr.test(id)) {
12510:                 if (form.elements[i].type == 'radio') {
12511:                     form.elements[i].checked = true;
12512:                     var nostart = i-$startcount;
12513:                     var offset = nostart%7;
12514:                     var count = (nostart-offset)/7;    
12515:                     dependencyCheck(form,count,offset);
12516:                 }
12517:             }
12518:         }
12519:     }
12520: }
12521: 
12522: function propagateCheck(form,count) {
12523:     if (count > 0) {
12524:         var startelement = $startcount + ((count-1) * 7);
12525:         for (var j=1; j<6; j++) {
12526:             if ((j != 2) && (j != 4)) {
12527:                 var item = startelement + j; 
12528:                 if (form.elements[item].type == 'radio') {
12529:                     if (form.elements[item].checked) {
12530:                         containerCheck(form,count,j);
12531:                         break;
12532:                     }
12533:                 }
12534:             }
12535:         }
12536:     }
12537: }
12538: 
12539: numitems = $numitems
12540: var titles = new Array(numitems);
12541: var parents = new Array(numitems);
12542: for (var i=0; i<numitems; i++) {
12543:     parents[i] = new Array;
12544: }
12545: var maintitle = '$maintitle';
12546: 
12547: START
12548: 
12549:     foreach my $container (sort { $a <=> $b } (keys(%{$children}))) {
12550:         my @contents = split(/:/,$children->{$container});
12551:         for (my $i=0; $i<@contents; $i ++) {
12552:             $scripttag .= 'parents['.$container.']['.$i.'] = '.$contents[$i]."\n";
12553:         }
12554:     }
12555: 
12556:     foreach my $key (sort { $a <=> $b } (keys(%{$titles}))) {
12557:         $scripttag .= "titles[$key] = '".$titles->{$key}."';\n";
12558:     }
12559: 
12560:     $scripttag .= <<END;
12561: 
12562: function containerCheck(form,count,offset) {
12563:     if (count > 0) {
12564:         dependencyCheck(form,count,offset);
12565:         var item = (offset+$startcount)+7*(count-1);
12566:         form.elements[item].checked = true;
12567:         if(Object.prototype.toString.call(parents[count]) === '[object Array]') {
12568:             if (parents[count].length > 0) {
12569:                 for (var j=0; j<parents[count].length; j++) {
12570:                     containerCheck(form,parents[count][j],offset);
12571:                 }
12572:             }
12573:         }
12574:     }
12575: }
12576: 
12577: function dependencyCheck(form,count,offset) {
12578:     if (count > 0) {
12579:         var chosen = (offset+$startcount)+7*(count-1);
12580:         var depitem = $startcount + ((count-1) * 7) + 4;
12581:         var currtype = form.elements[depitem].type;
12582:         if (form.elements[chosen].value == 'dependency') {
12583:             document.getElementById('arc_depon_'+count).style.display='block'; 
12584:             form.elements[depitem].options.length = 0;
12585:             form.elements[depitem].options[0] = new Option('Select','',true,true);
12586:             for (var i=1; i<=numitems; i++) {
12587:                 if (i == count) {
12588:                     continue;
12589:                 }
12590:                 var startelement = $startcount + (i-1) * 7;
12591:                 for (var j=1; j<6; j++) {
12592:                     if ((j != 2) && (j!= 4)) {
12593:                         var item = startelement + j;
12594:                         if (form.elements[item].type == 'radio') {
12595:                             if (form.elements[item].checked) {
12596:                                 if (form.elements[item].value == 'display') {
12597:                                     var n = form.elements[depitem].options.length;
12598:                                     form.elements[depitem].options[n] = new Option(titles[i],i,false,false);
12599:                                 }
12600:                             }
12601:                         }
12602:                     }
12603:                 }
12604:             }
12605:         } else {
12606:             document.getElementById('arc_depon_'+count).style.display='none';
12607:             form.elements[depitem].options.length = 0;
12608:             form.elements[depitem].options[0] = new Option('Select','',true,true);
12609:         }
12610:         titleCheck(form,count,offset);
12611:     }
12612: }
12613: 
12614: function propagateSelect(form,count,offset) {
12615:     if (count > 0) {
12616:         var item = (1+offset+$startcount)+7*(count-1);
12617:         var picked = form.elements[item].options[form.elements[item].selectedIndex].value; 
12618:         if (Object.prototype.toString.call(parents[count]) === '[object Array]') {
12619:             if (parents[count].length > 0) {
12620:                 for (var j=0; j<parents[count].length; j++) {
12621:                     containerSelect(form,parents[count][j],offset,picked);
12622:                 }
12623:             }
12624:         }
12625:     }
12626: }
12627: 
12628: function containerSelect(form,count,offset,picked) {
12629:     if (count > 0) {
12630:         var item = (offset+$startcount)+7*(count-1);
12631:         if (form.elements[item].type == 'radio') {
12632:             if (form.elements[item].value == 'dependency') {
12633:                 if (form.elements[item+1].type == 'select-one') {
12634:                     for (var i=0; i<form.elements[item+1].options.length; i++) {
12635:                         if (form.elements[item+1].options[i].value == picked) {
12636:                             form.elements[item+1].selectedIndex = i;
12637:                             break;
12638:                         }
12639:                     }
12640:                 }
12641:                 if (Object.prototype.toString.call(parents[count]) === '[object Array]') {
12642:                     if (parents[count].length > 0) {
12643:                         for (var j=0; j<parents[count].length; j++) {
12644:                             containerSelect(form,parents[count][j],offset,picked);
12645:                         }
12646:                     }
12647:                 }
12648:             }
12649:         }
12650:     }
12651: }
12652: 
12653: function titleCheck(form,count,offset) {
12654:     if (count > 0) {
12655:         var chosen = (offset+$startcount)+7*(count-1);
12656:         var depitem = $startcount + ((count-1) * 7) + 2;
12657:         var currtype = form.elements[depitem].type;
12658:         if (form.elements[chosen].value == 'display') {
12659:             document.getElementById('arc_title_'+count).style.display='block';
12660:             if ((count==1) && ((parents[count].length > 0) || (numitems == 1))) {
12661:                 document.getElementById('archive_title_'+count).value=maintitle;
12662:             }
12663:         } else {
12664:             document.getElementById('arc_title_'+count).style.display='none';
12665:             if (currtype == 'text') { 
12666:                 document.getElementById('archive_title_'+count).value='';
12667:             }
12668:         }
12669:     }
12670:     return;
12671: }
12672: 
12673: // ]]>
12674: </script>
12675: END
12676:     return $scripttag;
12677: }
12678: 
12679: sub process_extracted_files {
12680:     my ($context,$docudom,$docuname,$destination,$dir_root,$hiddenelem) = @_;
12681:     my $numitems = $env{'form.archive_count'};
12682:     return if ((!$numitems) || ($numitems =~ /\D/));
12683:     my @ids=&Apache::lonnet::current_machine_ids();
12684:     my ($prefix,$pathtocheck,$dir,$ishome,$error,$warning,%toplevelitems,%is_dir,
12685:         %folders,%containers,%mapinner,%prompttofetch);
12686:     my $docuhome = &Apache::lonnet::homeserver($docuname,$docudom);
12687:     if (grep(/^\Q$docuhome\E$/,@ids)) {
12688:         $prefix = &LONCAPA::propath($docudom,$docuname);
12689:         $pathtocheck = "$dir_root/$destination";
12690:         $dir = $dir_root;
12691:         $ishome = 1;
12692:     } else {
12693:         $prefix = $Apache::lonnet::perlvar{'lonDocRoot'};
12694:         $pathtocheck = "$dir_root/$docudom/$docuname/$destination";
12695:         $dir = "$dir_root/$docudom/$docuname";
12696:     }
12697:     my $currdir = "$dir_root/$destination";
12698:     (my $docstype,$mapinner{'0'}) = ($destination =~ m{^(docs|supplemental)/(\w+)/});
12699:     if ($env{'form.folderpath'}) {
12700:         my @items = split('&',$env{'form.folderpath'});
12701:         $folders{'0'} = $items[-2];
12702:         if ($env{'form.folderpath'} =~ /\:1$/) {
12703:             $containers{'0'}='page';
12704:         } else {
12705:             $containers{'0'}='sequence';
12706:         }
12707:     }
12708:     my @archdirs = &get_env_multiple('form.archive_directory');
12709:     if ($numitems) {
12710:         for (my $i=1; $i<=$numitems; $i++) {
12711:             my $path = $env{'form.archive_content_'.$i};
12712:             if ($path =~ m{^\Q$pathtocheck\E/([^/]+)$}) {
12713:                 my $item = $1;
12714:                 $toplevelitems{$item} = $i;
12715:                 if (grep(/^\Q$i\E$/,@archdirs)) {
12716:                     $is_dir{$item} = 1;
12717:                 }
12718:             }
12719:         }
12720:     }
12721:     my ($output,%children,%parent,%titles,%dirorder,$result);
12722:     if (keys(%toplevelitems) > 0) {
12723:         my @contents = sort(keys(%toplevelitems));
12724:         (my $count,undef) = &get_extracted($docudom,$docuname,$currdir,\%is_dir,\%children,
12725:                                            \%parent,\@contents,\%dirorder,\%titles);
12726:     }
12727:     my (%referrer,%orphaned,%todelete,%todeletedir,%newdest,%newseqid);
12728:     if ($numitems) {
12729:         for (my $i=1; $i<=$numitems; $i++) {
12730:             next if ($env{'form.archive_'.$i} eq 'dependency');
12731:             my $path = $env{'form.archive_content_'.$i};
12732:             if ($path =~ /^\Q$pathtocheck\E/) {
12733:                 if ($env{'form.archive_'.$i} eq 'discard') {
12734:                     if ($prefix ne '' && $path ne '') {
12735:                         if (-e $prefix.$path) {
12736:                             if ((@archdirs > 0) && 
12737:                                 (grep(/^\Q$i\E$/,@archdirs))) {
12738:                                 $todeletedir{$prefix.$path} = 1;
12739:                             } else {
12740:                                 $todelete{$prefix.$path} = 1;
12741:                             }
12742:                         }
12743:                     }
12744:                 } elsif ($env{'form.archive_'.$i} eq 'display') {
12745:                     my ($docstitle,$title,$url,$outer);
12746:                     ($title) = ($path =~ m{/([^/]+)$});
12747:                     $docstitle = $env{'form.archive_title_'.$i};
12748:                     if ($docstitle eq '') {
12749:                         $docstitle = $title;
12750:                     }
12751:                     $outer = 0;
12752:                     if (ref($dirorder{$i}) eq 'ARRAY') {
12753:                         if (@{$dirorder{$i}} > 0) {
12754:                             foreach my $item (reverse(@{$dirorder{$i}})) {
12755:                                 if ($env{'form.archive_'.$item} eq 'display') {
12756:                                     $outer = $item;
12757:                                     last;
12758:                                 }
12759:                             }
12760:                         }
12761:                     }
12762:                     my ($errtext,$fatal) = 
12763:                         &LONCAPA::map::mapread('/uploaded/'.$docudom.'/'.$docuname.
12764:                                                '/'.$folders{$outer}.'.'.
12765:                                                $containers{$outer});
12766:                     next if ($fatal);
12767:                     if ((@archdirs > 0) && (grep(/^\Q$i\E$/,@archdirs))) {
12768:                         if ($context eq 'coursedocs') {
12769:                             $mapinner{$i} = time;
12770:                             $folders{$i} = 'default_'.$mapinner{$i};
12771:                             $containers{$i} = 'sequence';
12772:                             my $url = '/uploaded/'.$docudom.'/'.$docuname.'/'.
12773:                                       $folders{$i}.'.'.$containers{$i};
12774:                             my $newidx = &LONCAPA::map::getresidx();
12775:                             $LONCAPA::map::resources[$newidx]=
12776:                                 $docstitle.':'.$url.':false:normal:res';
12777:                             push(@LONCAPA::map::order,$newidx);
12778:                             my ($outtext,$errtext) =
12779:                                 &LONCAPA::map::storemap('/uploaded/'.$docudom.'/'.
12780:                                                         $docuname.'/'.$folders{$outer}.
12781:                                                         '.'.$containers{$outer},1,1);
12782:                             $newseqid{$i} = $newidx;
12783:                             unless ($errtext) {
12784:                                 $result .=  '<li>'.&mt('Folder: [_1] added to course',
12785:                                                        &HTML::Entities::encode($docstitle,'<>&"')).
12786:                                             '</li>'."\n";
12787:                             }
12788:                         }
12789:                     } else {
12790:                         if ($context eq 'coursedocs') {
12791:                             my $newidx=&LONCAPA::map::getresidx();
12792:                             my $url = '/uploaded/'.$docudom.'/'.$docuname.'/'.
12793:                                       $docstype.'/'.$mapinner{$outer}.'/'.$newidx.'/'.
12794:                                       $title;
12795:                             if (($outer !~ /\D/) && ($mapinner{$outer} !~ /\D/) && ($newidx !~ /\D/)) {
12796:                                 if (!-e "$prefix$dir/$docstype/$mapinner{$outer}") {
12797:                                     mkdir("$prefix$dir/$docstype/$mapinner{$outer}",0755);
12798:                                 }
12799:                                 if (!-e "$prefix$dir/$docstype/$mapinner{$outer}/$newidx") {
12800:                                     mkdir("$prefix$dir/$docstype/$mapinner{$outer}/$newidx");
12801:                                 }
12802:                                 if (-e "$prefix$dir/$docstype/$mapinner{$outer}/$newidx") {
12803:                                     if (rename("$prefix$path","$prefix$dir/$docstype/$mapinner{$outer}/$newidx/$title")) {
12804:                                         $newdest{$i} = "$prefix$dir/$docstype/$mapinner{$outer}/$newidx";
12805:                                         unless ($ishome) {
12806:                                             my $fetch = "$newdest{$i}/$title";
12807:                                             $fetch =~ s/^\Q$prefix$dir\E//;
12808:                                             $prompttofetch{$fetch} = 1;
12809:                                         }
12810:                                     }
12811:                                 }
12812:                                 $LONCAPA::map::resources[$newidx]=
12813:                                     $docstitle.':'.$url.':false:normal:res';
12814:                                 push(@LONCAPA::map::order, $newidx);
12815:                                 my ($outtext,$errtext)=
12816:                                     &LONCAPA::map::storemap('/uploaded/'.$docudom.'/'.
12817:                                                             $docuname.'/'.$folders{$outer}.
12818:                                                             '.'.$containers{$outer},1,1);
12819:                                 unless ($errtext) {
12820:                                     if (-e "$prefix$dir/$docstype/$mapinner{$outer}/$newidx/$title") {
12821:                                         $result .= '<li>'.&mt('File: [_1] added to course',
12822:                                                               &HTML::Entities::encode($docstitle,'<>&"')).
12823:                                                    '</li>'."\n";
12824:                                     }
12825:                                 }
12826:                             } else {
12827:                                 $warning .= &mt('Item extracted from archive: [_1] has unexpected path.',
12828:                                                 &HTML::Entities::encode($path,'<>&"')).'<br />';
12829:                             }
12830:                         }
12831:                     }
12832:                 }
12833:             } else {
12834:                 $warning .= &mt('Item extracted from archive: [_1] has unexpected path.',
12835:                                 &HTML::Entities::encode($path,'<>&"')).'<br />';
12836:             }
12837:         }
12838:         for (my $i=1; $i<=$numitems; $i++) {
12839:             next unless ($env{'form.archive_'.$i} eq 'dependency');
12840:             my $path = $env{'form.archive_content_'.$i};
12841:             if ($path =~ /^\Q$pathtocheck\E/) {
12842:                 my ($title) = ($path =~ m{/([^/]+)$});
12843:                 $referrer{$i} = $env{'form.archive_dependent_on_'.$i};
12844:                 if ($env{'form.archive_'.$referrer{$i}} eq 'display') {
12845:                     if (ref($dirorder{$i}) eq 'ARRAY') {
12846:                         my ($itemidx,$fullpath,$relpath);
12847:                         if (ref($dirorder{$referrer{$i}}) eq 'ARRAY') {
12848:                             my $container = $dirorder{$referrer{$i}}->[-1];
12849:                             for (my $j=0; $j<@{$dirorder{$i}}; $j++) {
12850:                                 if ($dirorder{$i}->[$j] eq $container) {
12851:                                     $itemidx = $j;
12852:                                 }
12853:                             }
12854:                         }
12855:                         if ($itemidx eq '') {
12856:                             $itemidx =  0;
12857:                         }
12858:                         if (grep(/^\Q$referrer{$i}\E$/,@archdirs)) {
12859:                             if ($mapinner{$referrer{$i}}) {
12860:                                 $fullpath = "$prefix$dir/$docstype/$mapinner{$referrer{$i}}";
12861:                                 for (my $j=$itemidx; $j<@{$dirorder{$i}}; $j++) {
12862:                                     if (grep(/^\Q$dirorder{$i}->[$j]\E$/,@archdirs)) {
12863:                                         unless (defined($newseqid{$dirorder{$i}->[$j]})) {
12864:                                             $fullpath .= '/'.$titles{$dirorder{$i}->[$j]};
12865:                                             $relpath .= '/'.$titles{$dirorder{$i}->[$j]};
12866:                                             if (!-e $fullpath) {
12867:                                                 mkdir($fullpath,0755);
12868:                                             }
12869:                                         }
12870:                                     } else {
12871:                                         last;
12872:                                     }
12873:                                 }
12874:                             }
12875:                         } elsif ($newdest{$referrer{$i}}) {
12876:                             $fullpath = $newdest{$referrer{$i}};
12877:                             for (my $j=$itemidx; $j<@{$dirorder{$i}}; $j++) {
12878:                                 if ($env{'form.archive_'.$dirorder{$i}->[$j]} eq 'discard') {
12879:                                     $orphaned{$i} = $env{'form.archive_'.$dirorder{$i}->[$j]};
12880:                                     last;
12881:                                 } elsif (grep(/^\Q$dirorder{$i}->[$j]\E$/,@archdirs)) {
12882:                                     unless (defined($newseqid{$dirorder{$i}->[$j]})) {
12883:                                         $fullpath .= '/'.$titles{$dirorder{$i}->[$j]};
12884:                                         $relpath .= '/'.$titles{$dirorder{$i}->[$j]};
12885:                                         if (!-e $fullpath) {
12886:                                             mkdir($fullpath,0755);
12887:                                         }
12888:                                     }
12889:                                 } else {
12890:                                     last;
12891:                                 }
12892:                             }
12893:                         }
12894:                         if ($fullpath ne '') {
12895:                             if (-e "$prefix$path") {
12896:                                 unless (rename("$prefix$path","$fullpath/$title")) {
12897:                                      $warning .= &mt('Failed to rename dependency').'<br />';
12898:                                 }
12899:                             }
12900:                             if (-e "$fullpath/$title") {
12901:                                 my $showpath;
12902:                                 if ($relpath ne '') {
12903:                                     $showpath = "$relpath/$title";
12904:                                 } else {
12905:                                     $showpath = "/$title";
12906:                                 }
12907:                                 $result .= '<li>'.&mt('[_1] included as a dependency',
12908:                                                       &HTML::Entities::encode($showpath,'<>&"')).
12909:                                            '</li>'."\n";
12910:                             }
12911:                             unless ($ishome) {
12912:                                 my $fetch = "$fullpath/$title";
12913:                                 $fetch =~ s/^\Q$prefix$dir\E//;
12914:                                 $prompttofetch{$fetch} = 1;
12915:                             }
12916:                         }
12917:                     }
12918:                 } elsif ($env{'form.archive_'.$referrer{$i}} eq 'discard') {
12919:                     $warning .= &mt('[_1] is a dependency of [_2], which was discarded.',
12920:                                     &HTML::Entities::encode($path,'<>&"'),
12921:                                     &HTML::Entities::encode($env{'form.archive_content_'.$referrer{$i}},'<>&"')).
12922:                                 '<br />';
12923:                 }
12924:             } else {
12925:                 $warning .= &mt('Item extracted from archive: [_1] has unexpected path.',
12926:                                 &HTML::Entities::encode($path)).'<br />';
12927:             }
12928:         }
12929:         if (keys(%todelete)) {
12930:             foreach my $key (keys(%todelete)) {
12931:                 unlink($key);
12932:             }
12933:         }
12934:         if (keys(%todeletedir)) {
12935:             foreach my $key (keys(%todeletedir)) {
12936:                 rmdir($key);
12937:             }
12938:         }
12939:         foreach my $dir (sort(keys(%is_dir))) {
12940:             if (($pathtocheck ne '') && ($dir ne ''))  {
12941:                 &cleanup_empty_dirs($prefix."$pathtocheck/$dir");
12942:             }
12943:         }
12944:         if ($result ne '') {
12945:             $output .= '<ul>'."\n".
12946:                        $result."\n".
12947:                        '</ul>';
12948:         }
12949:         unless ($ishome) {
12950:             my $replicationfail;
12951:             foreach my $item (keys(%prompttofetch)) {
12952:                 my $fetchresult= &Apache::lonnet::reply('fetchuserfile:'.$item,$docuhome);
12953:                 unless ($fetchresult eq 'ok') {
12954:                     $replicationfail .= '<li>'.$item.'</li>'."\n";
12955:                 }
12956:             }
12957:             if ($replicationfail) {
12958:                 $output .= '<p class="LC_error">'.
12959:                            &mt('Course home server failed to retrieve:').'<ul>'.
12960:                            $replicationfail.
12961:                            '</ul></p>';
12962:             }
12963:         }
12964:     } else {
12965:         $warning = &mt('No items found in archive.');
12966:     }
12967:     if ($error) {
12968:         $output .= '<p class="LC_error">'.&mt('Not extracted.').'<br />'.
12969:                    $error.'</p>'."\n";
12970:     }
12971:     if ($warning) {
12972:         $output .= '<p class="LC_warning">'.$warning.'</p>'."\n";
12973:     }
12974:     return $output;
12975: }
12976: 
12977: sub cleanup_empty_dirs {
12978:     my ($path) = @_;
12979:     if (($path ne '') && (-d $path)) {
12980:         if (opendir(my $dirh,$path)) {
12981:             my @dircontents = grep(!/^\./,readdir($dirh));
12982:             my $numitems = 0;
12983:             foreach my $item (@dircontents) {
12984:                 if (-d "$path/$item") {
12985:                     &cleanup_empty_dirs("$path/$item");
12986:                     if (-e "$path/$item") {
12987:                         $numitems ++;
12988:                     }
12989:                 } else {
12990:                     $numitems ++;
12991:                 }
12992:             }
12993:             if ($numitems == 0) {
12994:                 rmdir($path);
12995:             }
12996:             closedir($dirh);
12997:         }
12998:     }
12999:     return;
13000: }
13001: 
13002: =pod
13003: 
13004: =item * &get_folder_hierarchy()
13005: 
13006: Provides hierarchy of names of folders/sub-folders containing the current
13007: item,
13008: 
13009: Inputs: 3
13010:      - $navmap - navmaps object
13011: 
13012:      - $map - url for map (either the trigger itself, or map containing
13013:                            the resource, which is the trigger).
13014: 
13015:      - $showitem - 1 => show title for map itself; 0 => do not show.
13016: 
13017: Outputs: 1 @pathitems - array of folder/subfolder names.
13018: 
13019: =cut
13020: 
13021: sub get_folder_hierarchy {
13022:     my ($navmap,$map,$showitem) = @_;
13023:     my @pathitems;
13024:     if (ref($navmap)) {
13025:         my $mapres = $navmap->getResourceByUrl($map);
13026:         if (ref($mapres)) {
13027:             my $pcslist = $mapres->map_hierarchy();
13028:             if ($pcslist ne '') {
13029:                 my @pcs = split(/,/,$pcslist);
13030:                 foreach my $pc (@pcs) {
13031:                     if ($pc == 1) {
13032:                         push(@pathitems,&mt('Main Content'));
13033:                     } else {
13034:                         my $res = $navmap->getByMapPc($pc);
13035:                         if (ref($res)) {
13036:                             my $title = $res->compTitle();
13037:                             $title =~ s/\W+/_/g;
13038:                             if ($title ne '') {
13039:                                 push(@pathitems,$title);
13040:                             }
13041:                         }
13042:                     }
13043:                 }
13044:             }
13045:             if ($showitem) {
13046:                 if ($mapres->{ID} eq '0.0') {
13047:                     push(@pathitems,&mt('Main Content'));
13048:                 } else {
13049:                     my $maptitle = $mapres->compTitle();
13050:                     $maptitle =~ s/\W+/_/g;
13051:                     if ($maptitle ne '') {
13052:                         push(@pathitems,$maptitle);
13053:                     }
13054:                 }
13055:             }
13056:         }
13057:     }
13058:     return @pathitems;
13059: }
13060: 
13061: =pod
13062: 
13063: =item * &get_turnedin_filepath()
13064: 
13065: Determines path in a user's portfolio file for storage of files uploaded
13066: to a specific essayresponse or dropbox item.
13067: 
13068: Inputs: 3 required + 1 optional.
13069: $symb is symb for resource, $uname and $udom are for current user (required).
13070: $caller is optional (can be "submission", if routine is called when storing
13071: an upoaded file when "Submit Answer" button was pressed).
13072: 
13073: Returns array containing $path and $multiresp. 
13074: $path is path in portfolio.  $multiresp is 1 if this resource contains more
13075: than one file upload item.  Callers of routine should append partid as a 
13076: subdirectory to $path in cases where $multiresp is 1.
13077: 
13078: Called by: homework/essayresponse.pm and homework/structuretags.pm
13079: 
13080: =cut
13081: 
13082: sub get_turnedin_filepath {
13083:     my ($symb,$uname,$udom,$caller) = @_;
13084:     my ($map,$resid,$resurl)=&Apache::lonnet::decode_symb($symb);
13085:     my $turnindir;
13086:     my %userhash = &Apache::lonnet::userenvironment($udom,$uname,'turnindir');
13087:     $turnindir = $userhash{'turnindir'};
13088:     my ($path,$multiresp);
13089:     if ($turnindir eq '') {
13090:         if ($caller eq 'submission') {
13091:             $turnindir = &mt('turned in');
13092:             $turnindir =~ s/\W+/_/g;
13093:             my %newhash = (
13094:                             'turnindir' => $turnindir,
13095:                           );
13096:             &Apache::lonnet::put('environment',\%newhash,$udom,$uname);
13097:         }
13098:     }
13099:     if ($turnindir ne '') {
13100:         $path = '/'.$turnindir.'/';
13101:         my ($multipart,$turnin,@pathitems);
13102:         my $navmap = Apache::lonnavmaps::navmap->new();
13103:         if (defined($navmap)) {
13104:             my $mapres = $navmap->getResourceByUrl($map);
13105:             if (ref($mapres)) {
13106:                 my $pcslist = $mapres->map_hierarchy();
13107:                 if ($pcslist ne '') {
13108:                     foreach my $pc (split(/,/,$pcslist)) {
13109:                         my $res = $navmap->getByMapPc($pc);
13110:                         if (ref($res)) {
13111:                             my $title = $res->compTitle();
13112:                             $title =~ s/\W+/_/g;
13113:                             if ($title ne '') {
13114:                                 if (($pc > 1) && (length($title) > 12)) {
13115:                                     $title = substr($title,0,12);
13116:                                 }
13117:                                 push(@pathitems,$title);
13118:                             }
13119:                         }
13120:                     }
13121:                 }
13122:                 my $maptitle = $mapres->compTitle();
13123:                 $maptitle =~ s/\W+/_/g;
13124:                 if ($maptitle ne '') {
13125:                     if (length($maptitle) > 12) {
13126:                         $maptitle = substr($maptitle,0,12);
13127:                     }
13128:                     push(@pathitems,$maptitle);
13129:                 }
13130:                 unless ($env{'request.state'} eq 'construct') {
13131:                     my $res = $navmap->getBySymb($symb);
13132:                     if (ref($res)) {
13133:                         my $partlist = $res->parts();
13134:                         my $totaluploads = 0;
13135:                         if (ref($partlist) eq 'ARRAY') {
13136:                             foreach my $part (@{$partlist}) {
13137:                                 my @types = $res->responseType($part);
13138:                                 my @ids = $res->responseIds($part);
13139:                                 for (my $i=0; $i < scalar(@ids); $i++) {
13140:                                     if ($types[$i] eq 'essay') {
13141:                                         my $partid = $part.'_'.$ids[$i];
13142:                                         if (&Apache::lonnet::EXT("resource.$partid.uploadedfiletypes") ne '') {
13143:                                             $totaluploads ++;
13144:                                         }
13145:                                     }
13146:                                 }
13147:                             }
13148:                             if ($totaluploads > 1) {
13149:                                 $multiresp = 1;
13150:                             }
13151:                         }
13152:                     }
13153:                 }
13154:             } else {
13155:                 return;
13156:             }
13157:         } else {
13158:             return;
13159:         }
13160:         my $restitle=&Apache::lonnet::gettitle($symb);
13161:         $restitle =~ s/\W+/_/g;
13162:         if ($restitle eq '') {
13163:             $restitle = ($resurl =~ m{/[^/]+$});
13164:             if ($restitle eq '') {
13165:                 $restitle = time;
13166:             }
13167:         }
13168:         if (length($restitle) > 12) {
13169:             $restitle = substr($restitle,0,12);
13170:         }
13171:         push(@pathitems,$restitle);
13172:         $path .= join('/',@pathitems);
13173:     }
13174:     return ($path,$multiresp);
13175: }
13176: 
13177: =pod
13178: 
13179: =back
13180: 
13181: =head1 CSV Upload/Handling functions
13182: 
13183: =over 4
13184: 
13185: =item * &upfile_store($r)
13186: 
13187: Store uploaded file, $r should be the HTTP Request object,
13188: needs $env{'form.upfile'}
13189: returns $datatoken to be put into hidden field
13190: 
13191: =cut
13192: 
13193: sub upfile_store {
13194:     my $r=shift;
13195:     $env{'form.upfile'}=~s/\r/\n/gs;
13196:     $env{'form.upfile'}=~s/\f/\n/gs;
13197:     $env{'form.upfile'}=~s/\n+/\n/gs;
13198:     $env{'form.upfile'}=~s/\n+$//gs;
13199: 
13200:     my $datatoken = &valid_datatoken($env{'user.name'}.'_'.$env{'user.domain'}.
13201: 	                             '_enroll_'.$env{'request.course.id'}.'_'.
13202:                                      time.'_'.$$);
13203:     return if ($datatoken eq '');
13204:     {
13205:         my $datafile = $r->dir_config('lonDaemons').
13206:                            '/tmp/'.$datatoken.'.tmp';
13207:         if ( open(my $fh,'>',$datafile) ) {
13208:             print $fh $env{'form.upfile'};
13209:             close($fh);
13210:         }
13211:     }
13212:     return $datatoken;
13213: }
13214: 
13215: =pod
13216: 
13217: =item * &load_tmp_file($r,$datatoken)
13218: 
13219: Load uploaded file from tmp, $r should be the HTTP Request object,
13220: $datatoken is the name to assign to the temporary file.
13221: sets $env{'form.upfile'} to the contents of the file
13222: 
13223: =cut
13224: 
13225: sub load_tmp_file {
13226:     my ($r,$datatoken) = @_;
13227:     return if ($datatoken eq '');
13228:     my @studentdata=();
13229:     {
13230:         my $studentfile = $r->dir_config('lonDaemons').
13231:                               '/tmp/'.$datatoken.'.tmp';
13232:         if ( open(my $fh,'<',$studentfile) ) {
13233:             @studentdata=<$fh>;
13234:             close($fh);
13235:         }
13236:     }
13237:     $env{'form.upfile'}=join('',@studentdata);
13238: }
13239: 
13240: sub valid_datatoken {
13241:     my ($datatoken) = @_;
13242:     if ($datatoken =~ /^$match_username\_$match_domain\_enroll_(|$match_domain\_$match_courseid)\_\d+_\d+$/) {
13243:         return $datatoken;
13244:     }
13245:     return;
13246: }
13247: 
13248: =pod
13249: 
13250: =item * &upfile_record_sep()
13251: 
13252: Separate uploaded file into records
13253: returns array of records,
13254: needs $env{'form.upfile'} and $env{'form.upfiletype'}
13255: 
13256: =cut
13257: 
13258: sub upfile_record_sep {
13259:     if ($env{'form.upfiletype'} eq 'xml') {
13260:     } else {
13261: 	my @records;
13262: 	foreach my $line (split(/\n/,$env{'form.upfile'})) {
13263: 	    if ($line=~/^\s*$/) { next; }
13264: 	    push(@records,$line);
13265: 	}
13266: 	return @records;
13267:     }
13268: }
13269: 
13270: =pod
13271: 
13272: =item * &record_sep($record)
13273: 
13274: Separate a record into fields $record should be an item from the upfile_record_sep(), needs $env{'form.upfiletype'}
13275: 
13276: =cut
13277: 
13278: sub takeleft {
13279:     my $index=shift;
13280:     return substr('0000'.$index,-4,4);
13281: }
13282: 
13283: sub record_sep {
13284:     my $record=shift;
13285:     my %components=();
13286:     if ($env{'form.upfiletype'} eq 'xml') {
13287:     } elsif ($env{'form.upfiletype'} eq 'space') {
13288:         my $i=0;
13289:         foreach my $field (split(/\s+/,$record)) {
13290:             $field=~s/^(\"|\')//;
13291:             $field=~s/(\"|\')$//;
13292:             $components{&takeleft($i)}=$field;
13293:             $i++;
13294:         }
13295:     } elsif ($env{'form.upfiletype'} eq 'tab') {
13296:         my $i=0;
13297:         foreach my $field (split(/\t/,$record)) {
13298:             $field=~s/^(\"|\')//;
13299:             $field=~s/(\"|\')$//;
13300:             $components{&takeleft($i)}=$field;
13301:             $i++;
13302:         }
13303:     } else {
13304:         my $separator=',';
13305:         if ($env{'form.upfiletype'} eq 'semisv') {
13306:             $separator=';';
13307:         }
13308:         my $i=0;
13309: # the character we are looking for to indicate the end of a quote or a record 
13310:         my $looking_for=$separator;
13311: # do not add the characters to the fields
13312:         my $ignore=0;
13313: # we just encountered a separator (or the beginning of the record)
13314:         my $just_found_separator=1;
13315: # store the field we are working on here
13316:         my $field='';
13317: # work our way through all characters in record
13318:         foreach my $character ($record=~/(.)/g) {
13319:             if ($character eq $looking_for) {
13320:                if ($character ne $separator) {
13321: # Found the end of a quote, again looking for separator
13322:                   $looking_for=$separator;
13323:                   $ignore=1;
13324:                } else {
13325: # Found a separator, store away what we got
13326:                   $components{&takeleft($i)}=$field;
13327: 	          $i++;
13328:                   $just_found_separator=1;
13329:                   $ignore=0;
13330:                   $field='';
13331:                }
13332:                next;
13333:             }
13334: # single or double quotation marks after a separator indicate beginning of a quote
13335: # we are now looking for the end of the quote and need to ignore separators
13336:             if ((($character eq '"') || ($character eq "'")) && ($just_found_separator))  {
13337:                $looking_for=$character;
13338:                next;
13339:             }
13340: # ignore would be true after we reached the end of a quote
13341:             if ($ignore) { next; }
13342:             if (($just_found_separator) && ($character=~/\s/)) { next; }
13343:             $field.=$character;
13344:             $just_found_separator=0; 
13345:         }
13346: # catch the very last entry, since we never encountered the separator
13347:         $components{&takeleft($i)}=$field;
13348:     }
13349:     return %components;
13350: }
13351: 
13352: ######################################################
13353: ######################################################
13354: 
13355: =pod
13356: 
13357: =item * &upfile_select_html()
13358: 
13359: Return HTML code to select a file from the users machine and specify 
13360: the file type.
13361: 
13362: =cut
13363: 
13364: ######################################################
13365: ######################################################
13366: sub upfile_select_html {
13367:     my %Types = (
13368:                  csv   => &mt('CSV (comma separated values, spreadsheet)'),
13369:                  semisv => &mt('Semicolon separated values'),
13370:                  space => &mt('Space separated'),
13371:                  tab   => &mt('Tabulator separated'),
13372: #                 xml   => &mt('HTML/XML'),
13373:                  );
13374:     my $Str = '<input type="file" name="upfile" size="50" />'.
13375:         '<br />'.&mt('Type').': <select name="upfiletype">';
13376:     foreach my $type (sort(keys(%Types))) {
13377:         $Str .= '<option value="'.$type.'" >'.$Types{$type}."</option>\n";
13378:     }
13379:     $Str .= "</select>\n";
13380:     return $Str;
13381: }
13382: 
13383: sub get_samples {
13384:     my ($records,$toget) = @_;
13385:     my @samples=({});
13386:     my $got=0;
13387:     foreach my $rec (@$records) {
13388: 	my %temp = &record_sep($rec);
13389: 	if (! grep(/\S/, values(%temp))) { next; }
13390: 	if (%temp) {
13391: 	    $samples[$got]=\%temp;
13392: 	    $got++;
13393: 	    if ($got == $toget) { last; }
13394: 	}
13395:     }
13396:     return \@samples;
13397: }
13398: 
13399: ######################################################
13400: ######################################################
13401: 
13402: =pod
13403: 
13404: =item * &csv_print_samples($r,$records)
13405: 
13406: Prints a table of sample values from each column uploaded $r is an
13407: Apache Request ref, $records is an arrayref from
13408: &Apache::loncommon::upfile_record_sep
13409: 
13410: =cut
13411: 
13412: ######################################################
13413: ######################################################
13414: sub csv_print_samples {
13415:     my ($r,$records) = @_;
13416:     my $samples = &get_samples($records,5);
13417: 
13418:     $r->print(&mt('Samples').'<br />'.&start_data_table().
13419:               &start_data_table_header_row());
13420:     foreach my $sample (sort({$a <=> $b} keys(%{ $samples->[0] }))) { 
13421:         $r->print('<th>'.&mt('Column [_1]',($sample+1)).'</th>'); }
13422:     $r->print(&end_data_table_header_row());
13423:     foreach my $hash (@$samples) {
13424: 	$r->print(&start_data_table_row());
13425: 	foreach my $sample (sort({$a <=> $b} keys(%{ $samples->[0] }))) {
13426: 	    $r->print('<td>');
13427: 	    if (defined($$hash{$sample})) { $r->print($$hash{$sample}); }
13428: 	    $r->print('</td>');
13429: 	}
13430: 	$r->print(&end_data_table_row());
13431:     }
13432:     $r->print(&end_data_table().'<br />'."\n");
13433: }
13434: 
13435: ######################################################
13436: ######################################################
13437: 
13438: =pod
13439: 
13440: =item * &csv_print_select_table($r,$records,$d)
13441: 
13442: Prints a table to create associations between values and table columns.
13443: 
13444: $r is an Apache Request ref,
13445: $records is an arrayref from &Apache::loncommon::upfile_record_sep,
13446: $d is an array of 2 element arrays (internal name, displayed name,defaultcol)
13447: 
13448: =cut
13449: 
13450: ######################################################
13451: ######################################################
13452: sub csv_print_select_table {
13453:     my ($r,$records,$d) = @_;
13454:     my $i=0;
13455:     my $samples = &get_samples($records,1);
13456:     $r->print(&mt('Associate columns with student attributes.')."\n".
13457: 	      &start_data_table().&start_data_table_header_row().
13458:               '<th>'.&mt('Attribute').'</th>'.
13459:               '<th>'.&mt('Column').'</th>'.
13460:               &end_data_table_header_row()."\n");
13461:     foreach my $array_ref (@$d) {
13462: 	my ($value,$display,$defaultcol)=@{ $array_ref };
13463: 	$r->print(&start_data_table_row().'<td>'.$display.'</td>');
13464: 
13465: 	$r->print('<td><select name="f'.$i.'"'.
13466: 		  ' onchange="javascript:flip(this.form,'.$i.');">');
13467: 	$r->print('<option value="none"></option>');
13468: 	foreach my $sample (sort({$a <=> $b} keys(%{ $samples->[0] }))) {
13469: 	    $r->print('<option value="'.$sample.'"'.
13470:                       ($sample eq $defaultcol ? ' selected="selected" ' : '').
13471:                       '>'.&mt('Column [_1]',($sample+1)).'</option>');
13472: 	}
13473: 	$r->print('</select></td>'.&end_data_table_row()."\n");
13474: 	$i++;
13475:     }
13476:     $r->print(&end_data_table());
13477:     $i--;
13478:     return $i;
13479: }
13480: 
13481: ######################################################
13482: ######################################################
13483: 
13484: =pod
13485: 
13486: =item * &csv_samples_select_table($r,$records,$d)
13487: 
13488: Prints a table of sample values from the upload and can make associate samples to internal names.
13489: 
13490: $r is an Apache Request ref,
13491: $records is an arrayref from &Apache::loncommon::upfile_record_sep,
13492: $d is an array of 2 element arrays (internal name, displayed name)
13493: 
13494: =cut
13495: 
13496: ######################################################
13497: ######################################################
13498: sub csv_samples_select_table {
13499:     my ($r,$records,$d) = @_;
13500:     my $i=0;
13501:     #
13502:     my $max_samples = 5;
13503:     my $samples = &get_samples($records,$max_samples);
13504:     $r->print(&start_data_table().
13505:               &start_data_table_header_row().'<th>'.
13506:               &mt('Field').'</th><th>'.&mt('Samples').'</th>'.
13507:               &end_data_table_header_row());
13508: 
13509:     foreach my $key (sort(keys(%{ $samples->[0] }))) {
13510: 	$r->print(&start_data_table_row().'<td><select name="f'.$i.'"'.
13511: 		  ' onchange="javascript:flip(this.form,'.$i.');">');
13512: 	foreach my $option (@$d) {
13513: 	    my ($value,$display,$defaultcol)=@{ $option };
13514: 	    $r->print('<option value="'.$value.'"'.
13515:                       ($i eq $defaultcol ? ' selected="selected" ':'').'>'.
13516:                       $display.'</option>');
13517: 	}
13518: 	$r->print('</select></td><td>');
13519: 	foreach my $line (0..($max_samples-1)) {
13520: 	    if (defined($samples->[$line]{$key})) { 
13521: 		$r->print($samples->[$line]{$key}."<br />\n"); 
13522: 	    }
13523: 	}
13524: 	$r->print('</td>'.&end_data_table_row());
13525: 	$i++;
13526:     }
13527:     $r->print(&end_data_table());
13528:     $i--;
13529:     return($i);
13530: }
13531: 
13532: ######################################################
13533: ######################################################
13534: 
13535: =pod
13536: 
13537: =item * &clean_excel_name($name)
13538: 
13539: Returns a replacement for $name which does not contain any illegal characters.
13540: 
13541: =cut
13542: 
13543: ######################################################
13544: ######################################################
13545: sub clean_excel_name {
13546:     my ($name) = @_;
13547:     $name =~ s/[:\*\?\/\\]//g;
13548:     if (length($name) > 31) {
13549:         $name = substr($name,0,31);
13550:     }
13551:     return $name;
13552: }
13553: 
13554: =pod
13555: 
13556: =item * &check_if_partid_hidden($id,$symb,$udom,$uname)
13557: 
13558: Returns either 1 or undef
13559: 
13560: 1 if the part is to be hidden, undef if it is to be shown
13561: 
13562: Arguments are:
13563: 
13564: $id the id of the part to be checked
13565: $symb, optional the symb of the resource to check
13566: $udom, optional the domain of the user to check for
13567: $uname, optional the username of the user to check for
13568: 
13569: =cut
13570: 
13571: sub check_if_partid_hidden {
13572:     my ($id,$symb,$udom,$uname) = @_;
13573:     my $hiddenparts=&Apache::lonnet::EXT('resource.0.hiddenparts',
13574: 					 $symb,$udom,$uname);
13575:     my $truth=1;
13576:     #if the string starts with !, then the list is the list to show not hide
13577:     if ($hiddenparts=~s/^\s*!//) { $truth=undef; }
13578:     my @hiddenlist=split(/,/,$hiddenparts);
13579:     foreach my $checkid (@hiddenlist) {
13580: 	if ($checkid =~ /^\s*\Q$id\E\s*$/) { return $truth; }
13581:     }
13582:     return !$truth;
13583: }
13584: 
13585: 
13586: ############################################################
13587: ############################################################
13588: 
13589: =pod
13590: 
13591: =back 
13592: 
13593: =head1 cgi-bin script and graphing routines
13594: 
13595: =over 4
13596: 
13597: =item * &get_cgi_id()
13598: 
13599: Inputs: none
13600: 
13601: Returns an id which can be used to pass environment variables
13602: to various cgi-bin scripts.  These environment variables will
13603: be removed from the users environment after a given time by
13604: the routine &Apache::lonnet::transfer_profile_to_env.
13605: 
13606: =cut
13607: 
13608: ############################################################
13609: ############################################################
13610: my $uniq=0;
13611: sub get_cgi_id {
13612:     $uniq=($uniq+1)%100000;
13613:     return (time.'_'.$$.'_'.$uniq);
13614: }
13615: 
13616: ############################################################
13617: ############################################################
13618: 
13619: =pod
13620: 
13621: =item * &DrawBarGraph()
13622: 
13623: Facilitates the plotting of data in a (stacked) bar graph.
13624: Puts plot definition data into the users environment in order for 
13625: graph.png to plot it.  Returns an <img> tag for the plot.
13626: The bars on the plot are labeled '1','2',...,'n'.
13627: 
13628: Inputs:
13629: 
13630: =over 4
13631: 
13632: =item $Title: string, the title of the plot
13633: 
13634: =item $xlabel: string, text describing the X-axis of the plot
13635: 
13636: =item $ylabel: string, text describing the Y-axis of the plot
13637: 
13638: =item $Max: scalar, the maximum Y value to use in the plot
13639: If $Max is < any data point, the graph will not be rendered.
13640: 
13641: =item $colors: array ref holding the colors to be used for the data sets when
13642: they are plotted.  If undefined, default values will be used.
13643: 
13644: =item $labels: array ref holding the labels to use on the x-axis for the bars.
13645: 
13646: =item @Values: An array of array references.  Each array reference holds data
13647: to be plotted in a stacked bar chart.
13648: 
13649: =item If the final element of @Values is a hash reference the key/value
13650: pairs will be added to the graph definition.
13651: 
13652: =back
13653: 
13654: Returns:
13655: 
13656: An <img> tag which references graph.png and the appropriate identifying
13657: information for the plot.
13658: 
13659: =cut
13660: 
13661: ############################################################
13662: ############################################################
13663: sub DrawBarGraph {
13664:     my ($Title,$xlabel,$ylabel,$Max,$colors,$labels,@Values)=@_;
13665:     #
13666:     if (! defined($colors)) {
13667:         $colors = ['#33ff00', 
13668:                   '#0033cc', '#990000', '#aaaa66', '#663399', '#ff9933',
13669:                   '#66ccff', '#ff9999', '#cccc33', '#660000', '#33cc66',
13670:                   ]; 
13671:     }
13672:     my $extra_settings = {};
13673:     if (ref($Values[-1]) eq 'HASH') {
13674:         $extra_settings = pop(@Values);
13675:     }
13676:     #
13677:     my $identifier = &get_cgi_id();
13678:     my $id = 'cgi.'.$identifier;        
13679:     if (! @Values || ref($Values[0]) ne 'ARRAY') {
13680:         return '';
13681:     }
13682:     #
13683:     my @Labels;
13684:     if (defined($labels)) {
13685:         @Labels = @$labels;
13686:     } else {
13687:         for (my $i=0;$i<@{$Values[0]};$i++) {
13688:             push(@Labels,$i+1);
13689:         }
13690:     }
13691:     #
13692:     my $NumBars = scalar(@{$Values[0]});
13693:     if ($NumBars < scalar(@Labels)) { $NumBars = scalar(@Labels); }
13694:     my %ValuesHash;
13695:     my $NumSets=1;
13696:     foreach my $array (@Values) {
13697:         next if (! ref($array));
13698:         $ValuesHash{$id.'.data.'.$NumSets++} = 
13699:             join(',',@$array);
13700:     }
13701:     #
13702:     my ($height,$width,$xskip,$bar_width) = (200,120,1,15);
13703:     if ($NumBars < 3) {
13704:         $width = 120+$NumBars*32;
13705:         $xskip = 1;
13706:         $bar_width = 30;
13707:     } elsif ($NumBars < 5) {
13708:         $width = 120+$NumBars*20;
13709:         $xskip = 1;
13710:         $bar_width = 20;
13711:     } elsif ($NumBars < 10) {
13712:         $width = 120+$NumBars*15;
13713:         $xskip = 1;
13714:         $bar_width = 15;
13715:     } elsif ($NumBars <= 25) {
13716:         $width = 120+$NumBars*11;
13717:         $xskip = 5;
13718:         $bar_width = 8;
13719:     } elsif ($NumBars <= 50) {
13720:         $width = 120+$NumBars*8;
13721:         $xskip = 5;
13722:         $bar_width = 4;
13723:     } else {
13724:         $width = 120+$NumBars*8;
13725:         $xskip = 5;
13726:         $bar_width = 4;
13727:     }
13728:     #
13729:     $Max = 1 if ($Max < 1);
13730:     if ( int($Max) < $Max ) {
13731:         $Max++;
13732:         $Max = int($Max);
13733:     }
13734:     $Title  = '' if (! defined($Title));
13735:     $xlabel = '' if (! defined($xlabel));
13736:     $ylabel = '' if (! defined($ylabel));
13737:     $ValuesHash{$id.'.title'}    = &escape($Title);
13738:     $ValuesHash{$id.'.xlabel'}   = &escape($xlabel);
13739:     $ValuesHash{$id.'.ylabel'}   = &escape($ylabel);
13740:     $ValuesHash{$id.'.y_max_value'} = $Max;
13741:     $ValuesHash{$id.'.NumBars'}  = $NumBars;
13742:     $ValuesHash{$id.'.NumSets'}  = $NumSets;
13743:     $ValuesHash{$id.'.PlotType'} = 'bar';
13744:     $ValuesHash{$id.'.Colors'}   = join(',',@{$colors});
13745:     $ValuesHash{$id.'.height'}   = $height;
13746:     $ValuesHash{$id.'.width'}    = $width;
13747:     $ValuesHash{$id.'.xskip'}    = $xskip;
13748:     $ValuesHash{$id.'.bar_width'} = $bar_width;
13749:     $ValuesHash{$id.'.labels'} = join(',',@Labels);
13750:     #
13751:     # Deal with other parameters
13752:     while (my ($key,$value) = each(%$extra_settings)) {
13753:         $ValuesHash{$id.'.'.$key} = $value;
13754:     }
13755:     #
13756:     &Apache::lonnet::appenv(\%ValuesHash);
13757:     return '<img src="/cgi-bin/graph.png?'.$identifier.'" border="1" />';
13758: }
13759: 
13760: ############################################################
13761: ############################################################
13762: 
13763: =pod
13764: 
13765: =item * &DrawXYGraph()
13766: 
13767: Facilitates the plotting of data in an XY graph.
13768: Puts plot definition data into the users environment in order for 
13769: graph.png to plot it.  Returns an <img> tag for the plot.
13770: 
13771: Inputs:
13772: 
13773: =over 4
13774: 
13775: =item $Title: string, the title of the plot
13776: 
13777: =item $xlabel: string, text describing the X-axis of the plot
13778: 
13779: =item $ylabel: string, text describing the Y-axis of the plot
13780: 
13781: =item $Max: scalar, the maximum Y value to use in the plot
13782: If $Max is < any data point, the graph will not be rendered.
13783: 
13784: =item $colors: Array ref containing the hex color codes for the data to be 
13785: plotted in.  If undefined, default values will be used.
13786: 
13787: =item $Xlabels: Array ref containing the labels to be used for the X-axis.
13788: 
13789: =item $Ydata: Array ref containing Array refs.  
13790: Each of the contained arrays will be plotted as a separate curve.
13791: 
13792: =item %Values: hash indicating or overriding any default values which are 
13793: passed to graph.png.  
13794: Possible values are: width, xskip, x_ticks, x_tick_offset, among others.
13795: 
13796: =back
13797: 
13798: Returns:
13799: 
13800: An <img> tag which references graph.png and the appropriate identifying
13801: information for the plot.
13802: 
13803: =cut
13804: 
13805: ############################################################
13806: ############################################################
13807: sub DrawXYGraph {
13808:     my ($Title,$xlabel,$ylabel,$Max,$colors,$Xlabels,$Ydata,%Values)=@_;
13809:     #
13810:     # Create the identifier for the graph
13811:     my $identifier = &get_cgi_id();
13812:     my $id = 'cgi.'.$identifier;
13813:     #
13814:     $Title  = '' if (! defined($Title));
13815:     $xlabel = '' if (! defined($xlabel));
13816:     $ylabel = '' if (! defined($ylabel));
13817:     my %ValuesHash = 
13818:         (
13819:          $id.'.title'  => &escape($Title),
13820:          $id.'.xlabel' => &escape($xlabel),
13821:          $id.'.ylabel' => &escape($ylabel),
13822:          $id.'.y_max_value'=> $Max,
13823:          $id.'.labels'     => join(',',@$Xlabels),
13824:          $id.'.PlotType'   => 'XY',
13825:          );
13826:     #
13827:     if (defined($colors) && ref($colors) eq 'ARRAY') {
13828:         $ValuesHash{$id.'.Colors'}   = join(',',@{$colors});
13829:     }
13830:     #
13831:     if (! ref($Ydata) || ref($Ydata) ne 'ARRAY') {
13832:         return '';
13833:     }
13834:     my $NumSets=1;
13835:     foreach my $array (@{$Ydata}){
13836:         next if (! ref($array));
13837:         $ValuesHash{$id.'.data.'.$NumSets++} = join(',',@$array);
13838:     }
13839:     $ValuesHash{$id.'.NumSets'} = $NumSets-1;
13840:     #
13841:     # Deal with other parameters
13842:     while (my ($key,$value) = each(%Values)) {
13843:         $ValuesHash{$id.'.'.$key} = $value;
13844:     }
13845:     #
13846:     &Apache::lonnet::appenv(\%ValuesHash);
13847:     return '<img src="/cgi-bin/graph.png?'.$identifier.'" border="1" />';
13848: }
13849: 
13850: ############################################################
13851: ############################################################
13852: 
13853: =pod
13854: 
13855: =item * &DrawXYYGraph()
13856: 
13857: Facilitates the plotting of data in an XY graph with two Y axes.
13858: Puts plot definition data into the users environment in order for 
13859: graph.png to plot it.  Returns an <img> tag for the plot.
13860: 
13861: Inputs:
13862: 
13863: =over 4
13864: 
13865: =item $Title: string, the title of the plot
13866: 
13867: =item $xlabel: string, text describing the X-axis of the plot
13868: 
13869: =item $ylabel: string, text describing the Y-axis of the plot
13870: 
13871: =item $colors: Array ref containing the hex color codes for the data to be 
13872: plotted in.  If undefined, default values will be used.
13873: 
13874: =item $Xlabels: Array ref containing the labels to be used for the X-axis.
13875: 
13876: =item $Ydata1: The first data set
13877: 
13878: =item $Min1: The minimum value of the left Y-axis
13879: 
13880: =item $Max1: The maximum value of the left Y-axis
13881: 
13882: =item $Ydata2: The second data set
13883: 
13884: =item $Min2: The minimum value of the right Y-axis
13885: 
13886: =item $Max2: The maximum value of the left Y-axis
13887: 
13888: =item %Values: hash indicating or overriding any default values which are 
13889: passed to graph.png.  
13890: Possible values are: width, xskip, x_ticks, x_tick_offset, among others.
13891: 
13892: =back
13893: 
13894: Returns:
13895: 
13896: An <img> tag which references graph.png and the appropriate identifying
13897: information for the plot.
13898: 
13899: =cut
13900: 
13901: ############################################################
13902: ############################################################
13903: sub DrawXYYGraph {
13904:     my ($Title,$xlabel,$ylabel,$colors,$Xlabels,$Ydata1,$Min1,$Max1,
13905:                                         $Ydata2,$Min2,$Max2,%Values)=@_;
13906:     #
13907:     # Create the identifier for the graph
13908:     my $identifier = &get_cgi_id();
13909:     my $id = 'cgi.'.$identifier;
13910:     #
13911:     $Title  = '' if (! defined($Title));
13912:     $xlabel = '' if (! defined($xlabel));
13913:     $ylabel = '' if (! defined($ylabel));
13914:     my %ValuesHash = 
13915:         (
13916:          $id.'.title'  => &escape($Title),
13917:          $id.'.xlabel' => &escape($xlabel),
13918:          $id.'.ylabel' => &escape($ylabel),
13919:          $id.'.labels' => join(',',@$Xlabels),
13920:          $id.'.PlotType' => 'XY',
13921:          $id.'.NumSets' => 2,
13922:          $id.'.two_axes' => 1,
13923:          $id.'.y1_max_value' => $Max1,
13924:          $id.'.y1_min_value' => $Min1,
13925:          $id.'.y2_max_value' => $Max2,
13926:          $id.'.y2_min_value' => $Min2,
13927:          );
13928:     #
13929:     if (defined($colors) && ref($colors) eq 'ARRAY') {
13930:         $ValuesHash{$id.'.Colors'}   = join(',',@{$colors});
13931:     }
13932:     #
13933:     if (! ref($Ydata1) || ref($Ydata1) ne 'ARRAY' ||
13934:         ! ref($Ydata2) || ref($Ydata2) ne 'ARRAY'){
13935:         return '';
13936:     }
13937:     my $NumSets=1;
13938:     foreach my $array ($Ydata1,$Ydata2){
13939:         next if (! ref($array));
13940:         $ValuesHash{$id.'.data.'.$NumSets++} = join(',',@$array);
13941:     }
13942:     #
13943:     # Deal with other parameters
13944:     while (my ($key,$value) = each(%Values)) {
13945:         $ValuesHash{$id.'.'.$key} = $value;
13946:     }
13947:     #
13948:     &Apache::lonnet::appenv(\%ValuesHash);
13949:     return '<img src="/cgi-bin/graph.png?'.$identifier.'" border="1" />';
13950: }
13951: 
13952: ############################################################
13953: ############################################################
13954: 
13955: =pod
13956: 
13957: =back 
13958: 
13959: =head1 Statistics helper routines?  
13960: 
13961: Bad place for them but what the hell.
13962: 
13963: =over 4
13964: 
13965: =item * &chartlink()
13966: 
13967: Returns a link to the chart for a specific student.  
13968: 
13969: Inputs:
13970: 
13971: =over 4
13972: 
13973: =item $linktext: The text of the link
13974: 
13975: =item $sname: The students username
13976: 
13977: =item $sdomain: The students domain
13978: 
13979: =back
13980: 
13981: =back
13982: 
13983: =cut
13984: 
13985: ############################################################
13986: ############################################################
13987: sub chartlink {
13988:     my ($linktext, $sname, $sdomain) = @_;
13989:     my $link = '<a href="/adm/statistics?reportSelected=student_assessment'.
13990:         '&amp;SelectedStudent='.&escape($sname.':'.$sdomain).
13991:         '&amp;chartoutputmode='.HTML::Entities::encode('html, with all links').
13992:        '">'.$linktext.'</a>';
13993: }
13994: 
13995: #######################################################
13996: #######################################################
13997: 
13998: =pod
13999: 
14000: =head1 Course Environment Routines
14001: 
14002: =over 4
14003: 
14004: =item * &restore_course_settings()
14005: 
14006: =item * &store_course_settings()
14007: 
14008: Restores/Store indicated form parameters from the course environment.
14009: Will not overwrite existing values of the form parameters.
14010: 
14011: Inputs: 
14012: a scalar describing the data (e.g. 'chart', 'problem_analysis')
14013: 
14014: a hash ref describing the data to be stored.  For example:
14015:    
14016: %Save_Parameters = ('Status' => 'scalar',
14017:     'chartoutputmode' => 'scalar',
14018:     'chartoutputdata' => 'scalar',
14019:     'Section' => 'array',
14020:     'Group' => 'array',
14021:     'StudentData' => 'array',
14022:     'Maps' => 'array');
14023: 
14024: Returns: both routines return nothing
14025: 
14026: =back
14027: 
14028: =cut
14029: 
14030: #######################################################
14031: #######################################################
14032: sub store_course_settings {
14033:     return &store_settings($env{'request.course.id'},@_);
14034: }
14035: 
14036: sub store_settings {
14037:     # save to the environment
14038:     # appenv the same items, just to be safe
14039:     my $udom  = $env{'user.domain'};
14040:     my $uname = $env{'user.name'};
14041:     my ($context,$prefix,$Settings) = @_;
14042:     my %SaveHash;
14043:     my %AppHash;
14044:     while (my ($setting,$type) = each(%$Settings)) {
14045:         my $basename = join('.','internal',$context,$prefix,$setting);
14046:         my $envname = 'environment.'.$basename;
14047:         if (exists($env{'form.'.$setting})) {
14048:             # Save this value away
14049:             if ($type eq 'scalar' &&
14050:                 (! exists($env{$envname}) || 
14051:                  $env{$envname} ne $env{'form.'.$setting})) {
14052:                 $SaveHash{$basename} = $env{'form.'.$setting};
14053:                 $AppHash{$envname}   = $env{'form.'.$setting};
14054:             } elsif ($type eq 'array') {
14055:                 my $stored_form;
14056:                 if (ref($env{'form.'.$setting})) {
14057:                     $stored_form = join(',',
14058:                                         map {
14059:                                             &escape($_);
14060:                                         } sort(@{$env{'form.'.$setting}}));
14061:                 } else {
14062:                     $stored_form = 
14063:                         &escape($env{'form.'.$setting});
14064:                 }
14065:                 # Determine if the array contents are the same.
14066:                 if ($stored_form ne $env{$envname}) {
14067:                     $SaveHash{$basename} = $stored_form;
14068:                     $AppHash{$envname}   = $stored_form;
14069:                 }
14070:             }
14071:         }
14072:     }
14073:     my $put_result = &Apache::lonnet::put('environment',\%SaveHash,
14074:                                           $udom,$uname);
14075:     if ($put_result !~ /^(ok|delayed)/) {
14076:         &Apache::lonnet::logthis('unable to save form parameters, '.
14077:                                  'got error:'.$put_result);
14078:     }
14079:     # Make sure these settings stick around in this session, too
14080:     &Apache::lonnet::appenv(\%AppHash);
14081:     return;
14082: }
14083: 
14084: sub restore_course_settings {
14085:     return &restore_settings($env{'request.course.id'},@_);
14086: }
14087: 
14088: sub restore_settings {
14089:     my ($context,$prefix,$Settings) = @_;
14090:     while (my ($setting,$type) = each(%$Settings)) {
14091:         next if (exists($env{'form.'.$setting}));
14092:         my $envname = 'environment.internal.'.$context.'.'.$prefix.
14093:             '.'.$setting;
14094:         if (exists($env{$envname})) {
14095:             if ($type eq 'scalar') {
14096:                 $env{'form.'.$setting} = $env{$envname};
14097:             } elsif ($type eq 'array') {
14098:                 $env{'form.'.$setting} = [ 
14099:                                            map { 
14100:                                                &unescape($_); 
14101:                                            } split(',',$env{$envname})
14102:                                            ];
14103:             }
14104:         }
14105:     }
14106: }
14107: 
14108: #######################################################
14109: #######################################################
14110: 
14111: =pod
14112: 
14113: =head1 Domain E-mail Routines  
14114: 
14115: =over 4
14116: 
14117: =item * &build_recipient_list()
14118: 
14119: Build recipient lists for following types of e-mail:
14120: (a) Error Reports, (b) Package Updates, (c) lonstatus warnings/errors
14121: (d) Help requests, (e) Course requests needing approval, (f) loncapa
14122: module change checking, student/employee ID conflict checks, as
14123: generated by lonerrorhandler.pm, CHECKRPMS, loncron,
14124: lonsupportreq.pm, loncoursequeueadmin.pm, searchcat.pl respectively.
14125: 
14126: Inputs:
14127: defmail (scalar - email address of default recipient),
14128: mailing type (scalar: errormail, packagesmail, helpdeskmail,
14129: requestsmail, updatesmail, or idconflictsmail).
14130: 
14131: defdom (domain for which to retrieve configuration settings),
14132: 
14133: origmail (scalar - email address of recipient from loncapa.conf,
14134: i.e., predates configuration by DC via domainprefs.pm
14135: 
14136: $requname username of requester (if mailing type is helpdeskmail)
14137: 
14138: $requdom domain of requester (if mailing type is helpdeskmail)
14139: 
14140: $reqemail e-mail address of requester (if mailing type is helpdeskmail)
14141: 
14142: 
14143: Returns: comma separated list of addresses to which to send e-mail.
14144: 
14145: =back
14146: 
14147: =cut
14148: 
14149: ############################################################
14150: ############################################################
14151: sub build_recipient_list {
14152:     my ($defmail,$mailing,$defdom,$origmail,$requname,$requdom,$reqemail) = @_;
14153:     my @recipients;
14154:     my ($otheremails,$lastresort,$allbcc,$addtext);
14155:     my %domconfig =
14156:         &Apache::lonnet::get_dom('configuration',['contacts'],$defdom);
14157:     if (ref($domconfig{'contacts'}) eq 'HASH') {
14158:         if (exists($domconfig{'contacts'}{$mailing})) {
14159:             if (ref($domconfig{'contacts'}{$mailing}) eq 'HASH') {
14160:                 my @contacts = ('adminemail','supportemail');
14161:                 foreach my $item (@contacts) {
14162:                     if ($domconfig{'contacts'}{$mailing}{$item}) {
14163:                         my $addr = $domconfig{'contacts'}{$item}; 
14164:                         if (!grep(/^\Q$addr\E$/,@recipients)) {
14165:                             push(@recipients,$addr);
14166:                         }
14167:                     }
14168:                 }
14169:                 $otheremails = $domconfig{'contacts'}{$mailing}{'others'};
14170:                 if ($mailing eq 'helpdeskmail') {
14171:                     if ($domconfig{'contacts'}{$mailing}{'bcc'}) {
14172:                         my @bccs = split(/,/,$domconfig{'contacts'}{$mailing}{'bcc'});
14173:                         my @ok_bccs;
14174:                         foreach my $bcc (@bccs) {
14175:                             $bcc =~ s/^\s+//g;
14176:                             $bcc =~ s/\s+$//g;
14177:                             if ($bcc =~ m/^[^\@]+\@[^\@]+$/) {
14178:                                 if (!(grep(/^\Q$bcc\E$/,@ok_bccs))) {
14179:                                     push(@ok_bccs,$bcc);
14180:                                 }
14181:                             }
14182:                         }
14183:                         if (@ok_bccs > 0) {
14184:                             $allbcc = join(', ',@ok_bccs);
14185:                         }
14186:                     }
14187:                     $addtext = $domconfig{'contacts'}{$mailing}{'include'};
14188:                 }
14189:             }
14190:         } elsif ($origmail ne '') {
14191:             $lastresort = $origmail;
14192:         }
14193:         if ($mailing eq 'helpdeskmail') {
14194:             if ((ref($domconfig{'contacts'}{'overrides'}) eq 'HASH') &&
14195:                 (keys(%{$domconfig{'contacts'}{'overrides'}}))) {
14196:                 my ($inststatus,$inststatus_checked);
14197:                 if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '') &&
14198:                     ($env{'user.domain'} ne 'public')) {
14199:                     $inststatus_checked = 1;
14200:                     $inststatus = $env{'environment.inststatus'};
14201:                 }
14202:                 unless ($inststatus_checked) {
14203:                     if (($requname ne '') && ($requdom ne '')) {
14204:                         if (($requname =~ /^$match_username$/) &&
14205:                             ($requdom =~ /^$match_domain$/) &&
14206:                             (&Apache::lonnet::domain($requdom))) {
14207:                             my $requhome = &Apache::lonnet::homeserver($requname,
14208:                                                                       $requdom);
14209:                             unless ($requhome eq 'no_host') {
14210:                                 my %userenv = &Apache::lonnet::userenvironment($requdom,$requname,'inststatus');
14211:                                 $inststatus = $userenv{'inststatus'};
14212:                                 $inststatus_checked = 1;
14213:                             }
14214:                         }
14215:                     }
14216:                 }
14217:                 unless ($inststatus_checked) {
14218:                     if ($reqemail =~ /^[^\@]+\@[^\@]+$/) {
14219:                         my %srch = (srchby     => 'email',
14220:                                     srchdomain => $defdom,
14221:                                     srchterm   => $reqemail,
14222:                                     srchtype   => 'exact');
14223:                         my %srch_results = &Apache::lonnet::usersearch(\%srch);
14224:                         foreach my $uname (keys(%srch_results)) {
14225:                             if (ref($srch_results{$uname}{'inststatus'}) eq 'ARRAY') {
14226:                                 $inststatus = join(',',@{$srch_results{$uname}{'inststatus'}});
14227:                                 $inststatus_checked = 1;
14228:                                 last;
14229:                             }
14230:                         }
14231:                         unless ($inststatus_checked) {
14232:                             my ($dirsrchres,%srch_results) = &Apache::lonnet::inst_directory_query(\%srch);
14233:                             if ($dirsrchres eq 'ok') {
14234:                                 foreach my $uname (keys(%srch_results)) {
14235:                                     if (ref($srch_results{$uname}{'inststatus'}) eq 'ARRAY') {
14236:                                         $inststatus = join(',',@{$srch_results{$uname}{'inststatus'}});
14237:                                         $inststatus_checked = 1;
14238:                                         last;
14239:                                     }
14240:                                 }
14241:                             }
14242:                         }
14243:                     }
14244:                 }
14245:                 if ($inststatus ne '') {
14246:                     foreach my $status (split(/\:/,$inststatus)) {
14247:                         if (ref($domconfig{'contacts'}{'overrides'}{$status}) eq 'HASH') {
14248:                             my @contacts = ('adminemail','supportemail');
14249:                             foreach my $item (@contacts) {
14250:                                 if ($domconfig{'contacts'}{'overrides'}{$status}{$item}) {
14251:                                     my $addr = $domconfig{'contacts'}{'overrides'}{$status};
14252:                                     if (!grep(/^\Q$addr\E$/,@recipients)) {
14253:                                         push(@recipients,$addr);
14254:                                     }
14255:                                 }
14256:                             }
14257:                             $otheremails = $domconfig{'contacts'}{'overrides'}{$status}{'others'};
14258:                             if ($domconfig{'contacts'}{'overrides'}{$status}{'bcc'}) {
14259:                                 my @bccs = split(/,/,$domconfig{'contacts'}{'overrides'}{$status}{'bcc'});
14260:                                 my @ok_bccs;
14261:                                 foreach my $bcc (@bccs) {
14262:                                     $bcc =~ s/^\s+//g;
14263:                                     $bcc =~ s/\s+$//g;
14264:                                     if ($bcc =~ m/^[^\@]+\@[^\@]+$/) {
14265:                                         if (!(grep(/^\Q$bcc\E$/,@ok_bccs))) {
14266:                                             push(@ok_bccs,$bcc);
14267:                                         }
14268:                                     }
14269:                                 }
14270:                                 if (@ok_bccs > 0) {
14271:                                     $allbcc = join(', ',@ok_bccs);
14272:                                 }
14273:                             }
14274:                             $addtext = $domconfig{'contacts'}{'overrides'}{$status}{'include'};
14275:                             last;
14276:                         }
14277:                     }
14278:                 }
14279:             }
14280:         }
14281:     } elsif ($origmail ne '') {
14282:         $lastresort = $origmail;
14283:     }
14284: 
14285:     if (($mailing eq 'helpdeskmail') && ($lastresort ne '')) {
14286:         unless (grep(/^\Q$defdom\E$/,&Apache::lonnet::current_machine_domains())) {
14287:             my $lonhost = $Apache::lonnet::perlvar{'lonHostID'};
14288:             my $machinedom = $Apache::lonnet::perlvar{'lonDefDomain'};
14289:             my %what = (
14290:                           perlvar => 1,
14291:                        );
14292:             my $primary = &Apache::lonnet::domain($defdom,'primary');
14293:             if ($primary) {
14294:                 my $gotaddr;
14295:                 my ($result,$returnhash) =
14296:                     &Apache::lonnet::get_remote_globals($primary,{ perlvar => 1 });
14297:                 if (($result eq 'ok') && (ref($returnhash) eq 'HASH')) {
14298:                     if ($returnhash->{'lonSupportEMail'} =~ /^[^\@]+\@[^\@]+$/) {
14299:                         $lastresort = $returnhash->{'lonSupportEMail'};
14300:                         $gotaddr = 1;
14301:                     }
14302:                 }
14303:                 unless ($gotaddr) {
14304:                     my $uintdom = &Apache::lonnet::internet_dom($primary);
14305:                     my $intdom = &Apache::lonnet::internet_dom($lonhost);
14306:                     unless ($uintdom eq $intdom) {
14307:                         my %domconfig =
14308:                             &Apache::lonnet::get_dom('configuration',['contacts'],$machinedom);
14309:                         if (ref($domconfig{'contacts'}) eq 'HASH') {
14310:                             if (ref($domconfig{'contacts'}{'otherdomsmail'}) eq 'HASH') {
14311:                                 my @contacts = ('adminemail','supportemail');
14312:                                 foreach my $item (@contacts) {
14313:                                     if ($domconfig{'contacts'}{'otherdomsmail'}{$item}) {
14314:                                         my $addr = $domconfig{'contacts'}{$item};
14315:                                         if (!grep(/^\Q$addr\E$/,@recipients)) {
14316:                                             push(@recipients,$addr);
14317:                                         }
14318:                                     }
14319:                                 }
14320:                                 if ($domconfig{'contacts'}{'otherdomsmail'}{'others'}) {
14321:                                     $otheremails = $domconfig{'contacts'}{'otherdomsmail'}{'others'};
14322:                                 }
14323:                                 if ($domconfig{'contacts'}{'otherdomsmail'}{'bcc'}) {
14324:                                     my @bccs = split(/,/,$domconfig{'contacts'}{'otherdomsmail'}{'bcc'});
14325:                                     my @ok_bccs;
14326:                                     foreach my $bcc (@bccs) {
14327:                                         $bcc =~ s/^\s+//g;
14328:                                         $bcc =~ s/\s+$//g;
14329:                                         if ($bcc =~ m/^[^\@]+\@[^\@]+$/) {
14330:                                             if (!(grep(/^\Q$bcc\E$/,@ok_bccs))) {
14331:                                                 push(@ok_bccs,$bcc);
14332:                                             }
14333:                                         }
14334:                                     }
14335:                                     if (@ok_bccs > 0) {
14336:                                         $allbcc = join(', ',@ok_bccs);
14337:                                     }
14338:                                 }
14339:                                 $addtext = $domconfig{'contacts'}{'otherdomsmail'}{'include'};
14340:                             }
14341:                         }
14342:                     }
14343:                 }
14344:             }
14345:         }
14346:     }
14347:     if (defined($defmail)) {
14348:         if ($defmail ne '') {
14349:             push(@recipients,$defmail);
14350:         }
14351:     }
14352:     if ($otheremails) {
14353:         my @others;
14354:         if ($otheremails =~ /,/) {
14355:             @others = split(/,/,$otheremails);
14356:         } else {
14357:             push(@others,$otheremails);
14358:         }
14359:         foreach my $addr (@others) {
14360:             if (!grep(/^\Q$addr\E$/,@recipients)) {
14361:                 push(@recipients,$addr);
14362:             }
14363:         }
14364:     }
14365:     if ($mailing eq 'helpdeskmail') {
14366:         if ((!@recipients) && ($lastresort ne '')) {
14367:             push(@recipients,$lastresort);
14368:         }
14369:     } elsif ($lastresort ne '') {
14370:         if (!grep(/^\Q$lastresort\E$/,@recipients)) {
14371:             push(@recipients,$lastresort);
14372:         }
14373:     }
14374:     my $recipientlist = join(',',@recipients);
14375:     if (wantarray) {
14376:         return ($recipientlist,$allbcc,$addtext);
14377:     } else {
14378:         return $recipientlist;
14379:     }
14380: }
14381: 
14382: ############################################################
14383: ############################################################
14384: 
14385: =pod
14386: 
14387: =head1 Course Catalog Routines
14388: 
14389: =over 4
14390: 
14391: =item * &gather_categories()
14392: 
14393: Converts category definitions - keys of categories hash stored in  
14394: coursecategories in configuration.db on the primary library server in a 
14395: domain - to an array.  Also generates javascript and idx hash used to 
14396: generate Domain Coordinator interface for editing Course Categories.
14397: 
14398: Inputs:
14399: 
14400: categories (reference to hash of category definitions).
14401: 
14402: cats (reference to array of arrays/hashes which encapsulates hierarchy of
14403:       categories and subcategories).
14404: 
14405: idx (reference to hash of counters used in Domain Coordinator interface for 
14406:       editing Course Categories).
14407: 
14408: jsarray (reference to array of categories used to create Javascript arrays for
14409:          Domain Coordinator interface for editing Course Categories).
14410: 
14411: Returns: nothing
14412: 
14413: Side effects: populates cats, idx and jsarray. 
14414: 
14415: =cut
14416: 
14417: sub gather_categories {
14418:     my ($categories,$cats,$idx,$jsarray) = @_;
14419:     my %counters;
14420:     my $num = 0;
14421:     foreach my $item (keys(%{$categories})) {
14422:         my ($cat,$container,$depth) = map { &unescape($_); } split(/:/,$item);
14423:         if ($container eq '' && $depth == 0) {
14424:             $cats->[$depth][$categories->{$item}] = $cat;
14425:         } else {
14426:             $cats->[$depth]{$container}[$categories->{$item}] = $cat;
14427:         }
14428:         my ($escitem,$tail) = split(/:/,$item,2);
14429:         if ($counters{$tail} eq '') {
14430:             $counters{$tail} = $num;
14431:             $num ++;
14432:         }
14433:         if (ref($idx) eq 'HASH') {
14434:             $idx->{$item} = $counters{$tail};
14435:         }
14436:         if (ref($jsarray) eq 'ARRAY') {
14437:             push(@{$jsarray->[$counters{$tail}]},$item);
14438:         }
14439:     }
14440:     return;
14441: }
14442: 
14443: =pod
14444: 
14445: =item * &extract_categories()
14446: 
14447: Used to generate breadcrumb trails for course categories.
14448: 
14449: Inputs:
14450: 
14451: categories (reference to hash of category definitions).
14452: 
14453: cats (reference to array of arrays/hashes which encapsulates hierarchy of
14454:       categories and subcategories).
14455: 
14456: trails (reference to array of breacrumb trails for each category).
14457: 
14458: allitems (reference to hash - key is category key 
14459:          (format: escaped(name):escaped(parent category):depth in hierarchy).
14460: 
14461: idx (reference to hash of counters used in Domain Coordinator interface for
14462:       editing Course Categories).
14463: 
14464: jsarray (reference to array of categories used to create Javascript arrays for
14465:          Domain Coordinator interface for editing Course Categories).
14466: 
14467: subcats (reference to hash of arrays containing all subcategories within each 
14468:          category, -recursive)
14469: 
14470: Returns: nothing
14471: 
14472: Side effects: populates trails and allitems hash references.
14473: 
14474: =cut
14475: 
14476: sub extract_categories {
14477:     my ($categories,$cats,$trails,$allitems,$idx,$jsarray,$subcats) = @_;
14478:     if (ref($categories) eq 'HASH') {
14479:         &gather_categories($categories,$cats,$idx,$jsarray);
14480:         if (ref($cats->[0]) eq 'ARRAY') {
14481:             for (my $i=0; $i<@{$cats->[0]}; $i++) {
14482:                 my $name = $cats->[0][$i];
14483:                 my $item = &escape($name).'::0';
14484:                 my $trailstr;
14485:                 if ($name eq 'instcode') {
14486:                     $trailstr = &mt('Official courses (with institutional codes)');
14487:                 } elsif ($name eq 'communities') {
14488:                     $trailstr = &mt('Communities');
14489:                 } else {
14490:                     $trailstr = $name;
14491:                 }
14492:                 if ($allitems->{$item} eq '') {
14493:                     push(@{$trails},$trailstr);
14494:                     $allitems->{$item} = scalar(@{$trails})-1;
14495:                 }
14496:                 my @parents = ($name);
14497:                 if (ref($cats->[1]{$name}) eq 'ARRAY') {
14498:                     for (my $j=0; $j<@{$cats->[1]{$name}}; $j++) {
14499:                         my $category = $cats->[1]{$name}[$j];
14500:                         if (ref($subcats) eq 'HASH') {
14501:                             push(@{$subcats->{$item}},&escape($category).':'.&escape($name).':1');
14502:                         }
14503:                         &recurse_categories($cats,2,$category,$trails,$allitems,\@parents,$subcats);
14504:                     }
14505:                 } else {
14506:                     if (ref($subcats) eq 'HASH') {
14507:                         $subcats->{$item} = [];
14508:                     }
14509:                 }
14510:             }
14511:         }
14512:     }
14513:     return;
14514: }
14515: 
14516: =pod
14517: 
14518: =item * &recurse_categories()
14519: 
14520: Recursively used to generate breadcrumb trails for course categories.
14521: 
14522: Inputs:
14523: 
14524: cats (reference to array of arrays/hashes which encapsulates hierarchy of
14525:       categories and subcategories).
14526: 
14527: depth (current depth in hierarchy of categories and sub-categories - 0 indexed).
14528: 
14529: category (current course category, for which breadcrumb trail is being generated).
14530: 
14531: trails (reference to array of breadcrumb trails for each category).
14532: 
14533: allitems (reference to hash - key is category key
14534:          (format: escaped(name):escaped(parent category):depth in hierarchy).
14535: 
14536: parents (array containing containers directories for current category, 
14537:          back to top level). 
14538: 
14539: Returns: nothing
14540: 
14541: Side effects: populates trails and allitems hash references
14542: 
14543: =cut
14544: 
14545: sub recurse_categories {
14546:     my ($cats,$depth,$category,$trails,$allitems,$parents,$subcats) = @_;
14547:     my $shallower = $depth - 1;
14548:     if (ref($cats->[$depth]{$category}) eq 'ARRAY') {
14549:         for (my $k=0; $k<@{$cats->[$depth]{$category}}; $k++) {
14550:             my $name = $cats->[$depth]{$category}[$k];
14551:             my $item = &escape($category).':'.&escape($parents->[-1]).':'.$shallower;
14552:             my $trailstr = join(' -&gt; ',(@{$parents},$category));
14553:             if ($allitems->{$item} eq '') {
14554:                 push(@{$trails},$trailstr);
14555:                 $allitems->{$item} = scalar(@{$trails})-1;
14556:             }
14557:             my $deeper = $depth+1;
14558:             push(@{$parents},$category);
14559:             if (ref($subcats) eq 'HASH') {
14560:                 my $subcat = &escape($name).':'.$category.':'.$depth;
14561:                 for (my $j=@{$parents}; $j>=0; $j--) {
14562:                     my $higher;
14563:                     if ($j > 0) {
14564:                         $higher = &escape($parents->[$j]).':'.
14565:                                   &escape($parents->[$j-1]).':'.$j;
14566:                     } else {
14567:                         $higher = &escape($parents->[$j]).'::'.$j;
14568:                     }
14569:                     push(@{$subcats->{$higher}},$subcat);
14570:                 }
14571:             }
14572:             &recurse_categories($cats,$deeper,$name,$trails,$allitems,$parents,
14573:                                 $subcats);
14574:             pop(@{$parents});
14575:         }
14576:     } else {
14577:         my $item = &escape($category).':'.&escape($parents->[-1]).':'.$shallower;
14578:         my $trailstr = join(' -&gt; ',(@{$parents},$category));
14579:         if ($allitems->{$item} eq '') {
14580:             push(@{$trails},$trailstr);
14581:             $allitems->{$item} = scalar(@{$trails})-1;
14582:         }
14583:     }
14584:     return;
14585: }
14586: 
14587: =pod
14588: 
14589: =item * &assign_categories_table()
14590: 
14591: Create a datatable for display of hierarchical categories in a domain,
14592: with checkboxes to allow a course to be categorized. 
14593: 
14594: Inputs:
14595: 
14596: cathash - reference to hash of categories defined for the domain (from
14597:           configuration.db)
14598: 
14599: currcat - scalar with an & separated list of categories assigned to a course. 
14600: 
14601: type    - scalar contains course type (Course or Community).
14602: 
14603: disabled - scalar (optional) contains disabled="disabled" if input elements are
14604:            to be readonly (e.g., Domain Helpdesk role viewing course settings).
14605: 
14606: Returns: $output (markup to be displayed) 
14607: 
14608: =cut
14609: 
14610: sub assign_categories_table {
14611:     my ($cathash,$currcat,$type,$disabled) = @_;
14612:     my $output;
14613:     if (ref($cathash) eq 'HASH') {
14614:         my (@cats,@trails,%allitems,%idx,@jsarray,@path,$maxdepth);
14615:         &extract_categories($cathash,\@cats,\@trails,\%allitems,\%idx,\@jsarray);
14616:         $maxdepth = scalar(@cats);
14617:         if (@cats > 0) {
14618:             my $itemcount = 0;
14619:             if (ref($cats[0]) eq 'ARRAY') {
14620:                 my @currcategories;
14621:                 if ($currcat ne '') {
14622:                     @currcategories = split('&',$currcat);
14623:                 }
14624:                 my $table;
14625:                 for (my $i=0; $i<@{$cats[0]}; $i++) {
14626:                     my $parent = $cats[0][$i];
14627:                     next if ($parent eq 'instcode');
14628:                     if ($type eq 'Community') {
14629:                         next unless ($parent eq 'communities');
14630:                     } else {
14631:                         next if ($parent eq 'communities');
14632:                     }
14633:                     my $css_class = $itemcount%2?' class="LC_odd_row"':'';
14634:                     my $item = &escape($parent).'::0';
14635:                     my $checked = '';
14636:                     if (@currcategories > 0) {
14637:                         if (grep(/^\Q$item\E$/,@currcategories)) {
14638:                             $checked = ' checked="checked"';
14639:                         }
14640:                     }
14641:                     my $parent_title = $parent;
14642:                     if ($parent eq 'communities') {
14643:                         $parent_title = &mt('Communities');
14644:                     }
14645:                     $table .= '<tr '.$css_class.'><td><span class="LC_nobreak">'.
14646:                               '<input type="checkbox" name="usecategory" value="'.
14647:                               $item.'"'.$checked.$disabled.' />'.$parent_title.'</span>'.
14648:                               '<input type="hidden" name="catname" value="'.$parent.'" /></td>';
14649:                     my $depth = 1;
14650:                     push(@path,$parent);
14651:                     $table .= &assign_category_rows($itemcount,\@cats,$depth,$parent,\@path,\@currcategories,$disabled);
14652:                     pop(@path);
14653:                     $table .= '</tr><tr><td colspan="'.$maxdepth.'" class="LC_row_separator"></td></tr>';
14654:                     $itemcount ++;
14655:                 }
14656:                 if ($itemcount) {
14657:                     $output = &Apache::loncommon::start_data_table().
14658:                               $table.
14659:                               &Apache::loncommon::end_data_table();
14660:                 }
14661:             }
14662:         }
14663:     }
14664:     return $output;
14665: }
14666: 
14667: =pod
14668: 
14669: =item * &assign_category_rows()
14670: 
14671: Create a datatable row for display of nested categories in a domain,
14672: with checkboxes to allow a course to be categorized,called recursively.
14673: 
14674: Inputs:
14675: 
14676: itemcount - track row number for alternating colors
14677: 
14678: cats - reference to array of arrays/hashes which encapsulates hierarchy of
14679:       categories and subcategories.
14680: 
14681: depth - current depth in hierarchy of categories and sub-categories - 0 indexed.
14682: 
14683: parent - parent of current category item
14684: 
14685: path - Array containing all categories back up through the hierarchy from the
14686:        current category to the top level.
14687: 
14688: currcategories - reference to array of current categories assigned to the course
14689: 
14690: disabled - scalar (optional) contains disabled="disabled" if input elements are
14691:            to be readonly (e.g., Domain Helpdesk role viewing course settings).
14692: 
14693: Returns: $output (markup to be displayed).
14694: 
14695: =cut
14696: 
14697: sub assign_category_rows {
14698:     my ($itemcount,$cats,$depth,$parent,$path,$currcategories,$disabled) = @_;
14699:     my ($text,$name,$item,$chgstr);
14700:     if (ref($cats) eq 'ARRAY') {
14701:         my $maxdepth = scalar(@{$cats});
14702:         if (ref($cats->[$depth]) eq 'HASH') {
14703:             if (ref($cats->[$depth]{$parent}) eq 'ARRAY') {
14704:                 my $numchildren = @{$cats->[$depth]{$parent}};
14705:                 my $css_class = $itemcount%2?' class="LC_odd_row"':'';
14706:                 $text .= '<td><table class="LC_data_table">';
14707:                 for (my $j=0; $j<$numchildren; $j++) {
14708:                     $name = $cats->[$depth]{$parent}[$j];
14709:                     $item = &escape($name).':'.&escape($parent).':'.$depth;
14710:                     my $deeper = $depth+1;
14711:                     my $checked = '';
14712:                     if (ref($currcategories) eq 'ARRAY') {
14713:                         if (@{$currcategories} > 0) {
14714:                             if (grep(/^\Q$item\E$/,@{$currcategories})) {
14715:                                 $checked = ' checked="checked"';
14716:                             }
14717:                         }
14718:                     }
14719:                     $text .= '<tr><td><span class="LC_nobreak"><label>'.
14720:                              '<input type="checkbox" name="usecategory" value="'.
14721:                              $item.'"'.$checked.$disabled.' />'.$name.'</label></span>'.
14722:                              '<input type="hidden" name="catname" value="'.$name.'" />'.
14723:                              '</td><td>';
14724:                     if (ref($path) eq 'ARRAY') {
14725:                         push(@{$path},$name);
14726:                         $text .= &assign_category_rows($itemcount,$cats,$deeper,$name,$path,$currcategories,$disabled);
14727:                         pop(@{$path});
14728:                     }
14729:                     $text .= '</td></tr>';
14730:                 }
14731:                 $text .= '</table></td>';
14732:             }
14733:         }
14734:     }
14735:     return $text;
14736: }
14737: 
14738: =pod
14739: 
14740: =back
14741: 
14742: =cut
14743: 
14744: ############################################################
14745: ############################################################
14746: 
14747: 
14748: sub commit_customrole {
14749:     my ($udom,$uname,$url,$three,$four,$five,$start,$end,$context) = @_;
14750:     my $output = &mt('Assigning custom role').' "'.$five.'" by '.$four.':'.$three.' in '.$url.
14751:                          ($start?', '.&mt('starting').' '.localtime($start):'').
14752:                          ($end?', ending '.localtime($end):'').': <b>'.
14753:               &Apache::lonnet::assigncustomrole(
14754:                  $udom,$uname,$url,$three,$four,$five,$end,$start,undef,undef,$context).
14755:                  '</b><br />';
14756:     return $output;
14757: }
14758: 
14759: sub commit_standardrole {
14760:     my ($udom,$uname,$url,$three,$start,$end,$one,$two,$sec,$context,$credits) = @_;
14761:     my ($output,$logmsg,$linefeed);
14762:     if ($context eq 'auto') {
14763:         $linefeed = "\n";
14764:     } else {
14765:         $linefeed = "<br />\n";
14766:     }  
14767:     if ($three eq 'st') {
14768:         my $result = &commit_studentrole(\$logmsg,$udom,$uname,$url,$three,$start,$end,
14769:                                          $one,$two,$sec,$context,$credits);
14770:         if (($result =~ /^error/) || ($result eq 'not_in_class') || 
14771:             ($result eq 'unknown_course') || ($result eq 'refused')) {
14772:             $output = $logmsg.' '.&mt('Error: ').$result."\n"; 
14773:         } else {
14774:             $output = $logmsg.$linefeed.&mt('Assigning').' '.$three.' in '.$url.
14775:                ($start?', '.&mt('starting').' '.localtime($start):'').
14776:                ($end?', '.&mt('ending').' '.localtime($end):'').': ';
14777:             if ($context eq 'auto') {
14778:                 $output .= $result.$linefeed.&mt('Add to classlist').': ok';
14779:             } else {
14780:                $output .= '<b>'.$result.'</b>'.$linefeed.
14781:                &mt('Add to classlist').': <b>ok</b>';
14782:             }
14783:             $output .= $linefeed;
14784:         }
14785:     } else {
14786:         $output = &mt('Assigning').' '.$three.' in '.$url.
14787:                ($start?', '.&mt('starting').' '.localtime($start):'').
14788:                ($end?', '.&mt('ending').' '.localtime($end):'').': ';
14789:         my $result = &Apache::lonnet::assignrole($udom,$uname,$url,$three,$end,$start,'','',$context);
14790:         if ($context eq 'auto') {
14791:             $output .= $result.$linefeed;
14792:         } else {
14793:             $output .= '<b>'.$result.'</b>'.$linefeed;
14794:         }
14795:     }
14796:     return $output;
14797: }
14798: 
14799: sub commit_studentrole {
14800:     my ($logmsg,$udom,$uname,$url,$three,$start,$end,$one,$two,$sec,$context,
14801:         $credits) = @_;
14802:     my ($result,$linefeed,$oldsecurl,$newsecurl);
14803:     if ($context eq 'auto') {
14804:         $linefeed = "\n";
14805:     } else {
14806:         $linefeed = '<br />'."\n";
14807:     }
14808:     if (defined($one) && defined($two)) {
14809:         my $cid=$one.'_'.$two;
14810:         my $oldsec=&Apache::lonnet::getsection($udom,$uname,$cid);
14811:         my $secchange = 0;
14812:         my $expire_role_result;
14813:         my $modify_section_result;
14814:         if ($oldsec ne '-1') { 
14815:             if ($oldsec ne $sec) {
14816:                 $secchange = 1;
14817:                 my $now = time;
14818:                 my $uurl='/'.$cid;
14819:                 $uurl=~s/\_/\//g;
14820:                 if ($oldsec) {
14821:                     $uurl.='/'.$oldsec;
14822:                 }
14823:                 $oldsecurl = $uurl;
14824:                 $expire_role_result = 
14825:                     &Apache::lonnet::assignrole($udom,$uname,$uurl,'st',$now,'','',$context);
14826:                 if ($env{'request.course.sec'} ne '') { 
14827:                     if ($expire_role_result eq 'refused') {
14828:                         my @roles = ('st');
14829:                         my @statuses = ('previous');
14830:                         my @roledoms = ($one);
14831:                         my $withsec = 1;
14832:                         my %roleshash = 
14833:                             &Apache::lonnet::get_my_roles($uname,$udom,'userroles',
14834:                                               \@statuses,\@roles,\@roledoms,$withsec);
14835:                         if (defined ($roleshash{$two.':'.$one.':st:'.$oldsec})) {
14836:                             my ($oldstart,$oldend) = 
14837:                                 split(':',$roleshash{$two.':'.$one.':st:'.$oldsec});
14838:                             if ($oldend > 0 && $oldend <= $now) {
14839:                                 $expire_role_result = 'ok';
14840:                             }
14841:                         }
14842:                     }
14843:                 }
14844:                 $result = $expire_role_result;
14845:             }
14846:         }
14847:         if (($expire_role_result eq 'ok') || ($secchange == 0)) {
14848:             $modify_section_result = 
14849:                 &Apache::lonnet::modify_student_enrollment($udom,$uname,undef,undef,
14850:                                                            undef,undef,undef,$sec,
14851:                                                            $end,$start,'','',$cid,
14852:                                                            '',$context,$credits);
14853:             if ($modify_section_result =~ /^ok/) {
14854:                 if ($secchange == 1) {
14855:                     if ($sec eq '') {
14856:                         $$logmsg .= &mt('Section for [_1] switched from (possibly expired) old section: [_2] to student role without a section.',$uname,$oldsec).$linefeed;
14857:                     } else {
14858:                         $$logmsg .= &mt('Section for [_1] switched from (possibly expired) old section: [_2] to new section: [_3].',$uname,$oldsec,$sec).$linefeed;
14859:                     }
14860:                 } elsif ($oldsec eq '-1') {
14861:                     if ($sec eq '') {
14862:                         $$logmsg .= &mt('New student role without a section for [_1] in course [_2].',$uname,$cid).$linefeed;
14863:                     } else {
14864:                         $$logmsg .= &mt('New student role for [_1] in section [_2] in course [_3].',$uname,$sec,$cid).$linefeed;
14865:                     }
14866:                 } else {
14867:                     if ($sec eq '') {
14868:                         $$logmsg .= &mt('Student [_1] assigned to course [_2] without a section.',$uname,$cid).$linefeed;
14869:                     } else {
14870:                         $$logmsg .= &mt('Student [_1] assigned to section [_2] in course [_3].',$uname,$sec,$cid).$linefeed;
14871:                     }
14872:                 }
14873:             } else {
14874:                 if ($secchange) {       
14875:                     $$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;
14876:                 } else {
14877:                     $$logmsg .= &mt('Error when attempting to modify role for [_1] for section: "[_2]" in course [_3] -error:',$uname,$sec,$cid).' '.$modify_section_result.$linefeed;
14878:                 }
14879:             }
14880:             $result = $modify_section_result;
14881:         } elsif ($secchange == 1) {
14882:             if ($oldsec eq '') {
14883:                 $$logmsg .= &mt('Error when attempting to expire existing role without a section for [_1] in course [_2] -error: ',$uname,$cid).' '.$expire_role_result.$linefeed;
14884:             } else {
14885:                 $$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;
14886:             }
14887:             if ($expire_role_result eq 'refused') {
14888:                 my $newsecurl = '/'.$cid;
14889:                 $newsecurl =~ s/\_/\//g;
14890:                 if ($sec ne '') {
14891:                     $newsecurl.='/'.$sec;
14892:                 }
14893:                 if (&Apache::lonnet::allowed('cst',$newsecurl) && !(&Apache::lonnet::allowed('cst',$oldsecurl))) {
14894:                     if ($sec eq '') {
14895:                         $$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;
14896:                     } else {
14897:                         $$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;
14898:                     }
14899:                 }
14900:             }
14901:         }
14902:     } else {
14903:         $$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;
14904:         $result = "error: incomplete course id\n";
14905:     }
14906:     return $result;
14907: }
14908: 
14909: sub show_role_extent {
14910:     my ($scope,$context,$role) = @_;
14911:     $scope =~ s{^/}{};
14912:     my @courseroles = &Apache::lonuserutils::roles_by_context('course',1);
14913:     push(@courseroles,'co');
14914:     my @authorroles = &Apache::lonuserutils::roles_by_context('author');
14915:     if (($context eq 'course') || (grep(/^\Q$role\E/,@courseroles))) {
14916:         $scope =~ s{/}{_};
14917:         return '<span class="LC_cusr_emph">'.$env{'course.'.$scope.'.description'}.'</span>';
14918:     } elsif (($context eq 'author') || (grep(/^\Q$role\E/,@authorroles))) {
14919:         my ($audom,$auname) = split(/\//,$scope);
14920:         return &mt('[_1] Author Space','<span class="LC_cusr_emph">'.
14921:                    &Apache::loncommon::plainname($auname,$audom).'</span>');
14922:     } else {
14923:         $scope =~ s{/$}{};
14924:         return &mt('Domain: [_1]','<span class="LC_cusr_emph">'.
14925:                    &Apache::lonnet::domain($scope,'description').'</span>');
14926:     }
14927: }
14928: 
14929: ############################################################
14930: ############################################################
14931: 
14932: sub check_clone {
14933:     my ($args,$linefeed) = @_;
14934:     my $cloneid='/'.$args->{'clonedomain'}.'/'.$args->{'clonecourse'};
14935:     my ($clonecrsudom,$clonecrsunum)= &LONCAPA::split_courseid($cloneid);
14936:     my $clonehome=&Apache::lonnet::homeserver($clonecrsunum,$clonecrsudom);
14937:     my $clonemsg;
14938:     my $can_clone = 0;
14939:     my $lctype = lc($args->{'crstype'});
14940:     if ($lctype ne 'community') {
14941:         $lctype = 'course';
14942:     }
14943:     if ($clonehome eq 'no_host') {
14944:         if ($args->{'crstype'} eq 'Community') {
14945:             $clonemsg = &mt('No new community created.').$linefeed.&mt('A new community could not be cloned from the specified original - [_1] - because it is a non-existent community.',$args->{'clonecourse'}.':'.$args->{'clonedomain'});
14946:         } else {
14947:             $clonemsg = &mt('No new course created.').$linefeed.&mt('A new course could not be cloned from the specified original - [_1] - because it is a non-existent course.',$args->{'clonecourse'}.':'.$args->{'clonedomain'});
14948:         }     
14949:     } else {
14950: 	my %clonedesc = &Apache::lonnet::coursedescription($cloneid,{'one_time' => 1});
14951:         if ($args->{'crstype'} eq 'Community') {
14952:             if ($clonedesc{'type'} ne 'Community') {
14953:                  $clonemsg = &mt('No new community created.').$linefeed.&mt('A new community could not be cloned from the specified original - [_1] - because it is a course not a community.',$args->{'clonecourse'}.':'.$args->{'clonedomain'});
14954:                 return ($can_clone, $clonemsg, $cloneid, $clonehome);
14955:             }
14956:         }
14957: 	if (($env{'request.role.domain'} eq $args->{'clonedomain'}) &&
14958:             (&Apache::lonnet::allowed('ccc',$env{'request.role.domain'}))) {
14959: 	    $can_clone = 1;
14960: 	} else {
14961: 	    my %clonehash = &Apache::lonnet::get('environment',['cloners','internal.coursecode'],
14962: 						 $args->{'clonedomain'},$args->{'clonecourse'});
14963:             if ($clonehash{'cloners'} eq '') {
14964:                 my %domdefs = &Apache::lonnet::get_domain_defaults($args->{'course_domain'});
14965:                 if ($domdefs{'canclone'}) {
14966:                     unless ($domdefs{'canclone'} eq 'none') {
14967:                         if ($domdefs{'canclone'} eq 'domain') {
14968:                             if ($args->{'ccdomain'} eq $args->{'clonedomain'}) {
14969:                                 $can_clone = 1;
14970:                             }
14971:                         } elsif (($clonehash{'internal.coursecode'}) && ($args->{'crscode'}) &&
14972:                                  ($args->{'clonedomain'} eq  $args->{'course_domain'})) {
14973:                             if (&Apache::lonnet::default_instcode_cloning($args->{'clonedomain'},$domdefs{'canclone'},
14974:                                                                           $clonehash{'internal.coursecode'},$args->{'crscode'})) {
14975:                                 $can_clone = 1;
14976:                             }
14977:                         }
14978:                     }
14979:                 }
14980:             } else {
14981: 	        my @cloners = split(/,/,$clonehash{'cloners'});
14982:                 if (grep(/^\*$/,@cloners)) {
14983:                     $can_clone = 1;
14984:                 } elsif (grep(/^\*\:\Q$args->{'ccdomain'}\E$/,@cloners)) {
14985:                     $can_clone = 1;
14986:                 } elsif (grep(/^\Q$args->{'ccuname'}\E:\Q$args->{'ccdomain'}\E$/,@cloners)) {
14987:                     $can_clone = 1;
14988:                 }
14989:                 unless ($can_clone) {
14990:                     if (($clonehash{'internal.coursecode'}) && ($args->{'crscode'}) &&
14991:                         ($args->{'clonedomain'} eq  $args->{'course_domain'})) {
14992:                         my (%gotdomdefaults,%gotcodedefaults);
14993:                         foreach my $cloner (@cloners) {
14994:                             if (($cloner ne '*') && ($cloner !~ /^\*\:$match_domain$/) &&
14995:                                 ($cloner !~ /^$match_username\:$match_domain$/) && ($cloner ne '')) {
14996:                                 my (%codedefaults,@code_order);
14997:                                 if (ref($gotcodedefaults{$args->{'clonedomain'}}) eq 'HASH') {
14998:                                     if (ref($gotcodedefaults{$args->{'clonedomain'}}{'defaults'}) eq 'HASH') {
14999:                                         %codedefaults = %{$gotcodedefaults{$args->{'clonedomain'}}{'defaults'}};
15000:                                     }
15001:                                     if (ref($gotcodedefaults{$args->{'clonedomain'}}{'order'}) eq 'ARRAY') {
15002:                                         @code_order = @{$gotcodedefaults{$args->{'clonedomain'}}{'order'}};
15003:                                     }
15004:                                 } else {
15005:                                     &Apache::lonnet::auto_instcode_defaults($args->{'clonedomain'},
15006:                                                                             \%codedefaults,
15007:                                                                             \@code_order);
15008:                                     $gotcodedefaults{$args->{'clonedomain'}}{'defaults'} = \%codedefaults;
15009:                                     $gotcodedefaults{$args->{'clonedomain'}}{'order'} = \@code_order;
15010:                                 }
15011:                                 if (@code_order > 0) {
15012:                                     if (&Apache::lonnet::check_instcode_cloning(\%codedefaults,\@code_order,
15013:                                                                                 $cloner,$clonehash{'internal.coursecode'},
15014:                                                                                 $args->{'crscode'})) {
15015:                                         $can_clone = 1;
15016:                                         last;
15017:                                     }
15018:                                 }
15019:                             }
15020:                         }
15021:                     }
15022:                 }
15023:             }
15024:             unless ($can_clone) {
15025:                 my $ccrole = 'cc';
15026:                 if ($args->{'crstype'} eq 'Community') {
15027:                     $ccrole = 'co';
15028:                 }
15029:                 my %roleshash =
15030:                     &Apache::lonnet::get_my_roles($args->{'ccuname'},
15031:                                                   $args->{'ccdomain'},
15032:                                                   'userroles',['active'],[$ccrole],
15033:                                                   [$args->{'clonedomain'}]);
15034:                 if ($roleshash{$args->{'clonecourse'}.':'.$args->{'clonedomain'}.':'.$ccrole}) {
15035:                     $can_clone = 1;
15036:                 } elsif (&Apache::lonnet::is_course_owner($args->{'clonedomain'},$args->{'clonecourse'},
15037:                                                           $args->{'ccuname'},$args->{'ccdomain'})) {
15038:                     $can_clone = 1;
15039:                 }
15040:             }
15041:             unless ($can_clone) {
15042:                 if ($args->{'crstype'} eq 'Community') {
15043:                     $clonemsg = &mt('No new community created.').$linefeed.&mt('The new community could not be cloned from the existing community because the new community owner ([_1]) does not have cloning rights in the existing community ([_2]).',$args->{'ccuname'}.':'.$args->{'ccdomain'},$clonedesc{'description'});
15044:                 } else {
15045:                     $clonemsg = &mt('No new course created.').$linefeed.&mt('The new course could not be cloned from the existing course because the new course owner ([_1]) does not have cloning rights in the existing course ([_2]).',$args->{'ccuname'}.':'.$args->{'ccdomain'},$clonedesc{'description'});
15046: 	        }
15047: 	    }
15048:         }
15049:     }
15050:     return ($can_clone, $clonemsg, $cloneid, $clonehome);
15051: }
15052: 
15053: sub construct_course {
15054:     my ($args,$logmsg,$courseid,$crsudom,$crsunum,$udom,$uname,$context,
15055:         $cnum,$category,$coderef) = @_;
15056:     my $outcome;
15057:     my $linefeed =  '<br />'."\n";
15058:     if ($context eq 'auto') {
15059:         $linefeed = "\n";
15060:     }
15061: 
15062: #
15063: # Are we cloning?
15064: #
15065:     my ($can_clone, $clonemsg, $cloneid, $clonehome);
15066:     if (($args->{'clonecourse'}) && ($args->{'clonedomain'})) {
15067: 	($can_clone, $clonemsg, $cloneid, $clonehome) = &check_clone($args,$linefeed);
15068: 	if ($context ne 'auto') {
15069:             if ($clonemsg ne '') {
15070: 	        $clonemsg = '<span class="LC_error">'.$clonemsg.'</span>';
15071:             }
15072: 	}
15073: 	$outcome .= $clonemsg.$linefeed;
15074: 
15075:         if (!$can_clone) {
15076: 	    return (0,$outcome);
15077: 	}
15078:     }
15079: 
15080: #
15081: # Open course
15082: #
15083:     my $crstype = lc($args->{'crstype'});
15084:     my %cenv=();
15085:     $$courseid=&Apache::lonnet::createcourse($args->{'course_domain'},
15086:                                              $args->{'cdescr'},
15087:                                              $args->{'curl'},
15088:                                              $args->{'course_home'},
15089:                                              $args->{'nonstandard'},
15090:                                              $args->{'crscode'},
15091:                                              $args->{'ccuname'}.':'.
15092:                                              $args->{'ccdomain'},
15093:                                              $args->{'crstype'},
15094:                                              $cnum,$context,$category);
15095: 
15096:     # Note: The testing routines depend on this being output; see 
15097:     # Utils::Course. This needs to at least be output as a comment
15098:     # if anyone ever decides to not show this, and Utils::Course::new
15099:     # will need to be suitably modified.
15100:     $outcome .= &mt('New LON-CAPA [_1] ID: [_2]',$crstype,$$courseid).$linefeed;
15101:     if ($$courseid =~ /^error:/) {
15102:         return (0,$outcome);
15103:     }
15104: 
15105: #
15106: # Check if created correctly
15107: #
15108:     ($$crsudom,$$crsunum)= &LONCAPA::split_courseid($$courseid);
15109:     my $crsuhome=&Apache::lonnet::homeserver($$crsunum,$$crsudom);
15110:     if ($crsuhome eq 'no_host') {
15111:         $outcome .= &mt('Course creation failed, unrecognized course home server.').$linefeed;
15112:         return (0,$outcome);
15113:     }
15114:     $outcome .= &mt('Created on').': '.$crsuhome.$linefeed;
15115: 
15116: #
15117: # Do the cloning
15118: #   
15119:     if ($can_clone && $cloneid) {
15120: 	$clonemsg = &mt('Cloning [_1] from [_2]',$crstype,$clonehome);
15121: 	if ($context ne 'auto') {
15122: 	    $clonemsg = '<span class="LC_success">'.$clonemsg.'</span>';
15123: 	}
15124: 	$outcome .= $clonemsg.$linefeed;
15125: 	my %oldcenv=&Apache::lonnet::dump('environment',$$crsudom,$$crsunum);
15126: # Copy all files
15127: 	&Apache::lonclonecourse::copycoursefiles($cloneid,$$courseid,$args->{'datemode'},$args->{'dateshift'});
15128: # Restore URL
15129: 	$cenv{'url'}=$oldcenv{'url'};
15130: # Restore title
15131: 	$cenv{'description'}=$oldcenv{'description'};
15132: # Restore creation date, creator and creation context.
15133:         $cenv{'internal.created'}=$oldcenv{'internal.created'};
15134:         $cenv{'internal.creator'}=$oldcenv{'internal.creator'};
15135:         $cenv{'internal.creationcontext'}=$oldcenv{'internal.creationcontext'};
15136: # Mark as cloned
15137: 	$cenv{'clonedfrom'}=$cloneid;
15138: # Need to clone grading mode
15139:         my %newenv=&Apache::lonnet::get('environment',['grading'],$$crsudom,$$crsunum);
15140:         $cenv{'grading'}=$newenv{'grading'};
15141: # Do not clone these environment entries
15142:         &Apache::lonnet::del('environment',
15143:                   ['default_enrollment_start_date',
15144:                    'default_enrollment_end_date',
15145:                    'question.email',
15146:                    'policy.email',
15147:                    'comment.email',
15148:                    'pch.users.denied',
15149:                    'plc.users.denied',
15150:                    'hidefromcat',
15151:                    'checkforpriv',
15152:                    'categories',
15153:                    'internal.uniquecode'],
15154:                    $$crsudom,$$crsunum);
15155:         if ($args->{'textbook'}) {
15156:             $cenv{'internal.textbook'} = $args->{'textbook'};
15157:         }
15158:     }
15159: 
15160: #
15161: # Set environment (will override cloned, if existing)
15162: #
15163:     my @sections = ();
15164:     my @xlists = ();
15165:     if ($args->{'crstype'}) {
15166:         $cenv{'type'}=$args->{'crstype'};
15167:     }
15168:     if ($args->{'crsid'}) {
15169:         $cenv{'courseid'}=$args->{'crsid'};
15170:     }
15171:     if ($args->{'crscode'}) {
15172:         $cenv{'internal.coursecode'}=$args->{'crscode'};
15173:     }
15174:     if ($args->{'crsquota'} ne '') {
15175:         $cenv{'internal.coursequota'}=$args->{'crsquota'};
15176:     } else {
15177:         $cenv{'internal.coursequota'}=$args->{'crsquota'} = 20;
15178:     }
15179:     if ($args->{'ccuname'}) {
15180:         $cenv{'internal.courseowner'} = $args->{'ccuname'}.
15181:                                         ':'.$args->{'ccdomain'};
15182:     } else {
15183:         $cenv{'internal.courseowner'} = $args->{'curruser'};
15184:     }
15185:     if ($args->{'defaultcredits'}) {
15186:         $cenv{'internal.defaultcredits'} = $args->{'defaultcredits'};
15187:     }
15188:     my @badclasses = (); # Used to accumulate sections/crosslistings that did not pass classlist access check for course owner.
15189:     if ($args->{'crssections'}) {
15190:         $cenv{'internal.sectionnums'} = '';
15191:         if ($args->{'crssections'} =~ m/,/) {
15192:             @sections = split/,/,$args->{'crssections'};
15193:         } else {
15194:             $sections[0] = $args->{'crssections'};
15195:         }
15196:         if (@sections > 0) {
15197:             foreach my $item (@sections) {
15198:                 my ($sec,$gp) = split/:/,$item;
15199:                 my $class = $args->{'crscode'}.$sec;
15200:                 my $addcheck = &Apache::lonnet::auto_new_course($$crsunum,$$crsudom,$class,$cenv{'internal.courseowner'});
15201:                 $cenv{'internal.sectionnums'} .= $item.',';
15202:                 unless ($addcheck eq 'ok') {
15203:                     push(@badclasses,$class);
15204:                 }
15205:             }
15206:             $cenv{'internal.sectionnums'} =~ s/,$//;
15207:         }
15208:     }
15209: # do not hide course coordinator from staff listing, 
15210: # even if privileged
15211:     $cenv{'nothideprivileged'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
15212: # add course coordinator's domain to domains to check for privileged users
15213: # if different to course domain
15214:     if ($$crsudom ne $args->{'ccdomain'}) {
15215:         $cenv{'checkforpriv'} = $args->{'ccdomain'};
15216:     }
15217: # add crosslistings
15218:     if ($args->{'crsxlist'}) {
15219:         $cenv{'internal.crosslistings'}='';
15220:         if ($args->{'crsxlist'} =~ m/,/) {
15221:             @xlists = split/,/,$args->{'crsxlist'};
15222:         } else {
15223:             $xlists[0] = $args->{'crsxlist'};
15224:         }
15225:         if (@xlists > 0) {
15226:             foreach my $item (@xlists) {
15227:                 my ($xl,$gp) = split/:/,$item;
15228:                 my $addcheck =  &Apache::lonnet::auto_new_course($$crsunum,$$crsudom,$xl,$cenv{'internal.courseowner'});
15229:                 $cenv{'internal.crosslistings'} .= $item.',';
15230:                 unless ($addcheck eq 'ok') {
15231:                     push(@badclasses,$xl);
15232:                 }
15233:             }
15234:             $cenv{'internal.crosslistings'} =~ s/,$//;
15235:         }
15236:     }
15237:     if ($args->{'autoadds'}) {
15238:         $cenv{'internal.autoadds'}=$args->{'autoadds'};
15239:     }
15240:     if ($args->{'autodrops'}) {
15241:         $cenv{'internal.autodrops'}=$args->{'autodrops'};
15242:     }
15243: # check for notification of enrollment changes
15244:     my @notified = ();
15245:     if ($args->{'notify_owner'}) {
15246:         if ($args->{'ccuname'} ne '') {
15247:             push(@notified,$args->{'ccuname'}.':'.$args->{'ccdomain'});
15248:         }
15249:     }
15250:     if ($args->{'notify_dc'}) {
15251:         if ($uname ne '') { 
15252:             push(@notified,$uname.':'.$udom);
15253:         }
15254:     }
15255:     if (@notified > 0) {
15256:         my $notifylist;
15257:         if (@notified > 1) {
15258:             $notifylist = join(',',@notified);
15259:         } else {
15260:             $notifylist = $notified[0];
15261:         }
15262:         $cenv{'internal.notifylist'} = $notifylist;
15263:     }
15264:     if (@badclasses > 0) {
15265:         my %lt=&Apache::lonlocal::texthash(
15266:                 'tclb' => 'The courses listed below were included as sections or crosslistings affiliated with your new LON-CAPA course.',
15267:                 'howi' => 'However, if automated course roster updates are enabled for this class, these particular sections/crosslistings are not guaranteed to contribute towards enrollment.',
15268:                 'itis' => 'It is possible that rights to access enrollment for these classes will be available through assignment of co-owners.',
15269:         );
15270:         my $badclass_msg = $lt{'tclb'}.$linefeed.$lt{'howi'}.$linefeed.
15271:                            &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'};
15272:         if ($context eq 'auto') {
15273:             $outcome .= $badclass_msg.$linefeed;
15274:         } else {
15275:             $outcome .= '<div class="LC_warning">'.$badclass_msg.$linefeed.'<ul>'."\n";
15276:         }
15277:         foreach my $item (@badclasses) {
15278:             if ($context eq 'auto') {
15279:                 $outcome .= " - $item\n";
15280:             } else {
15281:                 $outcome .= "<li>$item</li>\n";
15282:             }
15283:         }
15284:         if ($context eq 'auto') {
15285:             $outcome .= $linefeed;
15286:         } else {
15287:             $outcome .= "</ul><br /><br /></div>\n";
15288:         }
15289:     }
15290:     if ($args->{'no_end_date'}) {
15291:         $args->{'endaccess'} = 0;
15292:     }
15293:     $cenv{'internal.autostart'}=$args->{'enrollstart'};
15294:     $cenv{'internal.autoend'}=$args->{'enrollend'};
15295:     $cenv{'default_enrollment_start_date'}=$args->{'startaccess'};
15296:     $cenv{'default_enrollment_end_date'}=$args->{'endaccess'};
15297:     if ($args->{'showphotos'}) {
15298:       $cenv{'internal.showphotos'}=$args->{'showphotos'};
15299:     }
15300:     $cenv{'internal.authtype'} = $args->{'authtype'};
15301:     $cenv{'internal.autharg'} = $args->{'autharg'}; 
15302:     if ( ($cenv{'internal.authtype'} =~ /^krb/) && ($cenv{'internal.autoadds'} == 1)) {
15303:         if (! defined($cenv{'internal.autharg'}) || $cenv{'internal.autharg'}  eq '') {
15304:             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'); 
15305:             if ($context eq 'auto') {
15306:                 $outcome .= $krb_msg;
15307:             } else {
15308:                 $outcome .= '<span class="LC_error">'.$krb_msg.'</span>';
15309:             }
15310:             $outcome .= $linefeed;
15311:         }
15312:     }
15313:     if (($args->{'ccdomain'}) && ($args->{'ccuname'})) {
15314:        if ($args->{'setpolicy'}) {
15315:            $cenv{'policy.email'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
15316:        }
15317:        if ($args->{'setcontent'}) {
15318:            $cenv{'question.email'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
15319:        }
15320:        if ($args->{'setcomment'}) {
15321:            $cenv{'comment.email'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
15322:        }
15323:     }
15324:     if ($args->{'reshome'}) {
15325: 	$cenv{'reshome'}=$args->{'reshome'}.'/';
15326: 	$cenv{'reshome'}=~s/\/+$/\//;
15327:     }
15328: #
15329: # course has keyed access
15330: #
15331:     if ($args->{'setkeys'}) {
15332:        $cenv{'keyaccess'}='yes';
15333:     }
15334: # if specified, key authority is not course, but user
15335: # only active if keyaccess is yes
15336:     if ($args->{'keyauth'}) {
15337: 	my ($user,$domain) = split(':',$args->{'keyauth'});
15338: 	$user = &LONCAPA::clean_username($user);
15339: 	$domain = &LONCAPA::clean_username($domain);
15340: 	if ($user ne '' && $domain ne '') {
15341: 	    $cenv{'keyauth'}=$user.':'.$domain;
15342: 	}
15343:     }
15344: 
15345: #
15346: #  generate and store uniquecode (available to course requester), if course should have one.
15347: #
15348:     if ($args->{'uniquecode'}) {
15349:         my ($code,$error) = &make_unique_code($$crsudom,$$crsunum);
15350:         if ($code) {
15351:             $cenv{'internal.uniquecode'} = $code;
15352:             my %crsinfo =
15353:                 &Apache::lonnet::courseiddump($$crsudom,'.',1,'.','.',$$crsunum,undef,undef,'.');
15354:             if (ref($crsinfo{$$crsudom.'_'.$$crsunum}) eq 'HASH') {
15355:                 $crsinfo{$$crsudom.'_'.$$crsunum}{'uniquecode'} = $code;
15356:                 my $putres = &Apache::lonnet::courseidput($$crsudom,\%crsinfo,$crsuhome,'notime');
15357:             }
15358:             if (ref($coderef)) {
15359:                 $$coderef = $code;
15360:             }
15361:         }
15362:     }
15363: 
15364:     if ($args->{'disresdis'}) {
15365:         $cenv{'pch.roles.denied'}='st';
15366:     }
15367:     if ($args->{'disablechat'}) {
15368:         $cenv{'plc.roles.denied'}='st';
15369:     }
15370: 
15371:     # Record we've not yet viewed the Course Initialization Helper for this 
15372:     # course
15373:     $cenv{'course.helper.not.run'} = 1;
15374:     #
15375:     # Use new Randomseed
15376:     #
15377:     $cenv{'rndseed'}=&Apache::lonnet::latest_rnd_algorithm_id();;
15378:     $cenv{'receiptalg'}=&Apache::lonnet::latest_receipt_algorithm_id();;
15379:     #
15380:     # The encryption code and receipt prefix for this course
15381:     #
15382:     $cenv{'internal.encseed'}=$Apache::lonnet::perlvar{'lonReceipt'}.$$.time.int(rand(9999));
15383:     $cenv{'internal.encpref'}=100+int(9*rand(99));
15384:     #
15385:     # By default, use standard grading
15386:     if (!defined($cenv{'grading'})) { $cenv{'grading'} = 'standard'; }
15387: 
15388:     $outcome .= $linefeed.&mt('Setting environment').': '.                 
15389:           &Apache::lonnet::put('environment',\%cenv,$$crsudom,$$crsunum).$linefeed;
15390: #
15391: # Open all assignments
15392: #
15393:     if ($args->{'openall'}) {
15394:        my $storeunder=$$crsudom.'_'.$$crsunum.'.0.opendate';
15395:        my %storecontent = ($storeunder         => time,
15396:                            $storeunder.'.type' => 'date_start');
15397:        
15398:        $outcome .= &mt('Opening all assignments').': '.&Apache::lonnet::cput
15399:                  ('resourcedata',\%storecontent,$$crsudom,$$crsunum).$linefeed;
15400:    }
15401: #
15402: # Set first page
15403: #
15404:     unless (($args->{'nonstandard'}) || ($args->{'firstres'} eq 'blank')
15405: 	    || ($cloneid)) {
15406: 	use LONCAPA::map;
15407: 	$outcome .= &mt('Setting first resource').': ';
15408: 
15409: 	my $map = '/uploaded/'.$$crsudom.'/'.$$crsunum.'/default.sequence';
15410:         my ($errtext,$fatal)=&LONCAPA::map::mapread($map);
15411: 
15412:         $outcome .= ($fatal?$errtext:'read ok').' - ';
15413:         my $title; my $url;
15414:         if ($args->{'firstres'} eq 'syl') {
15415: 	    $title=&mt('Syllabus');
15416:             $url='/public/'.$$crsudom.'/'.$$crsunum.'/syllabus';
15417:         } else {
15418:             $title=&mt('Table of Contents');
15419:             $url='/adm/navmaps';
15420:         }
15421: 
15422:         $LONCAPA::map::resources[1]=$title.':'.$url.':false:start:res';
15423: 	(my $outtext,$errtext) = &LONCAPA::map::storemap($map,1);
15424: 
15425: 	if ($errtext) { $fatal=2; }
15426:         $outcome .= ($fatal?$errtext:'write ok').$linefeed;
15427:     }
15428: 
15429:     return (1,$outcome);
15430: }
15431: 
15432: sub make_unique_code {
15433:     my ($cdom,$cnum) = @_;
15434:     # get lock on uniquecodes db
15435:     my $lockhash = {
15436:                       $cnum."\0".'uniquecodes' => $env{'user.name'}.
15437:                                                   ':'.$env{'user.domain'},
15438:                    };
15439:     my $tries = 0;
15440:     my $gotlock = &Apache::lonnet::newput_dom('uniquecodes',$lockhash,$cdom);
15441:     my ($code,$error);
15442: 
15443:     while (($gotlock ne 'ok') && ($tries<3)) {
15444:         $tries ++;
15445:         sleep 1;
15446:         $gotlock = &Apache::lonnet::newput_dom('uniquecodes',$lockhash,$cdom);
15447:     }
15448:     if ($gotlock eq 'ok') {
15449:         my %currcodes = &Apache::lonnet::dump_dom('uniquecodes',$cdom);
15450:         my $gotcode;
15451:         my $attempts = 0;
15452:         while ((!$gotcode) && ($attempts < 100)) {
15453:             $code = &generate_code();
15454:             if (!exists($currcodes{$code})) {
15455:                 $gotcode = 1;
15456:                 unless (&Apache::lonnet::newput_dom('uniquecodes',{ $code => $cnum },$cdom) eq 'ok') {
15457:                     $error = 'nostore';
15458:                 }
15459:             }
15460:             $attempts ++;
15461:         }
15462:         my @del_lock = ($cnum."\0".'uniquecodes');
15463:         my $dellockoutcome = &Apache::lonnet::del_dom('uniquecodes',\@del_lock,$cdom);
15464:     } else {
15465:         $error = 'nolock';
15466:     }
15467:     return ($code,$error);
15468: }
15469: 
15470: sub generate_code {
15471:     my $code;
15472:     my @letts = qw(B C D G H J K M N P Q R S T V W X Z);
15473:     for (my $i=0; $i<6; $i++) {
15474:         my $lettnum = int (rand 2);
15475:         my $item = '';
15476:         if ($lettnum) {
15477:             $item = $letts[int( rand(18) )];
15478:         } else {
15479:             $item = 1+int( rand(8) );
15480:         }
15481:         $code .= $item;
15482:     }
15483:     return $code;
15484: }
15485: 
15486: ############################################################
15487: ############################################################
15488: 
15489: #SD
15490: # only Community and Course, or anything else?
15491: sub course_type {
15492:     my ($cid) = @_;
15493:     if (!defined($cid)) {
15494:         $cid = $env{'request.course.id'};
15495:     }
15496:     if (defined($env{'course.'.$cid.'.type'})) {
15497:         return $env{'course.'.$cid.'.type'};
15498:     } else {
15499:         return 'Course';
15500:     }
15501: }
15502: 
15503: sub group_term {
15504:     my $crstype = &course_type();
15505:     my %names = (
15506:                   'Course' => 'group',
15507:                   'Community' => 'group',
15508:                 );
15509:     return $names{$crstype};
15510: }
15511: 
15512: sub course_types {
15513:     my @types = ('official','unofficial','community','textbook');
15514:     my %typename = (
15515:                          official   => 'Official course',
15516:                          unofficial => 'Unofficial course',
15517:                          community  => 'Community',
15518:                          textbook   => 'Textbook course',
15519:                    );
15520:     return (\@types,\%typename);
15521: }
15522: 
15523: sub icon {
15524:     my ($file)=@_;
15525:     my $curfext = lc((split(/\./,$file))[-1]);
15526:     my $iconname=$Apache::lonnet::perlvar{'lonIconsURL'}.'/unknown.gif';
15527:     my $embstyle = &Apache::loncommon::fileembstyle($curfext);
15528:     if (!(!defined($embstyle) || $embstyle eq 'unk' || $embstyle eq 'hdn')) {
15529: 	if (-e  $Apache::lonnet::perlvar{'lonDocRoot'}.'/'.
15530: 	          $Apache::lonnet::perlvar{'lonIconsURL'}.'/'.
15531: 	            $curfext.".gif") {
15532: 	    $iconname=$Apache::lonnet::perlvar{'lonIconsURL'}.'/'.
15533: 		$curfext.".gif";
15534: 	}
15535:     }
15536:     return &lonhttpdurl($iconname);
15537: } 
15538: 
15539: sub lonhttpdurl {
15540: #
15541: # Had been used for "small fry" static images on separate port 8080.
15542: # Modify here if lightweight http functionality desired again.
15543: # Currently eliminated due to increasing firewall issues.
15544: #
15545:     my ($url)=@_;
15546:     return $url;
15547: }
15548: 
15549: sub connection_aborted {
15550:     my ($r)=@_;
15551:     $r->print(" ");$r->rflush();
15552:     my $c = $r->connection;
15553:     return $c->aborted();
15554: }
15555: 
15556: #    Escapes strings that may have embedded 's that will be put into
15557: #    strings as 'strings'.
15558: sub escape_single {
15559:     my ($input) = @_;
15560:     $input =~ s/\\/\\\\/g;	# Escape the \'s..(must be first)>
15561:     $input =~ s/\'/\\\'/g;	# Esacpe the 's....
15562:     return $input;
15563: }
15564: 
15565: #  Same as escape_single, but escape's "'s  This 
15566: #  can be used for  "strings"
15567: sub escape_double {
15568:     my ($input) = @_;
15569:     $input =~ s/\\/\\\\/g;	# Escape the /'s..(must be first)>
15570:     $input =~ s/\"/\\\"/g;	# Esacpe the "s....
15571:     return $input;
15572: }
15573:  
15574: #   Escapes the last element of a full URL.
15575: sub escape_url {
15576:     my ($url)   = @_;
15577:     my @urlslices = split(/\//, $url,-1);
15578:     my $lastitem = &escape(pop(@urlslices));
15579:     return &HTML::Entities::encode(join('/',@urlslices),"'").'/'.$lastitem;
15580: }
15581: 
15582: sub compare_arrays {
15583:     my ($arrayref1,$arrayref2) = @_;
15584:     my (@difference,%count);
15585:     @difference = ();
15586:     %count = ();
15587:     if ((ref($arrayref1) eq 'ARRAY') && (ref($arrayref2) eq 'ARRAY')) {
15588:         foreach my $element (@{$arrayref1}, @{$arrayref2}) { $count{$element}++; }
15589:         foreach my $element (keys(%count)) {
15590:             if ($count{$element} == 1) {
15591:                 push(@difference,$element);
15592:             }
15593:         }
15594:     }
15595:     return @difference;
15596: }
15597: 
15598: # -------------------------------------------------------- Initialize user login
15599: sub init_user_environment {
15600:     my ($r, $username, $domain, $authhost, $form, $args) = @_;
15601:     my $lonids=$Apache::lonnet::perlvar{'lonIDsDir'};
15602: 
15603:     my $public=($username eq 'public' && $domain eq 'public');
15604: 
15605: # See if old ID present, if so, remove
15606: 
15607:     my ($filename,$cookie,$userroles,$firstaccenv,$timerintenv);
15608:     my $now=time;
15609: 
15610:     if ($public) {
15611: 	my $max_public=100;
15612: 	my $oldest;
15613: 	my $oldest_time=0;
15614: 	for(my $next=1;$next<=$max_public;$next++) {
15615: 	    if (-e $lonids."/publicuser_$next.id") {
15616: 		my $mtime=(stat($lonids."/publicuser_$next.id"))[9];
15617: 		if ($mtime<$oldest_time || !$oldest_time) {
15618: 		    $oldest_time=$mtime;
15619: 		    $oldest=$next;
15620: 		}
15621: 	    } else {
15622: 		$cookie="publicuser_$next";
15623: 		last;
15624: 	    }
15625: 	}
15626: 	if (!$cookie) { $cookie="publicuser_$oldest"; }
15627:     } else {
15628: 	# if this isn't a robot, kill any existing non-robot sessions
15629: 	if (!$args->{'robot'}) {
15630: 	    opendir(DIR,$lonids);
15631: 	    while ($filename=readdir(DIR)) {
15632: 		if ($filename=~/^$username\_\d+\_$domain\_$authhost\.id$/) {
15633: 		    unlink($lonids.'/'.$filename);
15634: 		}
15635: 	    }
15636: 	    closedir(DIR);
15637: # If there is a undeleted lockfile for the user's paste buffer remove it.
15638:             my $namespace = 'nohist_courseeditor';
15639:             my $lockingkey = 'paste'."\0".'locked_num';
15640:             my %lockhash = &Apache::lonnet::get($namespace,[$lockingkey],
15641:                                                 $domain,$username);
15642:             if (exists($lockhash{$lockingkey})) {
15643:                 my $delresult = &Apache::lonnet::del($namespace,[$lockingkey],$domain,$username);
15644:                 unless ($delresult eq 'ok') {
15645:                     &Apache::lonnet::logthis("Failed to delete paste buffer locking key in $namespace for ".$username.":".$domain." Result was: $delresult");
15646:                 }
15647:             }
15648: 	}
15649: # Give them a new cookie
15650: 	my $id = ($args->{'robot'} ? 'robot'.$args->{'robot'}
15651: 		                   : $now.$$.int(rand(10000)));
15652: 	$cookie="$username\_$id\_$domain\_$authhost";
15653:     
15654: # Initialize roles
15655: 
15656: 	($userroles,$firstaccenv,$timerintenv) = 
15657:             &Apache::lonnet::rolesinit($domain,$username,$authhost);
15658:     }
15659: # ------------------------------------ Check browser type and MathML capability
15660: 
15661:     my ($httpbrowser,$clientbrowser,$clientversion,$clientmathml,$clientunicode,
15662:         $clientos,$clientmobile,$clientinfo,$clientosversion) = &decode_user_agent($r);
15663: 
15664: # ------------------------------------------------------------- Get environment
15665: 
15666:     my %userenv = &Apache::lonnet::dump('environment',$domain,$username);
15667:     my ($tmp) = keys(%userenv);
15668:     if ($tmp =~ /^(con_lost|error|no_such_host)/i) {
15669: 	undef(%userenv);
15670:     }
15671:     if (($userenv{'interface'}) && (!$form->{'interface'})) {
15672: 	$form->{'interface'}=$userenv{'interface'};
15673:     }
15674:     if ($userenv{'texengine'} eq 'ttm') { $clientmathml=1; }
15675: 
15676: # --------------- Do not trust query string to be put directly into environment
15677:     foreach my $option ('interface','localpath','localres') {
15678:         $form->{$option}=~s/[\n\r\=]//gs;
15679:     }
15680: # --------------------------------------------------------- Write first profile
15681: 
15682:     {
15683: 	my %initial_env = 
15684: 	    ("user.name"          => $username,
15685: 	     "user.domain"        => $domain,
15686: 	     "user.home"          => $authhost,
15687: 	     "browser.type"       => $clientbrowser,
15688: 	     "browser.version"    => $clientversion,
15689: 	     "browser.mathml"     => $clientmathml,
15690: 	     "browser.unicode"    => $clientunicode,
15691: 	     "browser.os"         => $clientos,
15692:              "browser.mobile"     => $clientmobile,
15693:              "browser.info"       => $clientinfo,
15694:              "browser.osversion"  => $clientosversion,
15695: 	     "server.domain"      => $Apache::lonnet::perlvar{'lonDefDomain'},
15696: 	     "request.course.fn"  => '',
15697: 	     "request.course.uri" => '',
15698: 	     "request.course.sec" => '',
15699: 	     "request.role"       => 'cm',
15700: 	     "request.role.adv"   => $env{'user.adv'},
15701: 	     "request.host"       => $ENV{'REMOTE_ADDR'},);
15702: 
15703:         if ($form->{'localpath'}) {
15704: 	    $initial_env{"browser.localpath"}  = $form->{'localpath'};
15705: 	    $initial_env{"browser.localres"}   = $form->{'localres'};
15706:         }
15707: 	
15708: 	if ($form->{'interface'}) {
15709: 	    $form->{'interface'}=~s/\W//gs;
15710: 	    $initial_env{"browser.interface"} = $form->{'interface'};
15711: 	    $env{'browser.interface'}=$form->{'interface'};
15712: 	}
15713: 
15714:         if ($form->{'iptoken'}) {
15715:             my $lonhost = $r->dir_config('lonHostID');
15716:             $initial_env{"user.noloadbalance"} = $lonhost;
15717:             $env{'user.noloadbalance'} = $lonhost;
15718:         }
15719: 
15720:         if ($form->{'noloadbalance'}) {
15721:             my @hosts = &Apache::lonnet::current_machine_ids();
15722:             my $hosthere = $form->{'noloadbalance'};
15723:             if (grep(/^\Q$hosthere\E$/,@hosts)) {
15724:                 $initial_env{"user.noloadbalance"} = $hosthere;
15725:                 $env{'user.noloadbalance'} = $hosthere;
15726:             }
15727:         }
15728: 
15729:         unless ($domain eq 'public') {
15730:             my %is_adv = ( is_adv => $env{'user.adv'} );
15731:             my %domdef = &Apache::lonnet::get_domain_defaults($domain);
15732: 
15733:             foreach my $tool ('aboutme','blog','webdav','portfolio') {
15734:                 $userenv{'availabletools.'.$tool} = 
15735:                     &Apache::lonnet::usertools_access($username,$domain,$tool,'reload',
15736:                                                       undef,\%userenv,\%domdef,\%is_adv);
15737:             }
15738: 
15739:             foreach my $crstype ('official','unofficial','community','textbook') {
15740:                 $userenv{'canrequest.'.$crstype} =
15741:                     &Apache::lonnet::usertools_access($username,$domain,$crstype,
15742:                                                       'reload','requestcourses',
15743:                                                       \%userenv,\%domdef,\%is_adv);
15744:             }
15745: 
15746:             $userenv{'canrequest.author'} =
15747:                 &Apache::lonnet::usertools_access($username,$domain,'requestauthor',
15748:                                                   'reload','requestauthor',
15749:                                                   \%userenv,\%domdef,\%is_adv);
15750:             my %reqauthor = &Apache::lonnet::get('requestauthor',['author_status','author'],
15751:                                                  $domain,$username);
15752:             my $reqstatus = $reqauthor{'author_status'};
15753:             if ($reqstatus eq 'approval' || $reqstatus eq 'approved') {
15754:                 if (ref($reqauthor{'author'}) eq 'HASH') {
15755:                     $userenv{'requestauthorqueued'} = $reqstatus.':'.
15756:                                                       $reqauthor{'author'}{'timestamp'};
15757:                 }
15758:             }
15759:         }
15760: 
15761: 	$env{'user.environment'} = "$lonids/$cookie.id";
15762: 
15763: 	if (tie(my %disk_env,'GDBM_File',"$lonids/$cookie.id",
15764: 		 &GDBM_WRCREAT(),0640)) {
15765: 	    &_add_to_env(\%disk_env,\%initial_env);
15766: 	    &_add_to_env(\%disk_env,\%userenv,'environment.');
15767: 	    &_add_to_env(\%disk_env,$userroles);
15768:             if (ref($firstaccenv) eq 'HASH') {
15769:                 &_add_to_env(\%disk_env,$firstaccenv);
15770:             }
15771:             if (ref($timerintenv) eq 'HASH') {
15772:                 &_add_to_env(\%disk_env,$timerintenv);
15773:             }
15774: 	    if (ref($args->{'extra_env'})) {
15775: 		&_add_to_env(\%disk_env,$args->{'extra_env'});
15776: 	    }
15777: 	    untie(%disk_env);
15778: 	} else {
15779: 	    &Apache::lonnet::logthis("<span style=\"color:blue;\">WARNING: ".
15780: 			   'Could not create environment storage in lonauth: '.$!.'</span>');
15781: 	    return 'error: '.$!;
15782: 	}
15783:     }
15784:     $env{'request.role'}='cm';
15785:     $env{'request.role.adv'}=$env{'user.adv'};
15786:     $env{'browser.type'}=$clientbrowser;
15787: 
15788:     return $cookie;
15789: 
15790: }
15791: 
15792: sub _add_to_env {
15793:     my ($idf,$env_data,$prefix) = @_;
15794:     if (ref($env_data) eq 'HASH') {
15795:         while (my ($key,$value) = each(%$env_data)) {
15796: 	    $idf->{$prefix.$key} = $value;
15797: 	    $env{$prefix.$key}   = $value;
15798:         }
15799:     }
15800: }
15801: 
15802: # --- Get the symbolic name of a problem and the url
15803: sub get_symb {
15804:     my ($request,$silent) = @_;
15805:     (my $url=$env{'form.url'}) =~ s-^https?\://($ENV{'SERVER_NAME'}|$ENV{'HTTP_HOST'})--;
15806:     my $symb=($env{'form.symb'} ne '' ? $env{'form.symb'} : (&Apache::lonnet::symbread($url)));
15807:     if ($symb eq '') {
15808:         if (!$silent) {
15809:             if (ref($request)) { 
15810:                 $request->print("Unable to handle ambiguous references:$url:.");
15811:             }
15812:             return ();
15813:         }
15814:     }
15815:     &Apache::lonenc::check_decrypt(\$symb);
15816:     return ($symb);
15817: }
15818: 
15819: # --------------------------------------------------------------Get annotation
15820: 
15821: sub get_annotation {
15822:     my ($symb,$enc) = @_;
15823: 
15824:     my $key = $symb;
15825:     if (!$enc) {
15826:         $key =
15827:             &Apache::lonnet::clutter((&Apache::lonnet::decode_symb($symb))[2]);
15828:     }
15829:     my %annotation=&Apache::lonnet::get('nohist_annotations',[$key]);
15830:     return $annotation{$key};
15831: }
15832: 
15833: sub clean_symb {
15834:     my ($symb,$delete_enc) = @_;
15835: 
15836:     &Apache::lonenc::check_decrypt(\$symb);
15837:     my $enc = $env{'request.enc'};
15838:     if ($delete_enc) {
15839:         delete($env{'request.enc'});
15840:     }
15841: 
15842:     return ($symb,$enc);
15843: }
15844: 
15845: ############################################################
15846: ############################################################
15847: 
15848: =pod
15849: 
15850: =head1 Routines for building display used to search for courses
15851: 
15852: 
15853: =over 4
15854: 
15855: =item * &build_filters()
15856: 
15857: Create markup for a table used to set filters to use when selecting
15858: courses in a domain.  Used by lonpickcourse.pm, lonmodifycourse.pm
15859: and quotacheck.pl
15860: 
15861: 
15862: Inputs:
15863: 
15864: filterlist - anonymous array of fields to include as potential filters
15865: 
15866: crstype - course type
15867: 
15868: roleelement - fifth arg in selectcourse_link() populates fifth arg in javascript: opencrsbrowser() function, used
15869:               to pop-open a course selector (will contain "extra element").
15870: 
15871: multelement - if multiple course selections will be allowed, this will be a hidden form element: name: multiple; value: 1
15872: 
15873: filter - anonymous hash of criteria and their values
15874: 
15875: action - form action
15876: 
15877: numfiltersref - ref to scalar (count of number of elements in institutional codes -- e.g., 4 for year, semester, department, and number)
15878: 
15879: caller - caller context (e.g., set to 'modifycourse' when routine is called from lonmodifycourse.pm)
15880: 
15881: cloneruname - username of owner of new course who wants to clone
15882: 
15883: clonerudom - domain of owner of new course who wants to clone
15884: 
15885: typeelem - text to use for left column in row containing course type (i.e., Course, Community or Course/Community)
15886: 
15887: codetitlesref - reference to array of titles of components in institutional codes (official courses)
15888: 
15889: codedom - domain
15890: 
15891: formname - value of form element named "form".
15892: 
15893: fixeddom - domain, if fixed.
15894: 
15895: prevphase - value to assign to form element named "phase" when going back to the previous screen
15896: 
15897: cnameelement - name of form element in form on opener page which will receive title of selected course
15898: 
15899: cnumelement - name of form element in form on opener page which will receive courseID  of selected course
15900: 
15901: cdomelement - name of form element in form on opener page which will receive domain of selected course
15902: 
15903: setroles - includes access constraint identifier when setting a roles-based condition for acces to a portfolio file
15904: 
15905: clonetext - hidden form elements containing list of courses cloneable by intended course owner when DC creates a course
15906: 
15907: clonewarning - warning message about missing information for intended course owner when DC creates a course
15908: 
15909: 
15910: Returns: $output - HTML for display of search criteria, and hidden form elements.
15911: 
15912: 
15913: Side Effects: None
15914: 
15915: =cut
15916: 
15917: # ---------------------------------------------- search for courses based on last activity etc.
15918: 
15919: sub build_filters {
15920:     my ($filterlist,$crstype,$roleelement,$multelement,$filter,$action,
15921:         $numtitlesref,$caller,$cloneruname,$clonerudom,$typeelement,
15922:         $codetitlesref,$codedom,$formname,$fixeddom,$prevphase,
15923:         $cnameelement,$cnumelement,$cdomelement,$setroles,
15924:         $clonetext,$clonewarning) = @_;
15925:     my ($list,$jscript);
15926:     my $onchange = 'javascript:updateFilters(this)';
15927:     my ($domainselectform,$sincefilterform,$createdfilterform,
15928:         $ownerdomselectform,$persondomselectform,$instcodeform,
15929:         $typeselectform,$instcodetitle);
15930:     if ($formname eq '') {
15931:         $formname = $caller;
15932:     }
15933:     foreach my $item (@{$filterlist}) {
15934:         unless (($item eq 'descriptfilter') || ($item eq 'instcodefilter') ||
15935:                 ($item eq 'sincefilter') || ($item eq 'createdfilter')) {
15936:             if ($item eq 'domainfilter') {
15937:                 $filter->{$item} = &LONCAPA::clean_domain($filter->{$item});
15938:             } elsif ($item eq 'coursefilter') {
15939:                 $filter->{$item} = &LONCAPA::clean_courseid($filter->{$item});
15940:             } elsif ($item eq 'ownerfilter') {
15941:                 $filter->{$item} = &LONCAPA::clean_username($filter->{$item});
15942:             } elsif ($item eq 'ownerdomfilter') {
15943:                 $filter->{'ownerdomfilter'} =
15944:                     &LONCAPA::clean_domain($filter->{$item});
15945:                 $ownerdomselectform = &select_dom_form($filter->{'ownerdomfilter'},
15946:                                                        'ownerdomfilter',1);
15947:             } elsif ($item eq 'personfilter') {
15948:                 $filter->{$item} = &LONCAPA::clean_username($filter->{$item});
15949:             } elsif ($item eq 'persondomfilter') {
15950:                 $persondomselectform = &select_dom_form($filter->{'persondomfilter'},
15951:                                                         'persondomfilter',1);
15952:             } else {
15953:                 $filter->{$item} =~ s/\W//g;
15954:             }
15955:             if (!$filter->{$item}) {
15956:                 $filter->{$item} = '';
15957:             }
15958:         }
15959:         if ($item eq 'domainfilter') {
15960:             my $allow_blank = 1;
15961:             if ($formname eq 'portform') {
15962:                 $allow_blank=0;
15963:             } elsif ($formname eq 'studentform') {
15964:                 $allow_blank=0;
15965:             }
15966:             if ($fixeddom) {
15967:                 $domainselectform = '<input type="hidden" name="domainfilter"'.
15968:                                     ' value="'.$codedom.'" />'.
15969:                                     &Apache::lonnet::domain($codedom,'description');
15970:             } else {
15971:                 $domainselectform = &select_dom_form($filter->{$item},
15972:                                                      'domainfilter',
15973:                                                       $allow_blank,'',$onchange);
15974:             }
15975:         } else {
15976:             $list->{$item} = &HTML::Entities::encode($filter->{$item},'<>&"');
15977:         }
15978:     }
15979: 
15980:     # last course activity filter and selection
15981:     $sincefilterform = &timebased_select_form('sincefilter',$filter);
15982: 
15983:     # course created filter and selection
15984:     if (exists($filter->{'createdfilter'})) {
15985:         $createdfilterform = &timebased_select_form('createdfilter',$filter);
15986:     }
15987: 
15988:     my %lt = &Apache::lonlocal::texthash(
15989:                 'cac' => "$crstype Activity",
15990:                 'ccr' => "$crstype Created",
15991:                 'cde' => "$crstype Title",
15992:                 'cdo' => "$crstype Domain",
15993:                 'ins' => 'Institutional Code',
15994:                 'inc' => 'Institutional Categorization',
15995:                 'cow' => "$crstype Owner/Co-owner",
15996:                 'cop' => "$crstype Personnel Includes",
15997:                 'cog' => 'Type',
15998:              );
15999: 
16000:     if (($formname eq 'ccrs') || ($formname eq 'requestcrs')) {
16001:         my $typeval = 'Course';
16002:         if ($crstype eq 'Community') {
16003:             $typeval = 'Community';
16004:         }
16005:         $typeselectform = '<input type="hidden" name="type" value="'.$typeval.'" />';
16006:     } else {
16007:         $typeselectform =  '<select name="type" size="1"';
16008:         if ($onchange) {
16009:             $typeselectform .= ' onchange="'.$onchange.'"';
16010:         }
16011:         $typeselectform .= '>'."\n";
16012:         foreach my $posstype ('Course','Community') {
16013:             $typeselectform.='<option value="'.$posstype.'"'.
16014:                 ($posstype eq $crstype ? ' selected="selected" ' : ''). ">".&mt($posstype)."</option>\n";
16015:         }
16016:         $typeselectform.="</select>";
16017:     }
16018: 
16019:     my ($cloneableonlyform,$cloneabletitle);
16020:     if (exists($filter->{'cloneableonly'})) {
16021:         my $cloneableon = '';
16022:         my $cloneableoff = ' checked="checked"';
16023:         if ($filter->{'cloneableonly'}) {
16024:             $cloneableon = $cloneableoff;
16025:             $cloneableoff = '';
16026:         }
16027:         $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>';
16028:         if ($formname eq 'ccrs') {
16029:             $cloneabletitle = &mt('Cloneable for [_1]',$cloneruname.':'.$clonerudom);
16030:         } else {
16031:             $cloneabletitle = &mt('Cloneable by you');
16032:         }
16033:     }
16034:     my $officialjs;
16035:     if ($crstype eq 'Course') {
16036:         if (exists($filter->{'instcodefilter'})) {
16037: #            if (($fixeddom) || ($formname eq 'requestcrs') ||
16038: #                ($formname eq 'modifycourse') || ($formname eq 'filterpicker')) {
16039:             if ($codedom) {
16040:                 $officialjs = 1;
16041:                 ($instcodeform,$jscript,$$numtitlesref) =
16042:                     &Apache::courseclassifier::instcode_selectors($codedom,'filterpicker',
16043:                                                                   $officialjs,$codetitlesref);
16044:                 if ($jscript) {
16045:                     $jscript = '<script type="text/javascript">'."\n".
16046:                                '// <![CDATA['."\n".
16047:                                $jscript."\n".
16048:                                '// ]]>'."\n".
16049:                                '</script>'."\n";
16050:                 }
16051:             }
16052:             if ($instcodeform eq '') {
16053:                 $instcodeform =
16054:                     '<input type="text" name="instcodefilter" size="10" value="'.
16055:                     $list->{'instcodefilter'}.'" />';
16056:                 $instcodetitle = $lt{'ins'};
16057:             } else {
16058:                 $instcodetitle = $lt{'inc'};
16059:             }
16060:             if ($fixeddom) {
16061:                 $instcodetitle .= '<br />('.$codedom.')';
16062:             }
16063:         }
16064:     }
16065:     my $output = qq|
16066: <form method="post" name="filterpicker" action="$action">
16067: <input type="hidden" name="form" value="$formname" />
16068: |;
16069:     if ($formname eq 'modifycourse') {
16070:         $output .= '<input type="hidden" name="phase" value="courselist" />'."\n".
16071:                    '<input type="hidden" name="prevphase" value="'.
16072:                    $prevphase.'" />'."\n";
16073:     } elsif ($formname eq 'quotacheck') {
16074:         $output .= qq|
16075: <input type="hidden" name="sortby" value="" />
16076: <input type="hidden" name="sortorder" value="" />
16077: |;
16078:     } else {
16079:         my $name_input;
16080:         if ($cnameelement ne '') {
16081:             $name_input = '<input type="hidden" name="cnameelement" value="'.
16082:                           $cnameelement.'" />';
16083:         }
16084:         $output .= qq|
16085: <input type="hidden" name="cnumelement" value="$cnumelement" />
16086: <input type="hidden" name="cdomelement" value="$cdomelement" />
16087: $name_input
16088: $roleelement
16089: $multelement
16090: $typeelement
16091: |;
16092:         if ($formname eq 'portform') {
16093:             $output .= '<input type="hidden" name="setroles" value="'.$setroles.'" />'."\n";
16094:         }
16095:     }
16096:     if ($fixeddom) {
16097:         $output .= '<input type="hidden" name="fixeddom" value="'.$fixeddom.'" />'."\n";
16098:     }
16099:     $output .= "<br />\n".&Apache::lonhtmlcommon::start_pick_box();
16100:     if ($sincefilterform) {
16101:         $output .= &Apache::lonhtmlcommon::row_title($lt{'cac'})
16102:                   .$sincefilterform
16103:                   .&Apache::lonhtmlcommon::row_closure();
16104:     }
16105:     if ($createdfilterform) {
16106:         $output .= &Apache::lonhtmlcommon::row_title($lt{'ccr'})
16107:                   .$createdfilterform
16108:                   .&Apache::lonhtmlcommon::row_closure();
16109:     }
16110:     if ($domainselectform) {
16111:         $output .= &Apache::lonhtmlcommon::row_title($lt{'cdo'})
16112:                   .$domainselectform
16113:                   .&Apache::lonhtmlcommon::row_closure();
16114:     }
16115:     if ($typeselectform) {
16116:         if (($formname eq 'ccrs') || ($formname eq 'requestcrs')) {
16117:             $output .= $typeselectform;
16118:         } else {
16119:             $output .= &Apache::lonhtmlcommon::row_title($lt{'cog'})
16120:                       .$typeselectform
16121:                       .&Apache::lonhtmlcommon::row_closure();
16122:         }
16123:     }
16124:     if ($instcodeform) {
16125:         $output .= &Apache::lonhtmlcommon::row_title($instcodetitle)
16126:                   .$instcodeform
16127:                   .&Apache::lonhtmlcommon::row_closure();
16128:     }
16129:     if (exists($filter->{'ownerfilter'})) {
16130:         $output .= &Apache::lonhtmlcommon::row_title($lt{'cow'}).
16131:                    '<table><tr><td>'.&mt('Username').'<br />'.
16132:                    '<input type="text" name="ownerfilter" size="20" value="'.
16133:                    $list->{'ownerfilter'}.'" /></td><td>'.&mt('Domain').'<br />'.
16134:                    $ownerdomselectform.'</td></tr></table>'.
16135:                    &Apache::lonhtmlcommon::row_closure();
16136:     }
16137:     if (exists($filter->{'personfilter'})) {
16138:         $output .= &Apache::lonhtmlcommon::row_title($lt{'cop'}).
16139:                    '<table><tr><td>'.&mt('Username').'<br />'.
16140:                    '<input type="text" name="personfilter" size="20" value="'.
16141:                    $list->{'personfilter'}.'" /></td><td>'.&mt('Domain').'<br />'.
16142:                    $persondomselectform.'</td></tr></table>'.
16143:                    &Apache::lonhtmlcommon::row_closure();
16144:     }
16145:     if (exists($filter->{'coursefilter'})) {
16146:         $output .= &Apache::lonhtmlcommon::row_title(&mt('LON-CAPA course ID'))
16147:                   .'<input type="text" name="coursefilter" size="25" value="'
16148:                   .$list->{'coursefilter'}.'" />'
16149:                   .&Apache::lonhtmlcommon::row_closure();
16150:     }
16151:     if ($cloneableonlyform) {
16152:         $output .= &Apache::lonhtmlcommon::row_title($cloneabletitle).
16153:                    $cloneableonlyform.&Apache::lonhtmlcommon::row_closure();
16154:     }
16155:     if (exists($filter->{'descriptfilter'})) {
16156:         $output .= &Apache::lonhtmlcommon::row_title($lt{'cde'})
16157:                   .'<input type="text" name="descriptfilter" size="40" value="'
16158:                   .$list->{'descriptfilter'}.'" />'
16159:                   .&Apache::lonhtmlcommon::row_closure(1);
16160:     }
16161:     $output .= &Apache::lonhtmlcommon::end_pick_box().'<p>'.$clonetext."\n".
16162:                '<input type="hidden" name="updater" value="" />'."\n".
16163:                '<input type="submit" name="gosearch" value="'.
16164:                &mt('Search').'" /></p>'."\n".'</form>'."\n".'<hr />'."\n";
16165:     return $jscript.$clonewarning.$output;
16166: }
16167: 
16168: =pod
16169: 
16170: =item * &timebased_select_form()
16171: 
16172: Create markup for a dropdown list used to select a time-based
16173: filter e.g., Course Activity, Course Created, when searching for courses
16174: or communities
16175: 
16176: Inputs:
16177: 
16178: item - name of form element (sincefilter or createdfilter)
16179: 
16180: filter - anonymous hash of criteria and their values
16181: 
16182: Returns: HTML for a select box contained a blank, then six time selections,
16183:          with value set in incoming form variables currently selected.
16184: 
16185: Side Effects: None
16186: 
16187: =cut
16188: 
16189: sub timebased_select_form {
16190:     my ($item,$filter) = @_;
16191:     if (ref($filter) eq 'HASH') {
16192:         $filter->{$item} =~ s/[^\d-]//g;
16193:         if (!$filter->{$item}) { $filter->{$item}=-1; }
16194:         return &select_form(
16195:                             $filter->{$item},
16196:                             $item,
16197:                             {      '-1' => '',
16198:                                 '86400' => &mt('today'),
16199:                                '604800' => &mt('last week'),
16200:                               '2592000' => &mt('last month'),
16201:                               '7776000' => &mt('last three months'),
16202:                              '15552000' => &mt('last six months'),
16203:                              '31104000' => &mt('last year'),
16204:                     'select_form_order' =>
16205:                            ['-1','86400','604800','2592000','7776000',
16206:                             '15552000','31104000']});
16207:     }
16208: }
16209: 
16210: =pod
16211: 
16212: =item * &js_changer()
16213: 
16214: Create script tag containing Javascript used to submit course search form
16215: when course type or domain is changed, and also to hide 'Searching ...' on
16216: page load completion for page showing search result.
16217: 
16218: Inputs: None
16219: 
16220: Returns: markup containing updateFilters() and hideSearching() javascript functions.
16221: 
16222: Side Effects: None
16223: 
16224: =cut
16225: 
16226: sub js_changer {
16227:     return <<ENDJS;
16228: <script type="text/javascript">
16229: // <![CDATA[
16230: function updateFilters(caller) {
16231:     if (typeof(caller) != "undefined") {
16232:         document.filterpicker.updater.value = caller.name;
16233:     }
16234:     document.filterpicker.submit();
16235: }
16236: 
16237: function hideSearching() {
16238:     if (document.getElementById('searching')) {
16239:         document.getElementById('searching').style.display = 'none';
16240:     }
16241:     return;
16242: }
16243: 
16244: // ]]>
16245: </script>
16246: 
16247: ENDJS
16248: }
16249: 
16250: =pod
16251: 
16252: =item * &search_courses()
16253: 
16254: Process selected filters form course search form and pass to lonnet::courseiddump
16255: to retrieve a hash for which keys are courseIDs which match the selected filters.
16256: 
16257: Inputs:
16258: 
16259: dom - domain being searched
16260: 
16261: type - course type ('Course' or 'Community' or '.' if any).
16262: 
16263: filter - anonymous hash of criteria and their values
16264: 
16265: numtitles - for institutional codes - number of categories
16266: 
16267: cloneruname - optional username of new course owner
16268: 
16269: clonerudom - optional domain of new course owner
16270: 
16271: domcloner - optional "domcloner" flag; has value=1 if user has ccc priv in domain being filtered by,
16272:             (used when DC is using course creation form)
16273: 
16274: codetitles - reference to array of titles of components in institutional codes (official courses).
16275: 
16276: cc_clone - escaped comma separated list of courses for which course cloner has active CC role
16277:            (and so can clone automatically)
16278: 
16279: reqcrsdom - domain of new course, where search_courses is used to identify potential courses to clone
16280: 
16281: reqinstcode - institutional code of new course, where search_courses is used to identify potential
16282:               courses to clone
16283: 
16284: Returns: %courses - hash of courses satisfying search criteria, keys = course IDs, values are corresponding colon-separated escaped description, institutional code, owner and type.
16285: 
16286: 
16287: Side Effects: None
16288: 
16289: =cut
16290: 
16291: 
16292: sub search_courses {
16293:     my ($dom,$type,$filter,$numtitles,$cloneruname,$clonerudom,$domcloner,$codetitles,
16294:         $cc_clone,$reqcrsdom,$reqinstcode) = @_;
16295:     my (%courses,%showcourses,$cloner);
16296:     if (($filter->{'ownerfilter'} ne '') ||
16297:         ($filter->{'ownerdomfilter'} ne '')) {
16298:         $filter->{'combownerfilter'} = $filter->{'ownerfilter'}.':'.
16299:                                        $filter->{'ownerdomfilter'};
16300:     }
16301:     foreach my $item ('descriptfilter','coursefilter','combownerfilter') {
16302:         if (!$filter->{$item}) {
16303:             $filter->{$item}='.';
16304:         }
16305:     }
16306:     my $now = time;
16307:     my $timefilter =
16308:        ($filter->{'sincefilter'}==-1?1:$now-$filter->{'sincefilter'});
16309:     my ($createdbefore,$createdafter);
16310:     if (($filter->{'createdfilter'} ne '') && ($filter->{'createdfilter'} !=-1)) {
16311:         $createdbefore = $now;
16312:         $createdafter = $now-$filter->{'createdfilter'};
16313:     }
16314:     my ($instcodefilter,$regexpok);
16315:     if ($numtitles) {
16316:         if ($env{'form.official'} eq 'on') {
16317:             $instcodefilter =
16318:                 &Apache::courseclassifier::instcode_search_str($dom,$numtitles,$codetitles);
16319:             $regexpok = 1;
16320:         } elsif ($env{'form.official'} eq 'off') {
16321:             $instcodefilter = &Apache::courseclassifier::instcode_search_str($dom,$numtitles,$codetitles);
16322:             unless ($instcodefilter eq '') {
16323:                 $regexpok = -1;
16324:             }
16325:         }
16326:     } else {
16327:         $instcodefilter = $filter->{'instcodefilter'};
16328:     }
16329:     if ($instcodefilter eq '') { $instcodefilter = '.'; }
16330:     if ($type eq '') { $type = '.'; }
16331: 
16332:     if (($clonerudom ne '') && ($cloneruname ne '')) {
16333:         $cloner = $cloneruname.':'.$clonerudom;
16334:     }
16335:     %courses = &Apache::lonnet::courseiddump($dom,
16336:                                              $filter->{'descriptfilter'},
16337:                                              $timefilter,
16338:                                              $instcodefilter,
16339:                                              $filter->{'combownerfilter'},
16340:                                              $filter->{'coursefilter'},
16341:                                              undef,undef,$type,$regexpok,undef,undef,
16342:                                              undef,undef,$cloner,$cc_clone,
16343:                                              $filter->{'cloneableonly'},
16344:                                              $createdbefore,$createdafter,undef,
16345:                                              $domcloner,undef,$reqcrsdom,$reqinstcode);
16346:     if (($filter->{'personfilter'} ne '') && ($filter->{'persondomfilter'} ne '')) {
16347:         my $ccrole;
16348:         if ($type eq 'Community') {
16349:             $ccrole = 'co';
16350:         } else {
16351:             $ccrole = 'cc';
16352:         }
16353:         my %rolehash = &Apache::lonnet::get_my_roles($filter->{'personfilter'},
16354:                                                      $filter->{'persondomfilter'},
16355:                                                      'userroles',undef,
16356:                                                      [$ccrole,'in','ad','ep','ta','cr'],
16357:                                                      $dom);
16358:         foreach my $role (keys(%rolehash)) {
16359:             my ($cnum,$cdom,$courserole) = split(':',$role);
16360:             my $cid = $cdom.'_'.$cnum;
16361:             if (exists($courses{$cid})) {
16362:                 if (ref($courses{$cid}) eq 'HASH') {
16363:                     if (ref($courses{$cid}{roles}) eq 'ARRAY') {
16364:                         if (!grep(/^\Q$courserole\E$/,@{$courses{$cid}{roles}})) {
16365:                             push(@{$courses{$cid}{roles}},$courserole);
16366:                         }
16367:                     } else {
16368:                         $courses{$cid}{roles} = [$courserole];
16369:                     }
16370:                     $showcourses{$cid} = $courses{$cid};
16371:                 }
16372:             }
16373:         }
16374:         %courses = %showcourses;
16375:     }
16376:     return %courses;
16377: }
16378: 
16379: =pod
16380: 
16381: =back
16382: 
16383: =head1 Routines for version requirements for current course.
16384: 
16385: =over 4
16386: 
16387: =item * &check_release_required()
16388: 
16389: Compares required LON-CAPA version with version on server, and
16390: if required version is newer looks for a server with the required version.
16391: 
16392: Looks first at servers in user's owen domain; if none suitable, looks at
16393: servers in course's domain are permitted to host sessions for user's domain.
16394: 
16395: Inputs:
16396: 
16397: $loncaparev - Version on current server (format: Major.Minor.Subrelease-datestamp)
16398: 
16399: $courseid - Course ID of current course
16400: 
16401: $rolecode - User's current role in course (for switchserver query string).
16402: 
16403: $required - LON-CAPA version needed by course (format: Major.Minor).
16404: 
16405: 
16406: Returns:
16407: 
16408: $switchserver - query string tp append to /adm/switchserver call (if
16409:                 current server's LON-CAPA version is too old.
16410: 
16411: $warning - Message is displayed if no suitable server could be found.
16412: 
16413: =cut
16414: 
16415: sub check_release_required {
16416:     my ($loncaparev,$courseid,$rolecode,$required) = @_;
16417:     my ($switchserver,$warning);
16418:     if ($required ne '') {
16419:         my ($reqdmajor,$reqdminor) = ($required =~ /^(\d+)\.(\d+)$/);
16420:         my ($major,$minor) = ($loncaparev =~ /^\'?(\d+)\.(\d+)\.[\w.\-]+\'?$/);
16421:         if ($reqdmajor ne '' && $reqdminor ne '') {
16422:             my $otherserver;
16423:             if (($major eq '' && $minor eq '') ||
16424:                 (($reqdmajor > $major) || (($reqdmajor == $major) && ($reqdminor > $minor)))) {
16425:                 my ($userdomserver) = &Apache::lonnet::choose_server($env{'user.domain'},undef,$required,1);
16426:                 my $switchlcrev =
16427:                     &Apache::lonnet::get_server_loncaparev($env{'user.domain'},
16428:                                                            $userdomserver);
16429:                 my ($swmajor,$swminor) = ($switchlcrev =~ /^\'?(\d+)\.(\d+)\.[\w.\-]+\'?$/);
16430:                 if (($swmajor eq '' && $swminor eq '') || ($reqdmajor > $swmajor) ||
16431:                     (($reqdmajor == $swmajor) && ($reqdminor > $swminor))) {
16432:                     my $cdom = $env{'course.'.$courseid.'.domain'};
16433:                     if ($cdom ne $env{'user.domain'}) {
16434:                         my ($coursedomserver,$coursehostname) = &Apache::lonnet::choose_server($cdom,undef,$required,1);
16435:                         my $serverhomeID = &Apache::lonnet::get_server_homeID($coursehostname);
16436:                         my $serverhomedom = &Apache::lonnet::host_domain($serverhomeID);
16437:                         my %defdomdefaults = &Apache::lonnet::get_domain_defaults($serverhomedom);
16438:                         my %udomdefaults = &Apache::lonnet::get_domain_defaults($env{'user.domain'});
16439:                         my $remoterev = &Apache::lonnet::get_server_loncaparev($serverhomedom,$coursedomserver);
16440:                         my $canhost =
16441:                             &Apache::lonnet::can_host_session($env{'user.domain'},
16442:                                                               $coursedomserver,
16443:                                                               $remoterev,
16444:                                                               $udomdefaults{'remotesessions'},
16445:                                                               $defdomdefaults{'hostedsessions'});
16446: 
16447:                         if ($canhost) {
16448:                             $otherserver = $coursedomserver;
16449:                         } else {
16450:                             $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.");
16451:                         }
16452:                     } else {
16453:                         $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).");
16454:                     }
16455:                 } else {
16456:                     $otherserver = $userdomserver;
16457:                 }
16458:             }
16459:             if ($otherserver ne '') {
16460:                 $switchserver = 'otherserver='.$otherserver.'&amp;role='.$rolecode;
16461:             }
16462:         }
16463:     }
16464:     return ($switchserver,$warning);
16465: }
16466: 
16467: =pod
16468: 
16469: =item * &check_release_result()
16470: 
16471: Inputs:
16472: 
16473: $switchwarning - Warning message if no suitable server found to host session.
16474: 
16475: $switchserver - query string to append to /adm/switchserver containing lonHostID
16476:                 and current role.
16477: 
16478: Returns: HTML to display with information about requirement to switch server.
16479:          Either displaying warning with link to Roles/Courses screen or
16480:          display link to switchserver.
16481: 
16482: =cut
16483: 
16484: sub check_release_result {
16485:     my ($switchwarning,$switchserver) = @_;
16486:     my $output = &start_page('Selected course unavailable on this server').
16487:                  '<p class="LC_warning">';
16488:     if ($switchwarning) {
16489:         $output .= $switchwarning.'<br /><a href="/adm/roles">';
16490:         if (&show_course()) {
16491:             $output .= &mt('Display courses');
16492:         } else {
16493:             $output .= &mt('Display roles');
16494:         }
16495:         $output .= '</a>';
16496:     } elsif ($switchserver) {
16497:         $output .= &mt('This course requires a newer version of LON-CAPA than is installed on this server.').
16498:                    '<br />'.
16499:                    '<a href="/adm/switchserver?'.$switchserver.'">'.
16500:                    &mt('Switch Server').
16501:                    '</a>';
16502:     }
16503:     $output .= '</p>'.&end_page();
16504:     return $output;
16505: }
16506: 
16507: =pod
16508: 
16509: =item * &needs_coursereinit()
16510: 
16511: Determine if course contents stored for user's session needs to be
16512: refreshed, because content has changed since "Big Hash" last tied.
16513: 
16514: Check for change is made if time last checked is more than 10 minutes ago
16515: (by default).
16516: 
16517: Inputs:
16518: 
16519: $loncaparev - Version on current server (format: Major.Minor.Subrelease-datestamp)
16520: 
16521: $interval (optional) - Time which may elapse (in s) between last check for content
16522:                        change in current course. (default: 600 s).
16523: 
16524: Returns: an array; first element is:
16525: 
16526: =over 4
16527: 
16528: 'switch' - if content updates mean user's session
16529:            needs to be switched to a server running a newer LON-CAPA version
16530: 
16531: 'update' - if course session needs to be refreshed (i.e., Big Hash needs to be reloaded)
16532:            on current server hosting user's session
16533: 
16534: ''       - if no action required.
16535: 
16536: =back
16537: 
16538: If first item element is 'switch':
16539: 
16540: second item is $switchwarning - Warning message if no suitable server found to host session.
16541: 
16542: third item is $switchserver - query string to append to /adm/switchserver containing lonHostID
16543:                               and current role.
16544: 
16545: otherwise: no other elements returned.
16546: 
16547: =back
16548: 
16549: =cut
16550: 
16551: sub needs_coursereinit {
16552:     my ($loncaparev,$interval) = @_;
16553:     return() unless ($env{'request.course.id'} && $env{'request.course.tied'});
16554:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
16555:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
16556:     my $now = time;
16557:     if ($interval eq '') {
16558:         $interval = 600;
16559:     }
16560:     if (($now-$env{'request.course.timechecked'})>$interval) {
16561:         &Apache::lonnet::appenv({'request.course.timechecked'=>$now});
16562:         my $blocked = &blocking_status('reinit',$cnum,$cdom,undef,1);
16563:         if ($blocked) {
16564:             return ();
16565:         }
16566:         my $lastchange = &Apache::lonnet::get_coursechange($cdom,$cnum);
16567:         if ($lastchange > $env{'request.course.tied'}) {
16568:             my %curr_reqd_hash = &Apache::lonnet::userenvironment($cdom,$cnum,'internal.releaserequired');
16569:             if ($curr_reqd_hash{'internal.releaserequired'} ne '') {
16570:                 my $required = $env{'course.'.$cdom.'_'.$cnum.'.internal.releaserequired'};
16571:                 if ($curr_reqd_hash{'internal.releaserequired'} ne $required) {
16572:                     &Apache::lonnet::appenv({'course.'.$cdom.'_'.$cnum.'.internal.releaserequired' =>
16573:                                              $curr_reqd_hash{'internal.releaserequired'}});
16574:                     my ($switchserver,$switchwarning) =
16575:                         &check_release_required($loncaparev,$cdom.'_'.$cnum,$env{'request.role'},
16576:                                                 $curr_reqd_hash{'internal.releaserequired'});
16577:                     if ($switchwarning ne '' || $switchserver ne '') {
16578:                         return ('switch',$switchwarning,$switchserver);
16579:                     }
16580:                 }
16581:             }
16582:             return ('update');
16583:         }
16584:     }
16585:     return ();
16586: }
16587: 
16588: sub update_content_constraints {
16589:     my ($cdom,$cnum,$chome,$cid) = @_;
16590:     my %curr_reqd_hash = &Apache::lonnet::userenvironment($cdom,$cnum,'internal.releaserequired');
16591:     my ($reqdmajor,$reqdminor) = split(/\./,$curr_reqd_hash{'internal.releaserequired'});
16592:     my %checkresponsetypes;
16593:     foreach my $key (keys(%Apache::lonnet::needsrelease)) {
16594:         my ($item,$name,$value) = split(/:/,$key);
16595:         if ($item eq 'resourcetag') {
16596:             if ($name eq 'responsetype') {
16597:                 $checkresponsetypes{$value} = $Apache::lonnet::needsrelease{$key}
16598:             }
16599:         }
16600:     }
16601:     my $navmap = Apache::lonnavmaps::navmap->new();
16602:     if (defined($navmap)) {
16603:         my %allresponses;
16604:         foreach my $res ($navmap->retrieveResources(undef,sub { $_[0]->is_problem() },1,0)) {
16605:             my %responses = $res->responseTypes();
16606:             foreach my $key (keys(%responses)) {
16607:                 next unless(exists($checkresponsetypes{$key}));
16608:                 $allresponses{$key} += $responses{$key};
16609:             }
16610:         }
16611:         foreach my $key (keys(%allresponses)) {
16612:             my ($major,$minor) = split(/\./,$checkresponsetypes{$key});
16613:             if (($major > $reqdmajor) || ($major == $reqdmajor && $minor > $reqdminor)) {
16614:                 ($reqdmajor,$reqdminor) = ($major,$minor);
16615:             }
16616:         }
16617:         undef($navmap);
16618:     }
16619:     unless (($reqdmajor eq '') && ($reqdminor eq '')) {
16620:         &Apache::lonnet::update_released_required($reqdmajor.'.'.$reqdminor,$cdom,$cnum,$chome,$cid);
16621:     }
16622:     return;
16623: }
16624: 
16625: sub allmaps_incourse {
16626:     my ($cdom,$cnum,$chome,$cid) = @_;
16627:     if ($cdom eq '' || $cnum eq '' || $chome eq '' || $cid eq '') {
16628:         $cid = $env{'request.course.id'};
16629:         $cdom = $env{'course.'.$cid.'.domain'};
16630:         $cnum = $env{'course.'.$cid.'.num'};
16631:         $chome = $env{'course.'.$cid.'.home'};
16632:     }
16633:     my %allmaps = ();
16634:     my $lastchange =
16635:         &Apache::lonnet::get_coursechange($cdom,$cnum);
16636:     if ($lastchange > $env{'request.course.tied'}) {
16637:         my ($furl,$ferr) = &Apache::lonuserstate::readmap("$cdom/$cnum");
16638:         unless ($ferr) {
16639:             &update_content_constraints($cdom,$cnum,$chome,$cid);
16640:         }
16641:     }
16642:     my $navmap = Apache::lonnavmaps::navmap->new();
16643:     if (defined($navmap)) {
16644:         foreach my $res ($navmap->retrieveResources(undef,sub { $_[0]->is_map() },1,0,1)) {
16645:             $allmaps{$res->src()} = 1;
16646:         }
16647:     }
16648:     return \%allmaps;
16649: }
16650: 
16651: sub parse_supplemental_title {
16652:     my ($title) = @_;
16653: 
16654:     my ($foldertitle,$renametitle);
16655:     if ($title =~ /&amp;&amp;&amp;/) {
16656:         $title = &HTML::Entites::decode($title);
16657:     }
16658:     if ($title =~ m/^(\d+)___&&&___($match_username)___&&&___($match_domain)___&&&___(.*)$/) {
16659:         $renametitle=$4;
16660:         my ($time,$uname,$udom) = ($1,$2,$3);
16661:         $foldertitle=&Apache::lontexconvert::msgtexconverted($4);
16662:         my $name =  &plainname($uname,$udom);
16663:         $name = &HTML::Entities::encode($name,'"<>&\'');
16664:         $renametitle = &HTML::Entities::encode($renametitle,'"<>&\'');
16665:         $title='<i>'.&Apache::lonlocal::locallocaltime($time).'</i> '.
16666:             $name.': <br />'.$foldertitle;
16667:     }
16668:     if (wantarray) {
16669:         return ($title,$foldertitle,$renametitle);
16670:     }
16671:     return $title;
16672: }
16673: 
16674: sub recurse_supplemental {
16675:     my ($cnum,$cdom,$suppmap,$numfiles,$errors) = @_;
16676:     if ($suppmap) {
16677:         my ($errtext,$fatal) = &LONCAPA::map::mapread('/uploaded/'.$cdom.'/'.$cnum.'/'.$suppmap);
16678:         if ($fatal) {
16679:             $errors ++;
16680:         } else {
16681:             if ($#LONCAPA::map::resources > 0) {
16682:                 foreach my $res (@LONCAPA::map::resources) {
16683:                     my ($title,$src,$ext,$type,$status)=split(/\:/,$res);
16684:                     if (($src ne '') && ($status eq 'res')) {
16685:                         if ($src =~ m{^\Q/uploaded/$cdom/$cnum/\E(supplemental_\d+\.sequence)$}) {
16686:                             ($numfiles,$errors) = &recurse_supplemental($cnum,$cdom,$1,$numfiles,$errors);
16687:                         } else {
16688:                             $numfiles ++;
16689:                         }
16690:                     }
16691:                 }
16692:             }
16693:         }
16694:     }
16695:     return ($numfiles,$errors);
16696: }
16697: 
16698: sub symb_to_docspath {
16699:     my ($symb,$navmapref) = @_;
16700:     return unless ($symb && ref($navmapref));
16701:     my ($mapurl,$id,$resurl) = &Apache::lonnet::decode_symb($symb);
16702:     if ($resurl=~/\.(sequence|page)$/) {
16703:         $mapurl=$resurl;
16704:     } elsif ($resurl eq 'adm/navmaps') {
16705:         $mapurl=$env{'course.'.$env{'request.course.id'}.'.url'};
16706:     }
16707:     my $mapresobj;
16708:     unless (ref($$navmapref)) {
16709:         $$navmapref = Apache::lonnavmaps::navmap->new();
16710:     }
16711:     if (ref($$navmapref)) {
16712:         $mapresobj = $$navmapref->getResourceByUrl($mapurl);
16713:     }
16714:     $mapurl=~s{^.*/([^/]+)\.(\w+)$}{$1};
16715:     my $type=$2;
16716:     my $path;
16717:     if (ref($mapresobj)) {
16718:         my $pcslist = $mapresobj->map_hierarchy();
16719:         if ($pcslist ne '') {
16720:             foreach my $pc (split(/,/,$pcslist)) {
16721:                 next if ($pc <= 1);
16722:                 my $res = $$navmapref->getByMapPc($pc);
16723:                 if (ref($res)) {
16724:                     my $thisurl = $res->src();
16725:                     $thisurl=~s{^.*/([^/]+)\.\w+$}{$1};
16726:                     my $thistitle = $res->title();
16727:                     $path .= '&'.
16728:                              &Apache::lonhtmlcommon::entity_encode($thisurl).'&'.
16729:                              &escape($thistitle).
16730:                              ':'.$res->randompick().
16731:                              ':'.$res->randomout().
16732:                              ':'.$res->encrypted().
16733:                              ':'.$res->randomorder().
16734:                              ':'.$res->is_page();
16735:                 }
16736:             }
16737:         }
16738:         $path =~ s/^\&//;
16739:         my $maptitle = $mapresobj->title();
16740:         if ($mapurl eq 'default') {
16741:             $maptitle = 'Main Content';
16742:         }
16743:         $path .= (($path ne '')? '&' : '').
16744:                  &Apache::lonhtmlcommon::entity_encode($mapurl).'&'.
16745:                  &escape($maptitle).
16746:                  ':'.$mapresobj->randompick().
16747:                  ':'.$mapresobj->randomout().
16748:                  ':'.$mapresobj->encrypted().
16749:                  ':'.$mapresobj->randomorder().
16750:                  ':'.$mapresobj->is_page();
16751:     } else {
16752:         my $maptitle = &Apache::lonnet::gettitle($mapurl);
16753:         my $ispage = (($type eq 'page')? 1 : '');
16754:         if ($mapurl eq 'default') {
16755:             $maptitle = 'Main Content';
16756:         }
16757:         $path = &Apache::lonhtmlcommon::entity_encode($mapurl).'&'.
16758:                 &escape($maptitle).':::::'.$ispage;
16759:     }
16760:     unless ($mapurl eq 'default') {
16761:         $path = 'default&'.
16762:                 &escape('Main Content').
16763:                 ':::::&'.$path;
16764:     }
16765:     return $path;
16766: }
16767: 
16768: sub captcha_display {
16769:     my ($context,$lonhost) = @_;
16770:     my ($output,$error);
16771:     my ($captcha,$pubkey,$privkey,$version) =
16772:         &get_captcha_config($context,$lonhost);
16773:     if ($captcha eq 'original') {
16774:         $output = &create_captcha();
16775:         unless ($output) {
16776:             $error = 'captcha';
16777:         }
16778:     } elsif ($captcha eq 'recaptcha') {
16779:         $output = &create_recaptcha($pubkey,$version);
16780:         unless ($output) {
16781:             $error = 'recaptcha';
16782:         }
16783:     }
16784:     return ($output,$error,$captcha,$version);
16785: }
16786: 
16787: sub captcha_response {
16788:     my ($context,$lonhost) = @_;
16789:     my ($captcha_chk,$captcha_error);
16790:     my ($captcha,$pubkey,$privkey,$version) = &get_captcha_config($context,$lonhost);
16791:     if ($captcha eq 'original') {
16792:         ($captcha_chk,$captcha_error) = &check_captcha();
16793:     } elsif ($captcha eq 'recaptcha') {
16794:         $captcha_chk = &check_recaptcha($privkey,$version);
16795:     } else {
16796:         $captcha_chk = 1;
16797:     }
16798:     return ($captcha_chk,$captcha_error);
16799: }
16800: 
16801: sub get_captcha_config {
16802:     my ($context,$lonhost) = @_;
16803:     my ($captcha,$pubkey,$privkey,$version,$hashtocheck);
16804:     my $hostname = &Apache::lonnet::hostname($lonhost);
16805:     my $serverhomeID = &Apache::lonnet::get_server_homeID($hostname);
16806:     my $serverhomedom = &Apache::lonnet::host_domain($serverhomeID);
16807:     if ($context eq 'usercreation') {
16808:         my %domconfig = &Apache::lonnet::get_dom('configuration',[$context],$serverhomedom);
16809:         if (ref($domconfig{$context}) eq 'HASH') {
16810:             $hashtocheck = $domconfig{$context}{'cancreate'};
16811:             if (ref($hashtocheck) eq 'HASH') {
16812:                 if ($hashtocheck->{'captcha'} eq 'recaptcha') {
16813:                     if (ref($hashtocheck->{'recaptchakeys'}) eq 'HASH') {
16814:                         $pubkey = $hashtocheck->{'recaptchakeys'}{'public'};
16815:                         $privkey = $hashtocheck->{'recaptchakeys'}{'private'};
16816:                     }
16817:                     if ($privkey && $pubkey) {
16818:                         $captcha = 'recaptcha';
16819:                         $version = $hashtocheck->{'recaptchaversion'};
16820:                         if ($version ne '2') {
16821:                             $version = 1;
16822:                         }
16823:                     } else {
16824:                         $captcha = 'original';
16825:                     }
16826:                 } elsif ($hashtocheck->{'captcha'} ne 'notused') {
16827:                     $captcha = 'original';
16828:                 }
16829:             }
16830:         } else {
16831:             $captcha = 'captcha';
16832:         }
16833:     } elsif ($context eq 'login') {
16834:         my %domconfhash = &Apache::loncommon::get_domainconf($serverhomedom);
16835:         if ($domconfhash{$serverhomedom.'.login.captcha'} eq 'recaptcha') {
16836:             $pubkey = $domconfhash{$serverhomedom.'.login.recaptchakeys_public'};
16837:             $privkey = $domconfhash{$serverhomedom.'.login.recaptchakeys_private'};
16838:             if ($privkey && $pubkey) {
16839:                 $captcha = 'recaptcha';
16840:                 $version = $domconfhash{$serverhomedom.'.login.recaptchaversion'};
16841:                 if ($version ne '2') {
16842:                     $version = 1;
16843:                 }
16844:             } else {
16845:                 $captcha = 'original';
16846:             }
16847:         } elsif ($domconfhash{$serverhomedom.'.login.captcha'} eq 'original') {
16848:             $captcha = 'original';
16849:         }
16850:     }
16851:     return ($captcha,$pubkey,$privkey,$version);
16852: }
16853: 
16854: sub create_captcha {
16855:     my %captcha_params = &captcha_settings();
16856:     my ($output,$maxtries,$tries) = ('',10,0);
16857:     while ($tries < $maxtries) {
16858:         $tries ++;
16859:         my $captcha = Authen::Captcha->new (
16860:                                            output_folder => $captcha_params{'output_dir'},
16861:                                            data_folder   => $captcha_params{'db_dir'},
16862:                                           );
16863:         my $md5sum = $captcha->generate_code($captcha_params{'numchars'});
16864: 
16865:         if (-e $Apache::lonnet::perlvar{'lonCaptchaDir'}.'/'.$md5sum.'.png') {
16866:             $output = '<input type="hidden" name="crypt" value="'.$md5sum.'" />'."\n".
16867:                       &mt('Type in the letters/numbers shown below').'&nbsp;'.
16868:                       '<input type="text" size="5" name="code" value="" autocomplete="off" />'.
16869:                       '<br />'.
16870:                       '<img src="'.$captcha_params{'www_output_dir'}.'/'.$md5sum.'.png" alt="captcha" />';
16871:             last;
16872:         }
16873:     }
16874:     return $output;
16875: }
16876: 
16877: sub captcha_settings {
16878:     my %captcha_params = (
16879:                            output_dir     => $Apache::lonnet::perlvar{'lonCaptchaDir'},
16880:                            www_output_dir => "/captchaspool",
16881:                            db_dir         => $Apache::lonnet::perlvar{'lonCaptchaDb'},
16882:                            numchars       => '5',
16883:                          );
16884:     return %captcha_params;
16885: }
16886: 
16887: sub check_captcha {
16888:     my ($captcha_chk,$captcha_error);
16889:     my $code = $env{'form.code'};
16890:     my $md5sum = $env{'form.crypt'};
16891:     my %captcha_params = &captcha_settings();
16892:     my $captcha = Authen::Captcha->new(
16893:                       output_folder => $captcha_params{'output_dir'},
16894:                       data_folder   => $captcha_params{'db_dir'},
16895:                   );
16896:     $captcha_chk = $captcha->check_code($code,$md5sum);
16897:     my %captcha_hash = (
16898:                         0       => 'Code not checked (file error)',
16899:                        -1      => 'Failed: code expired',
16900:                        -2      => 'Failed: invalid code (not in database)',
16901:                        -3      => 'Failed: invalid code (code does not match crypt)',
16902:     );
16903:     if ($captcha_chk != 1) {
16904:         $captcha_error = $captcha_hash{$captcha_chk}
16905:     }
16906:     return ($captcha_chk,$captcha_error);
16907: }
16908: 
16909: sub create_recaptcha {
16910:     my ($pubkey,$version) = @_;
16911:     if ($version >= 2) {
16912:         return '<div class="g-recaptcha" data-sitekey="'.$pubkey.'"></div>';
16913:     } else {
16914:         my $use_ssl;
16915:         if ($ENV{'SERVER_PORT'} == 443) {
16916:             $use_ssl = 1;
16917:         }
16918:         my $captcha = Captcha::reCAPTCHA->new;
16919:         return $captcha->get_options_setter({theme => 'white'})."\n".
16920:                $captcha->get_html($pubkey,undef,$use_ssl).
16921:                &mt('If the text is hard to read, [_1] will replace them.',
16922:                    '<img src="/res/adm/pages/refresh.gif" alt="reCAPTCHA refresh" />').
16923:                '<br /><br />';
16924:      }
16925: }
16926: 
16927: sub check_recaptcha {
16928:     my ($privkey,$version) = @_;
16929:     my $captcha_chk;
16930:     if ($version >= 2) {
16931:         my $ua = LWP::UserAgent->new;
16932:         $ua->timeout(10);
16933:         my %info = (
16934:                      secret   => $privkey,
16935:                      response => $env{'form.g-recaptcha-response'},
16936:                      remoteip => $ENV{'REMOTE_ADDR'},
16937:                    );
16938:         my $response = $ua->post('https://www.google.com/recaptcha/api/siteverify',\%info);
16939:         if ($response->is_success)  {
16940:             my $data = JSON::DWIW->from_json($response->decoded_content);
16941:             if (ref($data) eq 'HASH') {
16942:                 if ($data->{'success'}) {
16943:                     $captcha_chk = 1;
16944:                 }
16945:             }
16946:         }
16947:     } else {
16948:         my $captcha = Captcha::reCAPTCHA->new;
16949:         my $captcha_result =
16950:             $captcha->check_answer(
16951:                                     $privkey,
16952:                                     $ENV{'REMOTE_ADDR'},
16953:                                     $env{'form.recaptcha_challenge_field'},
16954:                                     $env{'form.recaptcha_response_field'},
16955:                                   );
16956:         if ($captcha_result->{is_valid}) {
16957:             $captcha_chk = 1;
16958:         }
16959:     }
16960:     return $captcha_chk;
16961: }
16962: 
16963: sub emailusername_info {
16964:     my @fields = ('firstname','lastname','institution','web','location','officialemail','id');
16965:     my %titles = &Apache::lonlocal::texthash (
16966:                      lastname      => 'Last Name',
16967:                      firstname     => 'First Name',
16968:                      institution   => 'School/college/university',
16969:                      location      => "School's city, state/province, country",
16970:                      web           => "School's web address",
16971:                      officialemail => 'E-mail address at institution (if different)',
16972:                      id            => 'Student/Employee ID',
16973:                  );
16974:     return (\@fields,\%titles);
16975: }
16976: 
16977: sub cleanup_html {
16978:     my ($incoming) = @_;
16979:     my $outgoing;
16980:     if ($incoming ne '') {
16981:         $outgoing = $incoming;
16982:         $outgoing =~ s/;/&#059;/g;
16983:         $outgoing =~ s/\#/&#035;/g;
16984:         $outgoing =~ s/\&/&#038;/g;
16985:         $outgoing =~ s/</&#060;/g;
16986:         $outgoing =~ s/>/&#062;/g;
16987:         $outgoing =~ s/\(/&#040/g;
16988:         $outgoing =~ s/\)/&#041;/g;
16989:         $outgoing =~ s/"/&#034;/g;
16990:         $outgoing =~ s/'/&#039;/g;
16991:         $outgoing =~ s/\$/&#036;/g;
16992:         $outgoing =~ s{/}{&#047;}g;
16993:         $outgoing =~ s/=/&#061;/g;
16994:         $outgoing =~ s/\\/&#092;/g
16995:     }
16996:     return $outgoing;
16997: }
16998: 
16999: # Checks for critical messages and returns a redirect url if one exists.
17000: # $interval indicates how often to check for messages.
17001: # $context is the calling context -- roles, grades, contents, menu or flip.
17002: sub critical_redirect {
17003:     my ($interval,$context) = @_;
17004:     if ((time-$env{'user.criticalcheck.time'})>$interval) {
17005:         if (($env{'request.course.id'}) && (($context eq 'flip') || ($context eq 'contents'))) {
17006:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
17007:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
17008:             my $blocked = &blocking_status('alert',$cnum,$cdom,undef,1);
17009:             if ($blocked) {
17010:                 my $checkrole = "cm./$cdom/$cnum";
17011:                 if ($env{'request.course.sec'} ne '') {
17012:                     $checkrole .= "/$env{'request.course.sec'}";
17013:                 }
17014:                 unless ((&Apache::lonnet::allowed('evb',undef,undef,$checkrole)) &&
17015:                         ($env{'request.role'} !~ m{^st\./$cdom/$cnum})) {
17016:                     return;
17017:                 }
17018:             }
17019:         }
17020:         my @what=&Apache::lonnet::dump('critical', $env{'user.domain'},
17021:                                         $env{'user.name'});
17022:         &Apache::lonnet::appenv({'user.criticalcheck.time'=>time});
17023:         my $redirecturl;
17024:         if ($what[0]) {
17025:             if (($what[0] ne 'con_lost') && ($what[0]!~/^error\:/)) {
17026:                 $redirecturl='/adm/email?critical=display';
17027:                 my $url=&Apache::lonnet::absolute_url().$redirecturl;
17028:                 return (1, $url);
17029:             }
17030:         }
17031:     }
17032:     return ();
17033: }
17034: 
17035: # Use:
17036: #   my $answer=reply("encrypt:passwd:$udom:$uname:$upass",$tryserver);
17037: #
17038: ##################################################
17039: #          password associated functions         #
17040: ##################################################
17041: sub des_keys {
17042:     # Make a new key for DES encryption.
17043:     # Each key has two parts which are returned separately.
17044:     # Please note:  Each key must be passed through the &hex function
17045:     # before it is output to the web browser.  The hex versions cannot
17046:     # be used to decrypt.
17047:     my @hexstr=('0','1','2','3','4','5','6','7',
17048:                 '8','9','a','b','c','d','e','f');
17049:     my $lkey='';
17050:     for (0..7) {
17051:         $lkey.=$hexstr[rand(15)];
17052:     }
17053:     my $ukey='';
17054:     for (0..7) {
17055:         $ukey.=$hexstr[rand(15)];
17056:     }
17057:     return ($lkey,$ukey);
17058: }
17059: 
17060: sub des_decrypt {
17061:     my ($key,$cyphertext) = @_;
17062:     my $keybin=pack("H16",$key);
17063:     my $cypher;
17064:     if ($Crypt::DES::VERSION>=2.03) {
17065:         $cypher=new Crypt::DES $keybin;
17066:     } else {
17067:         $cypher=new DES $keybin;
17068:     }
17069:     my $plaintext='';
17070:     my $cypherlength = length($cyphertext);
17071:     my $numchunks = int($cypherlength/32);
17072:     for (my $j=0; $j<$numchunks; $j++) {
17073:         my $start = $j*32;
17074:         my $cypherblock = substr($cyphertext,$start,32);
17075:         my $chunk =
17076:             $cypher->decrypt(unpack("a8",pack("H16",substr($cypherblock,0,16))));
17077:         $chunk .=
17078:             $cypher->decrypt(unpack("a8",pack("H16",substr($cypherblock,16,16))));
17079:         $chunk=substr($chunk,1,ord(substr($chunk,0,1)) );
17080:         $plaintext .= $chunk;
17081:     }
17082:     return $plaintext;
17083: }
17084: 
17085: sub make_short_symbs {
17086:     my ($cdom,$cnum,$navmap) = @_;
17087:     return unless (ref($navmap));
17088:     my ($numnew,@errors);
17089:     my @toshorten = &Apache::loncommon::get_env_multiple('form.addtiny');
17090:     if (@toshorten) {
17091:         my (%maps,%resources,%titles);
17092:         &Apache::loncourserespicker::enumerate_course_contents($navmap,\%maps,\%resources,\%titles,
17093:                                                                'shorturls',$cdom,$cnum);
17094:         my %tocreate;
17095:         if (keys(%resources)) {
17096:             foreach my $item (sort {$a <=> $b} (@toshorten)) {
17097:                 my $symb = $resources{$item};
17098:                 if ($symb) {
17099:                     $tocreate{$cnum.'&'.$symb} = 1;
17100:                 }
17101:             }
17102:         }
17103:         if (keys(%tocreate)) {
17104:             my %coursetiny = &Apache::lonnet::dump('tiny',$cdom,$cnum);
17105:             my $su = Short::URL->new(no_vowels => 1);
17106:             my $init = '';
17107:             my (%newunique,%addcourse,%courseonly,%failed);
17108:             # get lock on tiny db
17109:             my $now = time;
17110:             my $lockhash = {
17111:                                 "lock\0$now" => $env{'user.name'}.
17112:                                                 ':'.$env{'user.domain'},
17113:                             };
17114:             my $tries = 0;
17115:             my $gotlock = &Apache::lonnet::newput_dom('tiny',$lockhash,$cdom);
17116:             my ($code,$error);
17117:             while (($gotlock ne 'ok') && ($tries<3)) {
17118:                 $tries ++;
17119:                 sleep 1;
17120:                 $gotlock = &Apache::lonnet::newput_dom('tiny',$lockhash,$cdom);
17121:             }
17122:             if ($gotlock eq 'ok') {
17123:                 $init = &shorten_symbs($cdom,$init,$su,\%coursetiny,\%tocreate,\%newunique,
17124:                                        \%addcourse,\%courseonly,\%failed);
17125:                 if (keys(%failed)) {
17126:                     my $numfailed = scalar(keys(%failed));
17127:                     push(@errors,&mt('error: could not obtain unique six character URL for [quant,_1,resource]',$numfailed));
17128:                 }
17129:                 if (keys(%newunique)) {
17130:                     my $putres = &Apache::lonnet::newput_dom('tiny',\%newunique,$cdom);
17131:                     if ($putres eq 'ok') {
17132:                         $numnew = scalar(keys(%newunique));
17133:                         my $newputres = &Apache::lonnet::newput('tiny',\%addcourse,$cdom,$cnum);
17134:                         unless ($newputres eq 'ok') {
17135:                             push(@errors,&mt('error: could not store course look-up of short URLs'));
17136:                         }
17137:                     } else {
17138:                         push(@errors,&mt('error: could not store unique six character URLs'));
17139:                     }
17140:                 }
17141:                 my $dellockres = &Apache::lonnet::del_dom('tiny',["lock\0$now"],$cdom);
17142:                 unless ($dellockres eq 'ok') {
17143:                     push(@errors,&mt('error: could not release lockfile'));
17144:                 }
17145:             } else {
17146:                 push(@errors,&mt('error: could not obtain lockfile'));
17147:             }
17148:             if (keys(%courseonly)) {
17149:                 my $result = &Apache::lonnet::newput('tiny',\%courseonly,$cdom,$cnum);
17150:                 if ($result ne 'ok') {
17151:                     push(@errors,&mt('error: could not update course look-up of short URLs'));
17152:                 }
17153:             }
17154:         }
17155:     }
17156:     return ($numnew,\@errors);
17157: }
17158: 
17159: sub shorten_symbs {
17160:     my ($cdom,$init,$su,$coursetiny,$tocreate,$newunique,$addcourse,$courseonly,$failed) = @_;
17161:     return unless ((ref($su)) && (ref($coursetiny) eq 'HASH') && (ref($tocreate) eq 'HASH') &&
17162:                    (ref($newunique) eq 'HASH') && (ref($addcourse) eq 'HASH') &&
17163:                    (ref($courseonly) eq 'HASH') && (ref($failed) eq 'HASH'));
17164:     my (%possibles,%collisions);
17165:     foreach my $key (keys(%{$tocreate})) {
17166:         my $num = String::CRC32::crc32($key);
17167:         my $tiny = $su->encode($num,$init);
17168:         if ($tiny) {
17169:             $possibles{$tiny} = $key;
17170:         }
17171:     }
17172:     if (!$init) {
17173:         $init = 1;
17174:     } else {
17175:         $init ++;
17176:     }
17177:     if (keys(%possibles)) {
17178:         my @posstiny = keys(%possibles);
17179:         my $configuname = &Apache::lonnet::get_domainconfiguser($cdom);
17180:         my %currtiny = &Apache::lonnet::get('tiny',\@posstiny,$cdom,$configuname);
17181:         if (keys(%currtiny)) {
17182:             foreach my $key (keys(%currtiny)) {
17183:                 next if ($currtiny{$key} eq '');
17184:                 if ($currtiny{$key} eq $possibles{$key}) {
17185:                     my ($tcnum,$tsymb) = split(/\&/,$currtiny{$key});
17186:                     unless (($coursetiny->{$tsymb} eq $key) || ($addcourse->{$tsymb} eq $key) || ($courseonly->{$tsymb} eq $key)) {
17187:                         $courseonly->{$tsymb} = $key;
17188:                     }
17189:                 } else {
17190:                     $collisions{$possibles{$key}} = 1;
17191:                 }
17192:                 delete($possibles{$key});
17193:             }
17194:         }
17195:         foreach my $key (keys(%possibles)) {
17196:             $newunique->{$key} = $possibles{$key};
17197:             my ($tcnum,$tsymb) = split(/\&/,$possibles{$key});
17198:             unless (($coursetiny->{$tsymb} eq $key) || ($addcourse->{$tsymb} eq $key) || ($courseonly->{$tsymb} eq $key)) {
17199:                 $addcourse->{$tsymb} = $key;
17200:             }
17201:         }
17202:     }
17203:     if (keys(%collisions)) {
17204:         if ($init <5) {
17205:             if (!$init) {
17206:                 $init = 1;
17207:             } else {
17208:                 $init ++;
17209:             }
17210:             $init = &shorten_symbs($cdom,$init,$su,$coursetiny,\%collisions,
17211:                                    $newunique,$addcourse,$courseonly,$failed);
17212:         } else {
17213:             foreach my $key (keys(%collisions)) {
17214:                 $failed->{$key} = 1;
17215:             }
17216:         }
17217:     }
17218:     return $init;
17219: }
17220: 
17221: 1;
17222: __END__;
17223: 

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