File:  [LON-CAPA] / loncom / interface / loncommon.pm
Revision 1.1075.2.127.6.4: download - view: text, annotated - select for diffs
Wed Jun 3 11:50:17 2020 UTC (3 years, 11 months ago) by raeburn
Branches: version_2_11_2_uiuc
Diff to branchpoint 1.1075.2.127: preferred, unified
- For 2.11.2 (modified)
  Include changes in 1.1342

    1: # The LearningOnline Network with CAPA
    2: # a pile of common routines
    3: #
    4: # $Id: loncommon.pm,v 1.1075.2.127.6.4 2020/06/03 11:50:17 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: 
   84: # ---------------------------------------------- Designs
   85: use vars qw(%defaultdesign);
   86: 
   87: my $readit;
   88: 
   89: 
   90: ##
   91: ## Global Variables
   92: ##
   93: 
   94: 
   95: # ----------------------------------------------- SSI with retries:
   96: #
   97: 
   98: =pod
   99: 
  100: =head1 Server Side include with retries:
  101: 
  102: =over 4
  103: 
  104: =item * &ssi_with_retries(resource,retries form)
  105: 
  106: Performs an ssi with some number of retries.  Retries continue either
  107: until the result is ok or until the retry count supplied by the
  108: caller is exhausted.  
  109: 
  110: Inputs:
  111: 
  112: =over 4
  113: 
  114: resource   - Identifies the resource to insert.
  115: 
  116: retries    - Count of the number of retries allowed.
  117: 
  118: form       - Hash that identifies the rendering options.
  119: 
  120: =back
  121: 
  122: Returns:
  123: 
  124: =over 4
  125: 
  126: content    - The content of the response.  If retries were exhausted this is empty.
  127: 
  128: response   - The response from the last attempt (which may or may not have been successful.
  129: 
  130: =back
  131: 
  132: =back
  133: 
  134: =cut
  135: 
  136: sub ssi_with_retries {
  137:     my ($resource, $retries, %form) = @_;
  138: 
  139: 
  140:     my $ok = 0;			# True if we got a good response.
  141:     my $content;
  142:     my $response;
  143: 
  144:     # Try to get the ssi done. within the retries count:
  145: 
  146:     do {
  147: 	($content, $response) = &Apache::lonnet::ssi($resource, %form);
  148: 	$ok      = $response->is_success;
  149:         if (!$ok) {
  150:             &Apache::lonnet::logthis("Failed ssi_with_retries on $resource: ".$response->is_success.', '.$response->code.', '.$response->message);
  151:         }
  152: 	$retries--;
  153:     } while (!$ok && ($retries > 0));
  154: 
  155:     if (!$ok) {
  156: 	$content = '';		# On error return an empty content.
  157:     }
  158:     return ($content, $response);
  159: 
  160: }
  161: 
  162: 
  163: 
  164: # ----------------------------------------------- Filetypes/Languages/Copyright
  165: my %language;
  166: my %supported_language;
  167: my %latex_language;		# For choosing hyphenation in <transl..>
  168: my %latex_language_bykey;	# for choosing hyphenation from metadata
  169: my %cprtag;
  170: my %scprtag;
  171: my %fe; my %fd; my %fm;
  172: my %category_extensions;
  173: 
  174: # ---------------------------------------------- Thesaurus variables
  175: #
  176: # %Keywords:
  177: #      A hash used by &keyword to determine if a word is considered a keyword.
  178: # $thesaurus_db_file 
  179: #      Scalar containing the full path to the thesaurus database.
  180: 
  181: my %Keywords;
  182: my $thesaurus_db_file;
  183: 
  184: #
  185: # Initialize values from language.tab, copyright.tab, filetypes.tab,
  186: # thesaurus.tab, and filecategories.tab.
  187: #
  188: BEGIN {
  189:     # Variable initialization
  190:     $thesaurus_db_file = $Apache::lonnet::perlvar{'lonTabDir'}."/thesaurus.db";
  191:     #
  192:     unless ($readit) {
  193: # ------------------------------------------------------------------- languages
  194:     {
  195:         my $langtabfile = $Apache::lonnet::perlvar{'lonTabDir'}.
  196:                                    '/language.tab';
  197:         if ( open(my $fh,"<$langtabfile") ) {
  198:             while (my $line = <$fh>) {
  199:                 next if ($line=~/^\#/);
  200:                 chomp($line);
  201:                 my ($key,$two,$country,$three,$enc,$val,$sup,$latex)=(split(/\t/,$line));
  202:                 $language{$key}=$val.' - '.$enc;
  203:                 if ($sup) {
  204:                     $supported_language{$key}=$sup;
  205:                 }
  206: 		if ($latex) {
  207: 		    $latex_language_bykey{$key} = $latex;
  208: 		    $latex_language{$two} = $latex;
  209: 		}
  210:             }
  211:             close($fh);
  212:         }
  213:     }
  214: # ------------------------------------------------------------------ copyrights
  215:     {
  216:         my $copyrightfile = $Apache::lonnet::perlvar{'lonIncludes'}.
  217:                                   '/copyright.tab';
  218:         if ( open (my $fh,"<$copyrightfile") ) {
  219:             while (my $line = <$fh>) {
  220:                 next if ($line=~/^\#/);
  221:                 chomp($line);
  222:                 my ($key,$val)=(split(/\s+/,$line,2));
  223:                 $cprtag{$key}=$val;
  224:             }
  225:             close($fh);
  226:         }
  227:     }
  228: # ----------------------------------------------------------- source copyrights
  229:     {
  230:         my $sourcecopyrightfile = $Apache::lonnet::perlvar{'lonIncludes'}.
  231:                                   '/source_copyright.tab';
  232:         if ( open (my $fh,"<$sourcecopyrightfile") ) {
  233:             while (my $line = <$fh>) {
  234:                 next if ($line =~ /^\#/);
  235:                 chomp($line);
  236:                 my ($key,$val)=(split(/\s+/,$line,2));
  237:                 $scprtag{$key}=$val;
  238:             }
  239:             close($fh);
  240:         }
  241:     }
  242: 
  243: # -------------------------------------------------------------- default domain designs
  244:     my $designdir=$Apache::lonnet::perlvar{'lonTabDir'}.'/lonDomColors';
  245:     my $designfile = $designdir.'/default.tab';
  246:     if ( open (my $fh,"<$designfile") ) {
  247:         while (my $line = <$fh>) {
  248:             next if ($line =~ /^\#/);
  249:             chomp($line);
  250:             my ($key,$val)=(split(/\=/,$line));
  251:             if ($val) { $defaultdesign{$key}=$val; }
  252:         }
  253:         close($fh);
  254:     }
  255: 
  256: # ------------------------------------------------------------- file categories
  257:     {
  258:         my $categoryfile = $Apache::lonnet::perlvar{'lonTabDir'}.
  259:                                   '/filecategories.tab';
  260:         if ( open (my $fh,"<$categoryfile") ) {
  261: 	    while (my $line = <$fh>) {
  262: 		next if ($line =~ /^\#/);
  263: 		chomp($line);
  264:                 my ($extension,$category)=(split(/\s+/,$line,2));
  265:                 push(@{$category_extensions{lc($category)}},$extension);
  266:             }
  267:             close($fh);
  268:         }
  269: 
  270:     }
  271: # ------------------------------------------------------------------ file types
  272:     {
  273:         my $typesfile = $Apache::lonnet::perlvar{'lonTabDir'}.
  274:                '/filetypes.tab';
  275:         if ( open (my $fh,"<$typesfile") ) {
  276:             while (my $line = <$fh>) {
  277: 		next if ($line =~ /^\#/);
  278: 		chomp($line);
  279:                 my ($ending,$emb,$mime,$descr)=split(/\s+/,$line,4);
  280:                 if ($descr ne '') {
  281:                     $fe{$ending}=lc($emb);
  282:                     $fd{$ending}=$descr;
  283:                     if ($mime ne 'unk') { $fm{$ending}=$mime; }
  284:                 }
  285:             }
  286:             close($fh);
  287:         }
  288:     }
  289:     &Apache::lonnet::logthis(
  290:              "<span style='color:yellow;'>INFO: Read file types</span>");
  291:     $readit=1;
  292:     }  # end of unless($readit) 
  293:     
  294: }
  295: 
  296: ###############################################################
  297: ##           HTML and Javascript Helper Functions            ##
  298: ###############################################################
  299: 
  300: =pod 
  301: 
  302: =head1 HTML and Javascript Functions
  303: 
  304: =over 4
  305: 
  306: =item * &browser_and_searcher_javascript()
  307: 
  308: X<browsing, javascript>X<searching, javascript>Returns a string
  309: containing javascript with two functions, C<openbrowser> and
  310: C<opensearcher>. Returned string does not contain E<lt>scriptE<gt>
  311: tags.
  312: 
  313: =item * &openbrowser(formname,elementname,only,omit) [javascript]
  314: 
  315: inputs: formname, elementname, only, omit
  316: 
  317: formname and elementname indicate the name of the html form and name of
  318: the element that the results of the browsing selection are to be placed in. 
  319: 
  320: Specifying 'only' will restrict the browser to displaying only files
  321: with the given extension.  Can be a comma separated list.
  322: 
  323: Specifying 'omit' will restrict the browser to NOT displaying files
  324: with the given extension.  Can be a comma separated list.
  325: 
  326: =item * &opensearcher(formname,elementname) [javascript]
  327: 
  328: Inputs: formname, elementname
  329: 
  330: formname and elementname specify the name of the html form and the name
  331: of the element the selection from the search results will be placed in.
  332: 
  333: =cut
  334: 
  335: sub browser_and_searcher_javascript {
  336:     my ($mode)=@_;
  337:     if (!defined($mode)) { $mode='edit'; }
  338:     my $resurl=&escape_single(&lastresurl());
  339:     return <<END;
  340: // <!-- BEGIN LON-CAPA Internal
  341:     var editbrowser = null;
  342:     function openbrowser(formname,elementname,only,omit,titleelement) {
  343:         var url = '$resurl/?';
  344:         if (editbrowser == null) {
  345:             url += 'launch=1&';
  346:         }
  347:         url += 'catalogmode=interactive&';
  348:         url += 'mode=$mode&';
  349:         url += 'inhibitmenu=yes&';
  350:         url += 'form=' + formname + '&';
  351:         if (only != null) {
  352:             url += 'only=' + only + '&';
  353:         } else {
  354:             url += 'only=&';
  355: 	}
  356:         if (omit != null) {
  357:             url += 'omit=' + omit + '&';
  358:         } else {
  359:             url += 'omit=&';
  360: 	}
  361:         if (titleelement != null) {
  362:             url += 'titleelement=' + titleelement + '&';
  363:         } else {
  364: 	    url += 'titleelement=&';
  365: 	}
  366:         url += 'element=' + elementname + '';
  367:         var title = 'Browser';
  368:         var options = 'scrollbars=1,resizable=1,menubar=0,toolbar=1,location=1';
  369:         options += ',width=700,height=600';
  370:         editbrowser = open(url,title,options,'1');
  371:         editbrowser.focus();
  372:     }
  373:     var editsearcher;
  374:     function opensearcher(formname,elementname,titleelement) {
  375:         var url = '/adm/searchcat?';
  376:         if (editsearcher == null) {
  377:             url += 'launch=1&';
  378:         }
  379:         url += 'catalogmode=interactive&';
  380:         url += 'mode=$mode&';
  381:         url += 'form=' + formname + '&';
  382:         if (titleelement != null) {
  383:             url += 'titleelement=' + titleelement + '&';
  384:         } else {
  385: 	    url += 'titleelement=&';
  386: 	}
  387:         url += 'element=' + elementname + '';
  388:         var title = 'Search';
  389:         var options = 'scrollbars=1,resizable=1,menubar=0,toolbar=1,location=1';
  390:         options += ',width=700,height=600';
  391:         editsearcher = open(url,title,options,'1');
  392:         editsearcher.focus();
  393:     }
  394: // END LON-CAPA Internal -->
  395: END
  396: }
  397: 
  398: sub lastresurl {
  399:     if ($env{'environment.lastresurl'}) {
  400: 	return $env{'environment.lastresurl'}
  401:     } else {
  402: 	return '/res';
  403:     }
  404: }
  405: 
  406: sub storeresurl {
  407:     my $resurl=&Apache::lonnet::clutter(shift);
  408:     unless ($resurl=~/^\/res/) { return 0; }
  409:     $resurl=~s/\/$//;
  410:     &Apache::lonnet::put('environment',{'lastresurl' => $resurl});
  411:     &Apache::lonnet::appenv({'environment.lastresurl' => $resurl});
  412:     return 1;
  413: }
  414: 
  415: sub studentbrowser_javascript {
  416:    unless (
  417:             (($env{'request.course.id'}) && 
  418:              (&Apache::lonnet::allowed('srm',$env{'request.course.id'})
  419: 	      || &Apache::lonnet::allowed('srm',$env{'request.course.id'}.
  420: 					  '/'.$env{'request.course.sec'})
  421: 	      ))
  422:          || ($env{'request.role'}=~/^(au|dc|su)/)
  423:           ) { return ''; }  
  424:    return (<<'ENDSTDBRW');
  425: <script type="text/javascript" language="Javascript">
  426: // <![CDATA[
  427:     var stdeditbrowser;
  428:     function openstdbrowser(formname,uname,udom,clicker,roleflag,ignorefilter,courseadvonly) {
  429:         var url = '/adm/pickstudent?';
  430:         var filter;
  431: 	if (!ignorefilter) {
  432: 	    eval('filter=document.'+formname+'.'+uname+'.value;');
  433: 	}
  434:         if (filter != null) {
  435:            if (filter != '') {
  436:                url += 'filter='+filter+'&';
  437: 	   }
  438:         }
  439:         url += 'form=' + formname + '&unameelement='+uname+
  440:                                     '&udomelement='+udom+
  441:                                     '&clicker='+clicker;
  442: 	if (roleflag) { url+="&roles=1"; }
  443:         if (courseadvonly) { url+="&courseadvonly=1"; }
  444:         var title = 'Student_Browser';
  445:         var options = 'scrollbars=1,resizable=1,menubar=0';
  446:         options += ',width=700,height=600';
  447:         stdeditbrowser = open(url,title,options,'1');
  448:         stdeditbrowser.focus();
  449:     }
  450: // ]]>
  451: </script>
  452: ENDSTDBRW
  453: }
  454: 
  455: sub resourcebrowser_javascript {
  456:    unless ($env{'request.course.id'}) { return ''; }
  457:    return (<<'ENDRESBRW');
  458: <script type="text/javascript" language="Javascript">
  459: // <![CDATA[
  460:     var reseditbrowser;
  461:     function openresbrowser(formname,reslink) {
  462:         var url = '/adm/pickresource?form='+formname+'&reslink='+reslink;
  463:         var title = 'Resource_Browser';
  464:         var options = 'scrollbars=1,resizable=1,menubar=0';
  465:         options += ',width=700,height=500';
  466:         reseditbrowser = open(url,title,options,'1');
  467:         reseditbrowser.focus();
  468:     }
  469: // ]]>
  470: </script>
  471: ENDRESBRW
  472: }
  473: 
  474: sub selectstudent_link {
  475:    my ($form,$unameele,$udomele,$courseadvonly,$clickerid)=@_;
  476:    my $callargs = "'".&Apache::lonhtmlcommon::entity_encode($form)."','".
  477:                       &Apache::lonhtmlcommon::entity_encode($unameele)."','".
  478:                       &Apache::lonhtmlcommon::entity_encode($udomele)."'";
  479:    if ($env{'request.course.id'}) {  
  480:        if (!&Apache::lonnet::allowed('srm',$env{'request.course.id'})
  481: 	   && !&Apache::lonnet::allowed('srm',$env{'request.course.id'}.
  482: 					'/'.$env{'request.course.sec'})) {
  483: 	   return '';
  484:        }
  485:        $callargs.=",'".&Apache::lonhtmlcommon::entity_encode($clickerid)."'";
  486:        if ($courseadvonly)  {
  487:            $callargs .= ",'',1,1";
  488:        }
  489:        return '<span class="LC_nobreak">'.
  490:               '<a href="javascript:openstdbrowser('.$callargs.');">'.
  491:               &mt('Select User').'</a></span>';
  492:    }
  493:    if ($env{'request.role'}=~/^(au|dc|su)/) {
  494:        $callargs .= ",'',1"; 
  495:        return '<span class="LC_nobreak">'.
  496:               '<a href="javascript:openstdbrowser('.$callargs.');">'.
  497:               &mt('Select User').'</a></span>';
  498:    }
  499:    return '';
  500: }
  501: 
  502: sub selectresource_link {
  503:    my ($form,$reslink,$arg)=@_;
  504:    
  505:    my $callargs = "'".&Apache::lonhtmlcommon::entity_encode($form)."','".
  506:                       &Apache::lonhtmlcommon::entity_encode($reslink)."'";
  507:    unless ($env{'request.course.id'}) { return $arg; }
  508:    return '<span class="LC_nobreak">'.
  509:               '<a href="javascript:openresbrowser('.$callargs.');">'.
  510:               $arg.'</a></span>';
  511: }
  512: 
  513: 
  514: 
  515: sub authorbrowser_javascript {
  516:     return <<"ENDAUTHORBRW";
  517: <script type="text/javascript" language="JavaScript">
  518: // <![CDATA[
  519: var stdeditbrowser;
  520: 
  521: function openauthorbrowser(formname,udom) {
  522:     var url = '/adm/pickauthor?';
  523:     url += 'form='+formname+'&roledom='+udom;
  524:     var title = 'Author_Browser';
  525:     var options = 'scrollbars=1,resizable=1,menubar=0';
  526:     options += ',width=700,height=600';
  527:     stdeditbrowser = open(url,title,options,'1');
  528:     stdeditbrowser.focus();
  529: }
  530: 
  531: // ]]>
  532: </script>
  533: ENDAUTHORBRW
  534: }
  535: 
  536: sub coursebrowser_javascript {
  537:     my ($domainfilter,$sec_element,$formname,$role_element,$crstype,
  538:         $credits_element,$instcode) = @_;
  539:     my $wintitle = 'Course_Browser';
  540:     if ($crstype eq 'Community') {
  541:         $wintitle = 'Community_Browser';
  542:     }
  543:     my $id_functions = &javascript_index_functions();
  544:     my $output = '
  545: <script type="text/javascript" language="JavaScript">
  546: // <![CDATA[
  547:     var stdeditbrowser;'."\n";
  548: 
  549:     $output .= <<"ENDSTDBRW";
  550:     function opencrsbrowser(formname,uname,udom,desc,extra_element,multflag,type,type_elem) {
  551:         var url = '/adm/pickcourse?';
  552:         var formid = getFormIdByName(formname);
  553:         var domainfilter = getDomainFromSelectbox(formname,udom);
  554:         if (domainfilter != null) {
  555:            if (domainfilter != '') {
  556:                url += 'domainfilter='+domainfilter+'&';
  557: 	   }
  558:         }
  559:         url += 'form=' + formname + '&cnumelement='+uname+
  560: 	                            '&cdomelement='+udom+
  561:                                     '&cnameelement='+desc;
  562:         if (extra_element !=null && extra_element != '') {
  563:             if (formname == 'rolechoice' || formname == 'studentform') {
  564:                 url += '&roleelement='+extra_element;
  565:                 if (domainfilter == null || domainfilter == '') {
  566:                     url += '&domainfilter='+extra_element;
  567:                 }
  568:             }
  569:             else {
  570:                 if (formname == 'portform') {
  571:                     url += '&setroles='+extra_element;
  572:                 } else {
  573:                     if (formname == 'rules') {
  574:                         url += '&fixeddom='+extra_element; 
  575:                     }
  576:                 }
  577:             }     
  578:         }
  579:         if (type != null && type != '') {
  580:             url += '&type='+type;
  581:         }
  582:         if (type_elem != null && type_elem != '') {
  583:             url += '&typeelement='+type_elem;
  584:         }
  585:         if (formname == 'ccrs') {
  586:             var ownername = document.forms[formid].ccuname.value;
  587:             var ownerdom =  document.forms[formid].ccdomain.options[document.forms[formid].ccdomain.selectedIndex].value;
  588:             url += '&cloner='+ownername+':'+ownerdom;
  589:             if (type == 'Course') {
  590:                 url += '&crscode='+document.forms[formid].crscode.value;
  591:             }
  592:         }
  593:         if (formname == 'requestcrs') {
  594:             url += '&crsdom=$domainfilter&crscode=$instcode';
  595:         }
  596:         if (multflag !=null && multflag != '') {
  597:             url += '&multiple='+multflag;
  598:         }
  599:         var title = '$wintitle';
  600:         var options = 'scrollbars=1,resizable=1,menubar=0';
  601:         options += ',width=700,height=600';
  602:         stdeditbrowser = open(url,title,options,'1');
  603:         stdeditbrowser.focus();
  604:     }
  605: $id_functions
  606: ENDSTDBRW
  607:     if (($sec_element ne '') || ($role_element ne '') || ($credits_element ne '')) {
  608:         $output .= &setsec_javascript($sec_element,$formname,$role_element,
  609:                                       $credits_element);
  610:     }
  611:     $output .= '
  612: // ]]>
  613: </script>';
  614:     return $output;
  615: }
  616: 
  617: sub javascript_index_functions {
  618:     return <<"ENDJS";
  619: 
  620: function getFormIdByName(formname) {
  621:     for (var i=0;i<document.forms.length;i++) {
  622:         if (document.forms[i].name == formname) {
  623:             return i;
  624:         }
  625:     }
  626:     return -1;
  627: }
  628: 
  629: function getIndexByName(formid,item) {
  630:     for (var i=0;i<document.forms[formid].elements.length;i++) {
  631:         if (document.forms[formid].elements[i].name == item) {
  632:             return i;
  633:         }
  634:     }
  635:     return -1;
  636: }
  637: 
  638: function getDomainFromSelectbox(formname,udom) {
  639:     var userdom;
  640:     var formid = getFormIdByName(formname);
  641:     if (formid > -1) {
  642:         var domid = getIndexByName(formid,udom);
  643:         if (domid > -1) {
  644:             if (document.forms[formid].elements[domid].type == 'select-one') {
  645:                 userdom=document.forms[formid].elements[domid].options[document.forms[formid].elements[domid].selectedIndex].value;
  646:             }
  647:             if (document.forms[formid].elements[domid].type == 'hidden') {
  648:                 userdom=document.forms[formid].elements[domid].value;
  649:             }
  650:         }
  651:     }
  652:     return userdom;
  653: }
  654: 
  655: ENDJS
  656: 
  657: }
  658: 
  659: sub javascript_array_indexof {
  660:     return <<ENDJS;
  661: <script type="text/javascript" language="JavaScript">
  662: // <![CDATA[
  663: 
  664: if (!Array.prototype.indexOf) {
  665:     Array.prototype.indexOf = function (searchElement /*, fromIndex */ ) {
  666:         "use strict";
  667:         if (this === void 0 || this === null) {
  668:             throw new TypeError();
  669:         }
  670:         var t = Object(this);
  671:         var len = t.length >>> 0;
  672:         if (len === 0) {
  673:             return -1;
  674:         }
  675:         var n = 0;
  676:         if (arguments.length > 0) {
  677:             n = Number(arguments[1]);
  678:             if (n !== n) { // shortcut for verifying if it's NaN
  679:                 n = 0;
  680:             } else if (n !== 0 && n !== (1 / 0) && n !== -(1 / 0)) {
  681:                 n = (n > 0 || -1) * Math.floor(Math.abs(n));
  682:             }
  683:         }
  684:         if (n >= len) {
  685:             return -1;
  686:         }
  687:         var k = n >= 0 ? n : Math.max(len - Math.abs(n), 0);
  688:         for (; k < len; k++) {
  689:             if (k in t && t[k] === searchElement) {
  690:                 return k;
  691:             }
  692:         }
  693:         return -1;
  694:     }
  695: }
  696: 
  697: // ]]>
  698: </script>
  699: 
  700: ENDJS
  701: 
  702: }
  703: 
  704: sub userbrowser_javascript {
  705:     my $id_functions = &javascript_index_functions();
  706:     return <<"ENDUSERBRW";
  707: 
  708: function openuserbrowser(formname,uname,udom,ulast,ufirst,uemail,hideudom,crsdom,caller) {
  709:     var url = '/adm/pickuser?';
  710:     var userdom = getDomainFromSelectbox(formname,udom);
  711:     if (userdom != null) {
  712:        if (userdom != '') {
  713:            url += 'srchdom='+userdom+'&';
  714:        }
  715:     }
  716:     url += 'form=' + formname + '&unameelement='+uname+
  717:                                 '&udomelement='+udom+
  718:                                 '&ulastelement='+ulast+
  719:                                 '&ufirstelement='+ufirst+
  720:                                 '&uemailelement='+uemail+
  721:                                 '&hideudomelement='+hideudom+
  722:                                 '&coursedom='+crsdom;
  723:     if ((caller != null) && (caller != undefined)) {
  724:         url += '&caller='+caller;
  725:     }
  726:     var title = 'User_Browser';
  727:     var options = 'scrollbars=1,resizable=1,menubar=0';
  728:     options += ',width=700,height=600';
  729:     var stdeditbrowser = open(url,title,options,'1');
  730:     stdeditbrowser.focus();
  731: }
  732: 
  733: function fix_domain (formname,udom,origdom,uname) {
  734:     var formid = getFormIdByName(formname);
  735:     if (formid > -1) {
  736:         var unameid = getIndexByName(formid,uname);
  737:         var domid = getIndexByName(formid,udom);
  738:         var hidedomid = getIndexByName(formid,origdom);
  739:         if (hidedomid > -1) {
  740:             var fixeddom = document.forms[formid].elements[hidedomid].value;
  741:             var unameval = document.forms[formid].elements[unameid].value;
  742:             if ((fixeddom != '') && (fixeddom != undefined) && (fixeddom != null) && (unameval != '') && (unameval != undefined) && (unameval != null)) {
  743:                 if (domid > -1) {
  744:                     var slct = document.forms[formid].elements[domid];
  745:                     if (slct.type == 'select-one') {
  746:                         var i;
  747:                         for (i=0;i<slct.length;i++) {
  748:                             if (slct.options[i].value==fixeddom) { slct.selectedIndex=i; }
  749:                         }
  750:                     }
  751:                     if (slct.type == 'hidden') {
  752:                         slct.value = fixeddom;
  753:                     }
  754:                 }
  755:             }
  756:         }
  757:     }
  758:     return;
  759: }
  760: 
  761: $id_functions
  762: ENDUSERBRW
  763: }
  764: 
  765: sub setsec_javascript {
  766:     my ($sec_element,$formname,$role_element,$credits_element) = @_;
  767:     my (@courserolenames,@communityrolenames,$rolestr,$courserolestr,
  768:         $communityrolestr);
  769:     if ($role_element ne '') {
  770:         my @allroles = ('st','ta','ep','in','ad');
  771:         foreach my $crstype ('Course','Community') {
  772:             if ($crstype eq 'Community') {
  773:                 foreach my $role (@allroles) {
  774:                     push(@communityrolenames,&Apache::lonnet::plaintext($role,$crstype));
  775:                 }
  776:                 push(@communityrolenames,&Apache::lonnet::plaintext('co'));
  777:             } else {
  778:                 foreach my $role (@allroles) {
  779:                     push(@courserolenames,&Apache::lonnet::plaintext($role,$crstype));
  780:                 }
  781:                 push(@courserolenames,&Apache::lonnet::plaintext('cc'));
  782:             }
  783:         }
  784:         $rolestr = '"'.join('","',@allroles).'"';
  785:         $courserolestr = '"'.join('","',@courserolenames).'"';
  786:         $communityrolestr = '"'.join('","',@communityrolenames).'"';
  787:     }
  788:     my $setsections = qq|
  789: function setSect(sectionlist) {
  790:     var sectionsArray = new Array();
  791:     if ((sectionlist != '') && (typeof sectionlist != "undefined")) {
  792:         sectionsArray = sectionlist.split(",");
  793:     }
  794:     var numSections = sectionsArray.length;
  795:     document.$formname.$sec_element.length = 0;
  796:     if (numSections == 0) {
  797:         document.$formname.$sec_element.multiple=false;
  798:         document.$formname.$sec_element.size=1;
  799:         document.$formname.$sec_element.options[0] = new Option('No existing sections','',false,false)
  800:     } else {
  801:         if (numSections == 1) {
  802:             document.$formname.$sec_element.multiple=false;
  803:             document.$formname.$sec_element.size=1;
  804:             document.$formname.$sec_element.options[0] = new Option('Select','',true,true);
  805:             document.$formname.$sec_element.options[1] = new Option('No section','',false,false)
  806:             document.$formname.$sec_element.options[2] = new Option(sectionsArray[0],sectionsArray[0],false,false);
  807:         } else {
  808:             for (var i=0; i<numSections; i++) {
  809:                 document.$formname.$sec_element.options[i] = new Option(sectionsArray[i],sectionsArray[i],false,false)
  810:             }
  811:             document.$formname.$sec_element.multiple=true
  812:             if (numSections < 3) {
  813:                 document.$formname.$sec_element.size=numSections;
  814:             } else {
  815:                 document.$formname.$sec_element.size=3;
  816:             }
  817:             document.$formname.$sec_element.options[0].selected = false
  818:         }
  819:     }
  820: }
  821: 
  822: function setRole(crstype) {
  823: |;
  824:     if ($role_element eq '') {
  825:         $setsections .= '    return;
  826: }
  827: ';
  828:     } else {
  829:         $setsections .= qq|
  830:     var elementLength = document.$formname.$role_element.length;
  831:     var allroles = Array($rolestr);
  832:     var courserolenames = Array($courserolestr);
  833:     var communityrolenames = Array($communityrolestr);
  834:     if (elementLength != undefined) {
  835:         if (document.$formname.$role_element.options[5].value == 'cc') {
  836:             if (crstype == 'Course') {
  837:                 return;
  838:             } else {
  839:                 allroles[5] = 'co';
  840:                 for (var i=0; i<6; i++) {
  841:                     document.$formname.$role_element.options[i].value = allroles[i];
  842:                     document.$formname.$role_element.options[i].text = communityrolenames[i];
  843:                 }
  844:             }
  845:         } else {
  846:             if (crstype == 'Community') {
  847:                 return;
  848:             } else {
  849:                 allroles[5] = 'cc';
  850:                 for (var i=0; i<6; i++) {
  851:                     document.$formname.$role_element.options[i].value = allroles[i];
  852:                     document.$formname.$role_element.options[i].text = courserolenames[i];
  853:                 }
  854:             }
  855:         }
  856:     }
  857:     return;
  858: }
  859: |;
  860:     }
  861:     if ($credits_element) {
  862:         $setsections .= qq|
  863: function setCredits(defaultcredits) {
  864:     document.$formname.$credits_element.value = defaultcredits;
  865:     return;
  866: }
  867: |;
  868:     }
  869:     return $setsections;
  870: }
  871: 
  872: sub selectcourse_link {
  873:    my ($form,$unameele,$udomele,$desc,$extra_element,$multflag,$selecttype,
  874:        $typeelement) = @_;
  875:    my $type = $selecttype;
  876:    my $linktext = &mt('Select Course');
  877:    if ($selecttype eq 'Community') {
  878:        $linktext = &mt('Select Community');
  879:    } elsif ($selecttype eq 'Course/Community') {
  880:        $linktext = &mt('Select Course/Community');
  881:        $type = '';
  882:    } elsif ($selecttype eq 'Select') {
  883:        $linktext = &mt('Select');
  884:        $type = '';
  885:    }
  886:    return '<span class="LC_nobreak">'
  887:          ."<a href='"
  888:          .'javascript:opencrsbrowser("'.$form.'","'.$unameele
  889:          .'","'.$udomele.'","'.$desc.'","'.$extra_element
  890:          .'","'.$multflag.'","'.$type.'","'.$typeelement.'");'
  891:          ."'>".$linktext.'</a>'
  892:          .'</span>';
  893: }
  894: 
  895: sub selectauthor_link {
  896:    my ($form,$udom)=@_;
  897:    return '<a href="javascript:openauthorbrowser('."'$form','$udom'".');">'.
  898:           &mt('Select Author').'</a>';
  899: }
  900: 
  901: sub selectuser_link {
  902:     my ($form,$unameelem,$domelem,$lastelem,$firstelem,$emailelem,$hdomelem,
  903:         $coursedom,$linktext,$caller) = @_;
  904:     return '<a href="javascript:openuserbrowser('."'$form','$unameelem','$domelem',".
  905:            "'$lastelem','$firstelem','$emailelem','$hdomelem','$coursedom','$caller'".
  906:            ');">'.$linktext.'</a>';
  907: }
  908: 
  909: sub check_uncheck_jscript {
  910:     my $jscript = <<"ENDSCRT";
  911: function checkAll(field) {
  912:     if (field.length > 0) {
  913:         for (i = 0; i < field.length; i++) {
  914:             if (!field[i].disabled) {
  915:                 field[i].checked = true;
  916:             }
  917:         }
  918:     } else {
  919:         if (!field.disabled) {
  920:             field.checked = true;
  921:         }
  922:     }
  923: }
  924:  
  925: function uncheckAll(field) {
  926:     if (field.length > 0) {
  927:         for (i = 0; i < field.length; i++) {
  928:             field[i].checked = false ;
  929:         }
  930:     } else {
  931:         field.checked = false ;
  932:     }
  933: }
  934: ENDSCRT
  935:     return $jscript;
  936: }
  937: 
  938: sub select_timezone {
  939:    my ($name,$selected,$onchange,$includeempty,$disabled)=@_;
  940:    my $output='<select name="'.$name.'" '.$onchange.$disabled.'>'."\n";
  941:    if ($includeempty) {
  942:        $output .= '<option value=""';
  943:        if (($selected eq '') || ($selected eq 'local')) {
  944:            $output .= ' selected="selected" ';
  945:        }
  946:        $output .= '> </option>';
  947:    }
  948:    my @timezones = DateTime::TimeZone->all_names;
  949:    foreach my $tzone (@timezones) {
  950:        $output.= '<option value="'.$tzone.'"';
  951:        if ($tzone eq $selected) {
  952:            $output.=' selected="selected"';
  953:        }
  954:        $output.=">$tzone</option>\n";
  955:    }
  956:    $output.="</select>";
  957:    return $output;
  958: }
  959: 
  960: sub select_datelocale {
  961:     my ($name,$selected,$onchange,$includeempty,$disabled)=@_;
  962:     my $output='<select name="'.$name.'" '.$onchange.$disabled.'>'."\n";
  963:     if ($includeempty) {
  964:         $output .= '<option value=""';
  965:         if ($selected eq '') {
  966:             $output .= ' selected="selected" ';
  967:         }
  968:         $output .= '> </option>';
  969:     }
  970:     my @languages = &Apache::lonlocal::preferred_languages();
  971:     my (@possibles,%locale_names);
  972:     my @locales = DateTime::Locale->ids();
  973:     foreach my $id (@locales) {
  974:         if ($id ne '') {
  975:             my ($en_terr,$native_terr);
  976:             my $loc = DateTime::Locale->load($id);
  977:             if (ref($loc)) {
  978:                 $en_terr = $loc->name();
  979:                 $native_terr = $loc->native_name();
  980:                 if (grep(/^en$/,@languages) || !@languages) {
  981:                     if ($en_terr ne '') {
  982:                         $locale_names{$id} = '('.$en_terr.')';
  983:                     } elsif ($native_terr ne '') {
  984:                         $locale_names{$id} = $native_terr;
  985:                     }
  986:                 } else {
  987:                     if ($native_terr ne '') {
  988:                         $locale_names{$id} = $native_terr.' ';
  989:                     } elsif ($en_terr ne '') {
  990:                         $locale_names{$id} = '('.$en_terr.')';
  991:                     }
  992:                 }
  993:                 $locale_names{$id} = Encode::encode('UTF-8',$locale_names{$id});
  994:                 push(@possibles,$id);
  995:             }
  996:         }
  997:     }
  998:     foreach my $item (sort(@possibles)) {
  999:         $output.= '<option value="'.$item.'"';
 1000:         if ($item eq $selected) {
 1001:             $output.=' selected="selected"';
 1002:         }
 1003:         $output.=">$item";
 1004:         if ($locale_names{$item} ne '') {
 1005:             $output.='  '.$locale_names{$item};
 1006:         }
 1007:         $output.="</option>\n";
 1008:     }
 1009:     $output.="</select>";
 1010:     return $output;
 1011: }
 1012: 
 1013: sub select_language {
 1014:     my ($name,$selected,$includeempty,$noedit) = @_;
 1015:     my %langchoices;
 1016:     if ($includeempty) {
 1017:         %langchoices = ('' => 'No language preference');
 1018:     }
 1019:     foreach my $id (&languageids()) {
 1020:         my $code = &supportedlanguagecode($id);
 1021:         if ($code) {
 1022:             $langchoices{$code} = &plainlanguagedescription($id);
 1023:         }
 1024:     }
 1025:     %langchoices = &Apache::lonlocal::texthash(%langchoices);
 1026:     return &select_form($selected,$name,\%langchoices,undef,$noedit);
 1027: }
 1028: 
 1029: =pod
 1030: 
 1031: =item * &linked_select_forms(...)
 1032: 
 1033: linked_select_forms returns a string containing a <script></script> block
 1034: and html for two <select> menus.  The select menus will be linked in that
 1035: changing the value of the first menu will result in new values being placed
 1036: in the second menu.  The values in the select menu will appear in alphabetical
 1037: order unless a defined order is provided.
 1038: 
 1039: linked_select_forms takes the following ordered inputs:
 1040: 
 1041: =over 4
 1042: 
 1043: =item * $formname, the name of the <form> tag
 1044: 
 1045: =item * $middletext, the text which appears between the <select> tags
 1046: 
 1047: =item * $firstdefault, the default value for the first menu
 1048: 
 1049: =item * $firstselectname, the name of the first <select> tag
 1050: 
 1051: =item * $secondselectname, the name of the second <select> tag
 1052: 
 1053: =item * $hashref, a reference to a hash containing the data for the menus.
 1054: 
 1055: =item * $menuorder, the order of values in the first menu
 1056: 
 1057: =item * $onchangefirst, additional javascript call to execute for an onchange
 1058:         event for the first <select> tag
 1059: 
 1060: =item * $onchangesecond, additional javascript call to execute for an onchange
 1061:         event for the second <select> tag
 1062: 
 1063: =back 
 1064: 
 1065: Below is an example of such a hash.  Only the 'text', 'default', and 
 1066: 'select2' keys must appear as stated.  keys(%menu) are the possible 
 1067: values for the first select menu.  The text that coincides with the 
 1068: first menu value is given in $menu{$choice1}->{'text'}.  The values 
 1069: and text for the second menu are given in the hash pointed to by 
 1070: $menu{$choice1}->{'select2'}.  
 1071: 
 1072:  my %menu = ( A1 => { text =>"Choice A1" ,
 1073:                        default => "B3",
 1074:                        select2 => { 
 1075:                            B1 => "Choice B1",
 1076:                            B2 => "Choice B2",
 1077:                            B3 => "Choice B3",
 1078:                            B4 => "Choice B4"
 1079:                            },
 1080:                        order => ['B4','B3','B1','B2'],
 1081:                    },
 1082:                A2 => { text =>"Choice A2" ,
 1083:                        default => "C2",
 1084:                        select2 => { 
 1085:                            C1 => "Choice C1",
 1086:                            C2 => "Choice C2",
 1087:                            C3 => "Choice C3"
 1088:                            },
 1089:                        order => ['C2','C1','C3'],
 1090:                    },
 1091:                A3 => { text =>"Choice A3" ,
 1092:                        default => "D6",
 1093:                        select2 => { 
 1094:                            D1 => "Choice D1",
 1095:                            D2 => "Choice D2",
 1096:                            D3 => "Choice D3",
 1097:                            D4 => "Choice D4",
 1098:                            D5 => "Choice D5",
 1099:                            D6 => "Choice D6",
 1100:                            D7 => "Choice D7"
 1101:                            },
 1102:                        order => ['D4','D3','D2','D1','D7','D6','D5'],
 1103:                    }
 1104:                );
 1105: 
 1106: =cut
 1107: 
 1108: sub linked_select_forms {
 1109:     my ($formname,
 1110:         $middletext,
 1111:         $firstdefault,
 1112:         $firstselectname,
 1113:         $secondselectname, 
 1114:         $hashref,
 1115:         $menuorder,
 1116:         $onchangefirst,
 1117:         $onchangesecond
 1118:         ) = @_;
 1119:     my $second = "document.$formname.$secondselectname";
 1120:     my $first = "document.$formname.$firstselectname";
 1121:     # output the javascript to do the changing
 1122:     my $result = '';
 1123:     $result.='<script type="text/javascript" language="JavaScript">'."\n";
 1124:     $result.="// <![CDATA[\n";
 1125:     $result.="var select2data = new Object();\n";
 1126:     $" = '","';
 1127:     my $debug = '';
 1128:     foreach my $s1 (sort(keys(%$hashref))) {
 1129:         $result.="select2data.d_$s1 = new Object();\n";        
 1130:         $result.="select2data.d_$s1.def = new String('".
 1131:             $hashref->{$s1}->{'default'}."');\n";
 1132:         $result.="select2data.d_$s1.values = new Array(";
 1133:         my @s2values = sort(keys( %{ $hashref->{$s1}->{'select2'} } ));
 1134:         if (ref($hashref->{$s1}->{'order'}) eq 'ARRAY') {
 1135:             @s2values = @{$hashref->{$s1}->{'order'}};
 1136:         }
 1137:         $result.="\"@s2values\");\n";
 1138:         $result.="select2data.d_$s1.texts = new Array(";        
 1139:         my @s2texts;
 1140:         foreach my $value (@s2values) {
 1141:             push(@s2texts, $hashref->{$s1}->{'select2'}->{$value});
 1142:         }
 1143:         $result.="\"@s2texts\");\n";
 1144:     }
 1145:     $"=' ';
 1146:     $result.= <<"END";
 1147: 
 1148: function select1_changed() {
 1149:     // Determine new choice
 1150:     var newvalue = "d_" + $first.value;
 1151:     // update select2
 1152:     var values     = select2data[newvalue].values;
 1153:     var texts      = select2data[newvalue].texts;
 1154:     var select2def = select2data[newvalue].def;
 1155:     var i;
 1156:     // out with the old
 1157:     for (i = 0; i < $second.options.length; i++) {
 1158:         $second.options[i] = null;
 1159:     }
 1160:     // in with the nuclear
 1161:     for (i=0;i<values.length; i++) {
 1162:         $second.options[i] = new Option(values[i]);
 1163:         $second.options[i].value = values[i];
 1164:         $second.options[i].text = texts[i];
 1165:         if (values[i] == select2def) {
 1166:             $second.options[i].selected = true;
 1167:         }
 1168:     }
 1169: }
 1170: // ]]>
 1171: </script>
 1172: END
 1173:     # output the initial values for the selection lists
 1174:     $result .= "<select size=\"1\" name=\"$firstselectname\" onchange=\"select1_changed();$onchangefirst\">\n";
 1175:     my @order = sort(keys(%{$hashref}));
 1176:     if (ref($menuorder) eq 'ARRAY') {
 1177:         @order = @{$menuorder};
 1178:     }
 1179:     foreach my $value (@order) {
 1180:         $result.="    <option value=\"$value\" ";
 1181:         $result.=" selected=\"selected\" " if ($value eq $firstdefault);
 1182:         $result.=">".&mt($hashref->{$value}->{'text'})."</option>\n";
 1183:     }
 1184:     $result .= "</select>\n";
 1185:     my %select2 = %{$hashref->{$firstdefault}->{'select2'}};
 1186:     $result .= $middletext;
 1187:     $result .= "<select size=\"1\" name=\"$secondselectname\"";
 1188:     if ($onchangesecond) {
 1189:         $result .= ' onchange="'.$onchangesecond.'"';
 1190:     }
 1191:     $result .= ">\n";
 1192:     my $seconddefault = $hashref->{$firstdefault}->{'default'};
 1193:     
 1194:     my @secondorder = sort(keys(%select2));
 1195:     if (ref($hashref->{$firstdefault}->{'order'}) eq 'ARRAY') {
 1196:         @secondorder = @{$hashref->{$firstdefault}->{'order'}};
 1197:     }
 1198:     foreach my $value (@secondorder) {
 1199:         $result.="    <option value=\"$value\" ";        
 1200:         $result.=" selected=\"selected\" " if ($value eq $seconddefault);
 1201:         $result.=">".&mt($select2{$value})."</option>\n";
 1202:     }
 1203:     $result .= "</select>\n";
 1204:     #    return $debug;
 1205:     return $result;
 1206: }   #  end of sub linked_select_forms {
 1207: 
 1208: =pod
 1209: 
 1210: =item * &help_open_topic($topic,$text,$stayOnPage,$width,$height,$imgid)
 1211: 
 1212: Returns a string corresponding to an HTML link to the given help
 1213: $topic, where $topic corresponds to the name of a .tex file in
 1214: /home/httpd/html/adm/help/tex, with underscores replaced by
 1215: spaces. 
 1216: 
 1217: $text will optionally be linked to the same topic, allowing you to
 1218: link text in addition to the graphic. If you do not want to link
 1219: text, but wish to specify one of the later parameters, pass an
 1220: empty string. 
 1221: 
 1222: $stayOnPage is a value that will be interpreted as a boolean. If true,
 1223: the link will not open a new window. If false, the link will open
 1224: a new window using Javascript. (Default is false.) 
 1225: 
 1226: $width and $height are optional numerical parameters that will
 1227: override the width and height of the popped up window, which may
 1228: be useful for certain help topics with big pictures included.
 1229: 
 1230: $imgid is the id of the img tag used for the help icon. This may be
 1231: used in a javascript call to switch the image src.  See 
 1232: lonhtmlcommon::htmlareaselectactive() for an example.
 1233: 
 1234: =cut
 1235: 
 1236: sub help_open_topic {
 1237:     my ($topic, $text, $stayOnPage, $width, $height, $imgid) = @_;
 1238:     $text = "" if (not defined $text);
 1239:     $stayOnPage = 0 if (not defined $stayOnPage);
 1240:     $width = 500 if (not defined $width);
 1241:     $height = 400 if (not defined $height);
 1242:     my $filename = $topic;
 1243:     $filename =~ s/ /_/g;
 1244: 
 1245:     my $template = "";
 1246:     my $link;
 1247:     
 1248:     $topic=~s/\W/\_/g;
 1249: 
 1250:     if (!$stayOnPage) {
 1251:         if ($env{'browser.mobile'}) {
 1252: 	    $link = "javascript:openMyModal('/adm/help/${filename}.hlp',$width,$height,'yes');";
 1253:         } else {
 1254:             $link = "javascript:void(open('/adm/help/${filename}.hlp', 'Help_for_$topic', 'menubar=0,toolbar=1,scrollbars=1,width=$width,height=$height,resizable=yes'))";
 1255:         }
 1256:     } elsif ($stayOnPage eq 'popup') {
 1257:         $link = "javascript:void(open('/adm/help/${filename}.hlp', 'Help_for_$topic', 'menubar=0,toolbar=1,scrollbars=1,width=$width,height=$height,resizable=yes'))";
 1258:     } else {
 1259: 	$link = "/adm/help/${filename}.hlp";
 1260:     }
 1261: 
 1262:     # Add the text
 1263:     if ($text ne "") {	
 1264: 	$template.='<span class="LC_help_open_topic">'
 1265:                   .'<a target="_top" href="'.$link.'">'
 1266:                   .$text.'</a>';
 1267:     }
 1268: 
 1269:     # (Always) Add the graphic
 1270:     my $title = &mt('Online Help');
 1271:     my $helpicon=&lonhttpdurl("/adm/help/help.png");
 1272:     if ($imgid ne '') {
 1273:         $imgid = ' id="'.$imgid.'"';
 1274:     }
 1275:     $template.=' <a target="_top" href="'.$link.'" title="'.$title.'">'
 1276:               .'<img src="'.$helpicon.'" border="0"'
 1277:               .' alt="'.&mt('Help: [_1]',$topic).'"'
 1278:               .' title="'.$title.'" style="vertical-align:middle;"'.$imgid 
 1279:               .' /></a>';
 1280:     if ($text ne "") {	
 1281:         $template.='</span>';
 1282:     }
 1283:     return $template;
 1284: 
 1285: }
 1286: 
 1287: # This is a quicky function for Latex cheatsheet editing, since it 
 1288: # appears in at least four places
 1289: sub helpLatexCheatsheet {
 1290:     my ($topic,$text,$not_author,$stayOnPage) = @_;
 1291:     my $out;
 1292:     my $addOther = '';
 1293:     if ($topic) {
 1294: 	$addOther = '<span>'.&help_open_topic($topic,&mt($text),$stayOnPage, undef, 600).'</span> ';
 1295:     }
 1296:     $out = '<span>' # Start cheatsheet
 1297: 	  .$addOther
 1298:           .'<span>'
 1299: 	  .&help_open_topic('Greek_Symbols',&mt('Greek Symbols'),$stayOnPage,undef,600)
 1300: 	  .'</span> <span>'
 1301: 	  .&help_open_topic('Other_Symbols',&mt('Other Symbols'),$stayOnPage,undef,600)
 1302: 	  .'</span>';
 1303:     unless ($not_author) {
 1304:         $out .= ' <span>'
 1305: 	       .&help_open_topic('Authoring_Output_Tags',&mt('Output Tags'),$stayOnPage,undef,600)
 1306: 	       .'</span> <span>'
 1307:                .&help_open_topic('Authoring_Multilingual_Problems',&mt('Languages'),$stayOnPage,undef,600)
 1308:                .'</span>';
 1309:     }
 1310:     $out .= '</span>'; # End cheatsheet
 1311:     return $out;
 1312: }
 1313: 
 1314: sub general_help {
 1315:     my $helptopic='Student_Intro';
 1316:     if ($env{'request.role'}=~/^(ca|au)/) {
 1317: 	$helptopic='Authoring_Intro';
 1318:     } elsif ($env{'request.role'}=~/^(cc|co)/) {
 1319: 	$helptopic='Course_Coordination_Intro';
 1320:     } elsif ($env{'request.role'}=~/^dc/) {
 1321:         $helptopic='Domain_Coordination_Intro';
 1322:     }
 1323:     return $helptopic;
 1324: }
 1325: 
 1326: sub update_help_link {
 1327:     my ($topic,$component_help,$faq,$bug,$stayOnPage) = @_;
 1328:     my $origurl = $ENV{'REQUEST_URI'};
 1329:     $origurl=~s|^/~|/priv/|;
 1330:     my $timestamp = time;
 1331:     foreach my $datum (\$topic,\$component_help,\$faq,\$bug,\$origurl) {
 1332:         $$datum = &escape($$datum);
 1333:     }
 1334: 
 1335:     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";
 1336:     my $output .= <<"ENDOUTPUT";
 1337: <script type="text/javascript">
 1338: // <![CDATA[
 1339: banner_link = '$banner_link';
 1340: // ]]>
 1341: </script>
 1342: ENDOUTPUT
 1343:     return $output;
 1344: }
 1345: 
 1346: # now just updates the help link and generates a blue icon
 1347: sub help_open_menu {
 1348:     my ($topic,$component_help,$faq,$bug,$stayOnPage,$width,$height,$text) 
 1349: 	= @_;    
 1350:     $stayOnPage = 1;
 1351:     my $output;
 1352:     if ($component_help) {
 1353: 	if (!$text) {
 1354: 	    $output=&help_open_topic($component_help,undef,$stayOnPage,
 1355: 				       $width,$height);
 1356: 	} else {
 1357: 	    my $help_text;
 1358: 	    $help_text=&unescape($topic);
 1359: 	    $output='<table><tr><td>'.
 1360: 		&help_open_topic($component_help,$help_text,$stayOnPage,
 1361: 				 $width,$height).'</td></tr></table>';
 1362: 	}
 1363:     }
 1364:     my $banner_link = &update_help_link($topic,$component_help,$faq,$bug,$stayOnPage);
 1365:     return $output.$banner_link;
 1366: }
 1367: 
 1368: sub top_nav_help {
 1369:     my ($text) = @_;
 1370:     $text = &mt($text);
 1371:     my $stay_on_page;
 1372:     unless ($env{'environment.remote'} eq 'on') {
 1373:         $stay_on_page = 1;
 1374:     }
 1375:     my ($link,$banner_link);
 1376:     unless ($env{'request.noversionuri'} =~ m{^/adm/helpmenu}) {
 1377:         $link = ($stay_on_page) ? "javascript:helpMenu('display')"
 1378: 	                         : "javascript:helpMenu('open')";
 1379:         $banner_link = &update_help_link(undef,undef,undef,undef,$stay_on_page);
 1380:     }
 1381:     my $title = &mt('Get help');
 1382:     if ($link) {
 1383:         return <<"END";
 1384: $banner_link
 1385: <a href="$link" title="$title">$text</a>
 1386: END
 1387:     } else {
 1388:         return '&nbsp;'.$text.'&nbsp;';
 1389:     }
 1390: }
 1391: 
 1392: sub help_menu_js {
 1393:     my ($httphost) = @_;
 1394:     my $stayOnPage = 1;
 1395:     my $width = 620;
 1396:     my $height = 600;
 1397:     my $helptopic=&general_help();
 1398:     my $details_link = $httphost.'/adm/help/'.$helptopic.'.hlp';
 1399:     my $nothing=&Apache::lonhtmlcommon::javascript_nothing();
 1400:     my $start_page =
 1401:         &Apache::loncommon::start_page('Help Menu', undef,
 1402: 				       {'frameset'    => 1,
 1403: 					'js_ready'    => 1,
 1404:                                         'use_absolute' => $httphost, 
 1405: 					'add_entries' => {
 1406: 					    'border' => '0',
 1407: 					    'rows'   => "110,*",},});
 1408:     my $end_page =
 1409:         &Apache::loncommon::end_page({'frameset' => 1,
 1410: 				      'js_ready' => 1,});
 1411: 
 1412:     my $template .= <<"ENDTEMPLATE";
 1413: <script type="text/javascript">
 1414: // <![CDATA[
 1415: // <!-- BEGIN LON-CAPA Internal
 1416: var banner_link = '';
 1417: function helpMenu(target) {
 1418:     var caller = this;
 1419:     if (target == 'open') {
 1420:         var newWindow = null;
 1421:         try {
 1422:             newWindow =  window.open($nothing,"helpmenu","HEIGHT=$height,WIDTH=$width,resizable=yes,scrollbars=yes" )
 1423:         }
 1424:         catch(error) {
 1425:             writeHelp(caller);
 1426:             return;
 1427:         }
 1428:         if (newWindow) {
 1429:             caller = newWindow;
 1430:         }
 1431:     }
 1432:     writeHelp(caller);
 1433:     return;
 1434: }
 1435: function writeHelp(caller) {
 1436:     caller.document.writeln('$start_page\\n<frame name="bannerframe" src="'+banner_link+'" marginwidth="0" marginheight="0" frameborder="0">\\n');
 1437:     caller.document.writeln('<frame name="bodyframe" src="$details_link" marginwidth="0" marginheight="0" frameborder="0">\\n$end_page');
 1438:     caller.document.close();
 1439:     caller.focus();
 1440: }
 1441: // END LON-CAPA Internal -->
 1442: // ]]>
 1443: </script>
 1444: ENDTEMPLATE
 1445:     return $template;
 1446: }
 1447: 
 1448: sub help_open_bug {
 1449:     my ($topic, $text, $stayOnPage, $width, $height) = @_;
 1450:     unless ($env{'user.adv'}) { return ''; }
 1451:     unless ($Apache::lonnet::perlvar{'BugzillaHost'}) { return ''; }
 1452:     $text = "" if (not defined $text);
 1453: 	$stayOnPage=1;
 1454:     $width = 600 if (not defined $width);
 1455:     $height = 600 if (not defined $height);
 1456: 
 1457:     $topic=~s/\W+/\+/g;
 1458:     my $link='';
 1459:     my $template='';
 1460:     my $url=$Apache::lonnet::perlvar{'BugzillaHost'}.'enter_bug.cgi?product=LON-CAPA&amp;bug_file_loc='.
 1461: 	&escape($ENV{'REQUEST_URI'}).'&amp;component='.$topic;
 1462:     if (!$stayOnPage)
 1463:     {
 1464: 	$link = "javascript:void(open('$url', 'Bugzilla', 'menubar=0,toolbar=1,scrollbars=1,width=$width,height=$height,resizable=yes'))";
 1465:     }
 1466:     else
 1467:     {
 1468: 	$link = $url;
 1469:     }
 1470:     # Add the text
 1471:     if ($text ne "")
 1472:     {
 1473: 	$template .= 
 1474:   "<table bgcolor='#AA3333' cellspacing='1' cellpadding='1' border='0'><tr>".
 1475:   "<td bgcolor='#FF5555'><a target=\"_top\" href=\"$link\"><span style=\"color:#FFFFFF;font-size:10pt;\">$text</span></a>";
 1476:     }
 1477: 
 1478:     # Add the graphic
 1479:     my $title = &mt('Report a Bug');
 1480:     my $bugicon=&lonhttpdurl("/adm/lonMisc/smallBug.gif");
 1481:     $template .= <<"ENDTEMPLATE";
 1482:  <a target="_top" href="$link" title="$title"><img src="$bugicon" border="0" alt="(Bug: $topic)" /></a>
 1483: ENDTEMPLATE
 1484:     if ($text ne '') { $template.='</td></tr></table>' };
 1485:     return $template;
 1486: 
 1487: }
 1488: 
 1489: sub help_open_faq {
 1490:     my ($topic, $text, $stayOnPage, $width, $height) = @_;
 1491:     unless ($env{'user.adv'}) { return ''; }
 1492:     unless ($Apache::lonnet::perlvar{'FAQHost'}) { return ''; }
 1493:     $text = "" if (not defined $text);
 1494: 	$stayOnPage=1;
 1495:     $width = 350 if (not defined $width);
 1496:     $height = 400 if (not defined $height);
 1497: 
 1498:     $topic=~s/\W+/\+/g;
 1499:     my $link='';
 1500:     my $template='';
 1501:     my $url=$Apache::lonnet::perlvar{'FAQHost'}.'/fom/cache/'.$topic.'.html';
 1502:     if (!$stayOnPage)
 1503:     {
 1504: 	$link = "javascript:void(open('$url', 'FAQ-O-Matic', 'menubar=0,toolbar=1,scrollbars=1,width=$width,height=$height,resizable=yes'))";
 1505:     }
 1506:     else
 1507:     {
 1508: 	$link = $url;
 1509:     }
 1510: 
 1511:     # Add the text
 1512:     if ($text ne "")
 1513:     {
 1514: 	$template .= 
 1515:   "<table bgcolor='#337733' cellspacing='1' cellpadding='1' border='0'><tr>".
 1516:   "<td bgcolor='#448844'><a target=\"_top\" href=\"$link\"><span style=\"color:#FFFFFF; font-size:10pt;\">$text</span></a>";
 1517:     }
 1518: 
 1519:     # Add the graphic
 1520:     my $title = &mt('View the FAQ');
 1521:     my $faqicon=&lonhttpdurl("/adm/lonMisc/smallFAQ.gif");
 1522:     $template .= <<"ENDTEMPLATE";
 1523:  <a target="_top" href="$link" title="$title"><img src="$faqicon" border="0" alt="(FAQ: $topic)" /></a>
 1524: ENDTEMPLATE
 1525:     if ($text ne '') { $template.='</td></tr></table>' };
 1526:     return $template;
 1527: 
 1528: }
 1529: 
 1530: ###############################################################
 1531: ###############################################################
 1532: 
 1533: =pod
 1534: 
 1535: =item * &change_content_javascript():
 1536: 
 1537: This and the next function allow you to create small sections of an
 1538: otherwise static HTML page that you can update on the fly with
 1539: Javascript, even in Netscape 4.
 1540: 
 1541: The Javascript fragment returned by this function (no E<lt>scriptE<gt> tag)
 1542: must be written to the HTML page once. It will prove the Javascript
 1543: function "change(name, content)". Calling the change function with the
 1544: name of the section 
 1545: you want to update, matching the name passed to C<changable_area>, and
 1546: the new content you want to put in there, will put the content into
 1547: that area.
 1548: 
 1549: B<Note>: Netscape 4 only reserves enough space for the changable area
 1550: to contain room for the original contents. You need to "make space"
 1551: for whatever changes you wish to make, and be B<sure> to check your
 1552: code in Netscape 4. This feature in Netscape 4 is B<not> powerful;
 1553: it's adequate for updating a one-line status display, but little more.
 1554: This script will set the space to 100% width, so you only need to
 1555: worry about height in Netscape 4.
 1556: 
 1557: Modern browsers are much less limiting, and if you can commit to the
 1558: user not using Netscape 4, this feature may be used freely with
 1559: pretty much any HTML.
 1560: 
 1561: =cut
 1562: 
 1563: sub change_content_javascript {
 1564:     # If we're on Netscape 4, we need to use Layer-based code
 1565:     if ($env{'browser.type'} eq 'netscape' &&
 1566: 	$env{'browser.version'} =~ /^4\./) {
 1567: 	return (<<NETSCAPE4);
 1568: 	function change(name, content) {
 1569: 	    doc = document.layers[name+"___escape"].layers[0].document;
 1570: 	    doc.open();
 1571: 	    doc.write(content);
 1572: 	    doc.close();
 1573: 	}
 1574: NETSCAPE4
 1575:     } else {
 1576: 	# Otherwise, we need to use semi-standards-compliant code
 1577: 	# (technically, "innerHTML" isn't standard but the equivalent
 1578: 	# is really scary, and every useful browser supports it
 1579: 	return (<<DOMBASED);
 1580: 	function change(name, content) {
 1581: 	    element = document.getElementById(name);
 1582: 	    element.innerHTML = content;
 1583: 	}
 1584: DOMBASED
 1585:     }
 1586: }
 1587: 
 1588: =pod
 1589: 
 1590: =item * &changable_area($name,$origContent):
 1591: 
 1592: This provides a "changable area" that can be modified on the fly via
 1593: the Javascript code provided in C<change_content_javascript>. $name is
 1594: the name you will use to reference the area later; do not repeat the
 1595: same name on a given HTML page more then once. $origContent is what
 1596: the area will originally contain, which can be left blank.
 1597: 
 1598: =cut
 1599: 
 1600: sub changable_area {
 1601:     my ($name, $origContent) = @_;
 1602: 
 1603:     if ($env{'browser.type'} eq 'netscape' &&
 1604: 	$env{'browser.version'} =~ /^4\./) {
 1605: 	# If this is netscape 4, we need to use the Layer tag
 1606: 	return "<ilayer width='100%' id='${name}___escape' overflow='none'><layer width='100%' id='$name' overflow='none'>$origContent</layer></ilayer>";
 1607:     } else {
 1608: 	return "<span id='$name'>$origContent</span>";
 1609:     }
 1610: }
 1611: 
 1612: =pod
 1613: 
 1614: =item * &viewport_geometry_js 
 1615: 
 1616: Provides javascript object (Geometry) which can provide information about the viewport geometry for the client browser.
 1617: 
 1618: =cut
 1619: 
 1620: 
 1621: sub viewport_geometry_js { 
 1622:     return <<"GEOMETRY";
 1623: var Geometry = {};
 1624: function init_geometry() {
 1625:     if (Geometry.init) { return };
 1626:     Geometry.init=1;
 1627:     if (window.innerHeight) {
 1628:         Geometry.getViewportHeight   = function() { return window.innerHeight; };
 1629:         Geometry.getViewportWidth   = function() { return window.innerWidth; };
 1630:         Geometry.getHorizontalScroll = function() { return window.pageXOffset; };
 1631:         Geometry.getVerticalScroll   = function() { return window.pageYOffset; };
 1632:     }
 1633:     else if (document.documentElement && document.documentElement.clientHeight) {
 1634:         Geometry.getViewportHeight =
 1635:             function() { return document.documentElement.clientHeight; };
 1636:         Geometry.getViewportWidth =
 1637:             function() { return document.documentElement.clientWidth; };
 1638: 
 1639:         Geometry.getHorizontalScroll =
 1640:             function() { return document.documentElement.scrollLeft; };
 1641:         Geometry.getVerticalScroll =
 1642:             function() { return document.documentElement.scrollTop; };
 1643:     }
 1644:     else if (document.body.clientHeight) {
 1645:         Geometry.getViewportHeight =
 1646:             function() { return document.body.clientHeight; };
 1647:         Geometry.getViewportWidth =
 1648:             function() { return document.body.clientWidth; };
 1649:         Geometry.getHorizontalScroll =
 1650:             function() { return document.body.scrollLeft; };
 1651:         Geometry.getVerticalScroll =
 1652:             function() { return document.body.scrollTop; };
 1653:     }
 1654: }
 1655: 
 1656: GEOMETRY
 1657: }
 1658: 
 1659: =pod
 1660: 
 1661: =item * &viewport_size_js()
 1662: 
 1663: 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. 
 1664: 
 1665: =cut
 1666: 
 1667: sub viewport_size_js {
 1668:     my $geometry = &viewport_geometry_js();
 1669:     return <<"DIMS";
 1670: 
 1671: $geometry
 1672: 
 1673: function getViewportDims(width,height) {
 1674:     init_geometry();
 1675:     width.value = Geometry.getViewportWidth();
 1676:     height.value = Geometry.getViewportHeight();
 1677:     return;
 1678: }
 1679: 
 1680: DIMS
 1681: }
 1682: 
 1683: =pod
 1684: 
 1685: =item * &resize_textarea_js()
 1686: 
 1687: emits the needed javascript to resize a textarea to be as big as possible
 1688: 
 1689: creates a function resize_textrea that takes two IDs first should be
 1690: the id of the element to resize, second should be the id of a div that
 1691: surrounds everything that comes after the textarea, this routine needs
 1692: to be attached to the <body> for the onload and onresize events.
 1693: 
 1694: =back
 1695: 
 1696: =cut
 1697: 
 1698: sub resize_textarea_js {
 1699:     my $geometry = &viewport_geometry_js();
 1700:     return <<"RESIZE";
 1701:     <script type="text/javascript">
 1702: // <![CDATA[
 1703: $geometry
 1704: 
 1705: function getX(element) {
 1706:     var x = 0;
 1707:     while (element) {
 1708: 	x += element.offsetLeft;
 1709: 	element = element.offsetParent;
 1710:     }
 1711:     return x;
 1712: }
 1713: function getY(element) {
 1714:     var y = 0;
 1715:     while (element) {
 1716: 	y += element.offsetTop;
 1717: 	element = element.offsetParent;
 1718:     }
 1719:     return y;
 1720: }
 1721: 
 1722: 
 1723: function resize_textarea(textarea_id,bottom_id) {
 1724:     init_geometry();
 1725:     var textarea        = document.getElementById(textarea_id);
 1726:     //alert(textarea);
 1727: 
 1728:     var textarea_top    = getY(textarea);
 1729:     var textarea_height = textarea.offsetHeight;
 1730:     var bottom          = document.getElementById(bottom_id);
 1731:     var bottom_top      = getY(bottom);
 1732:     var bottom_height   = bottom.offsetHeight;
 1733:     var window_height   = Geometry.getViewportHeight();
 1734:     var fudge           = 23;
 1735:     var new_height      = window_height-fudge-textarea_top-bottom_height;
 1736:     if (new_height < 300) {
 1737: 	new_height = 300;
 1738:     }
 1739:     textarea.style.height=new_height+'px';
 1740: }
 1741: // ]]>
 1742: </script>
 1743: RESIZE
 1744: 
 1745: }
 1746: 
 1747: sub colorfuleditor_js {
 1748:     return <<"COLORFULEDIT"
 1749: <script type="text/javascript">
 1750: // <![CDATA[>
 1751:     function fold_box(curDepth, lastresource){
 1752: 
 1753:     // we need a list because there can be several blocks you need to fold in one tag
 1754:         var block = document.getElementsByName('foldblock_'+curDepth);
 1755:     // but there is only one folding button per tag
 1756:         var foldbutton = document.getElementById('folding_btn_'+curDepth);
 1757: 
 1758:         if(block.item(0).style.display == 'none'){
 1759: 
 1760:             foldbutton.value = '@{[&mt("Hide")]}';
 1761:             for (i = 0; i < block.length; i++){
 1762:                 block.item(i).style.display = '';
 1763:             }
 1764:         }else{
 1765: 
 1766:             foldbutton.value = '@{[&mt("Show")]}';
 1767:             for (i = 0; i < block.length; i++){
 1768:                 // block.item(i).style.visibility = 'collapse';
 1769:                 block.item(i).style.display = 'none';
 1770:             }
 1771:         };
 1772:         saveState(lastresource);
 1773:     }
 1774: 
 1775:     function saveState (lastresource) {
 1776: 
 1777:         var tag_list = getTagList();
 1778:         if(tag_list != null){
 1779:             var timestamp = new Date().getTime();
 1780:             var key = lastresource;
 1781: 
 1782:             // the value pattern is: 'time;key1,value1;key2,value2; ... '
 1783:             // starting with timestamp
 1784:             var value = timestamp+';';
 1785: 
 1786:             // building the list of key-value pairs
 1787:             for(var i = 0; i < tag_list.length; i++){
 1788:                 value += tag_list[i]+',';
 1789:                 value += document.getElementsByName(tag_list[i])[0].style.display+';';
 1790:             }
 1791: 
 1792:             // only iterate whole storage if nothing to override
 1793:             if(localStorage.getItem(key) == null){
 1794: 
 1795:                 // prevent storage from growing large
 1796:                 if(localStorage.length > 50){
 1797:                     var regex_getTimestamp = /^(?:\d)+;/;
 1798:                     var oldest_timestamp = regex_getTimestamp.exec(localStorage.key(0));
 1799:                     var oldest_key;
 1800: 
 1801:                     for(var i = 1; i < localStorage.length; i++){
 1802:                         if (regex_getTimestamp.exec(localStorage.key(i)) < oldest_timestamp) {
 1803:                             oldest_key = localStorage.key(i);
 1804:                             oldest_timestamp = regex_getTimestamp.exec(oldest_key);
 1805:                         }
 1806:                     }
 1807:                     localStorage.removeItem(oldest_key);
 1808:                 }
 1809:             }
 1810:             localStorage.setItem(key,value);
 1811:         }
 1812:     }
 1813: 
 1814:     // restore folding status of blocks (on page load)
 1815:     function restoreState (lastresource) {
 1816:         if(localStorage.getItem(lastresource) != null){
 1817:             var key = lastresource;
 1818:             var value = localStorage.getItem(key);
 1819:             var regex_delTimestamp = /^\d+;/;
 1820: 
 1821:             value.replace(regex_delTimestamp, '');
 1822: 
 1823:             var valueArr = value.split(';');
 1824:             var pairs;
 1825:             var elements;
 1826:             for (var i = 0; i < valueArr.length; i++){
 1827:                 pairs = valueArr[i].split(',');
 1828:                 elements = document.getElementsByName(pairs[0]);
 1829: 
 1830:                 for (var j = 0; j < elements.length; j++){
 1831:                     elements[j].style.display = pairs[1];
 1832:                     if (pairs[1] == "none"){
 1833:                         var regex_id = /([_\\d]+)\$/;
 1834:                         regex_id.exec(pairs[0]);
 1835:                         document.getElementById("folding_btn"+RegExp.\$1).value = "Show";
 1836:                     }
 1837:                 }
 1838:             }
 1839:         }
 1840:     }
 1841: 
 1842:     function getTagList () {
 1843: 
 1844:         var stringToSearch = document.lonhomework.innerHTML;
 1845: 
 1846:         var ret = new Array();
 1847:         var regex_findBlock = /(foldblock_.*?)"/g;
 1848:         var tag_list = stringToSearch.match(regex_findBlock);
 1849: 
 1850:         if(tag_list != null){
 1851:             for(var i = 0; i < tag_list.length; i++){
 1852:                 ret.push(tag_list[i].replace(/"/, ''));
 1853:             }
 1854:         }
 1855:         return ret;
 1856:     }
 1857: 
 1858:     function saveScrollPosition (resource) {
 1859:         var tag_list = getTagList();
 1860: 
 1861:         // we dont always want to jump to the first block
 1862:         // 170 is roughly above the "Problem Editing" header. we just want to save if the user scrolled down further than this
 1863:         if(\$(window).scrollTop() > 170){
 1864:             if(tag_list != null){
 1865:                 var result;
 1866:                 for(var i = 0; i < tag_list.length; i++){
 1867:                     if(isElementInViewport(tag_list[i])){
 1868:                         result += tag_list[i]+';';
 1869:                     }
 1870:                 }
 1871:                 sessionStorage.setItem('anchor_'+resource, result);
 1872:             }
 1873:         } else {
 1874:             // we dont need to save zero, just delete the item to leave everything tidy
 1875:             sessionStorage.removeItem('anchor_'+resource);
 1876:         }
 1877:     }
 1878: 
 1879:     function restoreScrollPosition(resource){
 1880: 
 1881:         var elem = sessionStorage.getItem('anchor_'+resource);
 1882:         if(elem != null){
 1883:             var tag_list = elem.split(';');
 1884:             var elem_list;
 1885: 
 1886:             for(var i = 0; i < tag_list.length; i++){
 1887:                 elem_list = document.getElementsByName(tag_list[i]);
 1888: 
 1889:                 if(elem_list.length > 0){
 1890:                     elem = elem_list[0];
 1891:                     break;
 1892:                 }
 1893:             }
 1894:             elem.scrollIntoView();
 1895:         }
 1896:     }
 1897: 
 1898:     function isElementInViewport(el) {
 1899: 
 1900:         // change to last element instead of first
 1901:         var elem = document.getElementsByName(el);
 1902:         var rect = elem[0].getBoundingClientRect();
 1903: 
 1904:         return (
 1905:             rect.top >= 0 &&
 1906:             rect.left >= 0 &&
 1907:             rect.bottom <= (window.innerHeight || document.documentElement.clientHeight) && /*or $(window).height() */
 1908:             rect.right <= (window.innerWidth || document.documentElement.clientWidth) /*or $(window).width() */
 1909:         );
 1910:     }
 1911: 
 1912:     function autosize(depth){
 1913:         var cmInst = window['cm'+depth];
 1914:         var fitsizeButton = document.getElementById('fitsize'+depth);
 1915: 
 1916:         // is fixed size, switching to dynamic
 1917:         if (sessionStorage.getItem("autosized_"+depth) == null) {
 1918:             cmInst.setSize("","auto");
 1919:             fitsizeButton.value = "@{[&mt('Fixed size')]}";
 1920:             sessionStorage.setItem("autosized_"+depth, "yes");
 1921: 
 1922:         // is dynamic size, switching to fixed
 1923:         } else {
 1924:             cmInst.setSize("","300px");
 1925:             fitsizeButton.value = "@{[&mt('Dynamic size')]}";
 1926:             sessionStorage.removeItem("autosized_"+depth);
 1927:         }
 1928:     }
 1929: 
 1930: 
 1931: 
 1932: // ]]>
 1933: </script>
 1934: COLORFULEDIT
 1935: }
 1936: 
 1937: sub xmleditor_js {
 1938:     return <<XMLEDIT
 1939: <script type="text/javascript" src="/adm/jQuery/addons/jquery-scrolltofixed.js"></script>
 1940: <script type="text/javascript">
 1941: // <![CDATA[>
 1942: 
 1943:     function saveScrollPosition (resource) {
 1944: 
 1945:         var scrollPos = \$(window).scrollTop();
 1946:         sessionStorage.setItem(resource,scrollPos);
 1947:     }
 1948: 
 1949:     function restoreScrollPosition(resource){
 1950: 
 1951:         var scrollPos = sessionStorage.getItem(resource);
 1952:         \$(window).scrollTop(scrollPos);
 1953:     }
 1954: 
 1955:     // unless internet explorer
 1956:     if (!(window.navigator.appName == "Microsoft Internet Explorer" && (document.documentMode || document.compatMode))){
 1957: 
 1958:         \$(document).ready(function() {
 1959:              \$(".LC_edit_actionbar").scrollToFixed(\{zIndex: 100\});
 1960:         });
 1961:     }
 1962: 
 1963:     // inserts text at cursor position into codemirror (xml editor only)
 1964:     function insertText(text){
 1965:         cm.focus();
 1966:         var curPos = cm.getCursor();
 1967:         cm.replaceRange(text.replace(/ESCAPEDSCRIPT/g,'script'), {line: curPos.line,ch: curPos.ch});
 1968:     }
 1969: // ]]>
 1970: </script>
 1971: XMLEDIT
 1972: }
 1973: 
 1974: sub insert_folding_button {
 1975:     my $curDepth = $Apache::lonxml::curdepth;
 1976:     my $lastresource = $env{'request.ambiguous'};
 1977: 
 1978:     return "<input type=\"button\" id=\"folding_btn_$curDepth\"
 1979:             value=\"".&mt('Hide')."\" onclick=\"fold_box('$curDepth','$lastresource')\">";
 1980: }
 1981: 
 1982: 
 1983: =pod
 1984: 
 1985: =head1 Excel and CSV file utility routines
 1986: 
 1987: =cut
 1988: 
 1989: ###############################################################
 1990: ###############################################################
 1991: 
 1992: =pod
 1993: 
 1994: =over 4
 1995: 
 1996: =item * &csv_translate($text) 
 1997: 
 1998: Translate $text to allow it to be output as a 'comma separated values' 
 1999: format.
 2000: 
 2001: =cut
 2002: 
 2003: ###############################################################
 2004: ###############################################################
 2005: sub csv_translate {
 2006:     my $text = shift;
 2007:     $text =~ s/\"/\"\"/g;
 2008:     $text =~ s/\n/ /g;
 2009:     return $text;
 2010: }
 2011: 
 2012: ###############################################################
 2013: ###############################################################
 2014: 
 2015: =pod
 2016: 
 2017: =item * &define_excel_formats()
 2018: 
 2019: Define some commonly used Excel cell formats.
 2020: 
 2021: Currently supported formats:
 2022: 
 2023: =over 4
 2024: 
 2025: =item header
 2026: 
 2027: =item bold
 2028: 
 2029: =item h1
 2030: 
 2031: =item h2
 2032: 
 2033: =item h3
 2034: 
 2035: =item h4
 2036: 
 2037: =item i
 2038: 
 2039: =item date
 2040: 
 2041: =back
 2042: 
 2043: Inputs: $workbook
 2044: 
 2045: Returns: $format, a hash reference.
 2046: 
 2047: 
 2048: =cut
 2049: 
 2050: ###############################################################
 2051: ###############################################################
 2052: sub define_excel_formats {
 2053:     my ($workbook) = @_;
 2054:     my $format;
 2055:     $format->{'header'} = $workbook->add_format(bold      => 1, 
 2056:                                                 bottom    => 1,
 2057:                                                 align     => 'center');
 2058:     $format->{'bold'} = $workbook->add_format(bold=>1);
 2059:     $format->{'h1'}   = $workbook->add_format(bold=>1, size=>18);
 2060:     $format->{'h2'}   = $workbook->add_format(bold=>1, size=>16);
 2061:     $format->{'h3'}   = $workbook->add_format(bold=>1, size=>14);
 2062:     $format->{'h4'}   = $workbook->add_format(bold=>1, size=>12);
 2063:     $format->{'i'}    = $workbook->add_format(italic=>1);
 2064:     $format->{'date'} = $workbook->add_format(num_format=>
 2065:                                             'mm/dd/yyyy hh:mm:ss');
 2066:     return $format;
 2067: }
 2068: 
 2069: ###############################################################
 2070: ###############################################################
 2071: 
 2072: =pod
 2073: 
 2074: =item * &create_workbook()
 2075: 
 2076: Create an Excel worksheet.  If it fails, output message on the
 2077: request object and return undefs.
 2078: 
 2079: Inputs: Apache request object
 2080: 
 2081: Returns (undef) on failure, 
 2082:     Excel worksheet object, scalar with filename, and formats 
 2083:     from &Apache::loncommon::define_excel_formats on success
 2084: 
 2085: =cut
 2086: 
 2087: ###############################################################
 2088: ###############################################################
 2089: sub create_workbook {
 2090:     my ($r) = @_;
 2091:         #
 2092:     # Create the excel spreadsheet
 2093:     my $filename = '/prtspool/'.
 2094:         $env{'user.name'}.'_'.$env{'user.domain'}.'_'.
 2095:         time.'_'.rand(1000000000).'.xls';
 2096:     my $workbook  = Spreadsheet::WriteExcel->new('/home/httpd'.$filename);
 2097:     if (! defined($workbook)) {
 2098:         $r->log_error("Error creating excel spreadsheet $filename: $!");
 2099:         $r->print(
 2100:             '<p class="LC_error">'
 2101:            .&mt('Problems occurred in creating the new Excel file.')
 2102:            .' '.&mt('This error has been logged.')
 2103:            .' '.&mt('Please alert your LON-CAPA administrator.')
 2104:            .'</p>'
 2105:         );
 2106:         return (undef);
 2107:     }
 2108:     #
 2109:     $workbook->set_tempdir(LONCAPA::tempdir());
 2110:     #
 2111:     my $format = &Apache::loncommon::define_excel_formats($workbook);
 2112:     return ($workbook,$filename,$format);
 2113: }
 2114: 
 2115: ###############################################################
 2116: ###############################################################
 2117: 
 2118: =pod
 2119: 
 2120: =item * &create_text_file()
 2121: 
 2122: Create a file to write to and eventually make available to the user.
 2123: If file creation fails, outputs an error message on the request object and 
 2124: return undefs.
 2125: 
 2126: Inputs: Apache request object, and file suffix
 2127: 
 2128: Returns (undef) on failure, 
 2129:     Filehandle and filename on success.
 2130: 
 2131: =cut
 2132: 
 2133: ###############################################################
 2134: ###############################################################
 2135: sub create_text_file {
 2136:     my ($r,$suffix) = @_;
 2137:     if (! defined($suffix)) { $suffix = 'txt'; };
 2138:     my $fh;
 2139:     my $filename = '/prtspool/'.
 2140:         $env{'user.name'}.'_'.$env{'user.domain'}.'_'.
 2141:         time.'_'.rand(1000000000).'.'.$suffix;
 2142:     $fh = Apache::File->new('>/home/httpd'.$filename);
 2143:     if (! defined($fh)) {
 2144:         $r->log_error("Couldn't open $filename for output $!");
 2145:         $r->print(
 2146:             '<p class="LC_error">'
 2147:            .&mt('Problems occurred in creating the output file.')
 2148:            .' '.&mt('This error has been logged.')
 2149:            .' '.&mt('Please alert your LON-CAPA administrator.')
 2150:            .'</p>'
 2151:         );
 2152:     }
 2153:     return ($fh,$filename)
 2154: }
 2155: 
 2156: 
 2157: =pod 
 2158: 
 2159: =back
 2160: 
 2161: =cut
 2162: 
 2163: ###############################################################
 2164: ##        Home server <option> list generating code          ##
 2165: ###############################################################
 2166: 
 2167: # ------------------------------------------
 2168: 
 2169: sub domain_select {
 2170:     my ($name,$value,$multiple)=@_;
 2171:     my %domains=map { 
 2172: 	$_ => $_.' '. &Apache::lonnet::domain($_,'description') 
 2173:     } &Apache::lonnet::all_domains();
 2174:     if ($multiple) {
 2175: 	$domains{''}=&mt('Any domain');
 2176: 	$domains{'select_form_order'} = [sort {lc($a) cmp lc($b) } (keys(%domains))];
 2177: 	return &multiple_select_form($name,$value,4,\%domains);
 2178:     } else {
 2179: 	$domains{'select_form_order'} = [sort {lc($a) cmp lc($b) } (keys(%domains))];
 2180: 	return &select_form($name,$value,\%domains);
 2181:     }
 2182: }
 2183: 
 2184: #-------------------------------------------
 2185: 
 2186: =pod
 2187: 
 2188: =head1 Routines for form select boxes
 2189: 
 2190: =over 4
 2191: 
 2192: =item * &multiple_select_form($name,$value,$size,$hash,$order)
 2193: 
 2194: Returns a string containing a <select> element int multiple mode
 2195: 
 2196: 
 2197: Args:
 2198:   $name - name of the <select> element
 2199:   $value - scalar or array ref of values that should already be selected
 2200:   $size - number of rows long the select element is
 2201:   $hash - the elements should be 'option' => 'shown text'
 2202:           (shown text should already have been &mt())
 2203:   $order - (optional) array ref of the order to show the elements in
 2204: 
 2205: =cut
 2206: 
 2207: #-------------------------------------------
 2208: sub multiple_select_form {
 2209:     my ($name,$value,$size,$hash,$order)=@_;
 2210:     my %selected = map { $_ => 1 } ref($value)?@{$value}:($value);
 2211:     my $output='';
 2212:     if (! defined($size)) {
 2213:         $size = 4;
 2214:         if (scalar(keys(%$hash))<4) {
 2215:             $size = scalar(keys(%$hash));
 2216:         }
 2217:     }
 2218:     $output.="\n".'<select name="'.$name.'" size="'.$size.'" multiple="multiple">';
 2219:     my @order;
 2220:     if (ref($order) eq 'ARRAY')  {
 2221:         @order = @{$order};
 2222:     } else {
 2223:         @order = sort(keys(%$hash));
 2224:     }
 2225:     if (exists($$hash{'select_form_order'})) {
 2226:         @order = @{$$hash{'select_form_order'}};
 2227:     }
 2228:         
 2229:     foreach my $key (@order) {
 2230:         $output.='<option value="'.&HTML::Entities::encode($key,'"<>&').'" ';
 2231:         $output.='selected="selected" ' if ($selected{$key});
 2232:         $output.='>'.$hash->{$key}."</option>\n";
 2233:     }
 2234:     $output.="</select>\n";
 2235:     return $output;
 2236: }
 2237: 
 2238: #-------------------------------------------
 2239: 
 2240: =pod
 2241: 
 2242: =item * &select_form($defdom,$name,$hashref,$onchange,$readonly)
 2243: 
 2244: Returns a string containing a <select name='$name' size='1'> form to 
 2245: allow a user to select options from a ref to a hash containing:
 2246: option_name => displayed text. An optional $onchange can include
 2247: a javascript onchange item, e.g., onchange="this.form.submit();".
 2248: An optional arg -- $readonly -- if true will cause the select form
 2249: to be disabled, e.g., for the case where an instructor has a section-
 2250: specific role, and is viewing/modifying parameters.  
 2251: 
 2252: See lonrights.pm for an example invocation and use.
 2253: 
 2254: =cut
 2255: 
 2256: #-------------------------------------------
 2257: sub select_form {
 2258:     my ($def,$name,$hashref,$onchange,$readonly) = @_;
 2259:     return unless (ref($hashref) eq 'HASH');
 2260:     if ($onchange) {
 2261:         $onchange = ' onchange="'.$onchange.'"';
 2262:     }
 2263:     my $selectform = "<select name=\"$name\" size=\"1\"$onchange>\n";
 2264:     my @keys;
 2265:     if (exists($hashref->{'select_form_order'})) {
 2266: 	@keys=@{$hashref->{'select_form_order'}};
 2267:     } else {
 2268: 	@keys=sort(keys(%{$hashref}));
 2269:     }
 2270:     foreach my $key (@keys) {
 2271:         $selectform.=
 2272: 	    '<option value="'.&HTML::Entities::encode($key,'"<>&').'" '.
 2273:             ($key eq $def ? 'selected="selected" ' : '').
 2274:                 ">".$hashref->{$key}."</option>\n";
 2275:     }
 2276:     $selectform.="</select>";
 2277:     return $selectform;
 2278: }
 2279: 
 2280: # For display filters
 2281: 
 2282: sub display_filter {
 2283:     my ($context) = @_;
 2284:     if (!$env{'form.show'}) { $env{'form.show'}=10; }
 2285:     if (!$env{'form.displayfilter'}) { $env{'form.displayfilter'}='currentfolder'; }
 2286:     my $phraseinput = 'hidden';
 2287:     my $includeinput = 'hidden';
 2288:     my ($checked,$includetypestext);
 2289:     if ($env{'form.displayfilter'} eq 'containing') {
 2290:         $phraseinput = 'text'; 
 2291:         if ($context eq 'parmslog') {
 2292:             $includeinput = 'checkbox';
 2293:             if ($env{'form.includetypes'}) {
 2294:                 $checked = ' checked="checked"';
 2295:             }
 2296:             $includetypestext = &mt('Include parameter types');
 2297:         }
 2298:     } else {
 2299:         $includetypestext = '&nbsp;';
 2300:     }
 2301:     my ($additional,$secondid,$thirdid);
 2302:     if ($context eq 'parmslog') {
 2303:         $additional = 
 2304:             '<label><input type="'.$includeinput.'" name="includetypes"'. 
 2305:             $checked.' name="includetypes" value="1" id="includetypes" />'.
 2306:             '&nbsp;<span id="includetypestext">'.$includetypestext.'</span>'.
 2307:             '</label>';
 2308:         $secondid = 'includetypes';
 2309:         $thirdid = 'includetypestext';
 2310:     }
 2311:     my $onchange = "javascript:toggleHistoryOptions(this,'containingphrase','$context',
 2312:                                                     '$secondid','$thirdid')";
 2313:     return '<span class="LC_nobreak"><label>'.&mt('Records: [_1]',
 2314: 			       &Apache::lonmeta::selectbox('show',$env{'form.show'},undef,
 2315: 							   (&mt('all'),10,20,50,100,1000,10000))).
 2316: 	   '</label></span> <span class="LC_nobreak">'.
 2317:            &mt('Filter: [_1]',
 2318: 	   &select_form($env{'form.displayfilter'},
 2319: 			'displayfilter',
 2320: 			{'currentfolder' => 'Current folder/page',
 2321: 			 'containing' => 'Containing phrase',
 2322: 			 'none' => 'None'},$onchange)).'&nbsp;'.
 2323: 			 '<input type="'.$phraseinput.'" name="containingphrase" id="containingphrase" size="30" value="'.
 2324:                          &HTML::Entities::encode($env{'form.containingphrase'}).
 2325:                          '" />'.$additional;
 2326: }
 2327: 
 2328: sub display_filter_js {
 2329:     my $includetext = &mt('Include parameter types');
 2330:     return <<"ENDJS";
 2331:   
 2332: function toggleHistoryOptions(setter,firstid,context,secondid,thirdid) {
 2333:     var firstType = 'hidden';
 2334:     if (setter.options[setter.selectedIndex].value == 'containing') {
 2335:         firstType = 'text';
 2336:     }
 2337:     firstObject = document.getElementById(firstid);
 2338:     if (typeof(firstObject) == 'object') {
 2339:         if (firstObject.type != firstType) {
 2340:             changeInputType(firstObject,firstType);
 2341:         }
 2342:     }
 2343:     if (context == 'parmslog') {
 2344:         var secondType = 'hidden';
 2345:         if (firstType == 'text') {
 2346:             secondType = 'checkbox';
 2347:         }
 2348:         secondObject = document.getElementById(secondid);  
 2349:         if (typeof(secondObject) == 'object') {
 2350:             if (secondObject.type != secondType) {
 2351:                 changeInputType(secondObject,secondType);
 2352:             }
 2353:         }
 2354:         var textItem = document.getElementById(thirdid);
 2355:         var currtext = textItem.innerHTML;
 2356:         var newtext;
 2357:         if (firstType == 'text') {
 2358:             newtext = '$includetext';
 2359:         } else {
 2360:             newtext = '&nbsp;';
 2361:         }
 2362:         if (currtext != newtext) {
 2363:             textItem.innerHTML = newtext;
 2364:         }
 2365:     }
 2366:     return;
 2367: }
 2368: 
 2369: function changeInputType(oldObject,newType) {
 2370:     var newObject = document.createElement('input');
 2371:     newObject.type = newType;
 2372:     if (oldObject.size) {
 2373:         newObject.size = oldObject.size;
 2374:     }
 2375:     if (oldObject.value) {
 2376:         newObject.value = oldObject.value;
 2377:     }
 2378:     if (oldObject.name) {
 2379:         newObject.name = oldObject.name;
 2380:     }
 2381:     if (oldObject.id) {
 2382:         newObject.id = oldObject.id;
 2383:     }
 2384:     oldObject.parentNode.replaceChild(newObject,oldObject);
 2385:     return;
 2386: }
 2387: 
 2388: ENDJS
 2389: }
 2390: 
 2391: sub gradeleveldescription {
 2392:     my $gradelevel=shift;
 2393:     my %gradelevels=(0 => 'Not specified',
 2394: 		     1 => 'Grade 1',
 2395: 		     2 => 'Grade 2',
 2396: 		     3 => 'Grade 3',
 2397: 		     4 => 'Grade 4',
 2398: 		     5 => 'Grade 5',
 2399: 		     6 => 'Grade 6',
 2400: 		     7 => 'Grade 7',
 2401: 		     8 => 'Grade 8',
 2402: 		     9 => 'Grade 9',
 2403: 		     10 => 'Grade 10',
 2404: 		     11 => 'Grade 11',
 2405: 		     12 => 'Grade 12',
 2406: 		     13 => 'Grade 13',
 2407: 		     14 => '100 Level',
 2408: 		     15 => '200 Level',
 2409: 		     16 => '300 Level',
 2410: 		     17 => '400 Level',
 2411: 		     18 => 'Graduate Level');
 2412:     return &mt($gradelevels{$gradelevel});
 2413: }
 2414: 
 2415: sub select_level_form {
 2416:     my ($deflevel,$name)=@_;
 2417:     unless ($deflevel) { $deflevel=0; }
 2418:     my $selectform = "<select name=\"$name\" size=\"1\">\n";
 2419:     for (my $i=0; $i<=18; $i++) {
 2420:         $selectform.="<option value=\"$i\" ".
 2421:             ($i==$deflevel ? 'selected="selected" ' : '').
 2422:                 ">".&gradeleveldescription($i)."</option>\n";
 2423:     }
 2424:     $selectform.="</select>";
 2425:     return $selectform;
 2426: }
 2427: 
 2428: #-------------------------------------------
 2429: 
 2430: =pod
 2431: 
 2432: =item * &select_dom_form($defdom,$name,$includeempty,$showdomdesc,$onchange,$incdoms,$excdoms,$disabled)
 2433: 
 2434: Returns a string containing a <select name='$name' size='1'> form to 
 2435: allow a user to select the domain to preform an operation in.  
 2436: See loncreateuser.pm for an example invocation and use.
 2437: 
 2438: If the $includeempty flag is set, it also includes an empty choice ("no domain
 2439: selected");
 2440: 
 2441: If the $showdomdesc flag is set, the domain name is followed by the domain description.
 2442: 
 2443: 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.
 2444: 
 2445: The optional $incdoms is a reference to an array of domains which will be the only available options.
 2446: 
 2447: The optional $excdoms is a reference to an array of domains which will be excluded from the available options.
 2448: 
 2449: The optional $disabled argument, if true, adds the disabled attribute to the select tag. 
 2450: 
 2451: =cut
 2452: 
 2453: #-------------------------------------------
 2454: sub select_dom_form {
 2455:     my ($defdom,$name,$includeempty,$showdomdesc,$onchange,$incdoms,$excdoms,$disabled) = @_;
 2456:     if ($onchange) {
 2457:         $onchange = ' onchange="'.$onchange.'"';
 2458:     }
 2459:     if ($disabled) {
 2460:         $disabled = ' disabled="disabled"';
 2461:     }
 2462:     my (@domains,%exclude);
 2463:     if (ref($incdoms) eq 'ARRAY') {
 2464:         @domains = sort {lc($a) cmp lc($b)} (@{$incdoms});
 2465:     } else {
 2466:         @domains = sort {lc($a) cmp lc($b)} (&Apache::lonnet::all_domains());
 2467:     }
 2468:     if ($includeempty) { @domains=('',@domains); }
 2469:     if (ref($excdoms) eq 'ARRAY') {
 2470:         map { $exclude{$_} = 1; } @{$excdoms};
 2471:     }
 2472:     my $selectdomain = "<select name=\"$name\" size=\"1\"$onchange$disabled>\n";
 2473:     foreach my $dom (@domains) {
 2474:         next if ($exclude{$dom});
 2475:         $selectdomain.="<option value=\"$dom\" ".
 2476:             ($dom eq $defdom ? 'selected="selected" ' : '').'>'.$dom;
 2477:         if ($showdomdesc) {
 2478:             if ($dom ne '') {
 2479:                 my $domdesc = &Apache::lonnet::domain($dom,'description');
 2480:                 if ($domdesc ne '') {
 2481:                     $selectdomain .= ' ('.$domdesc.')';
 2482:                 }
 2483:             } 
 2484:         }
 2485:         $selectdomain .= "</option>\n";
 2486:     }
 2487:     $selectdomain.="</select>";
 2488:     return $selectdomain;
 2489: }
 2490: 
 2491: #-------------------------------------------
 2492: 
 2493: =pod
 2494: 
 2495: =item * &home_server_form_item($domain,$name,$defaultflag)
 2496: 
 2497: input: 4 arguments (two required, two optional) - 
 2498:     $domain - domain of new user
 2499:     $name - name of form element
 2500:     $default - Value of 'default' causes a default item to be first 
 2501:                             option, and selected by default. 
 2502:     $hide - Value of 'hide' causes hiding of the name of the server, 
 2503:                             if 1 server found, or default, if 0 found.
 2504: output: returns 2 items: 
 2505: (a) form element which contains either:
 2506:    (i) <select name="$name">
 2507:         <option value="$hostid1">$hostid $servers{$hostid}</option>
 2508:         <option value="$hostid2">$hostid $servers{$hostid}</option>       
 2509:        </select>
 2510:        form item if there are multiple library servers in $domain, or
 2511:    (ii) an <input type="hidden" name="$name" value="$hostid" /> form item 
 2512:        if there is only one library server in $domain.
 2513: 
 2514: (b) number of library servers found.
 2515: 
 2516: See loncreateuser.pm for example of use.
 2517: 
 2518: =cut
 2519: 
 2520: #-------------------------------------------
 2521: sub home_server_form_item {
 2522:     my ($domain,$name,$default,$hide) = @_;
 2523:     my %servers = &Apache::lonnet::get_servers($domain,'library');
 2524:     my $result;
 2525:     my $numlib = keys(%servers);
 2526:     if ($numlib > 1) {
 2527:         $result .= '<select name="'.$name.'" />'."\n";
 2528:         if ($default) {
 2529:             $result .= '<option value="default" selected="selected">'.&mt('default').
 2530:                        '</option>'."\n";
 2531:         }
 2532:         foreach my $hostid (sort(keys(%servers))) {
 2533:             $result.= '<option value="'.$hostid.'">'.
 2534: 	              $hostid.' '.$servers{$hostid}."</option>\n";
 2535:         }
 2536:         $result .= '</select>'."\n";
 2537:     } elsif ($numlib == 1) {
 2538:         my $hostid;
 2539:         foreach my $item (keys(%servers)) {
 2540:             $hostid = $item;
 2541:         }
 2542:         $result .= '<input type="hidden" name="'.$name.'" value="'.
 2543:                    $hostid.'" />';
 2544:                    if (!$hide) {
 2545:                        $result .= $hostid.' '.$servers{$hostid};
 2546:                    }
 2547:                    $result .= "\n";
 2548:     } elsif ($default) {
 2549:         $result .= '<input type="hidden" name="'.$name.
 2550:                    '" value="default" />';
 2551:                    if (!$hide) {
 2552:                        $result .= &mt('default');
 2553:                    }
 2554:                    $result .= "\n";
 2555:     }
 2556:     return ($result,$numlib);
 2557: }
 2558: 
 2559: =pod
 2560: 
 2561: =back 
 2562: 
 2563: =cut
 2564: 
 2565: ###############################################################
 2566: ##                  Decoding User Agent                      ##
 2567: ###############################################################
 2568: 
 2569: =pod
 2570: 
 2571: =head1 Decoding the User Agent
 2572: 
 2573: =over 4
 2574: 
 2575: =item * &decode_user_agent()
 2576: 
 2577: Inputs: $r
 2578: 
 2579: Outputs:
 2580: 
 2581: =over 4
 2582: 
 2583: =item * $httpbrowser
 2584: 
 2585: =item * $clientbrowser
 2586: 
 2587: =item * $clientversion
 2588: 
 2589: =item * $clientmathml
 2590: 
 2591: =item * $clientunicode
 2592: 
 2593: =item * $clientos
 2594: 
 2595: =item * $clientmobile
 2596: 
 2597: =item * $clientinfo
 2598: 
 2599: =item * $clientosversion
 2600: 
 2601: =back
 2602: 
 2603: =back 
 2604: 
 2605: =cut
 2606: 
 2607: ###############################################################
 2608: ###############################################################
 2609: sub decode_user_agent {
 2610:     my ($r)=@_;
 2611:     my @browsertype=split(/\&/,$Apache::lonnet::perlvar{"lonBrowsDet"});
 2612:     my %mathcap=split(/\&/,$$Apache::lonnet::perlvar{"lonMathML"});
 2613:     my $httpbrowser=$ENV{"HTTP_USER_AGENT"};
 2614:     if (!$httpbrowser && $r) { $httpbrowser=$r->header_in('User-Agent'); }
 2615:     my $clientbrowser='unknown';
 2616:     my $clientversion='0';
 2617:     my $clientmathml='';
 2618:     my $clientunicode='0';
 2619:     my $clientmobile=0;
 2620:     my $clientosversion='';
 2621:     for (my $i=0;$i<=$#browsertype;$i++) {
 2622:         my ($bname,$match,$notmatch,$vreg,$minv,$univ)=split(/\%/,$browsertype[$i]);
 2623: 	if (($httpbrowser=~/$match/i)  && ($httpbrowser!~/$notmatch/i)) {
 2624: 	    $clientbrowser=$bname;
 2625:             $httpbrowser=~/$vreg/i;
 2626: 	    $clientversion=$1;
 2627:             $clientmathml=($clientversion>=$minv);
 2628:             $clientunicode=($clientversion>=$univ);
 2629: 	}
 2630:     }
 2631:     my $clientos='unknown';
 2632:     my $clientinfo;
 2633:     if (($httpbrowser=~/linux/i) ||
 2634:         ($httpbrowser=~/unix/i) ||
 2635:         ($httpbrowser=~/ux/i) ||
 2636:         ($httpbrowser=~/solaris/i)) { $clientos='unix'; }
 2637:     if (($httpbrowser=~/vax/i) ||
 2638:         ($httpbrowser=~/vms/i)) { $clientos='vms'; }
 2639:     if ($httpbrowser=~/next/i) { $clientos='next'; }
 2640:     if (($httpbrowser=~/mac/i) ||
 2641:         ($httpbrowser=~/powerpc/i)) { $clientos='mac'; }
 2642:     if ($httpbrowser=~/win/i) {
 2643:         $clientos='win';
 2644:         if ($httpbrowser =~/Windows\s+NT\s+(\d+\.\d+)/i) {
 2645:             $clientosversion = $1;
 2646:         }
 2647:     }
 2648:     if ($httpbrowser=~/embed/i) { $clientos='pda'; }
 2649:     if ($httpbrowser=~/(Android|iPod|iPad|iPhone|webOS|Blackberry|Windows Phone|Opera m(?:ob|in)|Fennec)/i) {
 2650:         $clientmobile=lc($1);
 2651:     }
 2652:     if ($httpbrowser=~ m{Firefox/(\d+\.\d+)}) {
 2653:         $clientinfo = 'firefox-'.$1;
 2654:     } elsif ($httpbrowser=~ m{chromeframe/(\d+\.\d+)\.}) {
 2655:         $clientinfo = 'chromeframe-'.$1;
 2656:     }
 2657:     return ($httpbrowser,$clientbrowser,$clientversion,$clientmathml,
 2658:             $clientunicode,$clientos,$clientmobile,$clientinfo,
 2659:             $clientosversion);
 2660: }
 2661: 
 2662: ###############################################################
 2663: ##    Authentication changing form generation subroutines    ##
 2664: ###############################################################
 2665: ##
 2666: ## All of the authform_xxxxxxx subroutines take their inputs in a
 2667: ## hash, and have reasonable default values.
 2668: ##
 2669: ##    formname = the name given in the <form> tag.
 2670: #-------------------------------------------
 2671: 
 2672: =pod
 2673: 
 2674: =head1 Authentication Routines
 2675: 
 2676: =over 4
 2677: 
 2678: =item * &authform_xxxxxx()
 2679: 
 2680: The authform_xxxxxx subroutines provide javascript and html forms which 
 2681: handle some of the conveniences required for authentication forms.  
 2682: This is not an optimal method, but it works.  
 2683: 
 2684: =over 4
 2685: 
 2686: =item * authform_header
 2687: 
 2688: =item * authform_authorwarning
 2689: 
 2690: =item * authform_nochange
 2691: 
 2692: =item * authform_kerberos
 2693: 
 2694: =item * authform_internal
 2695: 
 2696: =item * authform_filesystem
 2697: 
 2698: =back
 2699: 
 2700: See loncreateuser.pm for invocation and use examples.
 2701: 
 2702: =cut
 2703: 
 2704: #-------------------------------------------
 2705: sub authform_header{  
 2706:     my %in = (
 2707:         formname => 'cu',
 2708:         kerb_def_dom => '',
 2709:         @_,
 2710:     );
 2711:     $in{'formname'} = 'document.' . $in{'formname'};
 2712:     my $result='';
 2713: 
 2714: #---------------------------------------------- Code for upper case translation
 2715:     my $Javascript_toUpperCase;
 2716:     unless ($in{kerb_def_dom}) {
 2717:         $Javascript_toUpperCase =<<"END";
 2718:         switch (choice) {
 2719:            case 'krb': currentform.elements[choicearg].value =
 2720:                currentform.elements[choicearg].value.toUpperCase();
 2721:                break;
 2722:            default:
 2723:         }
 2724: END
 2725:     } else {
 2726:         $Javascript_toUpperCase = "";
 2727:     }
 2728: 
 2729:     my $radioval = "'nochange'";
 2730:     if (defined($in{'curr_authtype'})) {
 2731:         if ($in{'curr_authtype'} ne '') {
 2732:             $radioval = "'".$in{'curr_authtype'}."arg'";
 2733:         }
 2734:     }
 2735:     my $argfield = 'null';
 2736:     if (defined($in{'mode'})) {
 2737:         if ($in{'mode'} eq 'modifycourse')  {
 2738:             if (defined($in{'curr_autharg'})) {
 2739:                 if ($in{'curr_autharg'} ne '') {
 2740:                     $argfield = "'$in{'curr_autharg'}'";
 2741:                 }
 2742:             }
 2743:         }
 2744:     }
 2745: 
 2746:     $result.=<<"END";
 2747: var current = new Object();
 2748: current.radiovalue = $radioval;
 2749: current.argfield = $argfield;
 2750: 
 2751: function changed_radio(choice,currentform) {
 2752:     var choicearg = choice + 'arg';
 2753:     // If a radio button in changed, we need to change the argfield
 2754:     if (current.radiovalue != choice) {
 2755:         current.radiovalue = choice;
 2756:         if (current.argfield != null) {
 2757:             currentform.elements[current.argfield].value = '';
 2758:         }
 2759:         if (choice == 'nochange') {
 2760:             current.argfield = null;
 2761:         } else {
 2762:             current.argfield = choicearg;
 2763:             switch(choice) {
 2764:                 case 'krb': 
 2765:                     currentform.elements[current.argfield].value = 
 2766:                         "$in{'kerb_def_dom'}";
 2767:                 break;
 2768:               default:
 2769:                 break;
 2770:             }
 2771:         }
 2772:     }
 2773:     return;
 2774: }
 2775: 
 2776: function changed_text(choice,currentform) {
 2777:     var choicearg = choice + 'arg';
 2778:     if (currentform.elements[choicearg].value !='') {
 2779:         $Javascript_toUpperCase
 2780:         // clear old field
 2781:         if ((current.argfield != choicearg) && (current.argfield != null)) {
 2782:             currentform.elements[current.argfield].value = '';
 2783:         }
 2784:         current.argfield = choicearg;
 2785:     }
 2786:     set_auth_radio_buttons(choice,currentform);
 2787:     return;
 2788: }
 2789: 
 2790: function set_auth_radio_buttons(newvalue,currentform) {
 2791:     var numauthchoices = currentform.login.length;
 2792:     if (typeof numauthchoices  == "undefined") {
 2793:         return;
 2794:     } 
 2795:     var i=0;
 2796:     while (i < numauthchoices) {
 2797:         if (currentform.login[i].value == newvalue) { break; }
 2798:         i++;
 2799:     }
 2800:     if (i == numauthchoices) {
 2801:         return;
 2802:     }
 2803:     current.radiovalue = newvalue;
 2804:     currentform.login[i].checked = true;
 2805:     return;
 2806: }
 2807: END
 2808:     return $result;
 2809: }
 2810: 
 2811: sub authform_authorwarning {
 2812:     my $result='';
 2813:     $result='<i>'.
 2814:         &mt('As a general rule, only authors or co-authors should be '.
 2815:             'filesystem authenticated '.
 2816:             '(which allows access to the server filesystem).')."</i>\n";
 2817:     return $result;
 2818: }
 2819: 
 2820: sub authform_nochange {
 2821:     my %in = (
 2822:               formname => 'document.cu',
 2823:               kerb_def_dom => 'MSU.EDU',
 2824:               @_,
 2825:           );
 2826:     my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'}); 
 2827:     my $result;
 2828:     if (!$authnum) {
 2829:         $result = &mt('Under your current role you are not permitted to change login settings for this user');
 2830:     } else {
 2831:         $result = '<label>'.&mt('[_1] Do not change login data',
 2832:                   '<input type="radio" name="login" value="nochange" '.
 2833:                   'checked="checked" onclick="'.
 2834:             "javascript:changed_radio('nochange',$in{'formname'});".'" />').
 2835: 	    '</label>';
 2836:     }
 2837:     return $result;
 2838: }
 2839: 
 2840: sub authform_kerberos {
 2841:     my %in = (
 2842:               formname => 'document.cu',
 2843:               kerb_def_dom => 'MSU.EDU',
 2844:               kerb_def_auth => 'krb4',
 2845:               @_,
 2846:               );
 2847:     my ($check4,$check5,$krbcheck,$krbarg,$krbver,$result,$authtype,
 2848:         $autharg,$jscall,$disabled);
 2849:     my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
 2850:     if ($in{'kerb_def_auth'} eq 'krb5') {
 2851:        $check5 = ' checked="checked"';
 2852:     } else {
 2853:        $check4 = ' checked="checked"';
 2854:     }
 2855:     if ($in{'readonly'}) {
 2856:         $disabled = ' disabled="disabled"';
 2857:     }
 2858:     $krbarg = $in{'kerb_def_dom'};
 2859:     if (defined($in{'curr_authtype'})) {
 2860:         if ($in{'curr_authtype'} eq 'krb') {
 2861:             $krbcheck = ' checked="checked"';
 2862:             if (defined($in{'mode'})) {
 2863:                 if ($in{'mode'} eq 'modifyuser') {
 2864:                     $krbcheck = '';
 2865:                 }
 2866:             }
 2867:             if (defined($in{'curr_kerb_ver'})) {
 2868:                 if ($in{'curr_krb_ver'} eq '5') {
 2869:                     $check5 = ' checked="checked"';
 2870:                     $check4 = '';
 2871:                 } else {
 2872:                     $check4 = ' checked="checked"';
 2873:                     $check5 = '';
 2874:                 }
 2875:             }
 2876:             if (defined($in{'curr_autharg'})) {
 2877:                 $krbarg = $in{'curr_autharg'};
 2878:             }
 2879:             if (!$can_assign{'krb4'} && !$can_assign{'krb5'}) {
 2880:                 if (defined($in{'curr_autharg'})) {
 2881:                     $result = 
 2882:     &mt('Currently Kerberos authenticated with domain [_1] Version [_2].',
 2883:         $in{'curr_autharg'},$krbver);
 2884:                 } else {
 2885:                     $result =
 2886:     &mt('Currently Kerberos authenticated, Version [_1].',$krbver);
 2887:                 }
 2888:                 return $result; 
 2889:             }
 2890:         }
 2891:     } else {
 2892:         if ($authnum == 1) {
 2893:             $authtype = '<input type="hidden" name="login" value="krb" />';
 2894:         }
 2895:     }
 2896:     if (!$can_assign{'krb4'} && !$can_assign{'krb5'}) {
 2897:         return;
 2898:     } elsif ($authtype eq '') {
 2899:         if (defined($in{'mode'})) {
 2900:             if ($in{'mode'} eq 'modifycourse') {
 2901:                 if ($authnum == 1) {
 2902:                     $authtype = '<input type="radio" name="login" value="krb"'.$disabled.' />';
 2903:                 }
 2904:             }
 2905:         }
 2906:     }
 2907:     $jscall = "javascript:changed_radio('krb',$in{'formname'});";
 2908:     if ($authtype eq '') {
 2909:         $authtype = '<input type="radio" name="login" value="krb" '.
 2910:                     'onclick="'.$jscall.'" onchange="'.$jscall.'"'.
 2911:                     $krbcheck.$disabled.' />';
 2912:     }
 2913:     if (($can_assign{'krb4'} && $can_assign{'krb5'}) ||
 2914:         ($can_assign{'krb4'} && !$can_assign{'krb5'} &&
 2915:          $in{'curr_authtype'} eq 'krb5') ||
 2916:         (!$can_assign{'krb4'} && $can_assign{'krb5'} &&
 2917:          $in{'curr_authtype'} eq 'krb4')) {
 2918:         $result .= &mt
 2919:         ('[_1] Kerberos authenticated with domain [_2] '.
 2920:          '[_3] Version 4 [_4] Version 5 [_5]',
 2921:          '<label>'.$authtype,
 2922:          '</label><input type="text" size="10" name="krbarg" '.
 2923:              'value="'.$krbarg.'" '.
 2924:              'onchange="'.$jscall.'"'.$disabled.' />',
 2925:          '<label><input type="radio" name="krbver" value="4" '.$check4.$disabled.' />',
 2926:          '</label><label><input type="radio" name="krbver" value="5" '.$check5.$disabled.' />',
 2927: 	 '</label>');
 2928:     } elsif ($can_assign{'krb4'}) {
 2929:         $result .= &mt
 2930:         ('[_1] Kerberos authenticated with domain [_2] '.
 2931:          '[_3] Version 4 [_4]',
 2932:          '<label>'.$authtype,
 2933:          '</label><input type="text" size="10" name="krbarg" '.
 2934:              'value="'.$krbarg.'" '.
 2935:              'onchange="'.$jscall.'"'.$disabled.' />',
 2936:          '<label><input type="hidden" name="krbver" value="4" />',
 2937:          '</label>');
 2938:     } elsif ($can_assign{'krb5'}) {
 2939:         $result .= &mt
 2940:         ('[_1] Kerberos authenticated with domain [_2] '.
 2941:          '[_3] Version 5 [_4]',
 2942:          '<label>'.$authtype,
 2943:          '</label><input type="text" size="10" name="krbarg" '.
 2944:              'value="'.$krbarg.'" '.
 2945:              'onchange="'.$jscall.'"'.$disabled.' />',
 2946:          '<label><input type="hidden" name="krbver" value="5" />',
 2947:          '</label>');
 2948:     }
 2949:     return $result;
 2950: }
 2951: 
 2952: sub authform_internal {
 2953:     my %in = (
 2954:                 formname => 'document.cu',
 2955:                 kerb_def_dom => 'MSU.EDU',
 2956:                 @_,
 2957:                 );
 2958:     my ($intcheck,$intarg,$result,$authtype,$autharg,$jscall,$disabled);
 2959:     my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
 2960:     if ($in{'readonly'}) {
 2961:         $disabled = ' disabled="disabled"';
 2962:     }
 2963:     if (defined($in{'curr_authtype'})) {
 2964:         if ($in{'curr_authtype'} eq 'int') {
 2965:             if ($can_assign{'int'}) {
 2966:                 $intcheck = 'checked="checked" ';
 2967:                 if (defined($in{'mode'})) {
 2968:                     if ($in{'mode'} eq 'modifyuser') {
 2969:                         $intcheck = '';
 2970:                     }
 2971:                 }
 2972:                 if (defined($in{'curr_autharg'})) {
 2973:                     $intarg = $in{'curr_autharg'};
 2974:                 }
 2975:             } else {
 2976:                 $result = &mt('Currently internally authenticated.');
 2977:                 return $result;
 2978:             }
 2979:         }
 2980:     } else {
 2981:         if ($authnum == 1) {
 2982:             $authtype = '<input type="hidden" name="login" value="int" />';
 2983:         }
 2984:     }
 2985:     if (!$can_assign{'int'}) {
 2986:         return;
 2987:     } elsif ($authtype eq '') {
 2988:         if (defined($in{'mode'})) {
 2989:             if ($in{'mode'} eq 'modifycourse') {
 2990:                 if ($authnum == 1) {
 2991:                     $authtype = '<input type="radio" name="login" value="int"'.$disabled.' />';
 2992:                 }
 2993:             }
 2994:         }
 2995:     }
 2996:     $jscall = "javascript:changed_radio('int',$in{'formname'});";
 2997:     if ($authtype eq '') {
 2998:         $authtype = '<input type="radio" name="login" value="int" '.$intcheck.
 2999:                     ' onchange="'.$jscall.'" onclick="'.$jscall.'"'.$disabled.' />';
 3000:     }
 3001:     $autharg = '<input type="password" size="10" name="intarg" value="'.
 3002:                $intarg.'" onchange="'.$jscall.'"'.$disabled.' />';
 3003:     $result = &mt
 3004:         ('[_1] Internally authenticated (with initial password [_2])',
 3005:          '<label>'.$authtype,'</label>'.$autharg);
 3006:     $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>';
 3007:     return $result;
 3008: }
 3009: 
 3010: sub authform_local {
 3011:     my %in = (
 3012:               formname => 'document.cu',
 3013:               kerb_def_dom => 'MSU.EDU',
 3014:               @_,
 3015:               );
 3016:     my ($loccheck,$locarg,$result,$authtype,$autharg,$jscall,$disabled);
 3017:     my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
 3018:     if ($in{'readonly'}) {
 3019:         $disabled = ' disabled="disabled"';
 3020:     }
 3021:     if (defined($in{'curr_authtype'})) {
 3022:         if ($in{'curr_authtype'} eq 'loc') {
 3023:             if ($can_assign{'loc'}) {
 3024:                 $loccheck = 'checked="checked" ';
 3025:                 if (defined($in{'mode'})) {
 3026:                     if ($in{'mode'} eq 'modifyuser') {
 3027:                         $loccheck = '';
 3028:                     }
 3029:                 }
 3030:                 if (defined($in{'curr_autharg'})) {
 3031:                     $locarg = $in{'curr_autharg'};
 3032:                 }
 3033:             } else {
 3034:                 $result = &mt('Currently using local (institutional) authentication.');
 3035:                 return $result;
 3036:             }
 3037:         }
 3038:     } else {
 3039:         if ($authnum == 1) {
 3040:             $authtype = '<input type="hidden" name="login" value="loc" />';
 3041:         }
 3042:     }
 3043:     if (!$can_assign{'loc'}) {
 3044:         return;
 3045:     } elsif ($authtype eq '') {
 3046:         if (defined($in{'mode'})) {
 3047:             if ($in{'mode'} eq 'modifycourse') {
 3048:                 if ($authnum == 1) {
 3049:                     $authtype = '<input type="radio" name="login" value="loc"'.$disabled.' />';
 3050:                 }
 3051:             }
 3052:         }
 3053:     }
 3054:     $jscall = "javascript:changed_radio('loc',$in{'formname'});";
 3055:     if ($authtype eq '') {
 3056:         $authtype = '<input type="radio" name="login" value="loc" '.
 3057:                     $loccheck.' onchange="'.$jscall.'" onclick="'.
 3058:                     $jscall.'"'.$disabled.' />';
 3059:     }
 3060:     $autharg = '<input type="text" size="10" name="locarg" value="'.
 3061:                $locarg.'" onchange="'.$jscall.'"'.$disabled.' />';
 3062:     $result = &mt('[_1] Local Authentication with argument [_2]',
 3063:                   '<label>'.$authtype,'</label>'.$autharg);
 3064:     return $result;
 3065: }
 3066: 
 3067: sub authform_filesystem {
 3068:     my %in = (
 3069:               formname => 'document.cu',
 3070:               kerb_def_dom => 'MSU.EDU',
 3071:               @_,
 3072:               );
 3073:     my ($fsyscheck,$result,$authtype,$autharg,$jscall,$disabled);
 3074:     my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
 3075:     if ($in{'readonly'}) {
 3076:         $disabled = ' disabled="disabled"';
 3077:     }
 3078:     if (defined($in{'curr_authtype'})) {
 3079:         if ($in{'curr_authtype'} eq 'fsys') {
 3080:             if ($can_assign{'fsys'}) {
 3081:                 $fsyscheck = 'checked="checked" ';
 3082:                 if (defined($in{'mode'})) {
 3083:                     if ($in{'mode'} eq 'modifyuser') {
 3084:                         $fsyscheck = '';
 3085:                     }
 3086:                 }
 3087:             } else {
 3088:                 $result = &mt('Currently Filesystem Authenticated.');
 3089:                 return $result;
 3090:             }           
 3091:         }
 3092:     } else {
 3093:         if ($authnum == 1) {
 3094:             $authtype = '<input type="hidden" name="login" value="fsys" />';
 3095:         }
 3096:     }
 3097:     if (!$can_assign{'fsys'}) {
 3098:         return;
 3099:     } elsif ($authtype eq '') {
 3100:         if (defined($in{'mode'})) {
 3101:             if ($in{'mode'} eq 'modifycourse') {
 3102:                 if ($authnum == 1) {
 3103:                     $authtype = '<input type="radio" name="login" value="fsys"'.$disabled.' />';
 3104:                 }
 3105:             }
 3106:         }
 3107:     }
 3108:     $jscall = "javascript:changed_radio('fsys',$in{'formname'});";
 3109:     if ($authtype eq '') {
 3110:         $authtype = '<input type="radio" name="login" value="fsys" '.
 3111:                     $fsyscheck.' onchange="'.$jscall.'" onclick="'.
 3112:                     $jscall.'"'.$disabled.' />';
 3113:     }
 3114:     $autharg = '<input type="text" size="10" name="fsysarg" value=""'.
 3115:                ' onchange="'.$jscall.'"'.$disabled.' />';
 3116:     $result = &mt
 3117:         ('[_1] Filesystem Authenticated (with initial password [_2])',
 3118:          '<label><input type="radio" name="login" value="fsys" '.
 3119:          $fsyscheck.'onchange="'.$jscall.'" onclick="'.$jscall.'"'.$disabled.' />',
 3120:          '</label><input type="password" size="10" name="fsysarg" value="" '.
 3121:                   'onchange="'.$jscall.'"'.$disabled.' />');
 3122:     return $result;
 3123: }
 3124: 
 3125: sub get_assignable_auth {
 3126:     my ($dom) = @_;
 3127:     if ($dom eq '') {
 3128:         $dom = $env{'request.role.domain'};
 3129:     }
 3130:     my %can_assign = (
 3131:                           krb4 => 1,
 3132:                           krb5 => 1,
 3133:                           int  => 1,
 3134:                           loc  => 1,
 3135:                      );
 3136:     my %domconfig = &Apache::lonnet::get_dom('configuration',['usercreation'],$dom);
 3137:     if (ref($domconfig{'usercreation'}) eq 'HASH') {
 3138:         if (ref($domconfig{'usercreation'}{'authtypes'}) eq 'HASH') {
 3139:             my $authhash = $domconfig{'usercreation'}{'authtypes'};
 3140:             my $context;
 3141:             if ($env{'request.role'} =~ /^au/) {
 3142:                 $context = 'author';
 3143:             } elsif ($env{'request.role'} =~ /^(dc|dh)/) {
 3144:                 $context = 'domain';
 3145:             } elsif ($env{'request.course.id'}) {
 3146:                 $context = 'course';
 3147:             }
 3148:             if ($context) {
 3149:                 if (ref($authhash->{$context}) eq 'HASH') {
 3150:                    %can_assign = %{$authhash->{$context}}; 
 3151:                 }
 3152:             }
 3153:         }
 3154:     }
 3155:     my $authnum = 0;
 3156:     foreach my $key (keys(%can_assign)) {
 3157:         if ($can_assign{$key}) {
 3158:             $authnum ++;
 3159:         }
 3160:     }
 3161:     if ($can_assign{'krb4'} && $can_assign{'krb5'}) {
 3162:         $authnum --;
 3163:     }
 3164:     return ($authnum,%can_assign);
 3165: }
 3166: 
 3167: ###############################################################
 3168: ##    Get Kerberos Defaults for Domain                 ##
 3169: ###############################################################
 3170: ##
 3171: ## Returns default kerberos version and an associated argument
 3172: ## as listed in file domain.tab. If not listed, provides
 3173: ## appropriate default domain and kerberos version.
 3174: ##
 3175: #-------------------------------------------
 3176: 
 3177: =pod
 3178: 
 3179: =item * &get_kerberos_defaults()
 3180: 
 3181: get_kerberos_defaults($target_domain) returns the default kerberos
 3182: version and domain. If not found, it defaults to version 4 and the 
 3183: domain of the server.
 3184: 
 3185: =over 4
 3186: 
 3187: ($def_version, $def_krb_domain) = &get_kerberos_defaults($target_domain);
 3188: 
 3189: =back
 3190: 
 3191: =back
 3192: 
 3193: =cut
 3194: 
 3195: #-------------------------------------------
 3196: sub get_kerberos_defaults {
 3197:     my $domain=shift;
 3198:     my ($krbdef,$krbdefdom);
 3199:     my %domdefaults = &Apache::lonnet::get_domain_defaults($domain);
 3200:     if (($domdefaults{'auth_def'} =~/^krb(4|5)$/) && ($domdefaults{'auth_arg_def'} ne '')) {
 3201:         $krbdef = $domdefaults{'auth_def'};
 3202:         $krbdefdom = $domdefaults{'auth_arg_def'};
 3203:     } else {
 3204:         $ENV{'SERVER_NAME'}=~/(\w+\.\w+)$/;
 3205:         my $krbdefdom=$1;
 3206:         $krbdefdom=~tr/a-z/A-Z/;
 3207:         $krbdef = "krb4";
 3208:     }
 3209:     return ($krbdef,$krbdefdom);
 3210: }
 3211: 
 3212: 
 3213: ###############################################################
 3214: ##                Thesaurus Functions                        ##
 3215: ###############################################################
 3216: 
 3217: =pod
 3218: 
 3219: =head1 Thesaurus Functions
 3220: 
 3221: =over 4
 3222: 
 3223: =item * &initialize_keywords()
 3224: 
 3225: Initializes the package variable %Keywords if it is empty.  Uses the
 3226: package variable $thesaurus_db_file.
 3227: 
 3228: =cut
 3229: 
 3230: ###################################################
 3231: 
 3232: sub initialize_keywords {
 3233:     return 1 if (scalar keys(%Keywords));
 3234:     # If we are here, %Keywords is empty, so fill it up
 3235:     #   Make sure the file we need exists...
 3236:     if (! -e $thesaurus_db_file) {
 3237:         &Apache::lonnet::logthis("Attempt to access $thesaurus_db_file".
 3238:                                  " failed because it does not exist");
 3239:         return 0;
 3240:     }
 3241:     #   Set up the hash as a database
 3242:     my %thesaurus_db;
 3243:     if (! tie(%thesaurus_db,'GDBM_File',
 3244:               $thesaurus_db_file,&GDBM_READER(),0640)){
 3245:         &Apache::lonnet::logthis("Could not tie \%thesaurus_db to ".
 3246:                                  $thesaurus_db_file);
 3247:         return 0;
 3248:     } 
 3249:     #  Get the average number of appearances of a word.
 3250:     my $avecount = $thesaurus_db{'average.count'};
 3251:     #  Put keywords (those that appear > average) into %Keywords
 3252:     while (my ($word,$data)=each (%thesaurus_db)) {
 3253:         my ($count,undef) = split /:/,$data;
 3254:         $Keywords{$word}++ if ($count > $avecount);
 3255:     }
 3256:     untie %thesaurus_db;
 3257:     # Remove special values from %Keywords.
 3258:     foreach my $value ('total.count','average.count') {
 3259:         delete($Keywords{$value}) if (exists($Keywords{$value}));
 3260:   }
 3261:     return 1;
 3262: }
 3263: 
 3264: ###################################################
 3265: 
 3266: =pod
 3267: 
 3268: =item * &keyword($word)
 3269: 
 3270: Returns true if $word is a keyword.  A keyword is a word that appears more 
 3271: than the average number of times in the thesaurus database.  Calls 
 3272: &initialize_keywords
 3273: 
 3274: =cut
 3275: 
 3276: ###################################################
 3277: 
 3278: sub keyword {
 3279:     return if (!&initialize_keywords());
 3280:     my $word=lc(shift());
 3281:     $word=~s/\W//g;
 3282:     return exists($Keywords{$word});
 3283: }
 3284: 
 3285: ###############################################################
 3286: 
 3287: =pod 
 3288: 
 3289: =item * &get_related_words()
 3290: 
 3291: Look up a word in the thesaurus.  Takes a scalar argument and returns
 3292: an array of words.  If the keyword is not in the thesaurus, an empty array
 3293: will be returned.  The order of the words returned is determined by the
 3294: database which holds them.
 3295: 
 3296: Uses global $thesaurus_db_file.
 3297: 
 3298: 
 3299: =cut
 3300: 
 3301: ###############################################################
 3302: sub get_related_words {
 3303:     my $keyword = shift;
 3304:     my %thesaurus_db;
 3305:     if (! -e $thesaurus_db_file) {
 3306:         &Apache::lonnet::logthis("Attempt to access $thesaurus_db_file ".
 3307:                                  "failed because the file does not exist");
 3308:         return ();
 3309:     }
 3310:     if (! tie(%thesaurus_db,'GDBM_File',
 3311:               $thesaurus_db_file,&GDBM_READER(),0640)){
 3312:         return ();
 3313:     } 
 3314:     my @Words=();
 3315:     my $count=0;
 3316:     if (exists($thesaurus_db{$keyword})) {
 3317: 	# The first element is the number of times
 3318: 	# the word appears.  We do not need it now.
 3319: 	my (undef,@RelatedWords) = (split(/:/,$thesaurus_db{$keyword}));
 3320: 	my (undef,$mostfrequentcount)=split(/\,/,$RelatedWords[0]);
 3321: 	my $threshold=$mostfrequentcount/10;
 3322:         foreach my $possibleword (@RelatedWords) {
 3323:             my ($word,$wordcount)=split(/\,/,$possibleword);
 3324:             if ($wordcount>$threshold) {
 3325: 		push(@Words,$word);
 3326:                 $count++;
 3327:                 if ($count>10) { last; }
 3328: 	    }
 3329:         }
 3330:     }
 3331:     untie %thesaurus_db;
 3332:     return @Words;
 3333: }
 3334: 
 3335: =pod
 3336: 
 3337: =back
 3338: 
 3339: =cut
 3340: 
 3341: # -------------------------------------------------------------- Plaintext name
 3342: =pod
 3343: 
 3344: =head1 User Name Functions
 3345: 
 3346: =over 4
 3347: 
 3348: =item * &plainname($uname,$udom,$first)
 3349: 
 3350: Takes a users logon name and returns it as a string in
 3351: "first middle last generation" form 
 3352: if $first is set to 'lastname' then it returns it as
 3353: 'lastname generation, firstname middlename' if their is a lastname
 3354: 
 3355: =cut
 3356: 
 3357: 
 3358: ###############################################################
 3359: sub plainname {
 3360:     my ($uname,$udom,$first)=@_;
 3361:     return if (!defined($uname) || !defined($udom));
 3362:     my %names=&getnames($uname,$udom);
 3363:     my $name=&Apache::lonnet::format_name($names{'firstname'},
 3364: 					  $names{'middlename'},
 3365: 					  $names{'lastname'},
 3366: 					  $names{'generation'},$first);
 3367:     $name=~s/^\s+//;
 3368:     $name=~s/\s+$//;
 3369:     $name=~s/\s+/ /g;
 3370:     if ($name !~ /\S/) { $name=$uname.':'.$udom; }
 3371:     return $name;
 3372: }
 3373: 
 3374: # -------------------------------------------------------------------- Nickname
 3375: =pod
 3376: 
 3377: =item * &nickname($uname,$udom)
 3378: 
 3379: Gets a users name and returns it as a string as
 3380: 
 3381: "&quot;nickname&quot;"
 3382: 
 3383: if the user has a nickname or
 3384: 
 3385: "first middle last generation"
 3386: 
 3387: if the user does not
 3388: 
 3389: =cut
 3390: 
 3391: sub nickname {
 3392:     my ($uname,$udom)=@_;
 3393:     return if (!defined($uname) || !defined($udom));
 3394:     my %names=&getnames($uname,$udom);
 3395:     my $name=$names{'nickname'};
 3396:     if ($name) {
 3397:        $name='&quot;'.$name.'&quot;'; 
 3398:     } else {
 3399:        $name=$names{'firstname'}.' '.$names{'middlename'}.' '.
 3400: 	     $names{'lastname'}.' '.$names{'generation'};
 3401:        $name=~s/\s+$//;
 3402:        $name=~s/\s+/ /g;
 3403:     }
 3404:     return $name;
 3405: }
 3406: 
 3407: sub getnames {
 3408:     my ($uname,$udom)=@_;
 3409:     return if (!defined($uname) || !defined($udom));
 3410:     if ($udom eq 'public' && $uname eq 'public') {
 3411: 	return ('lastname' => &mt('Public'));
 3412:     }
 3413:     my $id=$uname.':'.$udom;
 3414:     my ($names,$cached)=&Apache::lonnet::is_cached_new('namescache',$id);
 3415:     if ($cached) {
 3416: 	return %{$names};
 3417:     } else {
 3418: 	my %loadnames=&Apache::lonnet::get('environment',
 3419:                     ['firstname','middlename','lastname','generation','nickname'],
 3420: 					 $udom,$uname);
 3421: 	&Apache::lonnet::do_cache_new('namescache',$id,\%loadnames);
 3422: 	return %loadnames;
 3423:     }
 3424: }
 3425: 
 3426: # -------------------------------------------------------------------- getemails
 3427: 
 3428: =pod
 3429: 
 3430: =item * &getemails($uname,$udom)
 3431: 
 3432: Gets a user's email information and returns it as a hash with keys:
 3433: notification, critnotification, permanentemail
 3434: 
 3435: For notification and critnotification, values are comma-separated lists 
 3436: of e-mail addresses; for permanentemail, value is a single e-mail address.
 3437:  
 3438: 
 3439: =cut
 3440: 
 3441: 
 3442: sub getemails {
 3443:     my ($uname,$udom)=@_;
 3444:     if ($udom eq 'public' && $uname eq 'public') {
 3445: 	return;
 3446:     }
 3447:     if (!$udom) { $udom=$env{'user.domain'}; }
 3448:     if (!$uname) { $uname=$env{'user.name'}; }
 3449:     my $id=$uname.':'.$udom;
 3450:     my ($names,$cached)=&Apache::lonnet::is_cached_new('emailscache',$id);
 3451:     if ($cached) {
 3452: 	return %{$names};
 3453:     } else {
 3454: 	my %loadnames=&Apache::lonnet::get('environment',
 3455:                     			   ['notification','critnotification',
 3456: 					    'permanentemail'],
 3457: 					   $udom,$uname);
 3458: 	&Apache::lonnet::do_cache_new('emailscache',$id,\%loadnames);
 3459: 	return %loadnames;
 3460:     }
 3461: }
 3462: 
 3463: sub flush_email_cache {
 3464:     my ($uname,$udom)=@_;
 3465:     if (!$udom)  { $udom =$env{'user.domain'}; }
 3466:     if (!$uname) { $uname=$env{'user.name'};   }
 3467:     return if ($udom eq 'public' && $uname eq 'public');
 3468:     my $id=$uname.':'.$udom;
 3469:     &Apache::lonnet::devalidate_cache_new('emailscache',$id);
 3470: }
 3471: 
 3472: # -------------------------------------------------------------------- getlangs
 3473: 
 3474: =pod
 3475: 
 3476: =item * &getlangs($uname,$udom)
 3477: 
 3478: Gets a user's language preference and returns it as a hash with key:
 3479: language.
 3480: 
 3481: =cut
 3482: 
 3483: 
 3484: sub getlangs {
 3485:     my ($uname,$udom) = @_;
 3486:     if (!$udom)  { $udom =$env{'user.domain'}; }
 3487:     if (!$uname) { $uname=$env{'user.name'};   }
 3488:     my $id=$uname.':'.$udom;
 3489:     my ($langs,$cached)=&Apache::lonnet::is_cached_new('userlangs',$id);
 3490:     if ($cached) {
 3491:         return %{$langs};
 3492:     } else {
 3493:         my %loadlangs=&Apache::lonnet::get('environment',['languages'],
 3494:                                            $udom,$uname);
 3495:         &Apache::lonnet::do_cache_new('userlangs',$id,\%loadlangs);
 3496:         return %loadlangs;
 3497:     }
 3498: }
 3499: 
 3500: sub flush_langs_cache {
 3501:     my ($uname,$udom)=@_;
 3502:     if (!$udom)  { $udom =$env{'user.domain'}; }
 3503:     if (!$uname) { $uname=$env{'user.name'};   }
 3504:     return if ($udom eq 'public' && $uname eq 'public');
 3505:     my $id=$uname.':'.$udom;
 3506:     &Apache::lonnet::devalidate_cache_new('userlangs',$id);
 3507: }
 3508: 
 3509: # ------------------------------------------------------------------ Screenname
 3510: 
 3511: =pod
 3512: 
 3513: =item * &screenname($uname,$udom)
 3514: 
 3515: Gets a users screenname and returns it as a string
 3516: 
 3517: =cut
 3518: 
 3519: sub screenname {
 3520:     my ($uname,$udom)=@_;
 3521:     if ($uname eq $env{'user.name'} &&
 3522: 	$udom eq $env{'user.domain'}) {return $env{'environment.screenname'};}
 3523:     my %names=&Apache::lonnet::get('environment',['screenname'],$udom,$uname);
 3524:     return $names{'screenname'};
 3525: }
 3526: 
 3527: 
 3528: # ------------------------------------------------------------- Confirm Wrapper
 3529: =pod
 3530: 
 3531: =item * &confirmwrapper($message)
 3532: 
 3533: Wrap messages about completion of operation in box
 3534: 
 3535: =cut
 3536: 
 3537: sub confirmwrapper {
 3538:     my ($message)=@_;
 3539:     if ($message) {
 3540:         return "\n".'<div class="LC_confirm_box">'."\n"
 3541:                .$message."\n"
 3542:                .'</div>'."\n";
 3543:     } else {
 3544:         return $message;
 3545:     }
 3546: }
 3547: 
 3548: # ------------------------------------------------------------- Message Wrapper
 3549: 
 3550: sub messagewrapper {
 3551:     my ($link,$username,$domain,$subject,$text)=@_;
 3552:     return 
 3553:         '<a href="/adm/email?compose=individual&amp;'.
 3554:         'recname='.$username.'&amp;recdom='.$domain.
 3555: 	'&amp;subject='.&escape($subject).'&amp;text='.&escape($text).'" '.
 3556:         'title="'.&mt('Send message').'">'.$link.'</a>';
 3557: }
 3558: 
 3559: # --------------------------------------------------------------- Notes Wrapper
 3560: 
 3561: sub noteswrapper {
 3562:     my ($link,$un,$do)=@_;
 3563:     return 
 3564: "<a href='/adm/email?recordftf=retrieve&amp;recname=$un&amp;recdom=$do'>$link</a>";
 3565: }
 3566: 
 3567: # ------------------------------------------------------------- Aboutme Wrapper
 3568: 
 3569: sub aboutmewrapper {
 3570:     my ($link,$username,$domain,$target,$class)=@_;
 3571:     if (!defined($username)  && !defined($domain)) {
 3572:         return;
 3573:     }
 3574:     return '<a href="/adm/'.$domain.'/'.$username.'/aboutme"'.
 3575: 	($target?' target="'.$target.'"':'').($class?' class="'.$class.'"':'').' title="'.&mt("View this user's personal information page").'">'.$link.'</a>';
 3576: }
 3577: 
 3578: # ------------------------------------------------------------ Syllabus Wrapper
 3579: 
 3580: sub syllabuswrapper {
 3581:     my ($linktext,$coursedir,$domain)=@_;
 3582:     return qq{<a href="/public/$domain/$coursedir/syllabus">$linktext</a>};
 3583: }
 3584: 
 3585: # -----------------------------------------------------------------------------
 3586: 
 3587: sub track_student_link {
 3588:     my ($linktext,$sname,$sdom,$target,$start,$only_body) = @_;
 3589:     my $link ="/adm/trackstudent?";
 3590:     my $title = 'View recent activity';
 3591:     if (defined($sname) && $sname !~ /^\s*$/ &&
 3592:         defined($sdom)  && $sdom  !~ /^\s*$/) {
 3593:         $link .= "selected_student=$sname:$sdom";
 3594:         $title .= ' of this student';
 3595:     } 
 3596:     if (defined($target) && $target !~ /^\s*$/) {
 3597:         $target = qq{target="$target"};
 3598:     } else {
 3599:         $target = '';
 3600:     }
 3601:     if ($start) { $link.='&amp;start='.$start; }
 3602:     if ($only_body) { $link .= '&amp;only_body=1'; }
 3603:     $title = &mt($title);
 3604:     $linktext = &mt($linktext);
 3605:     return qq{<a href="$link" title="$title" $target>$linktext</a>}.
 3606: 	&help_open_topic('View_recent_activity');
 3607: }
 3608: 
 3609: sub slot_reservations_link {
 3610:     my ($linktext,$sname,$sdom,$target) = @_;
 3611:     my $link ="/adm/slotrequest?command=showresv&amp;origin=aboutme";
 3612:     my $title = 'View slot reservation history';
 3613:     if (defined($sname) && $sname !~ /^\s*$/ &&
 3614:         defined($sdom)  && $sdom  !~ /^\s*$/) {
 3615:         $link .= "&amp;uname=$sname&amp;udom=$sdom";
 3616:         $title .= ' of this student';
 3617:     }
 3618:     if (defined($target) && $target !~ /^\s*$/) {
 3619:         $target = qq{target="$target"};
 3620:     } else {
 3621:         $target = '';
 3622:     }
 3623:     $title = &mt($title);
 3624:     $linktext = &mt($linktext);
 3625:     return qq{<a href="$link" title="$title" $target>$linktext</a>};
 3626: # FIXME uncomment when help item created: &help_open_topic('Slot_Reservation_History');
 3627: 
 3628: }
 3629: 
 3630: # ===================================================== Display a student photo
 3631: 
 3632: 
 3633: sub student_image_tag {
 3634:     my ($domain,$user)=@_;
 3635:     my $imgsrc=&Apache::lonnet::studentphoto($domain,$user,'jpg');
 3636:     if (($imgsrc) && ($imgsrc ne '/adm/lonKaputt/lonlogo_broken.gif')) {
 3637: 	return '<img src="'.$imgsrc.'" align="right" />';
 3638:     } else {
 3639: 	return '';
 3640:     }
 3641: }
 3642: 
 3643: =pod
 3644: 
 3645: =back
 3646: 
 3647: =head1 Access .tab File Data
 3648: 
 3649: =over 4
 3650: 
 3651: =item * &languageids() 
 3652: 
 3653: returns list of all language ids
 3654: 
 3655: =cut
 3656: 
 3657: sub languageids {
 3658:     return sort(keys(%language));
 3659: }
 3660: 
 3661: =pod
 3662: 
 3663: =item * &languagedescription() 
 3664: 
 3665: returns description of a specified language id
 3666: 
 3667: =cut
 3668: 
 3669: sub languagedescription {
 3670:     my $code=shift;
 3671:     return  ($supported_language{$code}?'* ':'').
 3672:             $language{$code}.
 3673: 	    ($supported_language{$code}?' ('.&mt('interface available').')':'');
 3674: }
 3675: 
 3676: =pod
 3677: 
 3678: =item * &plainlanguagedescription
 3679: 
 3680: Returns both the plain language description (e.g. 'Creoles and Pidgins, English-based (Other)')
 3681: and the language character encoding (e.g. ISO) separated by a ' - ' string.
 3682: 
 3683: =cut
 3684: 
 3685: sub plainlanguagedescription {
 3686:     my $code=shift;
 3687:     return $language{$code};
 3688: }
 3689: 
 3690: =pod
 3691: 
 3692: =item * &supportedlanguagecode
 3693: 
 3694: Returns the supported language code (e.g. sptutf maps to pt) given a language
 3695: code.
 3696: 
 3697: =cut
 3698: 
 3699: sub supportedlanguagecode {
 3700:     my $code=shift;
 3701:     return $supported_language{$code};
 3702: }
 3703: 
 3704: =pod
 3705: 
 3706: =item * &latexlanguage()
 3707: 
 3708: Given a language key code returns the correspondnig language to use
 3709: to select the correct hyphenation on LaTeX printouts.  This is undef if there
 3710: is no supported hyphenation for the language code.
 3711: 
 3712: =cut
 3713: 
 3714: sub latexlanguage {
 3715:     my $code = shift;
 3716:     return $latex_language{$code};
 3717: }
 3718: 
 3719: =pod
 3720: 
 3721: =item * &latexhyphenation()
 3722: 
 3723: Same as above but what's supplied is the language as it might be stored
 3724: in the metadata.
 3725: 
 3726: =cut
 3727: 
 3728: sub latexhyphenation {
 3729:     my $key = shift;
 3730:     return $latex_language_bykey{$key};
 3731: }
 3732: 
 3733: =pod
 3734: 
 3735: =item * &copyrightids() 
 3736: 
 3737: returns list of all copyrights
 3738: 
 3739: =cut
 3740: 
 3741: sub copyrightids {
 3742:     return sort(keys(%cprtag));
 3743: }
 3744: 
 3745: =pod
 3746: 
 3747: =item * &copyrightdescription() 
 3748: 
 3749: returns description of a specified copyright id
 3750: 
 3751: =cut
 3752: 
 3753: sub copyrightdescription {
 3754:     return &mt($cprtag{shift(@_)});
 3755: }
 3756: 
 3757: =pod
 3758: 
 3759: =item * &source_copyrightids() 
 3760: 
 3761: returns list of all source copyrights
 3762: 
 3763: =cut
 3764: 
 3765: sub source_copyrightids {
 3766:     return sort(keys(%scprtag));
 3767: }
 3768: 
 3769: =pod
 3770: 
 3771: =item * &source_copyrightdescription() 
 3772: 
 3773: returns description of a specified source copyright id
 3774: 
 3775: =cut
 3776: 
 3777: sub source_copyrightdescription {
 3778:     return &mt($scprtag{shift(@_)});
 3779: }
 3780: 
 3781: =pod
 3782: 
 3783: =item * &filecategories() 
 3784: 
 3785: returns list of all file categories
 3786: 
 3787: =cut
 3788: 
 3789: sub filecategories {
 3790:     return sort(keys(%category_extensions));
 3791: }
 3792: 
 3793: =pod
 3794: 
 3795: =item * &filecategorytypes() 
 3796: 
 3797: returns list of file types belonging to a given file
 3798: category
 3799: 
 3800: =cut
 3801: 
 3802: sub filecategorytypes {
 3803:     my ($cat) = @_;
 3804:     return @{$category_extensions{lc($cat)}};
 3805: }
 3806: 
 3807: =pod
 3808: 
 3809: =item * &fileembstyle() 
 3810: 
 3811: returns embedding style for a specified file type
 3812: 
 3813: =cut
 3814: 
 3815: sub fileembstyle {
 3816:     return $fe{lc(shift(@_))};
 3817: }
 3818: 
 3819: sub filemimetype {
 3820:     return $fm{lc(shift(@_))};
 3821: }
 3822: 
 3823: 
 3824: sub filecategoryselect {
 3825:     my ($name,$value)=@_;
 3826:     return &select_form($value,$name,
 3827:                         {'' => &mt('Any category'), map { $_,$_ } sort(keys(%category_extensions))});
 3828: }
 3829: 
 3830: =pod
 3831: 
 3832: =item * &filedescription() 
 3833: 
 3834: returns description for a specified file type
 3835: 
 3836: =cut
 3837: 
 3838: sub filedescription {
 3839:     my $file_description = $fd{lc(shift())};
 3840:     $file_description =~ s:([\[\]]):~$1:g;
 3841:     return &mt($file_description);
 3842: }
 3843: 
 3844: =pod
 3845: 
 3846: =item * &filedescriptionex() 
 3847: 
 3848: returns description for a specified file type with
 3849: extra formatting
 3850: 
 3851: =cut
 3852: 
 3853: sub filedescriptionex {
 3854:     my $ex=shift;
 3855:     my $file_description = $fd{lc($ex)};
 3856:     $file_description =~ s:([\[\]]):~$1:g;
 3857:     return '.'.$ex.' '.&mt($file_description);
 3858: }
 3859: 
 3860: # End of .tab access
 3861: =pod
 3862: 
 3863: =back
 3864: 
 3865: =cut
 3866: 
 3867: # ------------------------------------------------------------------ File Types
 3868: sub fileextensions {
 3869:     return sort(keys(%fe));
 3870: }
 3871: 
 3872: # ----------------------------------------------------------- Display Languages
 3873: # returns a hash with all desired display languages
 3874: #
 3875: 
 3876: sub display_languages {
 3877:     my %languages=();
 3878:     foreach my $lang (&Apache::lonlocal::preferred_languages()) {
 3879: 	$languages{$lang}=1;
 3880:     }
 3881:     &get_unprocessed_cgi($ENV{'QUERY_STRING'},['displaylanguage']);
 3882:     if ($env{'form.displaylanguage'}) {
 3883: 	foreach my $lang (split(/\s*(\,|\;|\:)\s*/,$env{'form.displaylanguage'})) {
 3884: 	    $languages{$lang}=1;
 3885:         }
 3886:     }
 3887:     return %languages;
 3888: }
 3889: 
 3890: sub languages {
 3891:     my ($possible_langs) = @_;
 3892:     my @preferred_langs = &Apache::lonlocal::preferred_languages();
 3893:     if (!ref($possible_langs)) {
 3894: 	if( wantarray ) {
 3895: 	    return @preferred_langs;
 3896: 	} else {
 3897: 	    return $preferred_langs[0];
 3898: 	}
 3899:     }
 3900:     my %possibilities = map { $_ => 1 } (@$possible_langs);
 3901:     my @preferred_possibilities;
 3902:     foreach my $preferred_lang (@preferred_langs) {
 3903: 	if (exists($possibilities{$preferred_lang})) {
 3904: 	    push(@preferred_possibilities, $preferred_lang);
 3905: 	}
 3906:     }
 3907:     if( wantarray ) {
 3908: 	return @preferred_possibilities;
 3909:     }
 3910:     return $preferred_possibilities[0];
 3911: }
 3912: 
 3913: sub user_lang {
 3914:     my ($touname,$toudom,$fromcid) = @_;
 3915:     my @userlangs;
 3916:     if (($fromcid ne '') && ($env{'course.'.$fromcid.'.languages'} ne '')) {
 3917:         @userlangs=(@userlangs,split(/\s*(\,|\;|\:)\s*/,
 3918:                     $env{'course.'.$fromcid.'.languages'}));
 3919:     } else {
 3920:         my %langhash = &getlangs($touname,$toudom);
 3921:         if ($langhash{'languages'} ne '') {
 3922:             @userlangs = split(/\s*(\,|\;|\:)\s*/,$langhash{'languages'});
 3923:         } else {
 3924:             my %domdefs = &Apache::lonnet::get_domain_defaults($toudom);
 3925:             if ($domdefs{'lang_def'} ne '') {
 3926:                 @userlangs = ($domdefs{'lang_def'});
 3927:             }
 3928:         }
 3929:     }
 3930:     my @languages=&Apache::lonlocal::get_genlanguages(@userlangs);
 3931:     my $user_lh = Apache::localize->get_handle(@languages);
 3932:     return $user_lh;
 3933: }
 3934: 
 3935: 
 3936: ###############################################################
 3937: ##               Student Answer Attempts                     ##
 3938: ###############################################################
 3939: 
 3940: =pod
 3941: 
 3942: =head1 Alternate Problem Views
 3943: 
 3944: =over 4
 3945: 
 3946: =item * &get_previous_attempt($symb, $username, $domain, $course,
 3947:     $getattempt, $regexp, $gradesub, $usec, $identifier)
 3948: 
 3949: Return string with previous attempt on problem. Arguments:
 3950: 
 3951: =over 4
 3952: 
 3953: =item * $symb: Problem, including path
 3954: 
 3955: =item * $username: username of the desired student
 3956: 
 3957: =item * $domain: domain of the desired student
 3958: 
 3959: =item * $course: Course ID
 3960: 
 3961: =item * $getattempt: Leave blank for all attempts, otherwise put
 3962:     something
 3963: 
 3964: =item * $regexp: if string matches this regexp, the string will be
 3965:     sent to $gradesub
 3966: 
 3967: =item * $gradesub: routine that processes the string if it matches $regexp
 3968: 
 3969: =item * $usec: section of the desired student
 3970: 
 3971: =item * $identifier: counter for student (multiple students one problem) or
 3972:     problem (one student; whole sequence).
 3973: 
 3974: =back
 3975: 
 3976: The output string is a table containing all desired attempts, if any.
 3977: 
 3978: =cut
 3979: 
 3980: sub get_previous_attempt {
 3981:   my ($symb,$username,$domain,$course,$getattempt,$regexp,$gradesub,$usec,$identifier)=@_;
 3982:   my $prevattempts='';
 3983:   no strict 'refs';
 3984:   if ($symb) {
 3985:     my (%returnhash)=
 3986:       &Apache::lonnet::restore($symb,$course,$domain,$username);
 3987:     if ($returnhash{'version'}) {
 3988:       my %lasthash=();
 3989:       my $version;
 3990:       for ($version=1;$version<=$returnhash{'version'};$version++) {
 3991:         foreach my $key (reverse(sort(split(/\:/,$returnhash{$version.':keys'})))) {
 3992:             if ($key =~ /\.rawrndseed$/) {
 3993:                 my ($id) = ($key =~ /^(.+)\.rawrndseed$/);
 3994:                 $lasthash{$id.'.rndseed'} = $returnhash{$version.':'.$key};
 3995:             } else {
 3996:                 $lasthash{$key}=$returnhash{$version.':'.$key};
 3997:             }
 3998:         }
 3999:       }
 4000:       $prevattempts=&start_data_table().&start_data_table_header_row();
 4001:       $prevattempts.='<th>'.&mt('History').'</th>';
 4002:       my (%typeparts,%lasthidden,%regraded,%hidestatus);
 4003:       my $showsurv=&Apache::lonnet::allowed('vas',$env{'request.course.id'});
 4004:       foreach my $key (sort(keys(%lasthash))) {
 4005: 	my ($ign,@parts) = split(/\./,$key);
 4006: 	if ($#parts > 0) {
 4007: 	  my $data=$parts[-1];
 4008:           next if ($data eq 'foilorder');
 4009: 	  pop(@parts);
 4010:           $prevattempts.='<th>'.&mt('Part ').join('.',@parts).'<br />'.$data.'&nbsp;</th>';
 4011:           if ($data eq 'type') {
 4012:               unless ($showsurv) {
 4013:                   my $id = join(',',@parts);
 4014:                   $typeparts{$ign.'.'.$id} = $lasthash{$key};
 4015:                   if (($lasthash{$key} eq 'anonsurvey') || ($lasthash{$key} eq 'anonsurveycred')) {
 4016:                       $lasthidden{$ign.'.'.$id} = 1;
 4017:                   }
 4018:               }
 4019:               if ($identifier ne '') {
 4020:                   my $id = join(',',@parts);
 4021:                   if (&Apache::lonnet::EXT("resource.$id.problemstatus",$symb,
 4022:                                                $domain,$username,$usec,undef,$course) =~ /^no/) {
 4023:                       $hidestatus{$ign.'.'.$id} = 1;
 4024:                   }
 4025:               }
 4026:           } elsif ($data eq 'regrader') {
 4027:               if (($identifier ne '') && (@parts)) {
 4028:                   my $id = join(',',@parts);
 4029:                   $regraded{$ign.'.'.$id} = 1;
 4030:               }
 4031:           } 
 4032: 	} else {
 4033: 	  if ($#parts == 0) {
 4034: 	    $prevattempts.='<th>'.$parts[0].'</th>';
 4035: 	  } else {
 4036: 	    $prevattempts.='<th>'.$ign.'</th>';
 4037: 	  }
 4038: 	}
 4039:       }
 4040:       $prevattempts.=&end_data_table_header_row();
 4041:       if ($getattempt eq '') {
 4042:         my (%solved,%resets,%probstatus);
 4043:         if (($identifier ne '') && (keys(%regraded) > 0)) {
 4044:             for ($version=1;$version<=$returnhash{'version'};$version++) {
 4045:                 foreach my $id (keys(%regraded)) {
 4046:                     if (($returnhash{$version.':'.$id.'.regrader'}) &&
 4047:                         ($returnhash{$version.':'.$id.'.tries'} eq '') &&
 4048:                         ($returnhash{$version.':'.$id.'.award'} eq '')) {
 4049:                         push(@{$resets{$id}},$version);
 4050:                     }
 4051:                 }
 4052:             }
 4053:         }
 4054: 	for ($version=1;$version<=$returnhash{'version'};$version++) {
 4055:             my (@hidden,@unsolved);
 4056:             if (%typeparts) {
 4057:                 foreach my $id (keys(%typeparts)) {
 4058:                     if (($returnhash{$version.':'.$id.'.type'} eq 'anonsurvey') ||
 4059:                         ($returnhash{$version.':'.$id.'.type'} eq 'anonsurveycred')) {
 4060:                         push(@hidden,$id);
 4061:                     } elsif ($identifier ne '') {
 4062:                         unless (($returnhash{$version.':'.$id.'.type'} eq 'survey') ||
 4063:                                 ($returnhash{$version.':'.$id.'.type'} eq 'surveycred') ||
 4064:                                 ($hidestatus{$id})) {
 4065:                             next if ((ref($resets{$id}) eq 'ARRAY') && grep(/^\Q$version\E$/,@{$resets{$id}}));
 4066:                             if ($returnhash{$version.':'.$id.'.solved'} eq 'correct_by_student') {
 4067:                                 push(@{$solved{$id}},$version);
 4068:                             } elsif (($returnhash{$version.':'.$id.'.solved'} ne '') &&
 4069:                                      (ref($solved{$id}) eq 'ARRAY')) {
 4070:                                 my $skip;
 4071:                                 if (ref($resets{$id}) eq 'ARRAY') {
 4072:                                     foreach my $reset (@{$resets{$id}}) {
 4073:                                         if ($reset > $solved{$id}[-1]) {
 4074:                                             $skip=1;
 4075:                                             last;
 4076:                                         }
 4077:                                     }
 4078:                                 }
 4079:                                 unless ($skip) {
 4080:                                     my ($ign,$partslist) = split(/\./,$id,2);
 4081:                                     push(@unsolved,$partslist);
 4082:                                 }
 4083:                             }
 4084:                         }
 4085:                     }
 4086:                 }
 4087:             }
 4088:             $prevattempts.=&start_data_table_row().
 4089:                            '<td>'.&mt('Transaction [_1]',$version);
 4090:             if (@unsolved) {
 4091:                 $prevattempts .= '<span class="LC_nobreak"><label>'.
 4092:                                  '<input type="checkbox" name="HIDE'.$identifier.'" value="'.$version.':'.join('_',@unsolved).'" />'.
 4093:                                  &mt('Hide').'</label></span>';
 4094:             }
 4095:             $prevattempts .= '</td>';
 4096:             if (@hidden) {
 4097:                 foreach my $key (sort(keys(%lasthash))) {
 4098:                     next if ($key =~ /\.foilorder$/);
 4099:                     my $hide;
 4100:                     foreach my $id (@hidden) {
 4101:                         if ($key =~ /^\Q$id\E/) {
 4102:                             $hide = 1;
 4103:                             last;
 4104:                         }
 4105:                     }
 4106:                     if ($hide) {
 4107:                         my ($id,$data) = ($key =~ /^(.+)\.([^.]+)$/);
 4108:                         if (($data eq 'award') || ($data eq 'awarddetail')) {
 4109:                             my $value = &format_previous_attempt_value($key,
 4110:                                              $returnhash{$version.':'.$key});
 4111:                             $prevattempts.='<td>'.$value.'&nbsp;</td>';
 4112:                         } else {
 4113:                             $prevattempts.='<td>&nbsp;</td>';
 4114:                         }
 4115:                     } else {
 4116:                         if ($key =~ /\./) {
 4117:                             my $value = $returnhash{$version.':'.$key};
 4118:                             if ($key =~ /\.rndseed$/) {
 4119:                                 my ($id) = ($key =~ /^(.+)\.rndseed$/);
 4120:                                 if (exists($returnhash{$version.':'.$id.'.rawrndseed'})) {
 4121:                                     $value = $returnhash{$version.':'.$id.'.rawrndseed'};
 4122:                                 }
 4123:                             }
 4124:                             $prevattempts.='<td>'.&format_previous_attempt_value($key,$value).
 4125:                                            '&nbsp;</td>';
 4126:                         } else {
 4127:                             $prevattempts.='<td>&nbsp;</td>';
 4128:                         }
 4129:                     }
 4130:                 }
 4131:             } else {
 4132: 	        foreach my $key (sort(keys(%lasthash))) {
 4133:                     next if ($key =~ /\.foilorder$/);
 4134:                     my $value = $returnhash{$version.':'.$key};
 4135:                     if ($key =~ /\.rndseed$/) {
 4136:                         my ($id) = ($key =~ /^(.+)\.rndseed$/);
 4137:                         if (exists($returnhash{$version.':'.$id.'.rawrndseed'})) {
 4138:                             $value = $returnhash{$version.':'.$id.'.rawrndseed'};
 4139:                         }
 4140:                     }
 4141:                     $prevattempts.='<td>'.&format_previous_attempt_value($key,$value).
 4142:                                    '&nbsp;</td>';
 4143: 	        }
 4144:             }
 4145: 	    $prevattempts.=&end_data_table_row();
 4146: 	 }
 4147:       }
 4148:       my @currhidden = keys(%lasthidden);
 4149:       $prevattempts.=&start_data_table_row().'<td>'.&mt('Current').'</td>';
 4150:       foreach my $key (sort(keys(%lasthash))) {
 4151:           next if ($key =~ /\.foilorder$/);
 4152:           if (%typeparts) {
 4153:               my $hidden;
 4154:               foreach my $id (@currhidden) {
 4155:                   if ($key =~ /^\Q$id\E/) {
 4156:                       $hidden = 1;
 4157:                       last;
 4158:                   }
 4159:               }
 4160:               if ($hidden) {
 4161:                   my ($id,$data) = ($key =~ /^(.+)\.([^.]+)$/);
 4162:                   if (($data eq 'award') || ($data eq 'awarddetail')) {
 4163:                       my $value = &format_previous_attempt_value($key,$lasthash{$key});
 4164:                       if ($key =~/$regexp$/ && (defined &$gradesub)) {
 4165:                           $value = &$gradesub($value);
 4166:                       }
 4167:                       $prevattempts.='<td>'.$value.'&nbsp;</td>';
 4168:                   } else {
 4169:                       $prevattempts.='<td>&nbsp;</td>';
 4170:                   }
 4171:               } else {
 4172:                   my $value = &format_previous_attempt_value($key,$lasthash{$key});
 4173:                   if ($key =~/$regexp$/ && (defined &$gradesub)) {
 4174:                       $value = &$gradesub($value);
 4175:                   }
 4176:                   $prevattempts.='<td>'.$value.'&nbsp;</td>';
 4177:               }
 4178:           } else {
 4179: 	      my $value = &format_previous_attempt_value($key,$lasthash{$key});
 4180: 	      if ($key =~/$regexp$/ && (defined &$gradesub)) {
 4181:                   $value = &$gradesub($value);
 4182:               }
 4183: 	      $prevattempts.='<td>'.$value.'&nbsp;</td>';
 4184:           }
 4185:       }
 4186:       $prevattempts.= &end_data_table_row().&end_data_table();
 4187:     } else {
 4188:       $prevattempts=
 4189: 	  &start_data_table().&start_data_table_row().
 4190: 	  '<td>'.&mt('Nothing submitted - no attempts.').'</td>'.
 4191: 	  &end_data_table_row().&end_data_table();
 4192:     }
 4193:   } else {
 4194:     $prevattempts=
 4195: 	  &start_data_table().&start_data_table_row().
 4196: 	  '<td>'.&mt('No data.').'</td>'.
 4197: 	  &end_data_table_row().&end_data_table();
 4198:   }
 4199: }
 4200: 
 4201: sub format_previous_attempt_value {
 4202:     my ($key,$value) = @_;
 4203:     if (($key =~ /timestamp/) || ($key=~/duedate/)) {
 4204: 	$value = &Apache::lonlocal::locallocaltime($value);
 4205:     } elsif (ref($value) eq 'ARRAY') {
 4206: 	$value = '('.join(', ', @{ $value }).')';
 4207:     } elsif ($key =~ /answerstring$/) {
 4208:         my %answers = &Apache::lonnet::str2hash($value);
 4209:         my @anskeys = sort(keys(%answers));
 4210:         if (@anskeys == 1) {
 4211:             my $answer = $answers{$anskeys[0]};
 4212:             if ($answer =~ m{\0}) {
 4213:                 $answer =~ s{\0}{,}g;
 4214:             }
 4215:             my $tag_internal_answer_name = 'INTERNAL';
 4216:             if ($anskeys[0] eq $tag_internal_answer_name) {
 4217:                 $value = $answer; 
 4218:             } else {
 4219:                 $value = $anskeys[0].'='.$answer;
 4220:             }
 4221:         } else {
 4222:             foreach my $ans (@anskeys) {
 4223:                 my $answer = $answers{$ans};
 4224:                 if ($answer =~ m{\0}) {
 4225:                     $answer =~ s{\0}{,}g;
 4226:                 }
 4227:                 $value .=  $ans.'='.$answer.'<br />';;
 4228:             } 
 4229:         }
 4230:     } else {
 4231: 	$value = &unescape($value);
 4232:     }
 4233:     return $value;
 4234: }
 4235: 
 4236: 
 4237: sub relative_to_absolute {
 4238:     my ($url,$output)=@_;
 4239:     my $parser=HTML::TokeParser->new(\$output);
 4240:     my $token;
 4241:     my $thisdir=$url;
 4242:     my @rlinks=();
 4243:     while ($token=$parser->get_token) {
 4244: 	if ($token->[0] eq 'S') {
 4245: 	    if ($token->[1] eq 'a') {
 4246: 		if ($token->[2]->{'href'}) {
 4247: 		    $rlinks[$#rlinks+1]=$token->[2]->{'href'};
 4248: 		}
 4249: 	    } elsif ($token->[1] eq 'img' || $token->[1] eq 'embed' ) {
 4250: 		$rlinks[$#rlinks+1]=$token->[2]->{'src'};
 4251: 	    } elsif ($token->[1] eq 'base') {
 4252: 		$thisdir=$token->[2]->{'href'};
 4253: 	    }
 4254: 	}
 4255:     }
 4256:     $thisdir=~s-/[^/]*$--;
 4257:     foreach my $link (@rlinks) {
 4258: 	unless (($link=~/^https?\:\/\//i) ||
 4259: 		($link=~/^\//) ||
 4260: 		($link=~/^javascript:/i) ||
 4261: 		($link=~/^mailto:/i) ||
 4262: 		($link=~/^\#/)) {
 4263: 	    my $newlocation=&Apache::lonnet::hreflocation($thisdir,$link);
 4264: 	    $output=~s/(\"|\'|\=\s*)\Q$link\E(\"|\'|\s|\>)/$1$newlocation$2/;
 4265: 	}
 4266:     }
 4267: # -------------------------------------------------- Deal with Applet codebases
 4268:     $output=~s/(\<applet[^\>]+)(codebase\=[^\S\>]+)*([^\>]*)\>/$1.($2?$2:' codebase="'.$thisdir.'"').$3.'>'/gei;
 4269:     return $output;
 4270: }
 4271: 
 4272: =pod
 4273: 
 4274: =item * &get_student_view()
 4275: 
 4276: show a snapshot of what student was looking at
 4277: 
 4278: =cut
 4279: 
 4280: sub get_student_view {
 4281:   my ($symb,$username,$domain,$courseid,$target,$moreenv) = @_;
 4282:   my ($map,$id,$feedurl) = &Apache::lonnet::decode_symb($symb);
 4283:   my (%form);
 4284:   my @elements=('symb','courseid','domain','username');
 4285:   foreach my $element (@elements) {
 4286:       $form{'grade_'.$element}=eval '$'.$element #'
 4287:   }
 4288:   if (defined($moreenv)) {
 4289:       %form=(%form,%{$moreenv});
 4290:   }
 4291:   if (defined($target)) { $form{'grade_target'} = $target; }
 4292:   $feedurl=&Apache::lonnet::clutter($feedurl);
 4293:   my ($userview,$response)=&Apache::lonnet::ssi_body($feedurl,%form);
 4294:   $userview=~s/\<body[^\>]*\>//gi;
 4295:   $userview=~s/\<\/body\>//gi;
 4296:   $userview=~s/\<html\>//gi;
 4297:   $userview=~s/\<\/html\>//gi;
 4298:   $userview=~s/\<head\>//gi;
 4299:   $userview=~s/\<\/head\>//gi;
 4300:   $userview=~s/action\s*\=/would_be_action\=/gi;
 4301:   $userview=&relative_to_absolute($feedurl,$userview);
 4302:   if (wantarray) {
 4303:      return ($userview,$response);
 4304:   } else {
 4305:      return $userview;
 4306:   }
 4307: }
 4308: 
 4309: sub get_student_view_with_retries {
 4310:   my ($symb,$retries,$username,$domain,$courseid,$target,$moreenv) = @_;
 4311: 
 4312:     my $ok = 0;                 # True if we got a good response.
 4313:     my $content;
 4314:     my $response;
 4315: 
 4316:     # Try to get the student_view done. within the retries count:
 4317:     
 4318:     do {
 4319:          ($content, $response) = &get_student_view($symb,$username,$domain,$courseid,$target,$moreenv);
 4320:          $ok      = $response->is_success;
 4321:          if (!$ok) {
 4322:             &Apache::lonnet::logthis("Failed get_student_view_with_retries on $symb: ".$response->is_success.', '.$response->code.', '.$response->message);
 4323:          }
 4324:          $retries--;
 4325:     } while (!$ok && ($retries > 0));
 4326:     
 4327:     if (!$ok) {
 4328:        $content = '';          # On error return an empty content.
 4329:     }
 4330:     if (wantarray) {
 4331:        return ($content, $response);
 4332:     } else {
 4333:        return $content;
 4334:     }
 4335: }
 4336: 
 4337: =pod
 4338: 
 4339: =item * &get_student_answers() 
 4340: 
 4341: show a snapshot of how student was answering problem
 4342: 
 4343: =cut
 4344: 
 4345: sub get_student_answers {
 4346:   my ($symb,$username,$domain,$courseid,%form) = @_;
 4347:   my ($map,$id,$feedurl) = &Apache::lonnet::decode_symb($symb);
 4348:   my (%moreenv);
 4349:   my @elements=('symb','courseid','domain','username');
 4350:   foreach my $element (@elements) {
 4351:     $moreenv{'grade_'.$element}=eval '$'.$element #'
 4352:   }
 4353:   $moreenv{'grade_target'}='answer';
 4354:   %moreenv=(%form,%moreenv);
 4355:   $feedurl = &Apache::lonnet::clutter($feedurl);
 4356:   my $userview=&Apache::lonnet::ssi($feedurl,%moreenv);
 4357:   return $userview;
 4358: }
 4359: 
 4360: =pod
 4361: 
 4362: =item * &submlink()
 4363: 
 4364: Inputs: $text $uname $udom $symb $target
 4365: 
 4366: Returns: A link to grades.pm such as to see the SUBM view of a student
 4367: 
 4368: =cut
 4369: 
 4370: ###############################################
 4371: sub submlink {
 4372:     my ($text,$uname,$udom,$symb,$target)=@_;
 4373:     if (!($uname && $udom)) {
 4374: 	(my $cursymb, my $courseid,$udom,$uname)=
 4375: 	    &Apache::lonnet::whichuser($symb);
 4376: 	if (!$symb) { $symb=$cursymb; }
 4377:     }
 4378:     if (!$symb) { $symb=&Apache::lonnet::symbread(); }
 4379:     $symb=&escape($symb);
 4380:     if ($target) { $target=" target=\"$target\""; }
 4381:     return
 4382:         '<a href="/adm/grades?command=submission'.
 4383:         '&amp;symb='.$symb.
 4384:         '&amp;student='.$uname.
 4385:         '&amp;userdom='.$udom.'"'.
 4386:         $target.'>'.$text.'</a>';
 4387: }
 4388: ##############################################
 4389: 
 4390: =pod
 4391: 
 4392: =item * &pgrdlink()
 4393: 
 4394: Inputs: $text $uname $udom $symb $target
 4395: 
 4396: Returns: A link to grades.pm such as to see the PGRD view of a student
 4397: 
 4398: =cut
 4399: 
 4400: ###############################################
 4401: sub pgrdlink {
 4402:     my $link=&submlink(@_);
 4403:     $link=~s/(&command=submission)/$1&showgrading=yes/;
 4404:     return $link;
 4405: }
 4406: ##############################################
 4407: 
 4408: =pod
 4409: 
 4410: =item * &pprmlink()
 4411: 
 4412: Inputs: $text $uname $udom $symb $target
 4413: 
 4414: Returns: A link to parmset.pm such as to see the PPRM view of a
 4415: student and a specific resource
 4416: 
 4417: =cut
 4418: 
 4419: ###############################################
 4420: sub pprmlink {
 4421:     my ($text,$uname,$udom,$symb,$target)=@_;
 4422:     if (!($uname && $udom)) {
 4423: 	(my $cursymb, my $courseid,$udom,$uname)=
 4424: 	    &Apache::lonnet::whichuser($symb);
 4425: 	if (!$symb) { $symb=$cursymb; }
 4426:     }
 4427:     if (!$symb) { $symb=&Apache::lonnet::symbread(); }
 4428:     $symb=&escape($symb);
 4429:     if ($target) { $target="target=\"$target\""; }
 4430:     return '<a href="/adm/parmset?command=set&amp;'.
 4431: 	'symb='.$symb.'&amp;uname='.$uname.
 4432: 	'&amp;udom='.$udom.'" '.$target.'>'.$text.'</a>';
 4433: }
 4434: ##############################################
 4435: 
 4436: =pod
 4437: 
 4438: =back
 4439: 
 4440: =cut
 4441: 
 4442: ###############################################
 4443: 
 4444: 
 4445: sub timehash {
 4446:     my ($thistime) = @_;
 4447:     my $timezone = &Apache::lonlocal::gettimezone();
 4448:     my $dt = DateTime->from_epoch(epoch => $thistime)
 4449:                      ->set_time_zone($timezone);
 4450:     my $wday = $dt->day_of_week();
 4451:     if ($wday == 7) { $wday = 0; }
 4452:     return ( 'second' => $dt->second(),
 4453:              'minute' => $dt->minute(),
 4454:              'hour'   => $dt->hour(),
 4455:              'day'     => $dt->day_of_month(),
 4456:              'month'   => $dt->month(),
 4457:              'year'    => $dt->year(),
 4458:              'weekday' => $wday,
 4459:              'dayyear' => $dt->day_of_year(),
 4460:              'dlsav'   => $dt->is_dst() );
 4461: }
 4462: 
 4463: sub utc_string {
 4464:     my ($date)=@_;
 4465:     return strftime("%Y%m%dT%H%M%SZ",gmtime($date));
 4466: }
 4467: 
 4468: sub maketime {
 4469:     my %th=@_;
 4470:     my ($epoch_time,$timezone,$dt);
 4471:     $timezone = &Apache::lonlocal::gettimezone();
 4472:     eval {
 4473:         $dt = DateTime->new( year   => $th{'year'},
 4474:                              month  => $th{'month'},
 4475:                              day    => $th{'day'},
 4476:                              hour   => $th{'hour'},
 4477:                              minute => $th{'minute'},
 4478:                              second => $th{'second'},
 4479:                              time_zone => $timezone,
 4480:                          );
 4481:     };
 4482:     if (!$@) {
 4483:         $epoch_time = $dt->epoch;
 4484:         if ($epoch_time) {
 4485:             return $epoch_time;
 4486:         }
 4487:     }
 4488:     return POSIX::mktime(
 4489:         ($th{'seconds'},$th{'minutes'},$th{'hours'},
 4490:          $th{'day'},$th{'month'}-1,$th{'year'}-1900,0,0,-1));
 4491: }
 4492: 
 4493: #########################################
 4494: 
 4495: sub findallcourses {
 4496:     my ($roles,$uname,$udom) = @_;
 4497:     my %roles;
 4498:     if (ref($roles)) { %roles = map { $_ => 1 } @{$roles}; }
 4499:     my %courses;
 4500:     my $now=time;
 4501:     if (!defined($uname)) {
 4502:         $uname = $env{'user.name'};
 4503:     }
 4504:     if (!defined($udom)) {
 4505:         $udom = $env{'user.domain'};
 4506:     }
 4507:     if (($uname ne $env{'user.name'}) || ($udom ne $env{'user.domain'})) {
 4508:         my %roleshash = &Apache::lonnet::dump('roles',$udom,$uname);
 4509:         if (!%roles) {
 4510:             %roles = (
 4511:                        cc => 1,
 4512:                        co => 1,
 4513:                        in => 1,
 4514:                        ep => 1,
 4515:                        ta => 1,
 4516:                        cr => 1,
 4517:                        st => 1,
 4518:              );
 4519:         }
 4520:         foreach my $entry (keys(%roleshash)) {
 4521:             my ($trole,$tend,$tstart) = split(/_/,$roleshash{$entry});
 4522:             if ($trole =~ /^cr/) { 
 4523:                 next if (!exists($roles{$trole}) && !exists($roles{'cr'}));
 4524:             } else {
 4525:                 next if (!exists($roles{$trole}));
 4526:             }
 4527:             if ($tend) {
 4528:                 next if ($tend < $now);
 4529:             }
 4530:             if ($tstart) {
 4531:                 next if ($tstart > $now);
 4532:             }
 4533:             my ($cdom,$cnum,$sec,$cnumpart,$secpart,$role);
 4534:             (undef,$cdom,$cnumpart,$secpart) = split(/\//,$entry);
 4535:             my $value = $trole.'/'.$cdom.'/';
 4536:             if ($secpart eq '') {
 4537:                 ($cnum,$role) = split(/_/,$cnumpart); 
 4538:                 $sec = 'none';
 4539:                 $value .= $cnum.'/';
 4540:             } else {
 4541:                 $cnum = $cnumpart;
 4542:                 ($sec,$role) = split(/_/,$secpart);
 4543:                 $value .= $cnum.'/'.$sec;
 4544:             }
 4545:             if (ref($courses{$cdom.'_'.$cnum}{$sec}) eq 'ARRAY') {
 4546:                 unless (grep(/^\Q$value\E$/,@{$courses{$cdom.'_'.$cnum}{$sec}})) {
 4547:                     push(@{$courses{$cdom.'_'.$cnum}{$sec}},$value);
 4548:                 }
 4549:             } else {
 4550:                 @{$courses{$cdom.'_'.$cnum}{$sec}} = ($value);
 4551:             }
 4552:         }
 4553:     } else {
 4554:         foreach my $key (keys(%env)) {
 4555: 	    if ( $key=~m{^user\.role\.(\w+)\./($match_domain)/($match_courseid)/?(\w*)$} ||
 4556:                  $key=~m{^user\.role\.(cr/$match_domain/$match_username/\w+)\./($match_domain)/($match_courseid)/?(\w*)$}) {
 4557: 	        my ($role,$cdom,$cnum,$sec) = ($1,$2,$3,$4);
 4558: 	        next if ($role eq 'ca' || $role eq 'aa');
 4559: 	        next if (%roles && !exists($roles{$role}));
 4560: 	        my ($starttime,$endtime)=split(/\./,$env{$key});
 4561:                 my $active=1;
 4562:                 if ($starttime) {
 4563: 		    if ($now<$starttime) { $active=0; }
 4564:                 }
 4565:                 if ($endtime) {
 4566:                     if ($now>$endtime) { $active=0; }
 4567:                 }
 4568:                 if ($active) {
 4569:                     my $value = $role.'/'.$cdom.'/'.$cnum.'/';
 4570:                     if ($sec eq '') {
 4571:                         $sec = 'none';
 4572:                     } else {
 4573:                         $value .= $sec;
 4574:                     }
 4575:                     if (ref($courses{$cdom.'_'.$cnum}{$sec}) eq 'ARRAY') {
 4576:                         unless (grep(/^\Q$value\E$/,@{$courses{$cdom.'_'.$cnum}{$sec}})) {
 4577:                             push(@{$courses{$cdom.'_'.$cnum}{$sec}},$value);
 4578:                         }
 4579:                     } else {
 4580:                         @{$courses{$cdom.'_'.$cnum}{$sec}} = ($value);
 4581:                     }
 4582:                 }
 4583:             }
 4584:         }
 4585:     }
 4586:     return %courses;
 4587: }
 4588: 
 4589: ###############################################
 4590: 
 4591: sub blockcheck {
 4592:     my ($setters,$activity,$uname,$udom,$url,$is_course) = @_;
 4593: 
 4594:     if (defined($udom) && defined($uname)) {
 4595:         # If uname and udom are for a course, check for blocks in the course.
 4596:         if (($is_course) || (&Apache::lonnet::is_course($udom,$uname))) {
 4597:             my ($startblock,$endblock,$triggerblock) =
 4598:                 &get_blocks($setters,$activity,$udom,$uname,$url);
 4599:             return ($startblock,$endblock,$triggerblock);
 4600:         }
 4601:     } else {
 4602:         $udom = $env{'user.domain'};
 4603:         $uname = $env{'user.name'};
 4604:     }
 4605: 
 4606:     my $startblock = 0;
 4607:     my $endblock = 0;
 4608:     my $triggerblock = '';
 4609:     my %live_courses = &findallcourses(undef,$uname,$udom);
 4610: 
 4611:     # If uname is for a user, and activity is course-specific, i.e.,
 4612:     # boards, chat or groups, check for blocking in current course only.
 4613: 
 4614:     if (($activity eq 'boards' || $activity eq 'chat' ||
 4615:          $activity eq 'groups' || $activity eq 'printout') &&
 4616:         ($env{'request.course.id'})) {
 4617:         foreach my $key (keys(%live_courses)) {
 4618:             if ($key ne $env{'request.course.id'}) {
 4619:                 delete($live_courses{$key});
 4620:             }
 4621:         }
 4622:     }
 4623: 
 4624:     my $otheruser = 0;
 4625:     my %own_courses;
 4626:     if ((($uname ne $env{'user.name'})) || ($udom ne $env{'user.domain'})) {
 4627:         # Resource belongs to user other than current user.
 4628:         $otheruser = 1;
 4629:         # Gather courses for current user
 4630:         %own_courses = 
 4631:             &findallcourses(undef,$env{'user.name'},$env{'user.domain'});
 4632:     }
 4633: 
 4634:     # Gather active course roles - course coordinator, instructor, 
 4635:     # exam proctor, ta, student, or custom role.
 4636: 
 4637:     foreach my $course (keys(%live_courses)) {
 4638:         my ($cdom,$cnum);
 4639:         if ((defined($env{'course.'.$course.'.domain'})) && (defined($env{'course.'.$course.'.num'}))) {
 4640:             $cdom = $env{'course.'.$course.'.domain'};
 4641:             $cnum = $env{'course.'.$course.'.num'};
 4642:         } else {
 4643:             ($cdom,$cnum) = split(/_/,$course); 
 4644:         }
 4645:         my $no_ownblock = 0;
 4646:         my $no_userblock = 0;
 4647:         if ($otheruser && $activity ne 'com') {
 4648:             # Check if current user has 'evb' priv for this
 4649:             if (defined($own_courses{$course})) {
 4650:                 foreach my $sec (keys(%{$own_courses{$course}})) {
 4651:                     my $checkrole = 'cm./'.$cdom.'/'.$cnum;
 4652:                     if ($sec ne 'none') {
 4653:                         $checkrole .= '/'.$sec;
 4654:                     }
 4655:                     if (&Apache::lonnet::allowed('evb',undef,undef,$checkrole)) {
 4656:                         $no_ownblock = 1;
 4657:                         last;
 4658:                     }
 4659:                 }
 4660:             }
 4661:             # if they have 'evb' priv and are currently not playing student
 4662:             next if (($no_ownblock) &&
 4663:                  ($env{'request.role'} !~ m{^st\./$cdom/$cnum}));
 4664:         }
 4665:         foreach my $sec (keys(%{$live_courses{$course}})) {
 4666:             my $checkrole = 'cm./'.$cdom.'/'.$cnum;
 4667:             if ($sec ne 'none') {
 4668:                 $checkrole .= '/'.$sec;
 4669:             }
 4670:             if ($otheruser) {
 4671:                 # Resource belongs to user other than current user.
 4672:                 # Assemble privs for that user, and check for 'evb' priv.
 4673:                 my (%allroles,%userroles);
 4674:                 if (ref($live_courses{$course}{$sec}) eq 'ARRAY') {
 4675:                     foreach my $entry (@{$live_courses{$course}{$sec}}) { 
 4676:                         my ($trole,$tdom,$tnum,$tsec);
 4677:                         if ($entry =~ /^cr/) {
 4678:                             ($trole,$tdom,$tnum,$tsec) = 
 4679:                                 ($entry =~ m|^(cr/$match_domain/$match_username/\w+)\./($match_domain)/($match_username)/?(\w*)$|);
 4680:                         } else {
 4681:                            ($trole,$tdom,$tnum,$tsec) = split(/\//,$entry);
 4682:                         }
 4683:                         my ($spec,$area,$trest);
 4684:                         $area = '/'.$tdom.'/'.$tnum;
 4685:                         $trest = $tnum;
 4686:                         if ($tsec ne '') {
 4687:                             $area .= '/'.$tsec;
 4688:                             $trest .= '/'.$tsec;
 4689:                         }
 4690:                         $spec = $trole.'.'.$area;
 4691:                         if ($trole =~ /^cr/) {
 4692:                             &Apache::lonnet::custom_roleprivs(\%allroles,$trole,
 4693:                                                               $tdom,$spec,$trest,$area);
 4694:                         } else {
 4695:                             &Apache::lonnet::standard_roleprivs(\%allroles,$trole,
 4696:                                                                 $tdom,$spec,$trest,$area);
 4697:                         }
 4698:                     }
 4699:                     my ($author,$adv,$rar) = &Apache::lonnet::set_userprivs(\%userroles,\%allroles);
 4700:                     if ($userroles{'user.priv.'.$checkrole} =~ /evb\&([^\:]*)/) {
 4701:                         if ($1) {
 4702:                             $no_userblock = 1;
 4703:                             last;
 4704:                         }
 4705:                     }
 4706:                 }
 4707:             } else {
 4708:                 # Resource belongs to current user
 4709:                 # Check for 'evb' priv via lonnet::allowed().
 4710:                 if (&Apache::lonnet::allowed('evb',undef,undef,$checkrole)) {
 4711:                     $no_ownblock = 1;
 4712:                     last;
 4713:                 }
 4714:             }
 4715:         }
 4716:         # if they have the evb priv and are currently not playing student
 4717:         next if (($no_ownblock) &&
 4718:                  ($env{'request.role'} !~ m{^st\./\Q$cdom\E/\Q$cnum\E}));
 4719:         next if ($no_userblock);
 4720: 
 4721:         # Retrieve blocking times and identity of locker for course
 4722:         # of specified user, unless user has 'evb' privilege.
 4723:         
 4724:         my ($start,$end,$trigger) = 
 4725:             &get_blocks($setters,$activity,$cdom,$cnum,$url);
 4726:         if (($start != 0) && 
 4727:             (($startblock == 0) || ($startblock > $start))) {
 4728:             $startblock = $start;
 4729:             if ($trigger ne '') {
 4730:                 $triggerblock = $trigger;
 4731:             }
 4732:         }
 4733:         if (($end != 0)  &&
 4734:             (($endblock == 0) || ($endblock < $end))) {
 4735:             $endblock = $end;
 4736:             if ($trigger ne '') {
 4737:                 $triggerblock = $trigger;
 4738:             }
 4739:         }
 4740:     }
 4741:     return ($startblock,$endblock,$triggerblock);
 4742: }
 4743: 
 4744: sub get_blocks {
 4745:     my ($setters,$activity,$cdom,$cnum,$url) = @_;
 4746:     my $startblock = 0;
 4747:     my $endblock = 0;
 4748:     my $triggerblock = '';
 4749:     my $course = $cdom.'_'.$cnum;
 4750:     $setters->{$course} = {};
 4751:     $setters->{$course}{'staff'} = [];
 4752:     $setters->{$course}{'times'} = [];
 4753:     $setters->{$course}{'triggers'} = [];
 4754:     my (@blockers,%triggered);
 4755:     my $now = time;
 4756:     my %commblocks = &Apache::lonnet::get_comm_blocks($cdom,$cnum);
 4757:     if ($activity eq 'docs') {
 4758:         @blockers = &Apache::lonnet::has_comm_blocking('bre',undef,$url,\%commblocks);
 4759:         foreach my $block (@blockers) {
 4760:             if ($block =~ /^firstaccess____(.+)$/) {
 4761:                 my $item = $1;
 4762:                 my $type = 'map';
 4763:                 my $timersymb = $item;
 4764:                 if ($item eq 'course') {
 4765:                     $type = 'course';
 4766:                 } elsif ($item =~ /___\d+___/) {
 4767:                     $type = 'resource';
 4768:                 } else {
 4769:                     $timersymb = &Apache::lonnet::symbread($item);
 4770:                 }
 4771:                 my $start = $env{'course.'.$cdom.'_'.$cnum.'.firstaccess.'.$timersymb};
 4772:                 my $end = $start + $env{'course.'.$cdom.'_'.$cnum.'.timerinterval.'.$timersymb};
 4773:                 $triggered{$block} = {
 4774:                                        start => $start,
 4775:                                        end   => $end,
 4776:                                        type  => $type,
 4777:                                      };
 4778:             }
 4779:         }
 4780:     } else {
 4781:         foreach my $block (keys(%commblocks)) {
 4782:             if ($block =~ m/^(\d+)____(\d+)$/) { 
 4783:                 my ($start,$end) = ($1,$2);
 4784:                 if ($start <= time && $end >= time) {
 4785:                     if (ref($commblocks{$block}) eq 'HASH') {
 4786:                         if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
 4787:                             if ($commblocks{$block}{'blocks'}{$activity} eq 'on') {
 4788:                                 unless(grep(/^\Q$block\E$/,@blockers)) {
 4789:                                     push(@blockers,$block);
 4790:                                 }
 4791:                             }
 4792:                         }
 4793:                     }
 4794:                 }
 4795:             } elsif ($block =~ /^firstaccess____(.+)$/) {
 4796:                 my $item = $1;
 4797:                 my $timersymb = $item; 
 4798:                 my $type = 'map';
 4799:                 if ($item eq 'course') {
 4800:                     $type = 'course';
 4801:                 } elsif ($item =~ /___\d+___/) {
 4802:                     $type = 'resource';
 4803:                 } else {
 4804:                     $timersymb = &Apache::lonnet::symbread($item);
 4805:                 }
 4806:                 my $start = $env{'course.'.$cdom.'_'.$cnum.'.firstaccess.'.$timersymb};
 4807:                 my $end = $start + $env{'course.'.$cdom.'_'.$cnum.'.timerinterval.'.$timersymb}; 
 4808:                 if ($start && $end) {
 4809:                     if (($start <= time) && ($end >= time)) {
 4810:                         unless (grep(/^\Q$block\E$/,@blockers)) {
 4811:                             push(@blockers,$block);
 4812:                             $triggered{$block} = {
 4813:                                                    start => $start,
 4814:                                                    end   => $end,
 4815:                                                    type  => $type,
 4816:                                                  };
 4817:                         }
 4818:                     }
 4819:                 }
 4820:             }
 4821:         }
 4822:     }
 4823:     foreach my $blocker (@blockers) {
 4824:         my ($staff_name,$staff_dom,$title,$blocks) =
 4825:             &parse_block_record($commblocks{$blocker});
 4826:         push(@{$$setters{$course}{'staff'}},[$staff_name,$staff_dom]);
 4827:         my ($start,$end,$triggertype);
 4828:         if ($blocker =~ m/^(\d+)____(\d+)$/) {
 4829:             ($start,$end) = ($1,$2);
 4830:         } elsif (ref($triggered{$blocker}) eq 'HASH') {
 4831:             $start = $triggered{$blocker}{'start'};
 4832:             $end = $triggered{$blocker}{'end'};
 4833:             $triggertype = $triggered{$blocker}{'type'};
 4834:         }
 4835:         if ($start) {
 4836:             push(@{$$setters{$course}{'times'}}, [$start,$end]);
 4837:             if ($triggertype) {
 4838:                 push(@{$$setters{$course}{'triggers'}},$triggertype);
 4839:             } else {
 4840:                 push(@{$$setters{$course}{'triggers'}},0);
 4841:             }
 4842:             if ( ($startblock == 0) || ($startblock > $start) ) {
 4843:                 $startblock = $start;
 4844:                 if ($triggertype) {
 4845:                     $triggerblock = $blocker;
 4846:                 }
 4847:             }
 4848:             if ( ($endblock == 0) || ($endblock < $end) ) {
 4849:                $endblock = $end;
 4850:                if ($triggertype) {
 4851:                    $triggerblock = $blocker;
 4852:                }
 4853:             }
 4854:         }
 4855:     }
 4856:     return ($startblock,$endblock,$triggerblock);
 4857: }
 4858: 
 4859: sub parse_block_record {
 4860:     my ($record) = @_;
 4861:     my ($setuname,$setudom,$title,$blocks);
 4862:     if (ref($record) eq 'HASH') {
 4863:         ($setuname,$setudom) = split(/:/,$record->{'setter'});
 4864:         $title = &unescape($record->{'event'});
 4865:         $blocks = $record->{'blocks'};
 4866:     } else {
 4867:         my @data = split(/:/,$record,3);
 4868:         if (scalar(@data) eq 2) {
 4869:             $title = $data[1];
 4870:             ($setuname,$setudom) = split(/@/,$data[0]);
 4871:         } else {
 4872:             ($setuname,$setudom,$title) = @data;
 4873:         }
 4874:         $blocks = { 'com' => 'on' };
 4875:     }
 4876:     return ($setuname,$setudom,$title,$blocks);
 4877: }
 4878: 
 4879: sub blocking_status {
 4880:     my ($activity,$uname,$udom,$url,$is_course) = @_;
 4881:     my %setters;
 4882: 
 4883: # check for active blocking
 4884:     my ($startblock,$endblock,$triggerblock) = 
 4885:         &blockcheck(\%setters,$activity,$uname,$udom,$url,$is_course);
 4886:     my $blocked = 0;
 4887:     if ($startblock && $endblock) {
 4888:         $blocked = 1;
 4889:     }
 4890: 
 4891: # caller just wants to know whether a block is active
 4892:     if (!wantarray) { return $blocked; }
 4893: 
 4894: # build a link to a popup window containing the details
 4895:     my $querystring  = "?activity=$activity";
 4896: # $uname and $udom decide whose portfolio the user is trying to look at
 4897:     if (($activity eq 'port') || ($activity eq 'passwd')) {
 4898:         $querystring .= "&amp;udom=$udom"      if ($udom =~ /^$match_domain$/);
 4899:         $querystring .= "&amp;uname=$uname"    if ($uname =~ /^$match_username$/);
 4900:     } elsif ($activity eq 'docs') {
 4901:         $querystring .= '&amp;url='.&HTML::Entities::encode($url,'&"');
 4902:     }
 4903: 
 4904:     my $output .= <<'END_MYBLOCK';
 4905: function openWindow(url, wdwName, w, h, toolbar,scrollbar) {
 4906:     var options = "width=" + w + ",height=" + h + ",";
 4907:     options += "resizable=yes,scrollbars="+scrollbar+",status=no,";
 4908:     options += "menubar=no,toolbar="+toolbar+",location=no,directories=no";
 4909:     var newWin = window.open(url, wdwName, options);
 4910:     newWin.focus();
 4911: }
 4912: END_MYBLOCK
 4913: 
 4914:     $output = Apache::lonhtmlcommon::scripttag($output);
 4915:   
 4916:     my $popupUrl = "/adm/blockingstatus/$querystring";
 4917:     my $text = &mt('Communication Blocked');
 4918:     my $class = 'LC_comblock';
 4919:     if ($activity eq 'docs') {
 4920:         $text = &mt('Content Access Blocked');
 4921:         $class = '';
 4922:     } elsif ($activity eq 'printout') {
 4923:         $text = &mt('Printing Blocked');
 4924:     } elsif ($activity eq 'passwd') {
 4925:         $text = &mt('Password Changing Blocked');
 4926:     }
 4927:     $output .= <<"END_BLOCK";
 4928: <div class='$class'>
 4929:   <a onclick='openWindow("$popupUrl","Blocking Table",600,300,"no","no");return false;' href='/adm/blockingstatus/$querystring'
 4930:   title='$text'>
 4931:   <img class='LC_noBorder LC_middle' title='$text' src='/res/adm/pages/comblock.png' alt='$text'/></a>
 4932:   <a onclick='openWindow("$popupUrl","Blocking Table",600,300,"no","no");return false;' href='/adm/blockingstatus/$querystring' 
 4933:   title='$text'>$text</a>
 4934: </div>
 4935: 
 4936: END_BLOCK
 4937: 
 4938:     return ($blocked, $output);
 4939: }
 4940: 
 4941: ###############################################
 4942: 
 4943: sub check_ip_acc {
 4944:     my ($acc,$clientip)=@_;
 4945:     &Apache::lonxml::debug("acc is $acc");
 4946:     if (!defined($acc) || $acc =~ /^\s*$/ || $acc =~/^\s*no\s*$/i) {
 4947:         return 1;
 4948:     }
 4949:     my ($ip,$allowed);
 4950:     if (($ENV{'REMOTE_ADDR'} eq '127.0.0.1') ||
 4951:         ($ENV{'REMOTE_ADDR'} eq &Apache::lonnet::get_host_ip($Apache::lonnet::perlvar{'lonHostID'}))) {
 4952:         $ip = $env{'request.host'} || $ENV{'REMOTE_ADDR'} || $clientip;
 4953:     } else {
 4954:         $ip = $ENV{'REMOTE_ADDR'} || $env{'request.host'} || $clientip;
 4955:     }
 4956: 
 4957:     my $name;
 4958:     my %access = (
 4959:                      allowfrom => 1,
 4960:                      denyfrom  => 0,
 4961:                  );
 4962:     my @allows;
 4963:     my @denies;
 4964:     foreach my $item (split(',',$acc)) {
 4965:         $item =~ s/^\s*//;
 4966:         $item =~ s/\s*$//;
 4967:         if ($item =~ /^\!(.+)$/) {
 4968:             push(@denies,$1);
 4969:         } else {
 4970:             push(@allows,$item);
 4971:         }
 4972:     }
 4973:     my $numdenies = scalar(@denies);
 4974:     my $numallows = scalar(@allows);
 4975:     my $count = 0;
 4976:     foreach my $pattern (@denies,@allows) {
 4977:         $count ++;
 4978:         my $acctype = 'allowfrom';
 4979:         if ($count <= $numdenies) {
 4980:             $acctype = 'denyfrom';
 4981:         }
 4982:         if ($pattern =~ /\*$/) {
 4983:             #35.8.*
 4984:             $pattern=~s/\*//;
 4985:             if ($ip =~ /^\Q$pattern\E/) { $allowed=$access{$acctype}; }
 4986:         } elsif ($pattern =~ /(\d+\.\d+\.\d+)\.\[(\d+)-(\d+)\]$/) {
 4987:             #35.8.3.[34-56]
 4988:             my $low=$2;
 4989:             my $high=$3;
 4990:             $pattern=$1;
 4991:             if ($ip =~ /^\Q$pattern\E/) {
 4992:                 my $last=(split(/\./,$ip))[3];
 4993:                 if ($last <=$high && $last >=$low) { $allowed=$access{$acctype}; }
 4994:             }
 4995:         } elsif ($pattern =~ /^\*/) {
 4996:             #*.msu.edu
 4997:             $pattern=~s/\*//;
 4998:             if (!defined($name)) {
 4999:                 use Socket;
 5000:                 my $netaddr=inet_aton($ip);
 5001:                 ($name)=gethostbyaddr($netaddr,AF_INET);
 5002:             }
 5003:             if ($name =~ /\Q$pattern\E$/i) { $allowed=$access{$acctype}; }
 5004:         } elsif ($pattern =~ /\d+\.\d+\.\d+\.\d+/) {
 5005:             #127.0.0.1
 5006:             if ($ip =~ /^\Q$pattern\E/) { $allowed=$access{$acctype}; }
 5007:         } else {
 5008:             #some.name.com
 5009:             if (!defined($name)) {
 5010:                 use Socket;
 5011:                 my $netaddr=inet_aton($ip);
 5012:                 ($name)=gethostbyaddr($netaddr,AF_INET);
 5013:             }
 5014:             if ($name =~ /\Q$pattern\E$/i) { $allowed=$access{$acctype}; }
 5015:         }
 5016:         if ($allowed =~ /^(0|1)$/) { last; }
 5017:     }
 5018:     if ($allowed eq '') {
 5019:         if ($numdenies && !$numallows) {
 5020:             $allowed = 1;
 5021:         } else {
 5022:             $allowed = 0;
 5023:         }
 5024:     }
 5025:     return $allowed;
 5026: }
 5027: 
 5028: ###############################################
 5029: 
 5030: =pod
 5031: 
 5032: =head1 Domain Template Functions
 5033: 
 5034: =over 4
 5035: 
 5036: =item * &determinedomain()
 5037: 
 5038: Inputs: $domain (usually will be undef)
 5039: 
 5040: Returns: Determines which domain should be used for designs
 5041: 
 5042: =cut
 5043: 
 5044: ###############################################
 5045: sub determinedomain {
 5046:     my $domain=shift;
 5047:     if (! $domain) {
 5048:         # Determine domain if we have not been given one
 5049:         $domain = &Apache::lonnet::default_login_domain();
 5050:         if ($env{'user.domain'}) { $domain=$env{'user.domain'}; }
 5051:         if ($env{'request.role.domain'}) { 
 5052:             $domain=$env{'request.role.domain'}; 
 5053:         }
 5054:     }
 5055:     return $domain;
 5056: }
 5057: ###############################################
 5058: 
 5059: sub devalidate_domconfig_cache {
 5060:     my ($udom)=@_;
 5061:     &Apache::lonnet::devalidate_cache_new('domainconfig',$udom);
 5062: }
 5063: 
 5064: # ---------------------- Get domain configuration for a domain
 5065: sub get_domainconf {
 5066:     my ($udom) = @_;
 5067:     my $cachetime=1800;
 5068:     my ($result,$cached)=&Apache::lonnet::is_cached_new('domainconfig',$udom);
 5069:     if (defined($cached)) { return %{$result}; }
 5070: 
 5071:     my %domconfig = &Apache::lonnet::get_dom('configuration',
 5072: 					     ['login','rolecolors','autoenroll'],$udom);
 5073:     my (%designhash,%legacy);
 5074:     if (keys(%domconfig) > 0) {
 5075:         if (ref($domconfig{'login'}) eq 'HASH') {
 5076:             if (keys(%{$domconfig{'login'}})) {
 5077:                 foreach my $key (keys(%{$domconfig{'login'}})) {
 5078:                     if (ref($domconfig{'login'}{$key}) eq 'HASH') {
 5079:                         if (($key eq 'loginvia') || ($key eq 'headtag')) {
 5080:                             if (ref($domconfig{'login'}{$key}) eq 'HASH') {
 5081:                                 foreach my $hostname (keys(%{$domconfig{'login'}{$key}})) {
 5082:                                     if (ref($domconfig{'login'}{$key}{$hostname}) eq 'HASH') {
 5083:                                         if ($key eq 'loginvia') {
 5084:                                             if ($domconfig{'login'}{'loginvia'}{$hostname}{'server'}) {
 5085:                                                 my $server = $domconfig{'login'}{'loginvia'}{$hostname}{'server'};
 5086:                                                 $designhash{$udom.'.login.loginvia'} = $server;
 5087:                                                 if ($domconfig{'login'}{'loginvia'}{$hostname}{'serverpath'} eq 'custom') {
 5088:                                                     $designhash{$udom.'.login.loginvia_'.$hostname} = $server.':'.$domconfig{'login'}{'loginvia'}{$hostname}{'custompath'};
 5089:                                                 } else {
 5090:                                                     $designhash{$udom.'.login.loginvia_'.$hostname} = $server.':'.$domconfig{'login'}{'loginvia'}{$hostname}{'serverpath'};
 5091:                                                 }
 5092:                                             }
 5093:                                         } elsif ($key eq 'headtag') {
 5094:                                             if ($domconfig{'login'}{'headtag'}{$hostname}{'url'}) {
 5095:                                                 $designhash{$udom.'.login.headtag_'.$hostname} = $domconfig{'login'}{'headtag'}{$hostname}{'url'};
 5096:                                             }
 5097:                                         }
 5098:                                         if ($domconfig{'login'}{$key}{$hostname}{'exempt'}) {
 5099:                                             $designhash{$udom.'.login.'.$key.'_exempt_'.$hostname} = $domconfig{'login'}{$key}{$hostname}{'exempt'};
 5100:                                         }
 5101:                                     }
 5102:                                 }
 5103:                             }
 5104:                         } else {
 5105:                             foreach my $img (keys(%{$domconfig{'login'}{$key}})) {
 5106:                                 $designhash{$udom.'.login.'.$key.'_'.$img} = 
 5107:                                     $domconfig{'login'}{$key}{$img};
 5108:                             }
 5109:                         }
 5110:                     } else {
 5111:                         $designhash{$udom.'.login.'.$key}=$domconfig{'login'}{$key};
 5112:                     }
 5113:                 }
 5114:             } else {
 5115:                 $legacy{'login'} = 1;
 5116:             }
 5117:         } else {
 5118:             $legacy{'login'} = 1;
 5119:         }
 5120:         if (ref($domconfig{'rolecolors'}) eq 'HASH') {
 5121:             if (keys(%{$domconfig{'rolecolors'}})) {
 5122:                 foreach my $role (keys(%{$domconfig{'rolecolors'}})) {
 5123:                     if (ref($domconfig{'rolecolors'}{$role}) eq 'HASH') {
 5124:                         foreach my $item (keys(%{$domconfig{'rolecolors'}{$role}})) {
 5125:                             $designhash{$udom.'.'.$role.'.'.$item}=$domconfig{'rolecolors'}{$role}{$item};
 5126:                         }
 5127:                     }
 5128:                 }
 5129:             } else {
 5130:                 $legacy{'rolecolors'} = 1;
 5131:             }
 5132:         } else {
 5133:             $legacy{'rolecolors'} = 1;
 5134:         }
 5135:         if (ref($domconfig{'autoenroll'}) eq 'HASH') {
 5136:             if ($domconfig{'autoenroll'}{'co-owners'}) {
 5137:                 $designhash{$udom.'.autoassign.co-owners'}=$domconfig{'autoenroll'}{'co-owners'};
 5138:             }
 5139:         }
 5140:         if (keys(%legacy) > 0) {
 5141:             my %legacyhash = &get_legacy_domconf($udom);
 5142:             foreach my $item (keys(%legacyhash)) {
 5143:                 if ($item =~ /^\Q$udom\E\.login/) {
 5144:                     if ($legacy{'login'}) { 
 5145:                         $designhash{$item} = $legacyhash{$item};
 5146:                     }
 5147:                 } else {
 5148:                     if ($legacy{'rolecolors'}) {
 5149:                         $designhash{$item} = $legacyhash{$item};
 5150:                     }
 5151:                 }
 5152:             }
 5153:         }
 5154:     } else {
 5155:         %designhash = &get_legacy_domconf($udom); 
 5156:     }
 5157:     &Apache::lonnet::do_cache_new('domainconfig',$udom,\%designhash,
 5158: 				  $cachetime);
 5159:     return %designhash;
 5160: }
 5161: 
 5162: sub get_legacy_domconf {
 5163:     my ($udom) = @_;
 5164:     my %legacyhash;
 5165:     my $designdir=$Apache::lonnet::perlvar{'lonTabDir'}.'/lonDomColors';
 5166:     my $designfile =  $designdir.'/'.$udom.'.tab';
 5167:     if (-e $designfile) {
 5168:         if ( open (my $fh,"<$designfile") ) {
 5169:             while (my $line = <$fh>) {
 5170:                 next if ($line =~ /^\#/);
 5171:                 chomp($line);
 5172:                 my ($key,$val)=(split(/\=/,$line));
 5173:                 if ($val) { $legacyhash{$udom.'.'.$key}=$val; }
 5174:             }
 5175:             close($fh);
 5176:         }
 5177:     }
 5178:     if (-e $Apache::lonnet::perlvar{'lonDocRoot'}.'/adm/lonDomLogos/'.$udom.'.gif') {
 5179:         $legacyhash{$udom.'.login.domlogo'} = "/adm/lonDomLogos/$udom.gif";
 5180:     }
 5181:     return %legacyhash;
 5182: }
 5183: 
 5184: =pod
 5185: 
 5186: =item * &domainlogo()
 5187: 
 5188: Inputs: $domain (usually will be undef)
 5189: 
 5190: Returns: A link to a domain logo, if the domain logo exists.
 5191: If the domain logo does not exist, a description of the domain.
 5192: 
 5193: =cut
 5194: 
 5195: ###############################################
 5196: sub domainlogo {
 5197:     my $domain = &determinedomain(shift);
 5198:     my %designhash = &get_domainconf($domain);    
 5199:     # See if there is a logo
 5200:     if ($designhash{$domain.'.login.domlogo'} ne '') {
 5201:         my $imgsrc = $designhash{$domain.'.login.domlogo'};
 5202:         if ($imgsrc =~ m{^/(adm|res)/}) {
 5203: 	    if ($imgsrc =~ m{^/res/}) {
 5204: 		my $local_name = &Apache::lonnet::filelocation('',$imgsrc);
 5205: 		&Apache::lonnet::repcopy($local_name);
 5206: 	    }
 5207: 	   $imgsrc = &lonhttpdurl($imgsrc);
 5208:         } 
 5209:         return '<img src="'.$imgsrc.'" alt="'.$domain.'" />';
 5210:     } elsif (defined(&Apache::lonnet::domain($domain,'description'))) {
 5211:         return &Apache::lonnet::domain($domain,'description');
 5212:     } else {
 5213:         return '';
 5214:     }
 5215: }
 5216: ##############################################
 5217: 
 5218: =pod
 5219: 
 5220: =item * &designparm()
 5221: 
 5222: Inputs: $which parameter; $domain (usually will be undef)
 5223: 
 5224: Returns: value of designparamter $which
 5225: 
 5226: =cut
 5227: 
 5228: 
 5229: ##############################################
 5230: sub designparm {
 5231:     my ($which,$domain)=@_;
 5232:     if (exists($env{'environment.color.'.$which})) {
 5233:         return $env{'environment.color.'.$which};
 5234:     }
 5235:     $domain=&determinedomain($domain);
 5236:     my %domdesign;
 5237:     unless ($domain eq 'public') {
 5238:         %domdesign = &get_domainconf($domain);
 5239:     }
 5240:     my $output;
 5241:     if ($domdesign{$domain.'.'.$which} ne '') {
 5242:         $output = $domdesign{$domain.'.'.$which};
 5243:     } else {
 5244:         $output = $defaultdesign{$which};
 5245:     }
 5246:     if (($which =~ /^(student|coordinator|author|admin)\.img$/) ||
 5247:         ($which =~ /login\.(img|logo|domlogo|login)/)) {
 5248:         if ($output =~ m{^/(adm|res)/}) {
 5249:             if ($output =~ m{^/res/}) {
 5250:                 my $local_name = &Apache::lonnet::filelocation('',$output);
 5251:                 &Apache::lonnet::repcopy($local_name);
 5252:             }
 5253:             $output = &lonhttpdurl($output);
 5254:         }
 5255:     }
 5256:     return $output;
 5257: }
 5258: 
 5259: ##############################################
 5260: =pod
 5261: 
 5262: =item * &authorspace()
 5263: 
 5264: Inputs: $url (usually will be undef).
 5265: 
 5266: Returns: Path to Authoring Space containing the resource or 
 5267:          directory being viewed (or for which action is being taken). 
 5268:          If $url is provided, and begins /priv/<domain>/<uname>
 5269:          the path will be that portion of the $context argument.
 5270:          Otherwise the path will be for the author space of the current
 5271:          user when the current role is author, or for that of the 
 5272:          co-author/assistant co-author space when the current role 
 5273:          is co-author or assistant co-author.
 5274: 
 5275: =cut
 5276: 
 5277: sub authorspace {
 5278:     my ($url) = @_;
 5279:     if ($url ne '') {
 5280:         if ($url =~ m{^(/priv/$match_domain/$match_username/)}) {
 5281:            return $1;
 5282:         }
 5283:     }
 5284:     my $caname = '';
 5285:     my $cadom = '';
 5286:     if ($env{'request.role'} =~ /^(?:ca|aa)/) {
 5287:         ($cadom,$caname) =
 5288:             ($env{'request.role'}=~/($match_domain)\/($match_username)$/);
 5289:     } elsif ($env{'request.role'} =~ m{^au\./($match_domain)/}) {
 5290:         $caname = $env{'user.name'};
 5291:         $cadom = $env{'user.domain'};
 5292:     }
 5293:     if (($caname ne '') && ($cadom ne '')) {
 5294:         return "/priv/$cadom/$caname/";
 5295:     }
 5296:     return;
 5297: }
 5298: 
 5299: ##############################################
 5300: =pod
 5301: 
 5302: =item * &head_subbox()
 5303: 
 5304: Inputs: $content (contains HTML code with page functions, etc.)
 5305: 
 5306: Returns: HTML div with $content
 5307:          To be included in page header
 5308: 
 5309: =cut
 5310: 
 5311: sub head_subbox {
 5312:     my ($content)=@_;
 5313:     my $output =
 5314:         '<div class="LC_head_subbox">'
 5315:        .$content
 5316:        .'</div>'
 5317: }
 5318: 
 5319: ##############################################
 5320: =pod
 5321: 
 5322: =item * &CSTR_pageheader()
 5323: 
 5324: Input: (optional) filename from which breadcrumb trail is built.
 5325:        In most cases no input as needed, as $env{'request.filename'}
 5326:        is appropriate for use in building the breadcrumb trail.
 5327: 
 5328: Returns: HTML div with CSTR path and recent box
 5329:          To be included on Authoring Space pages
 5330: 
 5331: =cut
 5332: 
 5333: sub CSTR_pageheader {
 5334:     my ($trailfile) = @_;
 5335:     if ($trailfile eq '') {
 5336:         $trailfile = $env{'request.filename'};
 5337:     }
 5338: 
 5339: # this is for resources; directories have customtitle, and crumbs
 5340: # and select recent are created in lonpubdir.pm
 5341: 
 5342:     my $londocroot = $Apache::lonnet::perlvar{'lonDocRoot'};
 5343:     my ($udom,$uname,$thisdisfn)=
 5344:         ($trailfile =~ m{^\Q$londocroot\E/priv/([^/]+)/([^/]+)(?:|/(.*))$});
 5345:     my $formaction = "/priv/$udom/$uname/$thisdisfn";
 5346:     $formaction =~ s{/+}{/}g;
 5347: 
 5348:     my $parentpath = '';
 5349:     my $lastitem = '';
 5350:     if ($thisdisfn =~ m-(.+/)([^/]*)$-) {
 5351:         $parentpath = $1;
 5352:         $lastitem = $2;
 5353:     } else {
 5354:         $lastitem = $thisdisfn;
 5355:     }
 5356: 
 5357:     my $output =
 5358:          '<div>'
 5359:         .&Apache::loncommon::help_open_menu('','',3,'Authoring') #FIXME: Broken? Where is it?
 5360:         .'<b>'.&mt('Authoring Space:').'</b> '
 5361:         .'<form name="dirs" method="post" action="'.$formaction
 5362:         .'" target="_top">' #FIXME lonpubdir: target="_parent"
 5363:         .&Apache::lonhtmlcommon::crumbs($uname.'/'.$parentpath,'_top','/priv/'.$udom,undef,undef);
 5364: 
 5365:     if ($lastitem) {
 5366:         $output .=
 5367:              '<span class="LC_filename">'
 5368:             .$lastitem
 5369:             .'</span>';
 5370:     }
 5371:     $output .=
 5372:          '<br />'
 5373:         #FIXME lonpubdir: &Apache::lonhtmlcommon::crumbs($uname.$thisdisfn.'/','_top','/priv','','+1',1)."</b></tt><br />"
 5374:         .&Apache::lonhtmlcommon::select_recent('construct','recent','this.form.action=this.form.recent.value;this.form.submit()')
 5375:         .'</form>'
 5376:         .&Apache::lonmenu::constspaceform()
 5377:         .'</div>';
 5378: 
 5379:     return $output;
 5380: }
 5381: 
 5382: ###############################################
 5383: ###############################################
 5384: 
 5385: =pod
 5386: 
 5387: =back
 5388: 
 5389: =head1 HTML Helpers
 5390: 
 5391: =over 4
 5392: 
 5393: =item * &bodytag()
 5394: 
 5395: Returns a uniform header for LON-CAPA web pages.
 5396: 
 5397: Inputs: 
 5398: 
 5399: =over 4
 5400: 
 5401: =item * $title, A title to be displayed on the page.
 5402: 
 5403: =item * $function, the current role (can be undef).
 5404: 
 5405: =item * $addentries, extra parameters for the <body> tag.
 5406: 
 5407: =item * $bodyonly, if defined, only return the <body> tag.
 5408: 
 5409: =item * $domain, if defined, force a given domain.
 5410: 
 5411: =item * $forcereg, if page should register as content page (relevant for 
 5412:             text interface only)
 5413: 
 5414: =item * $no_nav_bar, if true, keep the 'what is this' info but remove the
 5415:                      navigational links
 5416: 
 5417: =item * $bgcolor, used to override the bgcolor on a webpage to a specific value
 5418: 
 5419: =item * $no_inline_link, if true and in remote mode, don't show the
 5420:          'Switch To Inline Menu' link
 5421: 
 5422: =item * $args, optional argument valid values are
 5423:             no_auto_mt_title -> prevents &mt()ing the title arg
 5424: 
 5425: =item * $advtoolsref, optional argument, ref to an array containing
 5426:             inlineremote items to be added in "Functions" menu below
 5427:             breadcrumbs.
 5428: 
 5429: =back
 5430: 
 5431: Returns: A uniform header for LON-CAPA web pages.  
 5432: If $bodyonly is nonzero, a string containing a <body> tag will be returned.
 5433: If $bodyonly is undef or zero, an html string containing a <body> tag and 
 5434: other decorations will be returned.
 5435: 
 5436: =cut
 5437: 
 5438: sub bodytag {
 5439:     my ($title,$function,$addentries,$bodyonly,$domain,$forcereg,
 5440:         $no_nav_bar,$bgcolor,$no_inline_link,$args,$advtoolsref)=@_;
 5441: 
 5442:     my $public;
 5443:     if ((($env{'user.name'} eq 'public') && ($env{'user.domain'} eq 'public'))
 5444:         || ($env{'user.name'} eq '') && ($env{'user.domain'} eq '')) {
 5445:         $public = 1;
 5446:     }
 5447:     if (!$args->{'no_auto_mt_title'}) { $title = &mt($title); }
 5448:     my $httphost = $args->{'use_absolute'};
 5449: 
 5450:     $function = &get_users_function() if (!$function);
 5451:     my $img =    &designparm($function.'.img',$domain);
 5452:     my $font =   &designparm($function.'.font',$domain);
 5453:     my $pgbg   = $bgcolor || &designparm($function.'.pgbg',$domain);
 5454: 
 5455:     my %design = ( 'style'   => 'margin-top: 0',
 5456: 		   'bgcolor' => $pgbg,
 5457: 		   'text'    => $font,
 5458:                    'alink'   => &designparm($function.'.alink',$domain),
 5459: 		   'vlink'   => &designparm($function.'.vlink',$domain),
 5460: 		   'link'    => &designparm($function.'.link',$domain),);
 5461:     @design{keys(%$addentries)} = @$addentries{keys(%$addentries)}; 
 5462: 
 5463:  # role and realm
 5464:     my ($role,$realm) = split(m{\./},$env{'request.role'},2);
 5465:     if ($realm) {
 5466:         $realm = '/'.$realm;
 5467:     }
 5468:     if ($role  eq 'ca') {
 5469:         my ($rdom,$rname) = ($realm =~ m{^/($match_domain)/($match_username)$});
 5470:         $realm = &plainname($rname,$rdom);
 5471:     } 
 5472: # realm
 5473:     if ($env{'request.course.id'}) {
 5474:         if ($env{'request.role'} !~ /^cr/) {
 5475:             $role = &Apache::lonnet::plaintext($role,&course_type());
 5476:         } elsif ($role =~ m{^cr/($match_domain)/\1-domainconfig/(\w+)$}) {
 5477:             if ($env{'request.role.desc'}) {
 5478:                 $role = $env{'request.role.desc'};
 5479:             } else {
 5480:                 $role = &mt('Helpdesk[_1]','&nbsp;'.$2);
 5481:             }
 5482:         } else {
 5483:             $role = (split(/\//,$role,4))[-1];
 5484:         }
 5485:         if ($env{'request.course.sec'}) {
 5486:             $role .= ('&nbsp;'x2).'-&nbsp;'.&mt('section:').'&nbsp;'.$env{'request.course.sec'};
 5487:         }   
 5488: 	$realm = $env{'course.'.$env{'request.course.id'}.'.description'};
 5489:     } else {
 5490:         $role = &Apache::lonnet::plaintext($role);
 5491:     }
 5492: 
 5493:     if (!$realm) { $realm='&nbsp;'; }
 5494: 
 5495:     my $extra_body_attr = &make_attr_string($forcereg,\%design);
 5496: 
 5497: # construct main body tag
 5498:     my $bodytag = "<body $extra_body_attr>".
 5499: 	&Apache::lontexconvert::init_math_support();
 5500: 
 5501:     &get_unprocessed_cgi($ENV{'QUERY_STRING'}, ['inhibitmenu']);
 5502: 
 5503:     if (($bodyonly) || ($no_nav_bar) || ($env{'form.inhibitmenu'} eq 'yes')) {
 5504:         return $bodytag;
 5505:     }
 5506: 
 5507:     if ($public) {
 5508: 	undef($role);
 5509:     }
 5510:     
 5511:     my $titleinfo = '<h1>'.$title.'</h1>';
 5512:     #
 5513:     # Extra info if you are the DC
 5514:     my $dc_info = '';
 5515:     if ($env{'user.adv'} && exists($env{'user.role.dc./'.
 5516:                         $env{'course.'.$env{'request.course.id'}.
 5517:                                  '.domain'}.'/'})) {
 5518:         my $cid = $env{'request.course.id'};
 5519:         $dc_info = $cid.' '.$env{'course.'.$cid.'.internal.coursecode'};
 5520:         $dc_info =~ s/\s+$//;
 5521:     }
 5522: 
 5523:     $role = '<span class="LC_nobreak">('.$role.')</span>' if ($role && !$env{'browser.mobile'});
 5524: 
 5525:     if ($env{'request.state'} eq 'construct') { $forcereg=1; }
 5526: 
 5527: 
 5528: 
 5529:     my $funclist;
 5530:     if (($env{'environment.remote'} eq 'on') && ($env{'request.state'} ne 'construct')) {
 5531:         $bodytag .= Apache::lonhtmlcommon::scripttag(Apache::lonmenu::utilityfunctions($httphost), 'start')."\n".
 5532:                     Apache::lonmenu::serverform();
 5533:         my $forbodytag;
 5534:         &Apache::lonmenu::prepare_functions($env{'request.noversionuri'},
 5535:                                             $forcereg,$args->{'group'},
 5536:                                             $args->{'bread_crumbs'},
 5537:                                             $advtoolsref,'',\$forbodytag);
 5538:         unless (ref($args->{'bread_crumbs'}) eq 'ARRAY') {
 5539:             $funclist = $forbodytag;
 5540:         }
 5541:     } else {
 5542: 
 5543:         #    if ($env{'request.state'} eq 'construct') {
 5544:         #        $titleinfo = &CSTR_pageheader(); #FIXME: Will be removed once all scripts have their own calls
 5545:         #    }
 5546: 
 5547:         $bodytag .= Apache::lonhtmlcommon::scripttag(
 5548:             Apache::lonmenu::utilityfunctions($httphost), 'start');
 5549: 
 5550:         my ($left,$right) = Apache::lonmenu::primary_menu();
 5551: 
 5552:         if ($env{'request.noversionuri'} =~ m{^/res/adm/pages/}) {
 5553:             if ($dc_info) {
 5554:                  $dc_info = qq|<span class="LC_cusr_subheading">$dc_info</span>|;
 5555:             }
 5556:             $bodytag .= qq|<div id="LC_nav_bar">$left $role<br />
 5557:                            <em>$realm</em> $dc_info</div>|;
 5558:             return $bodytag;
 5559:         }
 5560: 
 5561:         unless ($env{'request.symb'} =~ m/\.page___\d+___/) {
 5562:             $bodytag .= qq|<div id="LC_nav_bar">$left $role</div>|;
 5563:         }
 5564: 
 5565:         $bodytag .= $right;
 5566: 
 5567:         if ($dc_info) {
 5568:             $dc_info = &dc_courseid_toggle($dc_info);
 5569:         }
 5570:         $bodytag .= qq|<div id="LC_realm">$realm $dc_info</div>|;
 5571: 
 5572:         #if directed to not display the secondary menu, don't.
 5573:         if ($args->{'no_secondary_menu'}) {
 5574:             return $bodytag;
 5575:         }
 5576:         #don't show menus for public users
 5577:         if (!$public){
 5578:             $bodytag .= Apache::lonmenu::secondary_menu($httphost);
 5579:             $bodytag .= Apache::lonmenu::serverform();
 5580:             $bodytag .= Apache::lonhtmlcommon::scripttag('', 'end');
 5581:             if ($env{'request.state'} eq 'construct') {
 5582:                 $bodytag .= &Apache::lonmenu::innerregister($forcereg,
 5583:                                 $args->{'bread_crumbs'});
 5584:             } elsif ($forcereg) {
 5585:                 $bodytag .= &Apache::lonmenu::innerregister($forcereg,undef,
 5586:                                                             $args->{'group'},
 5587:                                                             $args->{'hide_buttons'});
 5588:             } else {
 5589:                 my $forbodytag;
 5590:                 &Apache::lonmenu::prepare_functions($env{'request.noversionuri'},
 5591:                                                     $forcereg,$args->{'group'},
 5592:                                                     $args->{'bread_crumbs'},
 5593:                                                     $advtoolsref,'',\$forbodytag);
 5594:                 unless (ref($args->{'bread_crumbs'}) eq 'ARRAY') {
 5595:                     $bodytag .= $forbodytag;
 5596:                 }
 5597:             }
 5598:         }else{
 5599:             # this is to seperate menu from content when there's no secondary
 5600:             # menu. Especially needed for public accessible ressources.
 5601:             $bodytag .= '<hr style="clear:both" />';
 5602:             $bodytag .= Apache::lonhtmlcommon::scripttag('', 'end'); 
 5603:         }
 5604: 
 5605:         return $bodytag;
 5606:     }
 5607: 
 5608: #
 5609: # Top frame rendering, Remote is up
 5610: #
 5611: 
 5612:     my $imgsrc = $img;
 5613:     if ($img =~ /^\/adm/) {
 5614:         $imgsrc = &lonhttpdurl($img);
 5615:     }
 5616:     my $upperleft='<img src="'.$imgsrc.'" alt="'.$function.'" />';
 5617: 
 5618:     my $help=($no_inline_link?''
 5619:               :&Apache::loncommon::top_nav_help('Help'));
 5620: 
 5621:     # Explicit link to get inline menu
 5622:     my $menu= ($no_inline_link?''
 5623:                :'<a href="/adm/remote?action=collapse" target="_top">'.&mt('Switch to Inline Menu Mode').'</a>');
 5624: 
 5625:     if ($dc_info) {
 5626:         $dc_info = qq|<span class="LC_cusr_subheading">($dc_info)</span>|;
 5627:     }
 5628: 
 5629:     my $name = &plainname($env{'user.name'},$env{'user.domain'});
 5630:     unless ($public) {
 5631:         $name = &aboutmewrapper($name,$env{'user.name'},$env{'user.domain'},
 5632:                                 undef,'LC_menubuttons_link');
 5633:     }
 5634: 
 5635:     unless ($env{'form.inhibitmenu'}) {
 5636:         $bodytag .= qq|<div id="LC_nav_bar">$name $role</div>
 5637:                        <ol class="LC_primary_menu LC_floatright LC_right">
 5638:                        <li>$help</li>
 5639:                        <li>$menu</li>
 5640:                        </ol><div id="LC_realm"> $realm $dc_info</div>|;
 5641:     }
 5642:     if ($env{'request.state'} eq 'construct') {
 5643:         if (!$public){
 5644:             if ($env{'request.state'} eq 'construct') {
 5645:                 $funclist = &Apache::lonhtmlcommon::scripttag(
 5646:                                 &Apache::lonmenu::utilityfunctions($httphost), 'start').
 5647:                             &Apache::lonhtmlcommon::scripttag('','end').
 5648:                             &Apache::lonmenu::innerregister($forcereg,
 5649:                                                             $args->{'bread_crumbs'});
 5650:             }
 5651:         }
 5652:     }
 5653:     return $bodytag."\n".$funclist;
 5654: }
 5655: 
 5656: sub dc_courseid_toggle {
 5657:     my ($dc_info) = @_;
 5658:     return ' <span id="dccidtext" class="LC_cusr_subheading LC_nobreak">'.
 5659:            '<a href="javascript:showCourseID();" class="LC_menubuttons_link">'.
 5660:            &mt('(More ...)').'</a></span>'.
 5661:            '<div id="dccid" class="LC_dccid">'.$dc_info.'</div>';
 5662: }
 5663: 
 5664: sub make_attr_string {
 5665:     my ($register,$attr_ref) = @_;
 5666: 
 5667:     if ($attr_ref && !ref($attr_ref)) {
 5668: 	die("addentries Must be a hash ref ".
 5669: 	    join(':',caller(1))." ".
 5670: 	    join(':',caller(0))." ");
 5671:     }
 5672: 
 5673:     if ($register) {
 5674: 	my ($on_load,$on_unload);
 5675: 	foreach my $key (keys(%{$attr_ref})) {
 5676: 	    if      (lc($key) eq 'onload') {
 5677: 		$on_load.=$attr_ref->{$key}.';';
 5678: 		delete($attr_ref->{$key});
 5679: 
 5680: 	    } elsif (lc($key) eq 'onunload') {
 5681: 		$on_unload.=$attr_ref->{$key}.';';
 5682: 		delete($attr_ref->{$key});
 5683: 	    }
 5684: 	}
 5685:         if ($env{'environment.remote'} eq 'on') {
 5686:             $attr_ref->{'onload'}  =
 5687:                 &Apache::lonmenu::loadevents().  $on_load;
 5688:             $attr_ref->{'onunload'}=
 5689:                 &Apache::lonmenu::unloadevents().$on_unload;
 5690:         } else {  
 5691: 	    $attr_ref->{'onload'}  = $on_load;
 5692: 	    $attr_ref->{'onunload'}= $on_unload;
 5693:         }
 5694:     }
 5695: 
 5696:     my $attr_string;
 5697:     foreach my $attr (sort(keys(%$attr_ref))) {
 5698: 	$attr_string .= " $attr=\"".$attr_ref->{$attr}.'" ';
 5699:     }
 5700:     return $attr_string;
 5701: }
 5702: 
 5703: 
 5704: ###############################################
 5705: ###############################################
 5706: 
 5707: =pod
 5708: 
 5709: =item * &endbodytag()
 5710: 
 5711: Returns a uniform footer for LON-CAPA web pages.
 5712: 
 5713: Inputs: 1 - optional reference to an args hash
 5714: If in the hash, key for noredirectlink has a value which evaluates to true,
 5715: a 'Continue' link is not displayed if the page contains an
 5716: internal redirect in the <head></head> section,
 5717: i.e., $env{'internal.head.redirect'} exists   
 5718: 
 5719: =cut
 5720: 
 5721: sub endbodytag {
 5722:     my ($args) = @_;
 5723:     my $endbodytag;
 5724:     unless ((ref($args) eq 'HASH') && ($args->{'notbody'})) {
 5725:         $endbodytag='</body>';
 5726:     }
 5727:     if ( exists( $env{'internal.head.redirect'} ) ) {
 5728:         if (!(ref($args) eq 'HASH' && $args->{'noredirectlink'})) {
 5729: 	    $endbodytag=
 5730: 	        "<br /><a href=\"$env{'internal.head.redirect'}\">".
 5731: 	        &mt('Continue').'</a>'.
 5732: 	        $endbodytag;
 5733:         }
 5734:     }
 5735:     return $endbodytag;
 5736: }
 5737: 
 5738: =pod
 5739: 
 5740: =item * &standard_css()
 5741: 
 5742: Returns a style sheet
 5743: 
 5744: Inputs: (all optional)
 5745:             domain         -> force to color decorate a page for a specific
 5746:                                domain
 5747:             function       -> force usage of a specific rolish color scheme
 5748:             bgcolor        -> override the default page bgcolor
 5749: 
 5750: =cut
 5751: 
 5752: sub standard_css {
 5753:     my ($function,$domain,$bgcolor) = @_;
 5754:     $function  = &get_users_function() if (!$function);
 5755:     my $img    = &designparm($function.'.img',   $domain);
 5756:     my $tabbg  = &designparm($function.'.tabbg', $domain);
 5757:     my $font   = &designparm($function.'.font',  $domain);
 5758:     my $fontmenu = &designparm($function.'.fontmenu', $domain);
 5759: #second colour for later usage
 5760:     my $sidebg = &designparm($function.'.sidebg',$domain);
 5761:     my $pgbg_or_bgcolor =
 5762: 	         $bgcolor ||
 5763: 	         &designparm($function.'.pgbg',  $domain);
 5764:     my $pgbg   = &designparm($function.'.pgbg',  $domain);
 5765:     my $alink  = &designparm($function.'.alink', $domain);
 5766:     my $vlink  = &designparm($function.'.vlink', $domain);
 5767:     my $link   = &designparm($function.'.link',  $domain);
 5768: 
 5769:     my $sans                 = 'Verdana,Arial,Helvetica,sans-serif';
 5770:     my $mono                 = 'monospace';
 5771:     my $data_table_head      = $sidebg;
 5772:     my $data_table_light     = '#FAFAFA';
 5773:     my $data_table_dark      = '#E0E0E0';
 5774:     my $data_table_darker    = '#CCCCCC';
 5775:     my $data_table_highlight = '#FFFF00';
 5776:     my $mail_new             = '#FFBB77';
 5777:     my $mail_new_hover       = '#DD9955';
 5778:     my $mail_read            = '#BBBB77';
 5779:     my $mail_read_hover      = '#999944';
 5780:     my $mail_replied         = '#AAAA88';
 5781:     my $mail_replied_hover   = '#888855';
 5782:     my $mail_other           = '#99BBBB';
 5783:     my $mail_other_hover     = '#669999';
 5784:     my $table_header         = '#DDDDDD';
 5785:     my $feedback_link_bg     = '#BBBBBB';
 5786:     my $lg_border_color      = '#C8C8C8';
 5787:     my $button_hover         = '#BF2317';
 5788: 
 5789:     my $border = ($env{'browser.type'} eq 'explorer' ||
 5790:       $env{'browser.type'} eq 'safari'     ) ? '0 2px 0 2px'
 5791:                                              : '0 3px 0 4px';
 5792: 
 5793: 
 5794:     return <<END;
 5795: 
 5796: /* needed for iframe to allow 100% height in FF */
 5797: body, html { 
 5798:     margin: 0;
 5799:     padding: 0 0.5%;
 5800:     height: 99%; /* to avoid scrollbars */
 5801: }
 5802: 
 5803: body {
 5804:   font-family: $sans;
 5805:   line-height:130%;
 5806:   font-size:0.83em;
 5807:   color:$font;
 5808: }
 5809: 
 5810: a:focus,
 5811: a:focus img {
 5812:   color: red;
 5813: }
 5814: 
 5815: form, .inline {
 5816:   display: inline;
 5817: }
 5818: 
 5819: .LC_right {
 5820:   text-align:right;
 5821: }
 5822: 
 5823: .LC_middle {
 5824:   vertical-align:middle;
 5825: }
 5826: 
 5827: .LC_floatleft {
 5828:   float: left;
 5829: }
 5830: 
 5831: .LC_floatright {
 5832:   float: right;
 5833: }
 5834: 
 5835: .LC_400Box {
 5836:   width:400px;
 5837: }
 5838: 
 5839: .LC_iframecontainer {
 5840:     width: 98%;
 5841:     margin: 0;
 5842:     position: fixed;
 5843:     top: 8.5em;
 5844:     bottom: 0;
 5845: }
 5846: 
 5847: .LC_iframecontainer iframe{
 5848:     border: none;
 5849:     width: 100%;
 5850:     height: 100%;
 5851: }
 5852: 
 5853: .LC_filename {
 5854:   font-family: $mono;
 5855:   white-space:pre;
 5856:   font-size: 120%;
 5857: }
 5858: 
 5859: .LC_fileicon {
 5860:   border: none;
 5861:   height: 1.3em;
 5862:   vertical-align: text-bottom;
 5863:   margin-right: 0.3em;
 5864:   text-decoration:none;
 5865: }
 5866: 
 5867: .LC_setting {
 5868:   text-decoration:underline;
 5869: }
 5870: 
 5871: .LC_error {
 5872:   color: red;
 5873: }
 5874: 
 5875: .LC_warning {
 5876:   color: darkorange;
 5877: }
 5878: 
 5879: .LC_diff_removed {
 5880:   color: red;
 5881: }
 5882: 
 5883: .LC_info,
 5884: .LC_success,
 5885: .LC_diff_added {
 5886:   color: green;
 5887: }
 5888: 
 5889: div.LC_confirm_box {
 5890:   background-color: #FAFAFA;
 5891:   border: 1px solid $lg_border_color;
 5892:   margin-right: 0;
 5893:   padding: 5px;
 5894: }
 5895: 
 5896: div.LC_confirm_box .LC_error img,
 5897: div.LC_confirm_box .LC_success img {
 5898:   vertical-align: middle;
 5899: }
 5900: 
 5901: .LC_maxwidth {
 5902:   max-width: 100%;
 5903:   height: auto;
 5904: }
 5905: 
 5906: .LC_textsize_mobile {
 5907:   \@media only screen and (max-device-width: 480px) {
 5908:       -webkit-text-size-adjust:100%; -moz-text-size-adjust:100%; -ms-text-size-adjust:100%;
 5909:   }
 5910: }
 5911: 
 5912: .LC_icon {
 5913:   border: none;
 5914:   vertical-align: middle;
 5915: }
 5916: 
 5917: .LC_docs_spacer {
 5918:   width: 25px;
 5919:   height: 1px;
 5920:   border: none;
 5921: }
 5922: 
 5923: .LC_internal_info {
 5924:   color: #999999;
 5925: }
 5926: 
 5927: .LC_discussion {
 5928:   background: $data_table_dark;
 5929:   border: 1px solid black;
 5930:   margin: 2px;
 5931: }
 5932: 
 5933: .LC_disc_action_left {
 5934:   background: $sidebg;
 5935:   text-align: left;
 5936:   padding: 4px;
 5937:   margin: 2px;
 5938: }
 5939: 
 5940: .LC_disc_action_right {
 5941:   background: $sidebg;
 5942:   text-align: right;
 5943:   padding: 4px;
 5944:   margin: 2px;
 5945: }
 5946: 
 5947: .LC_disc_new_item {
 5948:   background: white;
 5949:   border: 2px solid red;
 5950:   margin: 4px;
 5951:   padding: 4px;
 5952: }
 5953: 
 5954: .LC_disc_old_item {
 5955:   background: white;
 5956:   margin: 4px;
 5957:   padding: 4px;
 5958: }
 5959: 
 5960: table.LC_pastsubmission {
 5961:   border: 1px solid black;
 5962:   margin: 2px;
 5963: }
 5964: 
 5965: table#LC_menubuttons {
 5966:   width: 100%;
 5967:   background: $pgbg;
 5968:   border: 2px;
 5969:   border-collapse: separate;
 5970:   padding: 0;
 5971: }
 5972: 
 5973: table#LC_title_bar a {
 5974:   color: $fontmenu;
 5975: }
 5976: 
 5977: table#LC_title_bar {
 5978:   clear: both;
 5979:   display: none;
 5980: }
 5981: 
 5982: table#LC_title_bar,
 5983: table.LC_breadcrumbs, /* obsolete? */
 5984: table#LC_title_bar.LC_with_remote {
 5985:   width: 100%;
 5986:   border-color: $pgbg;
 5987:   border-style: solid;
 5988:   border-width: $border;
 5989:   background: $pgbg;
 5990:   color: $fontmenu;
 5991:   border-collapse: collapse;
 5992:   padding: 0;
 5993:   margin: 0;
 5994: }
 5995: 
 5996: ul.LC_breadcrumb_tools_outerlist {
 5997:     margin: 0;
 5998:     padding: 0;
 5999:     position: relative;
 6000:     list-style: none;
 6001: }
 6002: ul.LC_breadcrumb_tools_outerlist li {
 6003:     display: inline;
 6004: }
 6005: 
 6006: .LC_breadcrumb_tools_navigation {
 6007:     padding: 0;
 6008:     margin: 0;
 6009:     float: left;
 6010: }
 6011: .LC_breadcrumb_tools_tools {
 6012:     padding: 0;
 6013:     margin: 0;
 6014:     float: right;
 6015: }
 6016: 
 6017: table#LC_title_bar td {
 6018:   background: $tabbg;
 6019: }
 6020: 
 6021: table#LC_menubuttons img {
 6022:   border: none;
 6023: }
 6024: 
 6025: .LC_breadcrumbs_component {
 6026:   float: right;
 6027:   margin: 0 1em;
 6028: }
 6029: .LC_breadcrumbs_component img {
 6030:   vertical-align: middle;
 6031: }
 6032: 
 6033: .LC_breadcrumbs_hoverable {
 6034:   background: $sidebg;
 6035: }
 6036: 
 6037: td.LC_table_cell_checkbox {
 6038:   text-align: center;
 6039: }
 6040: 
 6041: .LC_fontsize_small {
 6042:   font-size: 70%;
 6043: }
 6044: 
 6045: #LC_breadcrumbs {
 6046:   clear:both;
 6047:   background: $sidebg;
 6048:   border-bottom: 1px solid $lg_border_color;
 6049:   line-height: 2.5em;
 6050:   overflow: hidden;
 6051:   margin: 0;
 6052:   padding: 0;
 6053:   text-align: left;
 6054: }
 6055: 
 6056: .LC_head_subbox, .LC_actionbox {
 6057:   clear:both;
 6058:   background: #F8F8F8; /* $sidebg; */
 6059:   border: 1px solid $sidebg;
 6060:   margin: 0 0 10px 0;
 6061:   padding: 3px;
 6062:   text-align: left;
 6063: }
 6064: 
 6065: .LC_fontsize_medium {
 6066:   font-size: 85%;
 6067: }
 6068: 
 6069: .LC_fontsize_large {
 6070:   font-size: 120%;
 6071: }
 6072: 
 6073: .LC_menubuttons_inline_text {
 6074:   color: $font;
 6075:   font-size: 90%;
 6076:   padding-left:3px;
 6077: }
 6078: 
 6079: .LC_menubuttons_inline_text img{
 6080:   vertical-align: middle;
 6081: }
 6082: 
 6083: li.LC_menubuttons_inline_text img {
 6084:   cursor:pointer;
 6085:   text-decoration: none;
 6086: }
 6087: 
 6088: .LC_menubuttons_link {
 6089:   text-decoration: none;
 6090: }
 6091: 
 6092: .LC_menubuttons_category {
 6093:   color: $font;
 6094:   background: $pgbg;
 6095:   font-size: larger;
 6096:   font-weight: bold;
 6097: }
 6098: 
 6099: td.LC_menubuttons_text {
 6100:   color: $font;
 6101: }
 6102: 
 6103: .LC_current_location {
 6104:   background: $tabbg;
 6105: }
 6106: 
 6107: table.LC_data_table {
 6108:   border: 1px solid #000000;
 6109:   border-collapse: separate;
 6110:   border-spacing: 1px;
 6111:   background: $pgbg;
 6112: }
 6113: 
 6114: .LC_data_table_dense {
 6115:   font-size: small;
 6116: }
 6117: 
 6118: table.LC_nested_outer {
 6119:   border: 1px solid #000000;
 6120:   border-collapse: collapse;
 6121:   border-spacing: 0;
 6122:   width: 100%;
 6123: }
 6124: 
 6125: table.LC_innerpickbox,
 6126: table.LC_nested {
 6127:   border: none;
 6128:   border-collapse: collapse;
 6129:   border-spacing: 0;
 6130:   width: 100%;
 6131: }
 6132: 
 6133: table.LC_data_table tr th,
 6134: table.LC_calendar tr th,
 6135: table.LC_prior_tries tr th,
 6136: table.LC_innerpickbox tr th {
 6137:   font-weight: bold;
 6138:   background-color: $data_table_head;
 6139:   color:$fontmenu;
 6140:   font-size:90%;
 6141: }
 6142: 
 6143: table.LC_innerpickbox tr th,
 6144: table.LC_innerpickbox tr td {
 6145:   vertical-align: top;
 6146: }
 6147: 
 6148: table.LC_data_table tr.LC_info_row > td {
 6149:   background-color: #CCCCCC;
 6150:   font-weight: bold;
 6151:   text-align: left;
 6152: }
 6153: 
 6154: table.LC_data_table tr.LC_odd_row > td {
 6155:   background-color: $data_table_light;
 6156:   padding: 2px;
 6157:   vertical-align: top;
 6158: }
 6159: 
 6160: table.LC_pick_box tr > td.LC_odd_row {
 6161:   background-color: $data_table_light;
 6162:   vertical-align: top;
 6163: }
 6164: 
 6165: table.LC_data_table tr.LC_even_row > td {
 6166:   background-color: $data_table_dark;
 6167:   padding: 2px;
 6168:   vertical-align: top;
 6169: }
 6170: 
 6171: table.LC_pick_box tr > td.LC_even_row {
 6172:   background-color: $data_table_dark;
 6173:   vertical-align: top;
 6174: }
 6175: 
 6176: table.LC_data_table tr.LC_data_table_highlight td {
 6177:   background-color: $data_table_darker;
 6178: }
 6179: 
 6180: table.LC_data_table tr td.LC_leftcol_header {
 6181:   background-color: $data_table_head;
 6182:   font-weight: bold;
 6183: }
 6184: 
 6185: table.LC_data_table tr.LC_empty_row td,
 6186: table.LC_nested tr.LC_empty_row td {
 6187:   font-weight: bold;
 6188:   font-style: italic;
 6189:   text-align: center;
 6190:   padding: 8px;
 6191: }
 6192: 
 6193: table.LC_data_table tr.LC_empty_row td,
 6194: table.LC_data_table tr.LC_footer_row td {
 6195:   background-color: $sidebg;
 6196: }
 6197: 
 6198: table.LC_nested tr.LC_empty_row td {
 6199:   background-color: #FFFFFF;
 6200: }
 6201: 
 6202: table.LC_caption {
 6203: }
 6204: 
 6205: table.LC_nested tr.LC_empty_row td {
 6206:   padding: 4ex
 6207: }
 6208: 
 6209: table.LC_nested_outer tr th {
 6210:   font-weight: bold;
 6211:   color:$fontmenu;
 6212:   background-color: $data_table_head;
 6213:   font-size: small;
 6214:   border-bottom: 1px solid #000000;
 6215: }
 6216: 
 6217: table.LC_nested_outer tr td.LC_subheader {
 6218:   background-color: $data_table_head;
 6219:   font-weight: bold;
 6220:   font-size: small;
 6221:   border-bottom: 1px solid #000000;
 6222:   text-align: right;
 6223: }
 6224: 
 6225: table.LC_nested tr.LC_info_row td {
 6226:   background-color: #CCCCCC;
 6227:   font-weight: bold;
 6228:   font-size: small;
 6229:   text-align: center;
 6230: }
 6231: 
 6232: table.LC_nested tr.LC_info_row td.LC_left_item,
 6233: table.LC_nested_outer tr th.LC_left_item {
 6234:   text-align: left;
 6235: }
 6236: 
 6237: table.LC_nested td {
 6238:   background-color: #FFFFFF;
 6239:   font-size: small;
 6240: }
 6241: 
 6242: table.LC_nested_outer tr th.LC_right_item,
 6243: table.LC_nested tr.LC_info_row td.LC_right_item,
 6244: table.LC_nested tr.LC_odd_row td.LC_right_item,
 6245: table.LC_nested tr td.LC_right_item {
 6246:   text-align: right;
 6247: }
 6248: 
 6249: table.LC_nested tr.LC_odd_row td {
 6250:   background-color: #EEEEEE;
 6251: }
 6252: 
 6253: table.LC_createuser {
 6254: }
 6255: 
 6256: table.LC_createuser tr.LC_section_row td {
 6257:   font-size: small;
 6258: }
 6259: 
 6260: table.LC_createuser tr.LC_info_row td  {
 6261:   background-color: #CCCCCC;
 6262:   font-weight: bold;
 6263:   text-align: center;
 6264: }
 6265: 
 6266: table.LC_calendar {
 6267:   border: 1px solid #000000;
 6268:   border-collapse: collapse;
 6269:   width: 98%;
 6270: }
 6271: 
 6272: table.LC_calendar_pickdate {
 6273:   font-size: xx-small;
 6274: }
 6275: 
 6276: table.LC_calendar tr td {
 6277:   border: 1px solid #000000;
 6278:   vertical-align: top;
 6279:   width: 14%;
 6280: }
 6281: 
 6282: table.LC_calendar tr td.LC_calendar_day_empty {
 6283:   background-color: $data_table_dark;
 6284: }
 6285: 
 6286: table.LC_calendar tr td.LC_calendar_day_current {
 6287:   background-color: $data_table_highlight;
 6288: }
 6289: 
 6290: table.LC_data_table tr td.LC_mail_new {
 6291:   background-color: $mail_new;
 6292: }
 6293: 
 6294: table.LC_data_table tr.LC_mail_new:hover {
 6295:   background-color: $mail_new_hover;
 6296: }
 6297: 
 6298: table.LC_data_table tr td.LC_mail_read {
 6299:   background-color: $mail_read;
 6300: }
 6301: 
 6302: /*
 6303: table.LC_data_table tr.LC_mail_read:hover {
 6304:   background-color: $mail_read_hover;
 6305: }
 6306: */
 6307: 
 6308: table.LC_data_table tr td.LC_mail_replied {
 6309:   background-color: $mail_replied;
 6310: }
 6311: 
 6312: /*
 6313: table.LC_data_table tr.LC_mail_replied:hover {
 6314:   background-color: $mail_replied_hover;
 6315: }
 6316: */
 6317: 
 6318: table.LC_data_table tr td.LC_mail_other {
 6319:   background-color: $mail_other;
 6320: }
 6321: 
 6322: /*
 6323: table.LC_data_table tr.LC_mail_other:hover {
 6324:   background-color: $mail_other_hover;
 6325: }
 6326: */
 6327: 
 6328: table.LC_data_table tr > td.LC_browser_file,
 6329: table.LC_data_table tr > td.LC_browser_file_published {
 6330:   background: #AAEE77;
 6331: }
 6332: 
 6333: table.LC_data_table tr > td.LC_browser_file_locked,
 6334: table.LC_data_table tr > td.LC_browser_file_unpublished {
 6335:   background: #FFAA99;
 6336: }
 6337: 
 6338: table.LC_data_table tr > td.LC_browser_file_obsolete {
 6339:   background: #888888;
 6340: }
 6341: 
 6342: table.LC_data_table tr > td.LC_browser_file_modified,
 6343: table.LC_data_table tr > td.LC_browser_file_metamodified {
 6344:   background: #F8F866;
 6345: }
 6346: 
 6347: table.LC_data_table tr.LC_browser_folder > td {
 6348:   background: #E0E8FF;
 6349: }
 6350: 
 6351: table.LC_data_table tr > td.LC_roles_is {
 6352:   /* background: #77FF77; */
 6353: }
 6354: 
 6355: table.LC_data_table tr > td.LC_roles_future {
 6356:   border-right: 8px solid #FFFF77;
 6357: }
 6358: 
 6359: table.LC_data_table tr > td.LC_roles_will {
 6360:   border-right: 8px solid #FFAA77;
 6361: }
 6362: 
 6363: table.LC_data_table tr > td.LC_roles_expired {
 6364:   border-right: 8px solid #FF7777;
 6365: }
 6366: 
 6367: table.LC_data_table tr > td.LC_roles_will_not {
 6368:   border-right: 8px solid #AAFF77;
 6369: }
 6370: 
 6371: table.LC_data_table tr > td.LC_roles_selected {
 6372:   border-right: 8px solid #11CC55;
 6373: }
 6374: 
 6375: span.LC_current_location {
 6376:   font-size:larger;
 6377:   background: $pgbg;
 6378: }
 6379: 
 6380: span.LC_current_nav_location {
 6381:   font-weight:bold;
 6382:   background: $sidebg;
 6383: }
 6384: 
 6385: span.LC_parm_menu_item {
 6386:   font-size: larger;
 6387: }
 6388: 
 6389: span.LC_parm_scope_all {
 6390:   color: red;
 6391: }
 6392: 
 6393: span.LC_parm_scope_folder {
 6394:   color: green;
 6395: }
 6396: 
 6397: span.LC_parm_scope_resource {
 6398:   color: orange;
 6399: }
 6400: 
 6401: span.LC_parm_part {
 6402:   color: blue;
 6403: }
 6404: 
 6405: span.LC_parm_folder,
 6406: span.LC_parm_symb {
 6407:   font-size: x-small;
 6408:   font-family: $mono;
 6409:   color: #AAAAAA;
 6410: }
 6411: 
 6412: ul.LC_parm_parmlist li {
 6413:   display: inline-block;
 6414:   padding: 0.3em 0.8em;
 6415:   vertical-align: top;
 6416:   width: 150px;
 6417:   border-top:1px solid $lg_border_color;
 6418: }
 6419: 
 6420: td.LC_parm_overview_level_menu,
 6421: td.LC_parm_overview_map_menu,
 6422: td.LC_parm_overview_parm_selectors,
 6423: td.LC_parm_overview_restrictions  {
 6424:   border: 1px solid black;
 6425:   border-collapse: collapse;
 6426: }
 6427: 
 6428: table.LC_parm_overview_restrictions td {
 6429:   border-width: 1px 4px 1px 4px;
 6430:   border-style: solid;
 6431:   border-color: $pgbg;
 6432:   text-align: center;
 6433: }
 6434: 
 6435: table.LC_parm_overview_restrictions th {
 6436:   background: $tabbg;
 6437:   border-width: 1px 4px 1px 4px;
 6438:   border-style: solid;
 6439:   border-color: $pgbg;
 6440: }
 6441: 
 6442: table#LC_helpmenu {
 6443:   border: none;
 6444:   height: 55px;
 6445:   border-spacing: 0;
 6446: }
 6447: 
 6448: table#LC_helpmenu fieldset legend {
 6449:   font-size: larger;
 6450: }
 6451: 
 6452: table#LC_helpmenu_links {
 6453:   width: 100%;
 6454:   border: 1px solid black;
 6455:   background: $pgbg;
 6456:   padding: 0;
 6457:   border-spacing: 1px;
 6458: }
 6459: 
 6460: table#LC_helpmenu_links tr td {
 6461:   padding: 1px;
 6462:   background: $tabbg;
 6463:   text-align: center;
 6464:   font-weight: bold;
 6465: }
 6466: 
 6467: table#LC_helpmenu_links a:link,
 6468: table#LC_helpmenu_links a:visited,
 6469: table#LC_helpmenu_links a:active {
 6470:   text-decoration: none;
 6471:   color: $font;
 6472: }
 6473: 
 6474: table#LC_helpmenu_links a:hover {
 6475:   text-decoration: underline;
 6476:   color: $vlink;
 6477: }
 6478: 
 6479: .LC_chrt_popup_exists {
 6480:   border: 1px solid #339933;
 6481:   margin: -1px;
 6482: }
 6483: 
 6484: .LC_chrt_popup_up {
 6485:   border: 1px solid yellow;
 6486:   margin: -1px;
 6487: }
 6488: 
 6489: .LC_chrt_popup {
 6490:   border: 1px solid #8888FF;
 6491:   background: #CCCCFF;
 6492: }
 6493: 
 6494: table.LC_pick_box {
 6495:   border-collapse: separate;
 6496:   background: white;
 6497:   border: 1px solid black;
 6498:   border-spacing: 1px;
 6499: }
 6500: 
 6501: table.LC_pick_box td.LC_pick_box_title {
 6502:   background: $sidebg;
 6503:   font-weight: bold;
 6504:   text-align: left;
 6505:   vertical-align: top;
 6506:   width: 184px;
 6507:   padding: 8px;
 6508: }
 6509: 
 6510: table.LC_pick_box td.LC_pick_box_value {
 6511:   text-align: left;
 6512:   padding: 8px;
 6513: }
 6514: 
 6515: table.LC_pick_box td.LC_pick_box_select {
 6516:   text-align: left;
 6517:   padding: 8px;
 6518: }
 6519: 
 6520: table.LC_pick_box td.LC_pick_box_separator {
 6521:   padding: 0;
 6522:   height: 1px;
 6523:   background: black;
 6524: }
 6525: 
 6526: table.LC_pick_box td.LC_pick_box_submit {
 6527:   text-align: right;
 6528: }
 6529: 
 6530: table.LC_pick_box td.LC_evenrow_value {
 6531:   text-align: left;
 6532:   padding: 8px;
 6533:   background-color: $data_table_light;
 6534: }
 6535: 
 6536: table.LC_pick_box td.LC_oddrow_value {
 6537:   text-align: left;
 6538:   padding: 8px;
 6539:   background-color: $data_table_light;
 6540: }
 6541: 
 6542: span.LC_helpform_receipt_cat {
 6543:   font-weight: bold;
 6544: }
 6545: 
 6546: table.LC_group_priv_box {
 6547:   background: white;
 6548:   border: 1px solid black;
 6549:   border-spacing: 1px;
 6550: }
 6551: 
 6552: table.LC_group_priv_box td.LC_pick_box_title {
 6553:   background: $tabbg;
 6554:   font-weight: bold;
 6555:   text-align: right;
 6556:   width: 184px;
 6557: }
 6558: 
 6559: table.LC_group_priv_box td.LC_groups_fixed {
 6560:   background: $data_table_light;
 6561:   text-align: center;
 6562: }
 6563: 
 6564: table.LC_group_priv_box td.LC_groups_optional {
 6565:   background: $data_table_dark;
 6566:   text-align: center;
 6567: }
 6568: 
 6569: table.LC_group_priv_box td.LC_groups_functionality {
 6570:   background: $data_table_darker;
 6571:   text-align: center;
 6572:   font-weight: bold;
 6573: }
 6574: 
 6575: table.LC_group_priv td {
 6576:   text-align: left;
 6577:   padding: 0;
 6578: }
 6579: 
 6580: .LC_navbuttons {
 6581:   margin: 2ex 0ex 2ex 0ex;
 6582: }
 6583: 
 6584: .LC_topic_bar {
 6585:   font-weight: bold;
 6586:   background: $tabbg;
 6587:   margin: 1em 0em 1em 2em;
 6588:   padding: 3px;
 6589:   font-size: 1.2em;
 6590: }
 6591: 
 6592: .LC_topic_bar span {
 6593:   left: 0.5em;
 6594:   position: absolute;
 6595:   vertical-align: middle;
 6596:   font-size: 1.2em;
 6597: }
 6598: 
 6599: table.LC_course_group_status {
 6600:   margin: 20px;
 6601: }
 6602: 
 6603: table.LC_status_selector td {
 6604:   vertical-align: top;
 6605:   text-align: center;
 6606:   padding: 4px;
 6607: }
 6608: 
 6609: div.LC_feedback_link {
 6610:   clear: both;
 6611:   background: $sidebg;
 6612:   width: 100%;
 6613:   padding-bottom: 10px;
 6614:   border: 1px $tabbg solid;
 6615:   height: 22px;
 6616:   line-height: 22px;
 6617:   padding-top: 5px;
 6618: }
 6619: 
 6620: div.LC_feedback_link img {
 6621:   height: 22px;
 6622:   vertical-align:middle;
 6623: }
 6624: 
 6625: div.LC_feedback_link a {
 6626:   text-decoration: none;
 6627: }
 6628: 
 6629: div.LC_comblock {
 6630:   display:inline;
 6631:   color:$font;
 6632:   font-size:90%;
 6633: }
 6634: 
 6635: div.LC_feedback_link div.LC_comblock {
 6636:   padding-left:5px;
 6637: }
 6638: 
 6639: div.LC_feedback_link div.LC_comblock a {
 6640:   color:$font;
 6641: }
 6642: 
 6643: span.LC_feedback_link {
 6644:   /* background: $feedback_link_bg; */
 6645:   font-size: larger;
 6646: }
 6647: 
 6648: span.LC_message_link {
 6649:   /* background: $feedback_link_bg; */
 6650:   font-size: larger;
 6651:   position: absolute;
 6652:   right: 1em;
 6653: }
 6654: 
 6655: table.LC_prior_tries {
 6656:   border: 1px solid #000000;
 6657:   border-collapse: separate;
 6658:   border-spacing: 1px;
 6659: }
 6660: 
 6661: table.LC_prior_tries td {
 6662:   padding: 2px;
 6663: }
 6664: 
 6665: .LC_answer_correct {
 6666:   background: lightgreen;
 6667:   color: darkgreen;
 6668:   padding: 6px;
 6669: }
 6670: 
 6671: .LC_answer_charged_try {
 6672:   background: #FFAAAA;
 6673:   color: darkred;
 6674:   padding: 6px;
 6675: }
 6676: 
 6677: .LC_answer_not_charged_try,
 6678: .LC_answer_no_grade,
 6679: .LC_answer_late {
 6680:   background: lightyellow;
 6681:   color: black;
 6682:   padding: 6px;
 6683: }
 6684: 
 6685: .LC_answer_previous {
 6686:   background: lightblue;
 6687:   color: darkblue;
 6688:   padding: 6px;
 6689: }
 6690: 
 6691: .LC_answer_no_message {
 6692:   background: #FFFFFF;
 6693:   color: black;
 6694:   padding: 6px;
 6695: }
 6696: 
 6697: .LC_answer_unknown {
 6698:   background: orange;
 6699:   color: black;
 6700:   padding: 6px;
 6701: }
 6702: 
 6703: span.LC_prior_numerical,
 6704: span.LC_prior_string,
 6705: span.LC_prior_custom,
 6706: span.LC_prior_reaction,
 6707: span.LC_prior_math {
 6708:   font-family: $mono;
 6709:   white-space: pre;
 6710: }
 6711: 
 6712: span.LC_prior_string {
 6713:   font-family: $mono;
 6714:   white-space: pre;
 6715: }
 6716: 
 6717: table.LC_prior_option {
 6718:   width: 100%;
 6719:   border-collapse: collapse;
 6720: }
 6721: 
 6722: table.LC_prior_rank,
 6723: table.LC_prior_match {
 6724:   border-collapse: collapse;
 6725: }
 6726: 
 6727: table.LC_prior_option tr td,
 6728: table.LC_prior_rank tr td,
 6729: table.LC_prior_match tr td {
 6730:   border: 1px solid #000000;
 6731: }
 6732: 
 6733: .LC_nobreak {
 6734:   white-space: nowrap;
 6735: }
 6736: 
 6737: span.LC_cusr_emph {
 6738:   font-style: italic;
 6739: }
 6740: 
 6741: span.LC_cusr_subheading {
 6742:   font-weight: normal;
 6743:   font-size: 85%;
 6744: }
 6745: 
 6746: div.LC_docs_entry_move {
 6747:   border: 1px solid #BBBBBB;
 6748:   background: #DDDDDD;
 6749:   width: 22px;
 6750:   padding: 1px;
 6751:   margin: 0;
 6752: }
 6753: 
 6754: table.LC_data_table tr > td.LC_docs_entry_commands,
 6755: table.LC_data_table tr > td.LC_docs_entry_parameter {
 6756:   font-size: x-small;
 6757: }
 6758: 
 6759: .LC_docs_entry_parameter {
 6760:   white-space: nowrap;
 6761: }
 6762: 
 6763: .LC_docs_copy {
 6764:   color: #000099;
 6765: }
 6766: 
 6767: .LC_docs_cut {
 6768:   color: #550044;
 6769: }
 6770: 
 6771: .LC_docs_rename {
 6772:   color: #009900;
 6773: }
 6774: 
 6775: .LC_docs_remove {
 6776:   color: #990000;
 6777: }
 6778: 
 6779: .LC_docs_reinit_warn,
 6780: .LC_docs_ext_edit {
 6781:   font-size: x-small;
 6782: }
 6783: 
 6784: table.LC_docs_adddocs td,
 6785: table.LC_docs_adddocs th {
 6786:   border: 1px solid #BBBBBB;
 6787:   padding: 4px;
 6788:   background: #DDDDDD;
 6789: }
 6790: 
 6791: table.LC_sty_begin {
 6792:   background: #BBFFBB;
 6793: }
 6794: 
 6795: table.LC_sty_end {
 6796:   background: #FFBBBB;
 6797: }
 6798: 
 6799: table.LC_double_column {
 6800:   border-width: 0;
 6801:   border-collapse: collapse;
 6802:   width: 100%;
 6803:   padding: 2px;
 6804: }
 6805: 
 6806: table.LC_double_column tr td.LC_left_col {
 6807:   top: 2px;
 6808:   left: 2px;
 6809:   width: 47%;
 6810:   vertical-align: top;
 6811: }
 6812: 
 6813: table.LC_double_column tr td.LC_right_col {
 6814:   top: 2px;
 6815:   right: 2px;
 6816:   width: 47%;
 6817:   vertical-align: top;
 6818: }
 6819: 
 6820: div.LC_left_float {
 6821:   float: left;
 6822:   padding-right: 5%;
 6823:   padding-bottom: 4px;
 6824: }
 6825: 
 6826: div.LC_clear_float_header {
 6827:   padding-bottom: 2px;
 6828: }
 6829: 
 6830: div.LC_clear_float_footer {
 6831:   padding-top: 10px;
 6832:   clear: both;
 6833: }
 6834: 
 6835: div.LC_grade_show_user {
 6836: /*  border-left: 5px solid $sidebg; */
 6837:   border-top: 5px solid #000000;
 6838:   margin: 50px 0 0 0;
 6839:   padding: 15px 0 5px 10px;
 6840: }
 6841: 
 6842: div.LC_grade_show_user_odd_row {
 6843: /*  border-left: 5px solid #000000; */
 6844: }
 6845: 
 6846: div.LC_grade_show_user div.LC_Box {
 6847:   margin-right: 50px;
 6848: }
 6849: 
 6850: div.LC_grade_submissions,
 6851: div.LC_grade_message_center,
 6852: div.LC_grade_info_links {
 6853:   margin: 5px;
 6854:   width: 99%;
 6855:   background: #FFFFFF;
 6856: }
 6857: 
 6858: div.LC_grade_submissions_header,
 6859: div.LC_grade_message_center_header {
 6860:   font-weight: bold;
 6861:   font-size: large;
 6862: }
 6863: 
 6864: div.LC_grade_submissions_body,
 6865: div.LC_grade_message_center_body {
 6866:   border: 1px solid black;
 6867:   width: 99%;
 6868:   background: #FFFFFF;
 6869: }
 6870: 
 6871: table.LC_scantron_action {
 6872:   width: 100%;
 6873: }
 6874: 
 6875: table.LC_scantron_action tr th {
 6876:   font-weight:bold;
 6877:   font-style:normal;
 6878: }
 6879: 
 6880: .LC_edit_problem_header,
 6881: div.LC_edit_problem_footer {
 6882:   font-weight: normal;
 6883:   font-size:  medium;
 6884:   margin: 2px;
 6885:   background-color: $sidebg;
 6886: }
 6887: 
 6888: div.LC_edit_problem_header,
 6889: div.LC_edit_problem_header div,
 6890: div.LC_edit_problem_footer,
 6891: div.LC_edit_problem_footer div,
 6892: div.LC_edit_problem_editxml_header,
 6893: div.LC_edit_problem_editxml_header div {
 6894:   z-index: 100;
 6895: }
 6896: 
 6897: div.LC_edit_problem_header_title {
 6898:   font-weight: bold;
 6899:   font-size: larger;
 6900:   background: $tabbg;
 6901:   padding: 3px;
 6902:   margin: 0 0 5px 0;
 6903: }
 6904: 
 6905: table.LC_edit_problem_header_title {
 6906:   width: 100%;
 6907:   background: $tabbg;
 6908: }
 6909: 
 6910: div.LC_edit_actionbar {
 6911:     background-color: $sidebg;
 6912:     margin: 0;
 6913:     padding: 0;
 6914:     line-height: 200%;
 6915: }
 6916: 
 6917: div.LC_edit_actionbar div{
 6918:     padding: 0;
 6919:     margin: 0;
 6920:     display: inline-block;
 6921: }
 6922: 
 6923: .LC_edit_opt {
 6924:   padding-left: 1em;
 6925:   white-space: nowrap;
 6926: }
 6927: 
 6928: .LC_edit_problem_latexhelper{
 6929:     text-align: right;
 6930: }
 6931: 
 6932: #LC_edit_problem_colorful div{
 6933:     margin-left: 40px;
 6934: }
 6935: 
 6936: #LC_edit_problem_codemirror div{
 6937:     margin-left: 0px;
 6938: }
 6939: 
 6940: img.stift {
 6941:   border-width: 0;
 6942:   vertical-align: middle;
 6943: }
 6944: 
 6945: table td.LC_mainmenu_col_fieldset {
 6946:   vertical-align: top;
 6947: }
 6948: 
 6949: div.LC_createcourse {
 6950:   margin: 10px 10px 10px 10px;
 6951: }
 6952: 
 6953: .LC_dccid {
 6954:   float: right;
 6955:   margin: 0.2em 0 0 0;
 6956:   padding: 0;
 6957:   font-size: 90%;
 6958:   display:none;
 6959: }
 6960: 
 6961: ol.LC_primary_menu a:hover,
 6962: ol#LC_MenuBreadcrumbs a:hover,
 6963: ol#LC_PathBreadcrumbs a:hover,
 6964: ul#LC_secondary_menu a:hover,
 6965: .LC_FormSectionClearButton input:hover
 6966: ul.LC_TabContent   li:hover a {
 6967:   color:$button_hover;
 6968:   text-decoration:none;
 6969: }
 6970: 
 6971: h1 {
 6972:   padding: 0;
 6973:   line-height:130%;
 6974: }
 6975: 
 6976: h2,
 6977: h3,
 6978: h4,
 6979: h5,
 6980: h6 {
 6981:   margin: 5px 0 5px 0;
 6982:   padding: 0;
 6983:   line-height:130%;
 6984: }
 6985: 
 6986: .LC_hcell {
 6987:   padding:3px 15px 3px 15px;
 6988:   margin: 0;
 6989:   background-color:$tabbg;
 6990:   color:$fontmenu;
 6991:   border-bottom:solid 1px $lg_border_color;
 6992: }
 6993: 
 6994: .LC_Box > .LC_hcell {
 6995:   margin: 0 -10px 10px -10px;
 6996: }
 6997: 
 6998: .LC_noBorder {
 6999:   border: 0;
 7000: }
 7001: 
 7002: .LC_FormSectionClearButton input {
 7003:   background-color:transparent;
 7004:   border: none;
 7005:   cursor:pointer;
 7006:   text-decoration:underline;
 7007: }
 7008: 
 7009: .LC_help_open_topic {
 7010:   color: #FFFFFF;
 7011:   background-color: #EEEEFF;
 7012:   margin: 1px;
 7013:   padding: 4px;
 7014:   border: 1px solid #000033;
 7015:   white-space: nowrap;
 7016:   /* vertical-align: middle; */
 7017: }
 7018: 
 7019: dl,
 7020: ul,
 7021: div,
 7022: fieldset {
 7023:   margin: 10px 10px 10px 0;
 7024:   /* overflow: hidden; */
 7025: }
 7026: 
 7027: article.geogebraweb div {
 7028:     margin: 0;
 7029: }
 7030: 
 7031: fieldset > legend {
 7032:   font-weight: bold;
 7033:   padding: 0 5px 0 5px;
 7034: }
 7035: 
 7036: #LC_nav_bar {
 7037:   float: left;
 7038:   background-color: $pgbg_or_bgcolor;
 7039:   margin: 0 0 2px 0;
 7040: }
 7041: 
 7042: #LC_realm {
 7043:   margin: 0.2em 0 0 0;
 7044:   padding: 0;
 7045:   font-weight: bold;
 7046:   text-align: center;
 7047:   background-color: $pgbg_or_bgcolor;
 7048: }
 7049: 
 7050: #LC_nav_bar em {
 7051:   font-weight: bold;
 7052:   font-style: normal;
 7053: }
 7054: 
 7055: ol.LC_primary_menu {
 7056:   margin: 0;
 7057:   padding: 0;
 7058: }
 7059: 
 7060: ol#LC_PathBreadcrumbs {
 7061:   margin: 0;
 7062: }
 7063: 
 7064: ol.LC_primary_menu li {
 7065:   color: RGB(80, 80, 80);
 7066:   vertical-align: middle;
 7067:   text-align: left;
 7068:   list-style: none;
 7069:   position: relative;
 7070:   float: left;
 7071:   z-index: 100; /* will be displayed above codemirror and underneath the help-layer */
 7072:   line-height: 1.5em;
 7073: }
 7074: 
 7075: ol.LC_primary_menu li a, 
 7076: ol.LC_primary_menu li p {
 7077:   display: block;
 7078:   margin: 0;
 7079:   padding: 0 5px 0 10px;
 7080:   text-decoration: none;
 7081: }
 7082: 
 7083: ol.LC_primary_menu li p span.LC_primary_menu_innertitle {
 7084:   display: inline-block;
 7085:   width: 95%;
 7086:   text-align: left;
 7087: }
 7088: 
 7089: ol.LC_primary_menu li p span.LC_primary_menu_innerarrow {
 7090:   display: inline-block;
 7091:   width: 5%;
 7092:   float: right;
 7093:   text-align: right;
 7094:   font-size: 70%;
 7095: }
 7096: 
 7097: ol.LC_primary_menu ul {
 7098:   display: none;
 7099:   width: 15em;
 7100:   background-color: $data_table_light;
 7101:   position: absolute;
 7102:   top: 100%;
 7103: }
 7104: 
 7105: ol.LC_primary_menu ul ul {
 7106:   left: 100%;
 7107:   top: 0;
 7108: }
 7109: 
 7110: ol.LC_primary_menu li:hover > ul, ol.LC_primary_menu li.hover > ul {
 7111:   display: block;
 7112:   position: absolute;
 7113:   margin: 0;
 7114:   padding: 0;
 7115:   z-index: 2;
 7116: }
 7117: 
 7118: ol.LC_primary_menu li:hover li, ol.LC_primary_menu li.hover li {
 7119: /* First Submenu -> size should be smaller than the menu title of the whole menu */
 7120:   font-size: 90%;
 7121:   vertical-align: top;
 7122:   float: none;
 7123:   border-left: 1px solid black;
 7124:   border-right: 1px solid black;
 7125: /* A dark bottom border to visualize different menu options;
 7126: overwritten in the create_submenu routine for the last border-bottom of the menu */
 7127:   border-bottom: 1px solid $data_table_dark;
 7128: }
 7129: 
 7130: ol.LC_primary_menu li li p:hover {
 7131:   color:$button_hover;
 7132:   text-decoration:none;
 7133:   background-color:$data_table_dark;
 7134: }
 7135: 
 7136: ol.LC_primary_menu li li a:hover {
 7137:    color:$button_hover;
 7138:    background-color:$data_table_dark;
 7139: }
 7140: 
 7141: /* Font-size equal to the size of the predecessors*/
 7142: ol.LC_primary_menu li:hover li li {
 7143:   font-size: 100%;
 7144: }
 7145: 
 7146: ol.LC_primary_menu li img {
 7147:   vertical-align: bottom;
 7148:   height: 1.1em;
 7149:   margin: 0.2em 0 0 0;
 7150: }
 7151: 
 7152: ol.LC_primary_menu a {
 7153:   color: RGB(80, 80, 80);
 7154:   text-decoration: none;
 7155: }
 7156: 
 7157: ol.LC_primary_menu a.LC_new_message {
 7158:   font-weight:bold;
 7159:   color: darkred;
 7160: }
 7161: 
 7162: ol.LC_docs_parameters {
 7163:   margin-left: 0;
 7164:   padding: 0;
 7165:   list-style: none;
 7166: }
 7167: 
 7168: ol.LC_docs_parameters li {
 7169:   margin: 0;
 7170:   padding-right: 20px;
 7171:   display: inline;
 7172: }
 7173: 
 7174: ol.LC_docs_parameters li:before {
 7175:   content: "\\002022 \\0020";
 7176: }
 7177: 
 7178: li.LC_docs_parameters_title {
 7179:   font-weight: bold;
 7180: }
 7181: 
 7182: ol.LC_docs_parameters li.LC_docs_parameters_title:before {
 7183:   content: "";
 7184: }
 7185: 
 7186: ul#LC_secondary_menu {
 7187:   clear: right;
 7188:   color: $fontmenu;
 7189:   background: $tabbg;
 7190:   list-style: none;
 7191:   padding: 0;
 7192:   margin: 0;
 7193:   width: 100%;
 7194:   text-align: left;
 7195:   float: left;
 7196: }
 7197: 
 7198: ul#LC_secondary_menu li {
 7199:   font-weight: bold;
 7200:   line-height: 1.8em;
 7201:   border-right: 1px solid black;
 7202:   float: left;
 7203: }
 7204: 
 7205: ul#LC_secondary_menu li.LC_hoverable:hover, ul#LC_secondary_menu li.hover {
 7206:   background-color: $data_table_light;
 7207: }
 7208: 
 7209: ul#LC_secondary_menu li a {
 7210:   padding: 0 0.8em;
 7211: }
 7212: 
 7213: ul#LC_secondary_menu li ul {
 7214:   display: none;
 7215: }
 7216: 
 7217: ul#LC_secondary_menu li:hover ul, ul#LC_secondary_menu li.hover ul {
 7218:   display: block;
 7219:   position: absolute;
 7220:   margin: 0;
 7221:   padding: 0;
 7222:   list-style:none;
 7223:   float: none;
 7224:   background-color: $data_table_light;
 7225:   z-index: 2;
 7226:   margin-left: -1px;
 7227: }
 7228: 
 7229: ul#LC_secondary_menu li ul li {
 7230:   font-size: 90%;
 7231:   vertical-align: top;
 7232:   border-left: 1px solid black;
 7233:   border-right: 1px solid black;
 7234:   background-color: $data_table_light;
 7235:   list-style:none;
 7236:   float: none;
 7237: }
 7238: 
 7239: ul#LC_secondary_menu li ul li:hover, ul#LC_secondary_menu li ul li.hover {
 7240:   background-color: $data_table_dark;
 7241: }
 7242: 
 7243: ul.LC_TabContent {
 7244:   display:block;
 7245:   background: $sidebg;
 7246:   border-bottom: solid 1px $lg_border_color;
 7247:   list-style:none;
 7248:   margin: -1px -10px 0 -10px;
 7249:   padding: 0;
 7250: }
 7251: 
 7252: ul.LC_TabContent li,
 7253: ul.LC_TabContentBigger li {
 7254:   float:left;
 7255: }
 7256: 
 7257: ul#LC_secondary_menu li a {
 7258:   color: $fontmenu;
 7259:   text-decoration: none;
 7260: }
 7261: 
 7262: ul.LC_TabContent {
 7263:   min-height:20px;
 7264: }
 7265: 
 7266: ul.LC_TabContent li {
 7267:   vertical-align:middle;
 7268:   padding: 0 16px 0 10px;
 7269:   background-color:$tabbg;
 7270:   border-bottom:solid 1px $lg_border_color;
 7271:   border-left: solid 1px $font;
 7272: }
 7273: 
 7274: ul.LC_TabContent .right {
 7275:   float:right;
 7276: }
 7277: 
 7278: ul.LC_TabContent li a,
 7279: ul.LC_TabContent li {
 7280:   color:rgb(47,47,47);
 7281:   text-decoration:none;
 7282:   font-size:95%;
 7283:   font-weight:bold;
 7284:   min-height:20px;
 7285: }
 7286: 
 7287: ul.LC_TabContent li a:hover,
 7288: ul.LC_TabContent li a:focus {
 7289:   color: $button_hover;
 7290:   background:none;
 7291:   outline:none;
 7292: }
 7293: 
 7294: ul.LC_TabContent li:hover {
 7295:   color: $button_hover;
 7296:   cursor:pointer;
 7297: }
 7298: 
 7299: ul.LC_TabContent li.active {
 7300:   color: $font;
 7301:   background:#FFFFFF url(/adm/lonIcons/open.gif) no-repeat scroll right center;
 7302:   border-bottom:solid 1px #FFFFFF;
 7303:   cursor: default;
 7304: }
 7305: 
 7306: ul.LC_TabContent li.active a {
 7307:   color:$font;
 7308:   background:#FFFFFF;
 7309:   outline: none;
 7310: }
 7311: 
 7312: ul.LC_TabContent li.goback {
 7313:   float: left;
 7314:   border-left: none;
 7315: }
 7316: 
 7317: #maincoursedoc {
 7318:   clear:both;
 7319: }
 7320: 
 7321: ul.LC_TabContentBigger {
 7322:   display:block;
 7323:   list-style:none;
 7324:   padding: 0;
 7325: }
 7326: 
 7327: ul.LC_TabContentBigger li {
 7328:   vertical-align:bottom;
 7329:   height: 30px;
 7330:   font-size:110%;
 7331:   font-weight:bold;
 7332:   color: #737373;
 7333: }
 7334: 
 7335: ul.LC_TabContentBigger li.active {
 7336:   position: relative;
 7337:   top: 1px;
 7338: }
 7339: 
 7340: ul.LC_TabContentBigger li a {
 7341:   background:url('/adm/lonIcons/tabbgleft.gif') left bottom no-repeat;
 7342:   height: 30px;
 7343:   line-height: 30px;
 7344:   text-align: center;
 7345:   display: block;
 7346:   text-decoration: none;
 7347:   outline: none;  
 7348: }
 7349: 
 7350: ul.LC_TabContentBigger li.active a {
 7351:   background:url('/adm/lonIcons/tabbgleft.gif') left top no-repeat;
 7352:   color:$font;
 7353: }
 7354: 
 7355: ul.LC_TabContentBigger li b {
 7356:   background: url('/adm/lonIcons/tabbgright.gif') no-repeat right bottom;
 7357:   display: block;
 7358:   float: left;
 7359:   padding: 0 30px;
 7360:   border-bottom: 1px solid $lg_border_color;
 7361: }
 7362: 
 7363: ul.LC_TabContentBigger li:hover b {
 7364:   color:$button_hover;
 7365: }
 7366: 
 7367: ul.LC_TabContentBigger li.active b {
 7368:   background:url('/adm/lonIcons/tabbgright.gif') right top no-repeat;
 7369:   color:$font;
 7370:   border: 0;
 7371: }
 7372: 
 7373: 
 7374: ul.LC_CourseBreadcrumbs {
 7375:   background: $sidebg;
 7376:   height: 2em;
 7377:   padding-left: 10px;
 7378:   margin: 0;
 7379:   list-style-position: inside;
 7380: }
 7381: 
 7382: ol#LC_MenuBreadcrumbs,
 7383: ol#LC_PathBreadcrumbs {
 7384:   padding-left: 10px;
 7385:   margin: 0;
 7386:   height: 2.5em;  /* equal to #LC_breadcrumbs line-height */
 7387: }
 7388: 
 7389: ol#LC_MenuBreadcrumbs li,
 7390: ol#LC_PathBreadcrumbs li,
 7391: ul.LC_CourseBreadcrumbs li {
 7392:   display: inline;
 7393:   white-space: normal;  
 7394: }
 7395: 
 7396: ol#LC_MenuBreadcrumbs li a,
 7397: ul.LC_CourseBreadcrumbs li a {
 7398:   text-decoration: none;
 7399:   font-size:90%;
 7400: }
 7401: 
 7402: ol#LC_MenuBreadcrumbs h1 {
 7403:   display: inline;
 7404:   font-size: 90%;
 7405:   line-height: 2.5em;
 7406:   margin: 0;
 7407:   padding: 0;
 7408: }
 7409: 
 7410: ol#LC_PathBreadcrumbs li a {
 7411:   text-decoration:none;
 7412:   font-size:100%;
 7413:   font-weight:bold;
 7414: }
 7415: 
 7416: .LC_Box {
 7417:   border: solid 1px $lg_border_color;
 7418:   padding: 0 10px 10px 10px;
 7419: }
 7420: 
 7421: .LC_DocsBox {
 7422:   border: solid 1px $lg_border_color;
 7423:   padding: 0 0 10px 10px;
 7424: }
 7425: 
 7426: .LC_AboutMe_Image {
 7427:   float:left;
 7428:   margin-right:10px;
 7429: }
 7430: 
 7431: .LC_Clear_AboutMe_Image {
 7432:   clear:left;
 7433: }
 7434: 
 7435: dl.LC_ListStyleClean dt {
 7436:   padding-right: 5px;
 7437:   display: table-header-group;
 7438: }
 7439: 
 7440: dl.LC_ListStyleClean dd {
 7441:   display: table-row;
 7442: }
 7443: 
 7444: .LC_ListStyleClean,
 7445: .LC_ListStyleSimple,
 7446: .LC_ListStyleNormal,
 7447: .LC_ListStyleSpecial {
 7448:   /* display:block; */
 7449:   list-style-position: inside;
 7450:   list-style-type: none;
 7451:   overflow: hidden;
 7452:   padding: 0;
 7453: }
 7454: 
 7455: .LC_ListStyleSimple li,
 7456: .LC_ListStyleSimple dd,
 7457: .LC_ListStyleNormal li,
 7458: .LC_ListStyleNormal dd,
 7459: .LC_ListStyleSpecial li,
 7460: .LC_ListStyleSpecial dd {
 7461:   margin: 0;
 7462:   padding: 5px 5px 5px 10px;
 7463:   clear: both;
 7464: }
 7465: 
 7466: .LC_ListStyleClean li,
 7467: .LC_ListStyleClean dd {
 7468:   padding-top: 0;
 7469:   padding-bottom: 0;
 7470: }
 7471: 
 7472: .LC_ListStyleSimple dd,
 7473: .LC_ListStyleSimple li {
 7474:   border-bottom: solid 1px $lg_border_color;
 7475: }
 7476: 
 7477: .LC_ListStyleSpecial li,
 7478: .LC_ListStyleSpecial dd {
 7479:   list-style-type: none;
 7480:   background-color: RGB(220, 220, 220);
 7481:   margin-bottom: 4px;
 7482: }
 7483: 
 7484: table.LC_SimpleTable {
 7485:   margin:5px;
 7486:   border:solid 1px $lg_border_color;
 7487: }
 7488: 
 7489: table.LC_SimpleTable tr {
 7490:   padding: 0;
 7491:   border:solid 1px $lg_border_color;
 7492: }
 7493: 
 7494: table.LC_SimpleTable thead {
 7495:   background:rgb(220,220,220);
 7496: }
 7497: 
 7498: div.LC_columnSection {
 7499:   display: block;
 7500:   clear: both;
 7501:   overflow: hidden;
 7502:   margin: 0;
 7503: }
 7504: 
 7505: div.LC_columnSection>* {
 7506:   float: left;
 7507:   margin: 10px 20px 10px 0;
 7508:   overflow:hidden;
 7509: }
 7510: 
 7511: table em {
 7512:   font-weight: bold;
 7513:   font-style: normal;
 7514: }
 7515: 
 7516: table.LC_tableBrowseRes,
 7517: table.LC_tableOfContent {
 7518:   border:none;
 7519:   border-spacing: 1px;
 7520:   padding: 3px;
 7521:   background-color: #FFFFFF;
 7522:   font-size: 90%;
 7523: }
 7524: 
 7525: table.LC_tableOfContent {
 7526:   border-collapse: collapse;
 7527: }
 7528: 
 7529: table.LC_tableBrowseRes a,
 7530: table.LC_tableOfContent a {
 7531:   background-color: transparent;
 7532:   text-decoration: none;
 7533: }
 7534: 
 7535: table.LC_tableOfContent img {
 7536:   border: none;
 7537:   height: 1.3em;
 7538:   vertical-align: text-bottom;
 7539:   margin-right: 0.3em;
 7540: }
 7541: 
 7542: a#LC_content_toolbar_firsthomework {
 7543:   background-image:url(/res/adm/pages/open-first-problem.gif);
 7544: }
 7545: 
 7546: a#LC_content_toolbar_everything {
 7547:   background-image:url(/res/adm/pages/show-all.gif);
 7548: }
 7549: 
 7550: a#LC_content_toolbar_uncompleted {
 7551:   background-image:url(/res/adm/pages/show-incomplete-problems.gif);
 7552: }
 7553: 
 7554: #LC_content_toolbar_clearbubbles {
 7555:   background-image:url(/res/adm/pages/mark-discussionentries-read.gif);
 7556: }
 7557: 
 7558: a#LC_content_toolbar_changefolder {
 7559:   background : url(/res/adm/pages/close-all-folders.gif) top center ;
 7560: }
 7561: 
 7562: a#LC_content_toolbar_changefolder_toggled {
 7563:   background-image:url(/res/adm/pages/open-all-folders.gif);
 7564: }
 7565: 
 7566: a#LC_content_toolbar_edittoplevel {
 7567:   background-image:url(/res/adm/pages/edittoplevel.gif);
 7568: }
 7569: 
 7570: ul#LC_toolbar li a:hover {
 7571:   background-position: bottom center;
 7572: }
 7573: 
 7574: ul#LC_toolbar {
 7575:   padding: 0;
 7576:   margin: 2px;
 7577:   list-style:none;
 7578:   position:relative;
 7579:   background-color:white;
 7580:   overflow: auto;
 7581: }
 7582: 
 7583: ul#LC_toolbar li {
 7584:   border:1px solid white;
 7585:   padding: 0;
 7586:   margin: 0;
 7587:   float: left;
 7588:   display:inline;
 7589:   vertical-align:middle;
 7590:   white-space: nowrap;
 7591: }
 7592: 
 7593: 
 7594: a.LC_toolbarItem {
 7595:   display:block;
 7596:   padding: 0;
 7597:   margin: 0;
 7598:   height: 32px;
 7599:   width: 32px;
 7600:   color:white;
 7601:   border: none;
 7602:   background-repeat:no-repeat;
 7603:   background-color:transparent;
 7604: }
 7605: 
 7606: ul.LC_funclist {
 7607:     margin: 0;
 7608:     padding: 0.5em 1em 0.5em 0;
 7609: }
 7610: 
 7611: ul.LC_funclist > li:first-child {
 7612:     font-weight:bold; 
 7613:     margin-left:0.8em;
 7614: }
 7615: 
 7616: ul.LC_funclist + ul.LC_funclist {
 7617:     /* 
 7618:        left border as a seperator if we have more than
 7619:        one list 
 7620:     */
 7621:     border-left: 1px solid $sidebg;
 7622:     /* 
 7623:        this hides the left border behind the border of the 
 7624:        outer box if element is wrapped to the next 'line' 
 7625:     */
 7626:     margin-left: -1px;
 7627: }
 7628: 
 7629: ul.LC_funclist li {
 7630:   display: inline;
 7631:   white-space: nowrap;
 7632:   margin: 0 0 0 25px;
 7633:   line-height: 150%;
 7634: }
 7635: 
 7636: .LC_hidden {
 7637:   display: none;
 7638: }
 7639: 
 7640: .LCmodal-overlay {
 7641: 		position:fixed;
 7642: 		top:0;
 7643: 		right:0;
 7644: 		bottom:0;
 7645: 		left:0;
 7646: 		height:100%;
 7647: 		width:100%;
 7648: 		margin:0;
 7649: 		padding:0;
 7650: 		background:#999;
 7651: 		opacity:.75;
 7652: 		filter: alpha(opacity=75);
 7653: 		-moz-opacity: 0.75;
 7654: 		z-index:101;
 7655: }
 7656: 
 7657: * html .LCmodal-overlay {   
 7658: 		position: absolute;
 7659: 		height: expression(document.body.scrollHeight > document.body.offsetHeight ? document.body.scrollHeight : document.body.offsetHeight + 'px');
 7660: }
 7661: 
 7662: .LCmodal-window {
 7663: 		position:fixed;
 7664: 		top:50%;
 7665: 		left:50%;
 7666: 		margin:0;
 7667: 		padding:0;
 7668: 		z-index:102;
 7669: 	}
 7670: 
 7671: * html .LCmodal-window {
 7672: 		position:absolute;
 7673: }
 7674: 
 7675: .LCclose-window {
 7676: 		position:absolute;
 7677: 		width:32px;
 7678: 		height:32px;
 7679: 		right:8px;
 7680: 		top:8px;
 7681: 		background:transparent url('/res/adm/pages/process-stop.png') no-repeat scroll right top;
 7682: 		text-indent:-99999px;
 7683: 		overflow:hidden;
 7684: 		cursor:pointer;
 7685: }
 7686: 
 7687: /*
 7688:   styles used by TTH when "Default set of options to pass to tth/m
 7689:   when converting TeX" in course settings has been set
 7690: 
 7691:   option passed: -t
 7692: 
 7693: */
 7694: 
 7695: td div.comp { margin-top: -0.6ex; margin-bottom: -1ex;}
 7696: td div.comb { margin-top: -0.6ex; margin-bottom: -.6ex;}
 7697: td div.hrcomp { line-height: 0.9; margin-top: -0.8ex; margin-bottom: -1ex;}
 7698: td div.norm {line-height:normal;}
 7699: 
 7700: /*
 7701:   option passed -y3
 7702: */
 7703: 
 7704: span.roman {font-family: serif; font-style: normal; font-weight: normal;}
 7705: span.overacc2 {position: relative;  left: .8em; top: -1.2ex;}
 7706: span.overacc1 {position: relative;  left: .6em; top: -1.2ex;}
 7707: 
 7708: #LC_minitab_header {
 7709:   float:left;
 7710:   width:100%;
 7711:   background:#DAE0D2 url("/res/adm/pages/minitabmenu_bg.gif") repeat-x bottom;
 7712:   font-size:93%;
 7713:   line-height:normal;
 7714:   margin: 0.5em 0 0.5em 0;
 7715: }
 7716: #LC_minitab_header ul {
 7717:   margin:0;
 7718:   padding:10px 10px 0;
 7719:   list-style:none;
 7720: }
 7721: #LC_minitab_header li {
 7722:   float:left;
 7723:   background:url("/res/adm/pages/minitabmenu_left.gif") no-repeat left top;
 7724:   margin:0;
 7725:   padding:0 0 0 9px;
 7726: }
 7727: #LC_minitab_header a {
 7728:   display:block;
 7729:   background:url("/res/adm/pages/minitabmenu_right.gif") no-repeat right top;
 7730:   padding:5px 15px 4px 6px;
 7731: }
 7732: #LC_minitab_header #LC_current_minitab {
 7733:   background-image:url("/res/adm/pages/minitabmenu_left_on.gif");
 7734: }
 7735: #LC_minitab_header #LC_current_minitab a {
 7736:   background-image:url("/res/adm/pages/minitabmenu_right_on.gif");
 7737:   padding-bottom:5px;
 7738: }
 7739: 
 7740: 
 7741: END
 7742: }
 7743: 
 7744: =pod
 7745: 
 7746: =item * &headtag()
 7747: 
 7748: Returns a uniform footer for LON-CAPA web pages.
 7749: 
 7750: Inputs: $title - optional title for the head
 7751:         $head_extra - optional extra HTML to put inside the <head>
 7752:         $args - optional arguments
 7753:             force_register - if is true call registerurl so the remote is 
 7754:                              informed
 7755:             redirect       -> array ref of
 7756:                                    1- seconds before redirect occurs
 7757:                                    2- url to redirect to
 7758:                                    3- whether the side effect should occur
 7759:                            (side effect of setting 
 7760:                                $env{'internal.head.redirect'} to the url 
 7761:                                redirected too)
 7762:             domain         -> force to color decorate a page for a specific
 7763:                                domain
 7764:             function       -> force usage of a specific rolish color scheme
 7765:             bgcolor        -> override the default page bgcolor
 7766:             no_auto_mt_title
 7767:                            -> prevent &mt()ing the title arg
 7768: 
 7769: =cut
 7770: 
 7771: sub headtag {
 7772:     my ($title,$head_extra,$args) = @_;
 7773:     
 7774:     my $function = $args->{'function'} || &get_users_function();
 7775:     my $domain   = $args->{'domain'}   || &determinedomain();
 7776:     my $bgcolor  = $args->{'bgcolor'}  || &designparm($function.'.pgbg',$domain);
 7777:     my $httphost = $args->{'use_absolute'};
 7778:     my $url = join(':',$env{'user.name'},$env{'user.domain'},
 7779: 		   $Apache::lonnet::perlvar{'lonVersion'},
 7780: 		   #time(),
 7781: 		   $env{'environment.color.timestamp'},
 7782: 		   $function,$domain,$bgcolor);
 7783: 
 7784:     $url = '/adm/css/'.&escape($url).'.css';
 7785: 
 7786:     my $result =
 7787: 	'<head>'.
 7788: 	&font_settings($args);
 7789: 
 7790:     my $inhibitprint;
 7791:     if ($args->{'print_suppress'}) {
 7792:         $inhibitprint = &print_suppression();
 7793:     }
 7794: 
 7795:     if (!$args->{'frameset'}) {
 7796: 	$result .= &Apache::lonhtmlcommon::htmlareaheaders();
 7797:     }
 7798:     if ($args->{'force_register'}) {
 7799:         $result .= &Apache::lonmenu::registerurl(1);
 7800:     }
 7801:     if (!$args->{'no_nav_bar'} 
 7802: 	&& !$args->{'only_body'}
 7803: 	&& !$args->{'frameset'}) {
 7804: 	$result .= &help_menu_js($httphost);
 7805:         $result.=&modal_window();
 7806:         $result.=&togglebox_script();
 7807:         $result.=&wishlist_window();
 7808:         $result.=&LCprogressbarUpdate_script();
 7809:     } else {
 7810:         if ($args->{'add_modal'}) {
 7811:            $result.=&modal_window();
 7812:         }
 7813:         if ($args->{'add_wishlist'}) {
 7814:            $result.=&wishlist_window();
 7815:         }
 7816:         if ($args->{'add_togglebox'}) {
 7817:            $result.=&togglebox_script();
 7818:         }
 7819:         if ($args->{'add_progressbar'}) {
 7820:            $result.=&LCprogressbarUpdate_script();
 7821:         }
 7822:     }
 7823:     if (ref($args->{'redirect'})) {
 7824: 	my ($time,$url,$inhibit_continue) = @{$args->{'redirect'}};
 7825: 	$url = &Apache::lonenc::check_encrypt($url);
 7826: 	if (!$inhibit_continue) {
 7827: 	    $env{'internal.head.redirect'} = $url;
 7828: 	}
 7829: 	$result.=<<ADDMETA
 7830: <meta http-equiv="pragma" content="no-cache" />
 7831: <meta http-equiv="Refresh" content="$time; url=$url" />
 7832: ADDMETA
 7833:     } else {
 7834:         unless (($args->{'frameset'}) || ($args->{'js_ready'}) || ($args->{'only_body'}) || ($args->{'no_nav_bar'})) {
 7835:             my $requrl = $env{'request.uri'};
 7836:             if ($requrl eq '') {
 7837:                 $requrl = $ENV{'REQUEST_URI'};
 7838:                 $requrl =~ s/\?.+$//;
 7839:             }
 7840:             unless (($requrl =~ m{^/adm/(?:switchserver|login|authenticate|logout|groupsort|cleanup|helper|slotrequest|grades)(\?|$)}) ||
 7841:                     (($requrl =~ m{^/res/}) && (($env{'form.submitted'} eq 'scantron') ||
 7842:                      ($env{'form.grade_symb'}) || ($Apache::lonhomework::scantronmode)))) {
 7843:                 my $dom_in_use = $Apache::lonnet::perlvar{'lonDefDomain'};
 7844:                 unless (&Apache::lonnet::allowed('mau',$dom_in_use)) {
 7845:                     my %domdefs = &Apache::lonnet::get_domain_defaults($dom_in_use);
 7846:                     if (ref($domdefs{'offloadnow'}) eq 'HASH') {
 7847:                         my $lonhost = $Apache::lonnet::perlvar{'lonHostID'};
 7848:                         if ($domdefs{'offloadnow'}{$lonhost}) {
 7849:                             my $newserver = &Apache::lonnet::spareserver(30000,undef,1,$dom_in_use);
 7850:                             if (($newserver) && ($newserver ne $lonhost)) {
 7851:                                 my $numsec = 5;
 7852:                                 my $timeout = $numsec * 1000;
 7853:                                 my ($newurl,$locknum,%locks,$msg);
 7854:                                 if ($env{'request.role.adv'}) {
 7855:                                     ($locknum,%locks) = &Apache::lonnet::get_locks();
 7856:                                 }
 7857:                                 my $disable_submit = 0;
 7858:                                 if ($requrl =~ /$LONCAPA::assess_re/) {
 7859:                                     $disable_submit = 1;
 7860:                                 }
 7861:                                 if ($locknum) {
 7862:                                     my @lockinfo = sort(values(%locks));
 7863:                                     $msg = &mt('Once the following tasks are complete: ')."\\n".
 7864:                                            join(", ",sort(values(%locks)))."\\n".
 7865:                                            &mt('your session will be transferred to a different server, after you click "Roles".');
 7866:                                 } else {
 7867:                                     if (($requrl =~ m{^/res/}) && ($env{'form.submitted'} =~ /^part_/)) {
 7868:                                         $msg = &mt('Your LON-CAPA submission has been recorded')."\\n";
 7869:                                     }
 7870:                                     $msg .= &mt('Your current LON-CAPA session will be transferred to a different server in [quant,_1,second].',$numsec);
 7871:                                     $newurl = '/adm/switchserver?otherserver='.$newserver;
 7872:                                     if (($env{'request.role'}) && ($env{'request.role'} ne 'cm')) {
 7873:                                         $newurl .= '&role='.$env{'request.role'};
 7874:                                     }
 7875:                                     if ($env{'request.symb'}) {
 7876:                                         $newurl .= '&symb='.$env{'request.symb'};
 7877:                                     } else {
 7878:                                         $newurl .= '&origurl='.$requrl;
 7879:                                     }
 7880:                                 }
 7881:                                 &js_escape(\$msg);
 7882:                                 $result.=<<OFFLOAD
 7883: <meta http-equiv="pragma" content="no-cache" />
 7884: <script type="text/javascript">
 7885: // <![CDATA[
 7886: function LC_Offload_Now() {
 7887:     var dest = "$newurl";
 7888:     if (dest != '') {
 7889:         window.location.href="$newurl";
 7890:     }
 7891: }
 7892: \$(document).ready(function () {
 7893:     window.alert('$msg');
 7894:     if ($disable_submit) {
 7895:         \$(".LC_hwk_submit").prop("disabled", true);
 7896:         \$( ".LC_textline" ).prop( "readonly", "readonly");
 7897:     }
 7898:     setTimeout('LC_Offload_Now()', $timeout);
 7899: });
 7900: // ]]>
 7901: </script>
 7902: OFFLOAD
 7903:                             }
 7904:                         }
 7905:                     }
 7906:                 }
 7907:             }
 7908:         }
 7909:     }
 7910:     if (!defined($title)) {
 7911: 	$title = 'The LearningOnline Network with CAPA';
 7912:     }
 7913:     if (!$args->{'no_auto_mt_title'}) { $title = &mt($title); }
 7914:     $result .= '<title> LON-CAPA '.$title.'</title>'
 7915: 	.'<link rel="stylesheet" type="text/css" href="'.$url.'"';
 7916:     if (!$args->{'frameset'}) {
 7917:         $result .= ' /';
 7918:     }
 7919:     $result .= '>'
 7920:         .$inhibitprint
 7921: 	.$head_extra;
 7922:     my $clientmobile;
 7923:     if (($env{'user.name'} eq '') && ($env{'user.domain'} eq '')) {
 7924:         (undef,undef,undef,undef,undef,undef,$clientmobile) = &decode_user_agent();
 7925:     } else {
 7926:         $clientmobile = $env{'browser.mobile'};
 7927:     }
 7928:     if ($clientmobile) {
 7929:         $result .= '
 7930: <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=0, minimum-scale=1.0, maximum-scale=1.0">
 7931: <meta name="apple-mobile-web-app-capable" content="yes" />';
 7932:     }
 7933:     $result .= '<meta name="google" content="notranslate" />'."\n";
 7934:     return $result.'</head>';
 7935: }
 7936: 
 7937: =pod
 7938: 
 7939: =item * &font_settings()
 7940: 
 7941: Returns neccessary <meta> to set the proper encoding
 7942: 
 7943: Inputs: optional reference to HASH -- $args passed to &headtag()
 7944: 
 7945: =cut
 7946: 
 7947: sub font_settings {
 7948:     my ($args) = @_;
 7949:     my $headerstring='';
 7950:     if ((!$env{'browser.mathml'} && $env{'browser.unicode'}) ||
 7951:         ((ref($args) eq 'HASH') && ($args->{'browser.unicode'}))) {
 7952: 	$headerstring.=
 7953: 	    '<meta http-equiv="Content-Type" content="text/html; charset=utf-8"';
 7954:         if (!$args->{'frameset'}) {
 7955:             $headerstring.= ' /';
 7956:         }
 7957:         $headerstring .= '>'."\n";
 7958:     }
 7959:     return $headerstring;
 7960: }
 7961: 
 7962: =pod
 7963: 
 7964: =item * &print_suppression()
 7965: 
 7966: In course context returns css which causes the body to be blank when media="print",
 7967: if printout generation is unavailable for the current resource.
 7968: 
 7969: This could be because:
 7970: 
 7971: (a) printstartdate is in the future
 7972: 
 7973: (b) printenddate is in the past
 7974: 
 7975: (c) there is an active exam block with "printout"
 7976: functionality blocked
 7977: 
 7978: Users with pav, pfo or evb privileges are exempt.
 7979: 
 7980: Inputs: none
 7981: 
 7982: =cut
 7983: 
 7984: 
 7985: sub print_suppression {
 7986:     my $noprint;
 7987:     if ($env{'request.course.id'}) {
 7988:         my $scope = $env{'request.course.id'};
 7989:         if ((&Apache::lonnet::allowed('pav',$scope)) ||
 7990:             (&Apache::lonnet::allowed('pfo',$scope))) {
 7991:             return;
 7992:         }
 7993:         if ($env{'request.course.sec'} ne '') {
 7994:             $scope .= "/$env{'request.course.sec'}";
 7995:             if ((&Apache::lonnet::allowed('pav',$scope)) ||
 7996:                 (&Apache::lonnet::allowed('pfo',$scope))) {
 7997:                 return;
 7998:             }
 7999:         }
 8000:         my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 8001:         my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 8002:         my $blocked = &blocking_status('printout',$cnum,$cdom,undef,1);
 8003:         if ($blocked) {
 8004:             my $checkrole = "cm./$cdom/$cnum";
 8005:             if ($env{'request.course.sec'} ne '') {
 8006:                 $checkrole .= "/$env{'request.course.sec'}";
 8007:             }
 8008:             unless ((&Apache::lonnet::allowed('evb',undef,undef,$checkrole)) &&
 8009:                     ($env{'request.role'} !~ m{^st\./$cdom/$cnum})) {
 8010:                 $noprint = 1;
 8011:             }
 8012:         }
 8013:         unless ($noprint) {
 8014:             my $symb = &Apache::lonnet::symbread();
 8015:             if ($symb ne '') {
 8016:                 my $navmap = Apache::lonnavmaps::navmap->new();
 8017:                 if (ref($navmap)) {
 8018:                     my $res = $navmap->getBySymb($symb);
 8019:                     if (ref($res)) {
 8020:                         if (!$res->resprintable()) {
 8021:                             $noprint = 1;
 8022:                         }
 8023:                     }
 8024:                 }
 8025:             }
 8026:         }
 8027:         if ($noprint) {
 8028:             return <<"ENDSTYLE";
 8029: <style type="text/css" media="print">
 8030:     body { display:none }
 8031: </style>
 8032: ENDSTYLE
 8033:         }
 8034:     }
 8035:     return;
 8036: }
 8037: 
 8038: =pod
 8039: 
 8040: =item * &xml_begin()
 8041: 
 8042: Returns the needed doctype and <html>
 8043: 
 8044: Inputs: none
 8045: 
 8046: =cut
 8047: 
 8048: sub xml_begin {
 8049:     my ($is_frameset) = @_;
 8050:     my $output='';
 8051: 
 8052:     if ($env{'browser.mathml'}) {
 8053: 	$output='<?xml version="1.0"?>'
 8054:             #.'<?xml-stylesheet type="text/css" href="/adm/MathML/mathml.css"?>'."\n"
 8055: #            .'<!DOCTYPE html SYSTEM "/adm/MathML/mathml.dtd" '
 8056:             
 8057: #	    .'<!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">] >'
 8058: 	    .'<!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">'
 8059:             .'<html xmlns:math="http://www.w3.org/1998/Math/MathML" ' 
 8060: 	    .'xmlns="http://www.w3.org/1999/xhtml">';
 8061:     } elsif ($is_frameset) {
 8062:         $output='<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Frameset//EN" "http://www.w3.org/TR/html4/frameset.dtd">'."\n".
 8063:                 '<html>'."\n";
 8064:     } else {
 8065: 	$output='<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">'."\n".
 8066:                 '<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">'."\n";
 8067:     }
 8068:     return $output;
 8069: }
 8070: 
 8071: =pod
 8072: 
 8073: =item * &start_page()
 8074: 
 8075: Returns a complete <html> .. <body> section for LON-CAPA web pages.
 8076: 
 8077: Inputs:
 8078: 
 8079: =over 4
 8080: 
 8081: $title - optional title for the page
 8082: 
 8083: $head_extra - optional extra HTML to incude inside the <head>
 8084: 
 8085: $args - additional optional args supported are:
 8086: 
 8087: =over 8
 8088: 
 8089:              only_body      -> is true will set &bodytag() onlybodytag
 8090:                                     arg on
 8091:              no_nav_bar     -> is true will set &bodytag() no_nav_bar arg on
 8092:              add_entries    -> additional attributes to add to the  <body>
 8093:              domain         -> force to color decorate a page for a 
 8094:                                     specific domain
 8095:              function       -> force usage of a specific rolish color
 8096:                                     scheme
 8097:              redirect       -> see &headtag()
 8098:              bgcolor        -> override the default page bg color
 8099:              js_ready       -> return a string ready for being used in 
 8100:                                     a javascript writeln
 8101:              html_encode    -> return a string ready for being used in 
 8102:                                     a html attribute
 8103:              force_register -> if is true will turn on the &bodytag()
 8104:                                     $forcereg arg
 8105:              frameset       -> if true will start with a <frameset>
 8106:                                     rather than <body>
 8107:              skip_phases    -> hash ref of 
 8108:                                     head -> skip the <html><head> generation
 8109:                                     body -> skip all <body> generation
 8110:              no_inline_link -> if true and in remote mode, don't show the
 8111:                                     'Switch To Inline Menu' link
 8112:              no_auto_mt_title -> prevent &mt()ing the title arg
 8113:              bread_crumbs ->             Array containing breadcrumbs
 8114:              bread_crumbs_component ->  if exists show it as headline else show only the breadcrumbs
 8115:              bread_crumbs_nomenu -> if true will pass false as the value of $menulink
 8116:                                     to lonhtmlcommon::breadcrumbs
 8117:              group          -> includes the current group, if page is for a
 8118:                                specific group
 8119: 
 8120: =back
 8121: 
 8122: =back
 8123: 
 8124: =cut
 8125: 
 8126: sub start_page {
 8127:     my ($title,$head_extra,$args) = @_;
 8128:     #&Apache::lonnet::logthis("start_page ".join(':',caller(0)));
 8129: 
 8130:     $env{'internal.start_page'}++;
 8131:     my ($result,@advtools);
 8132: 
 8133:     if (! exists($args->{'skip_phases'}{'head'}) ) {
 8134:         $result .= &xml_begin($args->{'frameset'}) . &headtag($title, $head_extra, $args);
 8135:     }
 8136:     
 8137:     if (! exists($args->{'skip_phases'}{'body'}) ) {
 8138: 	if ($args->{'frameset'}) {
 8139: 	    my $attr_string = &make_attr_string($args->{'force_register'},
 8140: 						$args->{'add_entries'});
 8141: 	    $result .= "\n<frameset $attr_string>\n";
 8142:         } else {
 8143:             $result .=
 8144:                 &bodytag($title, 
 8145:                          $args->{'function'},       $args->{'add_entries'},
 8146:                          $args->{'only_body'},      $args->{'domain'},
 8147:                          $args->{'force_register'}, $args->{'no_nav_bar'},
 8148:                          $args->{'bgcolor'},        $args->{'no_inline_link'},
 8149:                          $args,                     \@advtools);
 8150:         }
 8151:     }
 8152: 
 8153:     if ($args->{'js_ready'}) {
 8154: 		$result = &js_ready($result);
 8155:     }
 8156:     if ($args->{'html_encode'}) {
 8157: 		$result = &html_encode($result);
 8158:     }
 8159: 
 8160:     # Preparation for new and consistent functionlist at top of screen
 8161:     # if ($args->{'functionlist'}) {
 8162:     #            $result .= &build_functionlist();
 8163:     #}
 8164: 
 8165:     # Don't add anything more if only_body wanted or in const space
 8166:     return $result if    $args->{'only_body'} 
 8167:                       || $env{'request.state'} eq 'construct';
 8168: 
 8169:     #Breadcrumbs
 8170:     if (exists($args->{'bread_crumbs'}) or exists($args->{'bread_crumbs_component'})) {
 8171: 		&Apache::lonhtmlcommon::clear_breadcrumbs();
 8172: 		#if any br links exists, add them to the breadcrumbs
 8173: 		if (exists($args->{'bread_crumbs'}) and ref($args->{'bread_crumbs'}) eq 'ARRAY') {         
 8174: 			foreach my $crumb (@{$args->{'bread_crumbs'}}){
 8175: 				&Apache::lonhtmlcommon::add_breadcrumb($crumb);
 8176: 			}
 8177: 		}
 8178:                 # if @advtools array contains items add then to the breadcrumbs
 8179:                 if (@advtools > 0) {
 8180:                     &Apache::lonmenu::advtools_crumbs(@advtools);
 8181:                 }
 8182:                 my $menulink;
 8183:                 # if arg: bread_crumbs_nomenu is true pass 0 as $menulink item.
 8184:                 if (exists($args->{'bread_crumbs_nomenu'})) {
 8185:                     $menulink = 0;
 8186:                 } else {
 8187:                     undef($menulink);
 8188:                 }
 8189: 		#if bread_crumbs_component exists show it as headline else show only the breadcrumbs
 8190: 		if(exists($args->{'bread_crumbs_component'})){
 8191: 			$result .= &Apache::lonhtmlcommon::breadcrumbs($args->{'bread_crumbs_component'},'',$menulink);
 8192: 		}else{
 8193: 			$result .= &Apache::lonhtmlcommon::breadcrumbs('','',$menulink);
 8194: 		}
 8195:     } elsif (($env{'environment.remote'} eq 'on') &&
 8196:              ($env{'form.inhibitmenu'} ne 'yes') &&
 8197:              ($env{'request.noversionuri'} =~ m{^/res/}) &&
 8198:              ($env{'request.noversionuri'} !~ m{^/res/adm/pages/})) {
 8199:         $result .= '<div style="padding:0;margin:0;clear:both"><hr /></div>';
 8200:     }
 8201:     return $result;
 8202: }
 8203: 
 8204: sub end_page {
 8205:     my ($args) = @_;
 8206:     $env{'internal.end_page'}++;
 8207:     my $result;
 8208:     if ($args->{'discussion'}) {
 8209: 	my ($target,$parser);
 8210: 	if (ref($args->{'discussion'})) {
 8211: 	    ($target,$parser) =($args->{'discussion'}{'target'},
 8212: 				$args->{'discussion'}{'parser'});
 8213: 	}
 8214: 	$result .= &Apache::lonxml::xmlend($target,$parser);
 8215:     }
 8216:     if ($args->{'frameset'}) {
 8217: 	$result .= '</frameset>';
 8218:     } else {
 8219: 	$result .= &endbodytag($args);
 8220:     }
 8221:     unless ($args->{'notbody'}) {
 8222:         $result .= "\n</html>";
 8223:     }
 8224: 
 8225:     if ($args->{'js_ready'}) {
 8226: 	$result = &js_ready($result);
 8227:     }
 8228: 
 8229:     if ($args->{'html_encode'}) {
 8230: 	$result = &html_encode($result);
 8231:     }
 8232: 
 8233:     return $result;
 8234: }
 8235: 
 8236: sub wishlist_window {
 8237:     return(<<'ENDWISHLIST');
 8238: <script type="text/javascript">
 8239: // <![CDATA[
 8240: // <!-- BEGIN LON-CAPA Internal
 8241: function set_wishlistlink(title, path) {
 8242:     if (!title) {
 8243:         title = document.title;
 8244:         title = title.replace(/^LON-CAPA /,'');
 8245:     }
 8246:     title = encodeURIComponent(title);
 8247:     title = title.replace("'","\\\'");
 8248:     if (!path) {
 8249:         path = location.pathname;
 8250:     }
 8251:     path = encodeURIComponent(path);
 8252:     path = path.replace("'","\\\'");
 8253:     Win = window.open('/adm/wishlist?mode=newLink&setTitle='+title+'&setPath='+path,
 8254:                       'wishlistNewLink','width=560,height=350,scrollbars=0');
 8255: }
 8256: // END LON-CAPA Internal -->
 8257: // ]]>
 8258: </script>
 8259: ENDWISHLIST
 8260: }
 8261: 
 8262: sub modal_window {
 8263:     return(<<'ENDMODAL');
 8264: <script type="text/javascript">
 8265: // <![CDATA[
 8266: // <!-- BEGIN LON-CAPA Internal
 8267: var modalWindow = {
 8268: 	parent:"body",
 8269: 	windowId:null,
 8270: 	content:null,
 8271: 	width:null,
 8272: 	height:null,
 8273: 	close:function()
 8274: 	{
 8275: 	        $(".LCmodal-window").remove();
 8276: 	        $(".LCmodal-overlay").remove();
 8277: 	},
 8278: 	open:function()
 8279: 	{
 8280: 		var modal = "";
 8281: 		modal += "<div class=\"LCmodal-overlay\"></div>";
 8282: 		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;\">";
 8283: 		modal += this.content;
 8284: 		modal += "</div>";	
 8285: 
 8286: 		$(this.parent).append(modal);
 8287: 
 8288: 		$(".LCmodal-window").append("<a class=\"LCclose-window\"></a>");
 8289: 		$(".LCclose-window").click(function(){modalWindow.close();});
 8290: 		$(".LCmodal-overlay").click(function(){modalWindow.close();});
 8291: 	}
 8292: };
 8293: 	var openMyModal = function(source,width,height,scrolling,transparency,style)
 8294: 	{
 8295:                 source = source.replace(/'/g,"&#39;");
 8296: 		modalWindow.windowId = "myModal";
 8297: 		modalWindow.width = width;
 8298: 		modalWindow.height = height;
 8299: 		modalWindow.content = "<iframe width='"+width+"' height='"+height+"' frameborder='0' scrolling='"+scrolling+"' allowtransparency='"+transparency+"' src='" + source + "' style='"+style+"'></iframe>";
 8300: 		modalWindow.open();
 8301: 	};
 8302: // END LON-CAPA Internal -->
 8303: // ]]>
 8304: </script>
 8305: ENDMODAL
 8306: }
 8307: 
 8308: sub modal_link {
 8309:     my ($link,$linktext,$width,$height,$target,$scrolling,$title,$transparency,$style)=@_;
 8310:     unless ($width) { $width=480; }
 8311:     unless ($height) { $height=400; }
 8312:     unless ($scrolling) { $scrolling='yes'; }
 8313:     unless ($transparency) { $transparency='true'; }
 8314: 
 8315:     my $target_attr;
 8316:     if (defined($target)) {
 8317:         $target_attr = 'target="'.$target.'"';
 8318:     }
 8319:     return <<"ENDLINK";
 8320: <a href="$link" $target_attr title="$title" onclick="javascript:openMyModal('$link',$width,$height,'$scrolling','$transparency','$style'); return false;">
 8321:            $linktext</a>
 8322: ENDLINK
 8323: }
 8324: 
 8325: sub modal_adhoc_script {
 8326:     my ($funcname,$width,$height,$content)=@_;
 8327:     return (<<ENDADHOC);
 8328: <script type="text/javascript">
 8329: // <![CDATA[
 8330:         var $funcname = function()
 8331:         {
 8332:                 modalWindow.windowId = "myModal";
 8333:                 modalWindow.width = $width;
 8334:                 modalWindow.height = $height;
 8335:                 modalWindow.content = '$content';
 8336:                 modalWindow.open();
 8337:         };  
 8338: // ]]>
 8339: </script>
 8340: ENDADHOC
 8341: }
 8342: 
 8343: sub modal_adhoc_inner {
 8344:     my ($funcname,$width,$height,$content)=@_;
 8345:     my $innerwidth=$width-20;
 8346:     $content=&js_ready(
 8347:                &start_page('Dialog',undef,{'only_body'=>1,'bgcolor'=>'#FFFFFF'}).
 8348:                  &start_scrollbox($width.'px',$innerwidth.'px',$height.'px','myModal','#FFFFFF',undef,1).
 8349:                  $content.
 8350:                  &end_scrollbox().
 8351:                  &end_page()
 8352:              );
 8353:     return &modal_adhoc_script($funcname,$width,$height,$content);
 8354: }
 8355: 
 8356: sub modal_adhoc_window {
 8357:     my ($funcname,$width,$height,$content,$linktext)=@_;
 8358:     return &modal_adhoc_inner($funcname,$width,$height,$content).
 8359:            "<a href=\"javascript:$funcname();void(0);\">".$linktext."</a>";
 8360: }
 8361: 
 8362: sub modal_adhoc_launch {
 8363:     my ($funcname,$width,$height,$content)=@_;
 8364:     return &modal_adhoc_inner($funcname,$width,$height,$content).(<<ENDLAUNCH);
 8365: <script type="text/javascript">
 8366: // <![CDATA[
 8367: $funcname();
 8368: // ]]>
 8369: </script>
 8370: ENDLAUNCH
 8371: }
 8372: 
 8373: sub modal_adhoc_close {
 8374:     return (<<ENDCLOSE);
 8375: <script type="text/javascript">
 8376: // <![CDATA[
 8377: modalWindow.close();
 8378: // ]]>
 8379: </script>
 8380: ENDCLOSE
 8381: }
 8382: 
 8383: sub togglebox_script {
 8384:    return(<<ENDTOGGLE);
 8385: <script type="text/javascript"> 
 8386: // <![CDATA[
 8387: function LCtoggleDisplay(id,hidetext,showtext) {
 8388:    link = document.getElementById(id + "link").childNodes[0];
 8389:    with (document.getElementById(id).style) {
 8390:       if (display == "none" ) {
 8391:           display = "inline";
 8392:           link.nodeValue = hidetext;
 8393:         } else {
 8394:           display = "none";
 8395:           link.nodeValue = showtext;
 8396:        }
 8397:    }
 8398: }
 8399: // ]]>
 8400: </script>
 8401: ENDTOGGLE
 8402: }
 8403: 
 8404: sub start_togglebox {
 8405:     my ($id,$heading,$headerbg,$hidetext,$showtext)=@_;
 8406:     unless ($heading) { $heading=''; } else { $heading.=' '; }
 8407:     unless ($showtext) { $showtext=&mt('show'); }
 8408:     unless ($hidetext) { $hidetext=&mt('hide'); }
 8409:     unless ($headerbg) { $headerbg='#FFFFFF'; }
 8410:     return &start_data_table().
 8411:            &start_data_table_header_row().
 8412:            '<td bgcolor="'.$headerbg.'">'.$heading.
 8413:            '[<a id="'.$id.'link" href="javascript:LCtoggleDisplay(\''.$id.'\',\''.$hidetext.'\',\''.
 8414:            $showtext.'\')">'.$showtext.'</a>]</td>'.
 8415:            &end_data_table_header_row().
 8416:            '<tr id="'.$id.'" style="display:none""><td>';
 8417: }
 8418: 
 8419: sub end_togglebox {
 8420:     return '</td></tr>'.&end_data_table();
 8421: }
 8422: 
 8423: sub LCprogressbar_script {
 8424:    my ($id)=@_;
 8425:    return(<<ENDPROGRESS);
 8426: <script type="text/javascript">
 8427: // <![CDATA[
 8428: \$('#progressbar$id').progressbar({
 8429:   value: 0,
 8430:   change: function(event, ui) {
 8431:     var newVal = \$(this).progressbar('option', 'value');
 8432:     \$('.pblabel', this).text(LCprogressTxt);
 8433:   }
 8434: });
 8435: // ]]>
 8436: </script>
 8437: ENDPROGRESS
 8438: }
 8439: 
 8440: sub LCprogressbarUpdate_script {
 8441:    return(<<ENDPROGRESSUPDATE);
 8442: <style type="text/css">
 8443: .ui-progressbar { position:relative; }
 8444: .pblabel { position: absolute; width: 100%; text-align: center; line-height: 1.9em; }
 8445: </style>
 8446: <script type="text/javascript">
 8447: // <![CDATA[
 8448: var LCprogressTxt='---';
 8449: 
 8450: function LCupdateProgress(percent,progresstext,id) {
 8451:    LCprogressTxt=progresstext;
 8452:    \$('#progressbar'+id).progressbar('value',percent);
 8453: }
 8454: // ]]>
 8455: </script>
 8456: ENDPROGRESSUPDATE
 8457: }
 8458: 
 8459: my $LClastpercent;
 8460: my $LCidcnt;
 8461: my $LCcurrentid;
 8462: 
 8463: sub LCprogressbar {
 8464:     my ($r)=(@_);
 8465:     $LClastpercent=0;
 8466:     $LCidcnt++;
 8467:     $LCcurrentid=$$.'_'.$LCidcnt;
 8468:     my $starting=&mt('Starting');
 8469:     my $content=(<<ENDPROGBAR);
 8470:   <div id="progressbar$LCcurrentid">
 8471:     <span class="pblabel">$starting</span>
 8472:   </div>
 8473: ENDPROGBAR
 8474:     &r_print($r,$content.&LCprogressbar_script($LCcurrentid));
 8475: }
 8476: 
 8477: sub LCprogressbarUpdate {
 8478:     my ($r,$val,$text)=@_;
 8479:     unless ($val) { 
 8480:        if ($LClastpercent) {
 8481:            $val=$LClastpercent;
 8482:        } else {
 8483:            $val=0;
 8484:        }
 8485:     }
 8486:     if ($val<0) { $val=0; }
 8487:     if ($val>100) { $val=0; }
 8488:     $LClastpercent=$val;
 8489:     unless ($text) { $text=$val.'%'; }
 8490:     $text=&js_ready($text);
 8491:     &r_print($r,<<ENDUPDATE);
 8492: <script type="text/javascript">
 8493: // <![CDATA[
 8494: LCupdateProgress($val,'$text','$LCcurrentid');
 8495: // ]]>
 8496: </script>
 8497: ENDUPDATE
 8498: }
 8499: 
 8500: sub LCprogressbarClose {
 8501:     my ($r)=@_;
 8502:     $LClastpercent=0;
 8503:     &r_print($r,<<ENDCLOSE);
 8504: <script type="text/javascript">
 8505: // <![CDATA[
 8506: \$("#progressbar$LCcurrentid").hide('slow'); 
 8507: // ]]>
 8508: </script>
 8509: ENDCLOSE
 8510: }
 8511: 
 8512: sub r_print {
 8513:     my ($r,$to_print)=@_;
 8514:     if ($r) {
 8515:       $r->print($to_print);
 8516:       $r->rflush();
 8517:     } else {
 8518:       print($to_print);
 8519:     }
 8520: }
 8521: 
 8522: sub html_encode {
 8523:     my ($result) = @_;
 8524: 
 8525:     $result = &HTML::Entities::encode($result,'<>&"');
 8526:     
 8527:     return $result;
 8528: }
 8529: 
 8530: sub js_ready {
 8531:     my ($result) = @_;
 8532: 
 8533:     $result =~ s/[\n\r]/ /xmsg;
 8534:     $result =~ s/\\/\\\\/xmsg;
 8535:     $result =~ s/'/\\'/xmsg;
 8536:     $result =~ s{</}{<\\/}xmsg;
 8537:     
 8538:     return $result;
 8539: }
 8540: 
 8541: sub validate_page {
 8542:     if (  exists($env{'internal.start_page'})
 8543: 	  &&     $env{'internal.start_page'} > 1) {
 8544: 	&Apache::lonnet::logthis('start_page called multiple times '.
 8545: 				 $env{'internal.start_page'}.' '.
 8546: 				 $ENV{'request.filename'});
 8547:     }
 8548:     if (  exists($env{'internal.end_page'})
 8549: 	  &&     $env{'internal.end_page'} > 1) {
 8550: 	&Apache::lonnet::logthis('end_page called multiple times '.
 8551: 				 $env{'internal.end_page'}.' '.
 8552: 				 $env{'request.filename'});
 8553:     }
 8554:     if (     exists($env{'internal.start_page'})
 8555: 	&& ! exists($env{'internal.end_page'})) {
 8556: 	&Apache::lonnet::logthis('start_page called without end_page '.
 8557: 				 $env{'request.filename'});
 8558:     }
 8559:     if (   ! exists($env{'internal.start_page'})
 8560: 	&&   exists($env{'internal.end_page'})) {
 8561: 	&Apache::lonnet::logthis('end_page called without start_page'.
 8562: 				 $env{'request.filename'});
 8563:     }
 8564: }
 8565: 
 8566: 
 8567: sub start_scrollbox {
 8568:     my ($outerwidth,$width,$height,$id,$bgcolor,$cursor,$needjsready) = @_;
 8569:     unless ($outerwidth) { $outerwidth='520px'; }
 8570:     unless ($width) { $width='500px'; }
 8571:     unless ($height) { $height='200px'; }
 8572:     my ($table_id,$div_id,$tdcol);
 8573:     if ($id ne '') {
 8574:         $table_id = ' id="table_'.$id.'"';
 8575:         $div_id = ' id="div_'.$id.'"';
 8576:     }
 8577:     if ($bgcolor ne '') {
 8578:         $tdcol = "background-color: $bgcolor;";
 8579:     }
 8580:     my $nicescroll_js;
 8581:     if ($env{'browser.mobile'}) {
 8582:         $nicescroll_js = &nicescroll_javascript('div_'.$id,$cursor,$needjsready);
 8583:     }
 8584:     return <<"END";
 8585: $nicescroll_js
 8586: 
 8587: <table style="width: $outerwidth; border: 1px solid none;"$table_id><tr><td style="width: $width;$tdcol">
 8588: <div style="overflow:auto; width:$width; height:$height;"$div_id>
 8589: END
 8590: }
 8591: 
 8592: sub end_scrollbox {
 8593:     return '</div></td></tr></table>';
 8594: }
 8595: 
 8596: sub nicescroll_javascript {
 8597:     my ($id,$cursor,$needjsready,$framecheck,$location) = @_;
 8598:     my %options;
 8599:     if (ref($cursor) eq 'HASH') {
 8600:         %options = %{$cursor};
 8601:     }
 8602:     unless ($options{'railalign'} =~ /^left|right$/) {
 8603:         $options{'railalign'} = 'left';
 8604:     }
 8605:     unless ($options{'cursorcolor'} =~ /^\#\w+$/) {
 8606:         my $function  = &get_users_function();
 8607:         $options{'cursorcolor'} = &designparm($function.'.sidebg',$env{'request.role.domain'});
 8608:         unless ($options{'cursorcolor'} =~ /^\#\w+$/) {
 8609:             $options{'cursorcolor'} = '#00F';
 8610:         }
 8611:     }
 8612:     if ($options{'cursoropacity'} =~ /^[\d.]+$/) {
 8613:         unless ($options{'cursoropacity'} >= 0.0 && $options{'cursoropacity'} <=1.0) {
 8614:             $options{'cursoropacity'}='1.0';
 8615:         }
 8616:     } else {
 8617:         $options{'cursoropacity'}='1.0';
 8618:     }
 8619:     if ($options{'cursorfixedheight'} eq 'none') {
 8620:         delete($options{'cursorfixedheight'});
 8621:     } else {
 8622:         unless ($options{'cursorfixedheight'} =~ /^\d+$/) { $options{'cursorfixedheight'}='50'; }
 8623:     }
 8624:     unless ($options{'railoffset'} =~ /^{[\w\:\d\-,]+}$/) {
 8625:         delete($options{'railoffset'});
 8626:     }
 8627:     my @niceoptions;
 8628:     while (my($key,$value) = each(%options)) {
 8629:         if ($value =~ /^\{.+\}$/) {
 8630:             push(@niceoptions,$key.':'.$value);
 8631:         } else {
 8632:             push(@niceoptions,$key.':"'.$value.'"');
 8633:         }
 8634:     }
 8635:     my $nicescroll_js = '
 8636: $(document).ready(
 8637:       function() {
 8638:           $("#'.$id.'").niceScroll({'.join(',',@niceoptions).'});
 8639:       }
 8640: );
 8641: ';
 8642:     if ($framecheck) {
 8643:         $nicescroll_js .= '
 8644: function expand_div(caller) {
 8645:     if (top === self) {
 8646:         document.getElementById("'.$id.'").style.width = "auto";
 8647:         document.getElementById("'.$id.'").style.height = "auto";
 8648:     } else {
 8649:         try {
 8650:             if (parent.frames) {
 8651:                 if (parent.frames.length > 1) {
 8652:                     var framesrc = parent.frames[1].location.href;
 8653:                     var currsrc = framesrc.replace(/\#.*$/,"");
 8654:                     if ((caller == "search") || (currsrc == "'.$location.'")) {
 8655:                         document.getElementById("'.$id.'").style.width = "auto";
 8656:                         document.getElementById("'.$id.'").style.height = "auto";
 8657:                     }
 8658:                 }
 8659:             }
 8660:         } catch (e) {
 8661:             return;
 8662:         }
 8663:     }
 8664:     return;
 8665: }
 8666: ';
 8667:     }
 8668:     if ($needjsready) {
 8669:         $nicescroll_js = '
 8670: <script type="text/javascript">'."\n".$nicescroll_js."\n</script>\n";
 8671:     } else {
 8672:         $nicescroll_js = &Apache::lonhtmlcommon::scripttag($nicescroll_js);
 8673:     }
 8674:     return $nicescroll_js;
 8675: }
 8676: 
 8677: sub simple_error_page {
 8678:     my ($r,$title,$msg,$args) = @_;
 8679:     if (ref($args) eq 'HASH') {
 8680:         if (!$args->{'no_auto_mt_msg'}) { $msg = &mt($msg); }
 8681:     } else {
 8682:         $msg = &mt($msg);
 8683:     }
 8684: 
 8685:     my $page =
 8686: 	&Apache::loncommon::start_page($title).
 8687: 	'<p class="LC_error">'.$msg.'</p>'.
 8688: 	&Apache::loncommon::end_page();
 8689:     if (ref($r)) {
 8690: 	$r->print($page);
 8691: 	return;
 8692:     }
 8693:     return $page;
 8694: }
 8695: 
 8696: {
 8697:     my @row_count;
 8698: 
 8699:     sub start_data_table_count {
 8700:         unshift(@row_count, 0);
 8701:         return;
 8702:     }
 8703: 
 8704:     sub end_data_table_count {
 8705:         shift(@row_count);
 8706:         return;
 8707:     }
 8708: 
 8709:     sub start_data_table {
 8710: 	my ($add_class,$id) = @_;
 8711: 	my $css_class = (join(' ','LC_data_table',$add_class));
 8712:         my $table_id;
 8713:         if (defined($id)) {
 8714:             $table_id = ' id="'.$id.'"';
 8715:         }
 8716: 	&start_data_table_count();
 8717: 	return '<table class="'.$css_class.'"'.$table_id.'>'."\n";
 8718:     }
 8719: 
 8720:     sub end_data_table {
 8721: 	&end_data_table_count();
 8722: 	return '</table>'."\n";;
 8723:     }
 8724: 
 8725:     sub start_data_table_row {
 8726: 	my ($add_class, $id) = @_;
 8727: 	$row_count[0]++;
 8728: 	my $css_class = ($row_count[0] % 2)?'LC_odd_row':'LC_even_row';
 8729: 	$css_class = (join(' ',$css_class,$add_class)) unless ($add_class eq '');
 8730:         $id = (' id="'.$id.'"') unless ($id eq '');
 8731:         return  '<tr class="'.$css_class.'"'.$id.'>'."\n";
 8732:     }
 8733:     
 8734:     sub continue_data_table_row {
 8735: 	my ($add_class, $id) = @_;
 8736: 	my $css_class = ($row_count[0] % 2)?'LC_odd_row':'LC_even_row';
 8737: 	$css_class = (join(' ',$css_class,$add_class)) unless ($add_class eq '');
 8738:         $id = (' id="'.$id.'"') unless ($id eq '');
 8739:         return  '<tr class="'.$css_class.'"'.$id.'>'."\n";
 8740:     }
 8741: 
 8742:     sub end_data_table_row {
 8743: 	return '</tr>'."\n";;
 8744:     }
 8745: 
 8746:     sub start_data_table_empty_row {
 8747: #	$row_count[0]++;
 8748: 	return  '<tr class="LC_empty_row" >'."\n";;
 8749:     }
 8750: 
 8751:     sub end_data_table_empty_row {
 8752: 	return '</tr>'."\n";;
 8753:     }
 8754: 
 8755:     sub start_data_table_header_row {
 8756: 	return  '<tr class="LC_header_row">'."\n";;
 8757:     }
 8758: 
 8759:     sub end_data_table_header_row {
 8760: 	return '</tr>'."\n";;
 8761:     }
 8762: 
 8763:     sub data_table_caption {
 8764:         my $caption = shift;
 8765:         return "<caption class=\"LC_caption\">$caption</caption>";
 8766:     }
 8767: }
 8768: 
 8769: =pod
 8770: 
 8771: =item * &inhibit_menu_check($arg)
 8772: 
 8773: Checks for a inhibitmenu state and generates output to preserve it
 8774: 
 8775: Inputs:         $arg - can be any of
 8776:                      - undef - in which case the return value is a string 
 8777:                                to add  into arguments list of a uri
 8778:                      - 'input' - in which case the return value is a HTML
 8779:                                  <form> <input> field of type hidden to
 8780:                                  preserve the value
 8781:                      - a url - in which case the return value is the url with
 8782:                                the neccesary cgi args added to preserve the
 8783:                                inhibitmenu state
 8784:                      - a ref to a url - no return value, but the string is
 8785:                                         updated to include the neccessary cgi
 8786:                                         args to preserve the inhibitmenu state
 8787: 
 8788: =cut
 8789: 
 8790: sub inhibit_menu_check {
 8791:     my ($arg) = @_;
 8792:     &get_unprocessed_cgi($ENV{'QUERY_STRING'}, ['inhibitmenu']);
 8793:     if ($arg eq 'input') {
 8794: 	if ($env{'form.inhibitmenu'}) {
 8795: 	    return '<input type="hidden" name="inhibitmenu" value="'.$env{'form.inhibitmenu'}.'" />';
 8796: 	} else {
 8797: 	    return
 8798: 	}
 8799:     }
 8800:     if ($env{'form.inhibitmenu'}) {
 8801: 	if (ref($arg)) {
 8802: 	    $$arg .= '?inhibitmenu='.$env{'form.inhibitmenu'};
 8803: 	} elsif ($arg eq '') {
 8804: 	    $arg .= 'inhibitmenu='.$env{'form.inhibitmenu'};
 8805: 	} else {
 8806: 	    $arg .= '?inhibitmenu='.$env{'form.inhibitmenu'};
 8807: 	}
 8808:     }
 8809:     if (!ref($arg)) {
 8810: 	return $arg;
 8811:     }
 8812: }
 8813: 
 8814: ###############################################
 8815: 
 8816: =pod
 8817: 
 8818: =back
 8819: 
 8820: =head1 User Information Routines
 8821: 
 8822: =over 4
 8823: 
 8824: =item * &get_users_function()
 8825: 
 8826: Used by &bodytag to determine the current users primary role.
 8827: Returns either 'student','coordinator','admin', or 'author'.
 8828: 
 8829: =cut
 8830: 
 8831: ###############################################
 8832: sub get_users_function {
 8833:     my $function = 'norole';
 8834:     if ($env{'request.role'}=~/^(st)/) {
 8835:         $function='student';
 8836:     }
 8837:     if ($env{'request.role'}=~/^(cc|co|in|ta|ep)/) {
 8838:         $function='coordinator';
 8839:     }
 8840:     if ($env{'request.role'}=~/^(su|dc|ad|li)/) {
 8841:         $function='admin';
 8842:     }
 8843:     if (($env{'request.role'}=~/^(au|ca|aa)/) ||
 8844:         ($ENV{'REQUEST_URI'}=~ m{/^(/priv)})) {
 8845:         $function='author';
 8846:     }
 8847:     return $function;
 8848: }
 8849: 
 8850: ###############################################
 8851: 
 8852: =pod
 8853: 
 8854: =item * &show_course()
 8855: 
 8856: Used by lonmenu.pm and lonroles.pm to determine whether to use the word
 8857: 'Courses' or 'Roles' in inline navigation and on screen displaying user's roles.
 8858: 
 8859: Inputs:
 8860: None
 8861: 
 8862: Outputs:
 8863: Scalar: 1 if 'Course' to be used, 0 otherwise.
 8864: 
 8865: =cut
 8866: 
 8867: ###############################################
 8868: sub show_course {
 8869:     my $course = !$env{'user.adv'};
 8870:     if (!$env{'user.adv'}) {
 8871:         foreach my $env (keys(%env)) {
 8872:             next if ($env !~ m/^user\.priv\./);
 8873:             if ($env !~ m/^user\.priv\.(?:st|cm)/) {
 8874:                 $course = 0;
 8875:                 last;
 8876:             }
 8877:         }
 8878:     }
 8879:     return $course;
 8880: }
 8881: 
 8882: ###############################################
 8883: 
 8884: =pod
 8885: 
 8886: =item * &check_user_status()
 8887: 
 8888: Determines current status of supplied role for a
 8889: specific user. Roles can be active, previous or future.
 8890: 
 8891: Inputs: 
 8892: user's domain, user's username, course's domain,
 8893: course's number, optional section ID.
 8894: 
 8895: Outputs:
 8896: role status: active, previous or future. 
 8897: 
 8898: =cut
 8899: 
 8900: sub check_user_status {
 8901:     my ($udom,$uname,$cdom,$crs,$role,$sec) = @_;
 8902:     my %userinfo = &Apache::lonnet::dump('roles',$udom,$uname);
 8903:     my @uroles = keys(%userinfo);
 8904:     my $srchstr;
 8905:     my $active_chk = 'none';
 8906:     my $now = time;
 8907:     if (@uroles > 0) {
 8908:         if (($role eq 'cc') || ($role eq 'co') || ($sec eq '') || (!defined($sec))) {
 8909:             $srchstr = '/'.$cdom.'/'.$crs.'_'.$role;
 8910:         } else {
 8911:             $srchstr = '/'.$cdom.'/'.$crs.'/'.$sec.'_'.$role;
 8912:         }
 8913:         if (grep/^\Q$srchstr\E$/,@uroles) {
 8914:             my $role_end = 0;
 8915:             my $role_start = 0;
 8916:             $active_chk = 'active';
 8917:             if ($userinfo{$srchstr} =~ m/^\Q$role\E_(\d+)/) {
 8918:                 $role_end = $1;
 8919:                 if ($userinfo{$srchstr} =~ m/^\Q$role\E_\Q$role_end\E_(\d+)$/) {
 8920:                     $role_start = $1;
 8921:                 }
 8922:             }
 8923:             if ($role_start > 0) {
 8924:                 if ($now < $role_start) {
 8925:                     $active_chk = 'future';
 8926:                 }
 8927:             }
 8928:             if ($role_end > 0) {
 8929:                 if ($now > $role_end) {
 8930:                     $active_chk = 'previous';
 8931:                 }
 8932:             }
 8933:         }
 8934:     }
 8935:     return $active_chk;
 8936: }
 8937: 
 8938: ###############################################
 8939: 
 8940: =pod
 8941: 
 8942: =item * &get_sections()
 8943: 
 8944: Determines all the sections for a course including
 8945: sections with students and sections containing other roles.
 8946: Incoming parameters: 
 8947: 
 8948: 1. domain
 8949: 2. course number 
 8950: 3. reference to array containing roles for which sections should 
 8951: be gathered (optional).
 8952: 4. reference to array containing status types for which sections 
 8953: should be gathered (optional).
 8954: 
 8955: If the third argument is undefined, sections are gathered for any role. 
 8956: If the fourth argument is undefined, sections are gathered for any status.
 8957: Permissible values are 'active' or 'future' or 'previous'.
 8958:  
 8959: Returns section hash (keys are section IDs, values are
 8960: number of users in each section), subject to the
 8961: optional roles filter, optional status filter 
 8962: 
 8963: =cut
 8964: 
 8965: ###############################################
 8966: sub get_sections {
 8967:     my ($cdom,$cnum,$possible_roles,$possible_status) = @_;
 8968:     if (!defined($cdom) || !defined($cnum)) {
 8969:         my $cid =  $env{'request.course.id'};
 8970: 
 8971: 	return if (!defined($cid));
 8972: 
 8973:         $cdom = $env{'course.'.$cid.'.domain'};
 8974:         $cnum = $env{'course.'.$cid.'.num'};
 8975:     }
 8976: 
 8977:     my %sectioncount;
 8978:     my $now = time;
 8979: 
 8980:     my $check_students = 1;
 8981:     my $only_students = 0;
 8982:     if (ref($possible_roles) eq 'ARRAY') {
 8983:         if (grep(/^st$/,@{$possible_roles})) {
 8984:             if (@{$possible_roles} == 1) {
 8985:                 $only_students = 1;
 8986:             }
 8987:         } else {
 8988:             $check_students = 0;
 8989:         }
 8990:     }
 8991: 
 8992:     if ($check_students) {
 8993: 	my ($classlist) = &Apache::loncoursedata::get_classlist($cdom,$cnum);
 8994: 	my $sec_index = &Apache::loncoursedata::CL_SECTION();
 8995: 	my $status_index = &Apache::loncoursedata::CL_STATUS();
 8996:         my $start_index = &Apache::loncoursedata::CL_START();
 8997:         my $end_index = &Apache::loncoursedata::CL_END();
 8998:         my $status;
 8999: 	while (my ($student,$data) = each(%$classlist)) {
 9000: 	    my ($section,$stu_status,$start,$end) = ($data->[$sec_index],
 9001: 				                     $data->[$status_index],
 9002:                                                      $data->[$start_index],
 9003:                                                      $data->[$end_index]);
 9004:             if ($stu_status eq 'Active') {
 9005:                 $status = 'active';
 9006:             } elsif ($end < $now) {
 9007:                 $status = 'previous';
 9008:             } elsif ($start > $now) {
 9009:                 $status = 'future';
 9010:             } 
 9011: 	    if ($section ne '-1' && $section !~ /^\s*$/) {
 9012:                 if ((!defined($possible_status)) || (($status ne '') && 
 9013:                     (grep/^\Q$status\E$/,@{$possible_status}))) { 
 9014: 		    $sectioncount{$section}++;
 9015:                 }
 9016: 	    }
 9017: 	}
 9018:     }
 9019:     if ($only_students) {
 9020:         return %sectioncount;
 9021:     }
 9022:     my %courseroles = &Apache::lonnet::dump('nohist_userroles',$cdom,$cnum);
 9023:     foreach my $user (sort(keys(%courseroles))) {
 9024: 	if ($user !~ /^(\w{2})/) { next; }
 9025: 	my ($role) = ($user =~ /^(\w{2})/);
 9026: 	if ($possible_roles && !(grep(/^$role$/,@$possible_roles))) { next; }
 9027: 	my ($section,$status);
 9028: 	if ($role eq 'cr' &&
 9029: 	    $user =~ m-^$role/[^/]*/[^/]*/[^/]*:[^:]*:[^:]*:(\w+)-) {
 9030: 	    $section=$1;
 9031: 	}
 9032: 	if ($user =~ /^$role:[^:]*:[^:]*:(\w+)/) { $section=$1; }
 9033: 	if (!defined($section) || $section eq '-1') { next; }
 9034:         my ($end,$start) = ($courseroles{$user} =~ /^([^:]*):([^:]*)$/);
 9035:         if ($end == -1 && $start == -1) {
 9036:             next; #deleted role
 9037:         }
 9038:         if (!defined($possible_status)) { 
 9039:             $sectioncount{$section}++;
 9040:         } else {
 9041:             if ((!$end || $end >= $now) && (!$start || $start <= $now)) {
 9042:                 $status = 'active';
 9043:             } elsif ($end < $now) {
 9044:                 $status = 'future';
 9045:             } elsif ($start > $now) {
 9046:                 $status = 'previous';
 9047:             }
 9048:             if (($status ne '') && (grep/^\Q$status\E$/,@{$possible_status})) {
 9049:                 $sectioncount{$section}++;
 9050:             }
 9051:         }
 9052:     }
 9053:     return %sectioncount;
 9054: }
 9055: 
 9056: ###############################################
 9057: 
 9058: =pod
 9059: 
 9060: =item * &get_course_users()
 9061: 
 9062: Retrieves usernames:domains for users in the specified course
 9063: with specific role(s), and access status. 
 9064: 
 9065: Incoming parameters:
 9066: 1. course domain
 9067: 2. course number
 9068: 3. access status: users must have - either active, 
 9069: previous, future, or all.
 9070: 4. reference to array of permissible roles
 9071: 5. reference to array of section restrictions (optional)
 9072: 6. reference to results object (hash of hashes).
 9073: 7. reference to optional userdata hash
 9074: 8. reference to optional statushash
 9075: 9. flag if privileged users (except those set to unhide in
 9076:    course settings) should be excluded    
 9077: Keys of top level results hash are roles.
 9078: Keys of inner hashes are username:domain, with 
 9079: values set to access type.
 9080: Optional userdata hash returns an array with arguments in the 
 9081: same order as loncoursedata::get_classlist() for student data.
 9082: 
 9083: Optional statushash returns
 9084: 
 9085: Entries for end, start, section and status are blank because
 9086: of the possibility of multiple values for non-student roles.
 9087: 
 9088: =cut
 9089: 
 9090: ###############################################
 9091: 
 9092: sub get_course_users {
 9093:     my ($cdom,$cnum,$types,$roles,$sections,$users,$userdata,$statushash,$hidepriv) = @_;
 9094:     my %idx = ();
 9095:     my %seclists;
 9096: 
 9097:     $idx{udom} = &Apache::loncoursedata::CL_SDOM();
 9098:     $idx{uname} =  &Apache::loncoursedata::CL_SNAME();
 9099:     $idx{end} = &Apache::loncoursedata::CL_END();
 9100:     $idx{start} = &Apache::loncoursedata::CL_START();
 9101:     $idx{id} = &Apache::loncoursedata::CL_ID();
 9102:     $idx{section} = &Apache::loncoursedata::CL_SECTION();
 9103:     $idx{fullname} = &Apache::loncoursedata::CL_FULLNAME();
 9104:     $idx{status} = &Apache::loncoursedata::CL_STATUS();
 9105: 
 9106:     if (grep(/^st$/,@{$roles})) {
 9107:         my ($classlist,$keylist)=&Apache::loncoursedata::get_classlist($cdom,$cnum);
 9108:         my $now = time;
 9109:         foreach my $student (keys(%{$classlist})) {
 9110:             my $match = 0;
 9111:             my $secmatch = 0;
 9112:             my $section = $$classlist{$student}[$idx{section}];
 9113:             my $status = $$classlist{$student}[$idx{status}];
 9114:             if ($section eq '') {
 9115:                 $section = 'none';
 9116:             }
 9117:             if ((ref($sections) eq 'ARRAY') && (@{$sections} > 0)) {
 9118:                 if (grep(/^all$/,@{$sections})) {
 9119:                     $secmatch = 1;
 9120:                 } elsif ($$classlist{$student}[$idx{section}] eq '') {
 9121:                     if (grep(/^none$/,@{$sections})) {
 9122:                         $secmatch = 1;
 9123:                     }
 9124:                 } else {  
 9125: 		    if (grep(/^\Q$section\E$/,@{$sections})) {
 9126: 		        $secmatch = 1;
 9127:                     }
 9128: 		}
 9129:                 if (!$secmatch) {
 9130:                     next;
 9131:                 }
 9132:             }
 9133:             if (defined($$types{'active'})) {
 9134:                 if ($$classlist{$student}[$idx{status}] eq 'Active') {
 9135:                     push(@{$$users{st}{$student}},'active');
 9136:                     $match = 1;
 9137:                 }
 9138:             }
 9139:             if (defined($$types{'previous'})) {
 9140:                 if ($$classlist{$student}[$idx{status}] eq 'Expired') {
 9141:                     push(@{$$users{st}{$student}},'previous');
 9142:                     $match = 1;
 9143:                 }
 9144:             }
 9145:             if (defined($$types{'future'})) {
 9146:                 if ($$classlist{$student}[$idx{status}] eq 'Future') {
 9147:                     push(@{$$users{st}{$student}},'future');
 9148:                     $match = 1;
 9149:                 }
 9150:             }
 9151:             if ($match) {
 9152:                 push(@{$seclists{$student}},$section);
 9153:                 if (ref($userdata) eq 'HASH') {
 9154:                     $$userdata{$student} = $$classlist{$student};
 9155:                 }
 9156:                 if (ref($statushash) eq 'HASH') {
 9157:                     $statushash->{$student}{'st'}{$section} = $status;
 9158:                 }
 9159:             }
 9160:         }
 9161:     }
 9162:     if ((@{$roles} > 1) || ((@{$roles} == 1) && ($$roles[0] ne "st"))) {
 9163:         my %coursepersonnel = &Apache::lonnet::dump('nohist_userroles',$cdom,$cnum);
 9164:         my $now = time;
 9165:         my %displaystatus = ( previous => 'Expired',
 9166:                               active   => 'Active',
 9167:                               future   => 'Future',
 9168:                             );
 9169:         my (%nothide,@possdoms);
 9170:         if ($hidepriv) {
 9171:             my %coursehash=&Apache::lonnet::coursedescription($cdom.'_'.$cnum);
 9172:             foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
 9173:                 if ($user !~ /:/) {
 9174:                     $nothide{join(':',split(/[\@]/,$user))}=1;
 9175:                 } else {
 9176:                     $nothide{$user} = 1;
 9177:                 }
 9178:             }
 9179:             my @possdoms = ($cdom);
 9180:             if ($coursehash{'checkforpriv'}) {
 9181:                 push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
 9182:             }
 9183:         }
 9184:         foreach my $person (sort(keys(%coursepersonnel))) {
 9185:             my $match = 0;
 9186:             my $secmatch = 0;
 9187:             my $status;
 9188:             my ($role,$user,$usec) = ($person =~ /^([^:]*):([^:]+:[^:]+):([^:]*)/);
 9189:             $user =~ s/:$//;
 9190:             my ($end,$start) = split(/:/,$coursepersonnel{$person});
 9191:             if ($end == -1 || $start == -1) {
 9192:                 next;
 9193:             }
 9194:             if (($role) && ((grep(/^\Q$role\E$/,@{$roles})) ||
 9195:                 (grep(/^cr$/,@{$roles}) && $role =~ /^cr\//))) {
 9196:                 my ($uname,$udom) = split(/:/,$user);
 9197:                 if ((ref($sections) eq 'ARRAY') && (@{$sections} > 0)) {
 9198:                     if (grep(/^all$/,@{$sections})) {
 9199:                         $secmatch = 1;
 9200:                     } elsif ($usec eq '') {
 9201:                         if (grep(/^none$/,@{$sections})) {
 9202:                             $secmatch = 1;
 9203:                         }
 9204:                     } else {
 9205:                         if (grep(/^\Q$usec\E$/,@{$sections})) {
 9206:                             $secmatch = 1;
 9207:                         }
 9208:                     }
 9209:                     if (!$secmatch) {
 9210:                         next;
 9211:                     }
 9212:                 }
 9213:                 if ($usec eq '') {
 9214:                     $usec = 'none';
 9215:                 }
 9216:                 if ($uname ne '' && $udom ne '') {
 9217:                     if ($hidepriv) {
 9218:                         if ((&Apache::lonnet::privileged($uname,$udom,\@possdoms)) &&
 9219:                             (!$nothide{$uname.':'.$udom})) {
 9220:                             next;
 9221:                         }
 9222:                     }
 9223:                     if ($end > 0 && $end < $now) {
 9224:                         $status = 'previous';
 9225:                     } elsif ($start > $now) {
 9226:                         $status = 'future';
 9227:                     } else {
 9228:                         $status = 'active';
 9229:                     }
 9230:                     foreach my $type (keys(%{$types})) { 
 9231:                         if ($status eq $type) {
 9232:                             if (!grep(/^\Q$type\E$/,@{$$users{$role}{$user}})) {
 9233:                                 push(@{$$users{$role}{$user}},$type);
 9234:                             }
 9235:                             $match = 1;
 9236:                         }
 9237:                     }
 9238:                     if (($match) && (ref($userdata) eq 'HASH')) {
 9239:                         if (!exists($$userdata{$uname.':'.$udom})) {
 9240: 			    &get_user_info($udom,$uname,\%idx,$userdata);
 9241:                         }
 9242:                         if (!grep(/^\Q$usec\E$/,@{$seclists{$uname.':'.$udom}})) {
 9243:                             push(@{$seclists{$uname.':'.$udom}},$usec);
 9244:                         }
 9245:                         if (ref($statushash) eq 'HASH') {
 9246:                             $statushash->{$uname.':'.$udom}{$role}{$usec} = $displaystatus{$status};
 9247:                         }
 9248:                     }
 9249:                 }
 9250:             }
 9251:         }
 9252:         if (grep(/^ow$/,@{$roles})) {
 9253:             if ((defined($cdom)) && (defined($cnum))) {
 9254:                 my %csettings = &Apache::lonnet::get('environment',['internal.courseowner'],$cdom,$cnum);
 9255:                 if ( defined($csettings{'internal.courseowner'}) ) {
 9256:                     my $owner = $csettings{'internal.courseowner'};
 9257:                     next if ($owner eq '');
 9258:                     my ($ownername,$ownerdom);
 9259:                     if ($owner =~ /^([^:]+):([^:]+)$/) {
 9260:                         $ownername = $1;
 9261:                         $ownerdom = $2;
 9262:                     } else {
 9263:                         $ownername = $owner;
 9264:                         $ownerdom = $cdom;
 9265:                         $owner = $ownername.':'.$ownerdom;
 9266:                     }
 9267:                     @{$$users{'ow'}{$owner}} = 'any';
 9268:                     if (defined($userdata) && 
 9269: 			!exists($$userdata{$owner})) {
 9270: 			&get_user_info($ownerdom,$ownername,\%idx,$userdata);
 9271:                         if (!grep(/^none$/,@{$seclists{$owner}})) {
 9272:                             push(@{$seclists{$owner}},'none');
 9273:                         }
 9274:                         if (ref($statushash) eq 'HASH') {
 9275:                             $statushash->{$owner}{'ow'}{'none'} = 'Any';
 9276:                         }
 9277: 		    }
 9278:                 }
 9279:             }
 9280:         }
 9281:         foreach my $user (keys(%seclists)) {
 9282:             @{$seclists{$user}} = (sort {$a <=> $b} @{$seclists{$user}});
 9283:             $$userdata{$user}[$idx{section}] = join(',',@{$seclists{$user}});
 9284:         }
 9285:     }
 9286:     return;
 9287: }
 9288: 
 9289: sub get_user_info {
 9290:     my ($udom,$uname,$idx,$userdata) = @_;
 9291:     $$userdata{$uname.':'.$udom}[$$idx{fullname}] = 
 9292: 	&plainname($uname,$udom,'lastname');
 9293:     $$userdata{$uname.':'.$udom}[$$idx{uname}] = $uname;
 9294:     $$userdata{$uname.':'.$udom}[$$idx{udom}] = $udom;
 9295:     my %idhash =  &Apache::lonnet::idrget($udom,($uname));
 9296:     $$userdata{$uname.':'.$udom}[$$idx{id}] = $idhash{$uname}; 
 9297:     return;
 9298: }
 9299: 
 9300: ###############################################
 9301: 
 9302: =pod
 9303: 
 9304: =item * &get_user_quota()
 9305: 
 9306: Retrieves quota assigned for storage of user files.
 9307: Default is to report quota for portfolio files.
 9308: 
 9309: Incoming parameters:
 9310: 1. user's username
 9311: 2. user's domain
 9312: 3. quota name - portfolio, author, or course
 9313:    (if no quota name provided, defaults to portfolio).
 9314: 4. crstype - official, unofficial, textbook or community, if quota name is
 9315:    course
 9316: 
 9317: Returns:
 9318: 1. Disk quota (in MB) assigned to student.
 9319: 2. (Optional) Type of setting: custom or default
 9320:    (individually assigned or default for user's 
 9321:    institutional status).
 9322: 3. (Optional) - User's institutional status (e.g., faculty, staff
 9323:    or student - types as defined in localenroll::inst_usertypes 
 9324:    for user's domain, which determines default quota for user.
 9325: 4. (Optional) - Default quota which would apply to the user.
 9326: 
 9327: If a value has been stored in the user's environment, 
 9328: it will return that, otherwise it returns the maximal default
 9329: defined for the user's institutional status(es) in the domain.
 9330: 
 9331: =cut
 9332: 
 9333: ###############################################
 9334: 
 9335: 
 9336: sub get_user_quota {
 9337:     my ($uname,$udom,$quotaname,$crstype) = @_;
 9338:     my ($quota,$quotatype,$settingstatus,$defquota);
 9339:     if (!defined($udom)) {
 9340:         $udom = $env{'user.domain'};
 9341:     }
 9342:     if (!defined($uname)) {
 9343:         $uname = $env{'user.name'};
 9344:     }
 9345:     if (($udom eq '' || $uname eq '') ||
 9346:         ($udom eq 'public') && ($uname eq 'public')) {
 9347:         $quota = 0;
 9348:         $quotatype = 'default';
 9349:         $defquota = 0; 
 9350:     } else {
 9351:         my $inststatus;
 9352:         if ($quotaname eq 'course') {
 9353:             if (($env{'course.'.$udom.'_'.$uname.'.num'} eq $uname) &&
 9354:                 ($env{'course.'.$udom.'_'.$uname.'.domain'} eq $udom)) {
 9355:                 $quota = $env{'course.'.$udom.'_'.$uname.'.internal.uploadquota'};
 9356:             } else {
 9357:                 my %cenv = &Apache::lonnet::coursedescription("$udom/$uname");
 9358:                 $quota = $cenv{'internal.uploadquota'};
 9359:             }
 9360:         } else {
 9361:             if ($udom eq $env{'user.domain'} && $uname eq $env{'user.name'}) {
 9362:                 if ($quotaname eq 'author') {
 9363:                     $quota = $env{'environment.authorquota'};
 9364:                 } else {
 9365:                     $quota = $env{'environment.portfolioquota'};
 9366:                 }
 9367:                 $inststatus = $env{'environment.inststatus'};
 9368:             } else {
 9369:                 my %userenv = 
 9370:                     &Apache::lonnet::get('environment',['portfolioquota',
 9371:                                          'authorquota','inststatus'],$udom,$uname);
 9372:                 my ($tmp) = keys(%userenv);
 9373:                 if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
 9374:                     if ($quotaname eq 'author') {
 9375:                         $quota = $userenv{'authorquota'};
 9376:                     } else {
 9377:                         $quota = $userenv{'portfolioquota'};
 9378:                     }
 9379:                     $inststatus = $userenv{'inststatus'};
 9380:                 } else {
 9381:                     undef(%userenv);
 9382:                 }
 9383:             }
 9384:         }
 9385:         if ($quota eq '' || wantarray) {
 9386:             if ($quotaname eq 'course') {
 9387:                 my %domdefs = &Apache::lonnet::get_domain_defaults($udom);
 9388:                 if (($crstype eq 'official') || ($crstype eq 'unofficial') ||
 9389:                     ($crstype eq 'community') || ($crstype eq 'textbook')) {
 9390:                     $defquota = $domdefs{$crstype.'quota'};
 9391:                 }
 9392:                 if ($defquota eq '') {
 9393:                     $defquota = 500;
 9394:                 }
 9395:             } else {
 9396:                 ($defquota,$settingstatus) = &default_quota($udom,$inststatus,$quotaname);
 9397:             }
 9398:             if ($quota eq '') {
 9399:                 $quota = $defquota;
 9400:                 $quotatype = 'default';
 9401:             } else {
 9402:                 $quotatype = 'custom';
 9403:             }
 9404:         }
 9405:     }
 9406:     if (wantarray) {
 9407:         return ($quota,$quotatype,$settingstatus,$defquota);
 9408:     } else {
 9409:         return $quota;
 9410:     }
 9411: }
 9412: 
 9413: ###############################################
 9414: 
 9415: =pod
 9416: 
 9417: =item * &default_quota()
 9418: 
 9419: Retrieves default quota assigned for storage of user portfolio files,
 9420: given an (optional) user's institutional status.
 9421: 
 9422: Incoming parameters:
 9423: 
 9424: 1. domain
 9425: 2. (Optional) institutional status(es).  This is a : separated list of 
 9426:    status types (e.g., faculty, staff, student etc.)
 9427:    which apply to the user for whom the default is being retrieved.
 9428:    If the institutional status string in undefined, the domain
 9429:    default quota will be returned.
 9430: 3.  quota name - portfolio, author, or course
 9431:    (if no quota name provided, defaults to portfolio).
 9432: 
 9433: Returns:
 9434: 
 9435: 1. Default disk quota (in MB) for user portfolios in the domain.
 9436: 2. (Optional) institutional type which determined the value of the
 9437:    default quota.
 9438: 
 9439: If a value has been stored in the domain's configuration db,
 9440: it will return that, otherwise it returns 20 (for backwards 
 9441: compatibility with domains which have not set up a configuration
 9442: db file; the original statically defined portfolio quota was 20 MB). 
 9443: 
 9444: If the user's status includes multiple types (e.g., staff and student),
 9445: the largest default quota which applies to the user determines the
 9446: default quota returned.
 9447: 
 9448: =cut
 9449: 
 9450: ###############################################
 9451: 
 9452: 
 9453: sub default_quota {
 9454:     my ($udom,$inststatus,$quotaname) = @_;
 9455:     my ($defquota,$settingstatus);
 9456:     my %quotahash = &Apache::lonnet::get_dom('configuration',
 9457:                                             ['quotas'],$udom);
 9458:     my $key = 'defaultquota';
 9459:     if ($quotaname eq 'author') {
 9460:         $key = 'authorquota';
 9461:     }
 9462:     if (ref($quotahash{'quotas'}) eq 'HASH') {
 9463:         if ($inststatus ne '') {
 9464:             my @statuses = map { &unescape($_); } split(/:/,$inststatus);
 9465:             foreach my $item (@statuses) {
 9466:                 if (ref($quotahash{'quotas'}{$key}) eq 'HASH') {
 9467:                     if ($quotahash{'quotas'}{$key}{$item} ne '') {
 9468:                         if ($defquota eq '') {
 9469:                             $defquota = $quotahash{'quotas'}{$key}{$item};
 9470:                             $settingstatus = $item;
 9471:                         } elsif ($quotahash{'quotas'}{$key}{$item} > $defquota) {
 9472:                             $defquota = $quotahash{'quotas'}{$key}{$item};
 9473:                             $settingstatus = $item;
 9474:                         }
 9475:                     }
 9476:                 } elsif ($key eq 'defaultquota') {
 9477:                     if ($quotahash{'quotas'}{$item} ne '') {
 9478:                         if ($defquota eq '') {
 9479:                             $defquota = $quotahash{'quotas'}{$item};
 9480:                             $settingstatus = $item;
 9481:                         } elsif ($quotahash{'quotas'}{$item} > $defquota) {
 9482:                             $defquota = $quotahash{'quotas'}{$item};
 9483:                             $settingstatus = $item;
 9484:                         }
 9485:                     }
 9486:                 }
 9487:             }
 9488:         }
 9489:         if ($defquota eq '') {
 9490:             if (ref($quotahash{'quotas'}{$key}) eq 'HASH') {
 9491:                 $defquota = $quotahash{'quotas'}{$key}{'default'};
 9492:             } elsif ($key eq 'defaultquota') {
 9493:                 $defquota = $quotahash{'quotas'}{'default'};
 9494:             }
 9495:             $settingstatus = 'default';
 9496:             if ($defquota eq '') {
 9497:                 if ($quotaname eq 'author') {
 9498:                     $defquota = 500;
 9499:                 }
 9500:             }
 9501:         }
 9502:     } else {
 9503:         $settingstatus = 'default';
 9504:         if ($quotaname eq 'author') {
 9505:             $defquota = 500;
 9506:         } else {
 9507:             $defquota = 20;
 9508:         }
 9509:     }
 9510:     if (wantarray) {
 9511:         return ($defquota,$settingstatus);
 9512:     } else {
 9513:         return $defquota;
 9514:     }
 9515: }
 9516: 
 9517: ###############################################
 9518: 
 9519: =pod
 9520: 
 9521: =item * &excess_filesize_warning()
 9522: 
 9523: Returns warning message if upload of file to authoring space, or copying
 9524: of existing file within authoring space will cause quota for the authoring
 9525: space to be exceeded.
 9526: 
 9527: Same, if upload of a file directly to a course/community via Course Editor
 9528: will cause quota for uploaded content for the course to be exceeded.
 9529: 
 9530: Inputs: 7 
 9531: 1. username or coursenum
 9532: 2. domain
 9533: 3. context ('author' or 'course')
 9534: 4. filename of file for which action is being requested
 9535: 5. filesize (kB) of file
 9536: 6. action being taken: copy or upload.
 9537: 7. quotatype (in course context -- official, unofficial, community or textbook).
 9538: 
 9539: Returns: 1 scalar: HTML to display containing warning if quota would be exceeded,
 9540:          otherwise return null.
 9541: 
 9542: =back
 9543: 
 9544: =cut
 9545: 
 9546: sub excess_filesize_warning {
 9547:     my ($uname,$udom,$context,$filename,$filesize,$action,$quotatype) = @_;
 9548:     my $current_disk_usage = 0;
 9549:     my $disk_quota = &get_user_quota($uname,$udom,$context,$quotatype); #expressed in MB
 9550:     if ($context eq 'author') {
 9551:         my $authorspace = $Apache::lonnet::perlvar{'lonDocRoot'}."/priv/$udom/$uname";
 9552:         $current_disk_usage = &Apache::lonnet::diskusage($udom,$uname,$authorspace);
 9553:     } else {
 9554:         foreach my $subdir ('docs','supplemental') {
 9555:             $current_disk_usage += &Apache::lonnet::diskusage($udom,$uname,"userfiles/$subdir",1);
 9556:         }
 9557:     }
 9558:     $disk_quota = int($disk_quota * 1000);
 9559:     if (($current_disk_usage + $filesize) > $disk_quota) {
 9560:         return '<p class="LC_warning">'.
 9561:                 &mt("Unable to $action [_1]. (size = [_2] kilobytes). Disk quota will be exceeded.",
 9562:                     '<span class="LC_filename">'.$filename.'</span>',$filesize).'</p>'.
 9563:                '<p>'.&mt('Disk quota is [_1] kilobytes. Your current disk usage is [_2] kilobytes.',
 9564:                             $disk_quota,$current_disk_usage).
 9565:                '</p>';
 9566:     }
 9567:     return;
 9568: }
 9569: 
 9570: ###############################################
 9571: 
 9572: 
 9573: sub get_secgrprole_info {
 9574:     my ($cdom,$cnum,$needroles,$type)  = @_;
 9575:     my %sections_count = &get_sections($cdom,$cnum);
 9576:     my @sections =  (sort {$a <=> $b} keys(%sections_count));
 9577:     my %curr_groups = &Apache::longroup::coursegroups($cdom,$cnum);
 9578:     my @groups = sort(keys(%curr_groups));
 9579:     my $allroles = [];
 9580:     my $rolehash;
 9581:     my $accesshash = {
 9582:                      active => 'Currently has access',
 9583:                      future => 'Will have future access',
 9584:                      previous => 'Previously had access',
 9585:                   };
 9586:     if ($needroles) {
 9587:         $rolehash = {'all' => 'all'};
 9588:         my %user_roles = &Apache::lonnet::dump('nohist_userroles',$cdom,$cnum);
 9589: 	if (&Apache::lonnet::error(%user_roles)) {
 9590: 	    undef(%user_roles);
 9591: 	}
 9592:         foreach my $item (keys(%user_roles)) {
 9593:             my ($role)=split(/\:/,$item,2);
 9594:             if ($role eq 'cr') { next; }
 9595:             if ($role =~ /^cr/) {
 9596:                 $$rolehash{$role} = (split('/',$role))[3];
 9597:             } else {
 9598:                 $$rolehash{$role} = &Apache::lonnet::plaintext($role,$type);
 9599:             }
 9600:         }
 9601:         foreach my $key (sort(keys(%{$rolehash}))) {
 9602:             push(@{$allroles},$key);
 9603:         }
 9604:         push (@{$allroles},'st');
 9605:         $$rolehash{'st'} = &Apache::lonnet::plaintext('st',$type);
 9606:     }
 9607:     return (\@sections,\@groups,$allroles,$rolehash,$accesshash);
 9608: }
 9609: 
 9610: sub user_picker {
 9611:     my ($dom,$srch,$forcenewuser,$caller,$cancreate,$usertype,$context,$fixeddom,$noinstd) = @_;
 9612:     my $currdom = $dom;
 9613:     my @alldoms = &Apache::lonnet::all_domains();
 9614:     if (@alldoms == 1) {
 9615:         my %domsrch = &Apache::lonnet::get_dom('configuration',
 9616:                                                ['directorysrch'],$alldoms[0]);
 9617:         my $domdesc = &Apache::lonnet::domain($alldoms[0],'description');
 9618:         my $showdom = $domdesc;
 9619:         if ($showdom eq '') {
 9620:             $showdom = $dom;
 9621:         }
 9622:         if (ref($domsrch{'directorysrch'}) eq 'HASH') {
 9623:             if ((!$domsrch{'directorysrch'}{'available'}) &&
 9624:                 ($domsrch{'directorysrch'}{'lcavailable'} eq '0')) {
 9625:                 return (&mt('LON-CAPA directory search is not available in domain: [_1]',$showdom),0);
 9626:             }
 9627:         }
 9628:     }
 9629:     my %curr_selected = (
 9630:                         srchin => 'dom',
 9631:                         srchby => 'lastname',
 9632:                       );
 9633:     my $srchterm;
 9634:     if ((ref($srch) eq 'HASH') && ($env{'form.origform'} ne 'crtusername')) {
 9635:         if ($srch->{'srchby'} ne '') {
 9636:             $curr_selected{'srchby'} = $srch->{'srchby'};
 9637:         }
 9638:         if ($srch->{'srchin'} ne '') {
 9639:             $curr_selected{'srchin'} = $srch->{'srchin'};
 9640:         }
 9641:         if ($srch->{'srchtype'} ne '') {
 9642:             $curr_selected{'srchtype'} = $srch->{'srchtype'};
 9643:         }
 9644:         if ($srch->{'srchdomain'} ne '') {
 9645:             $currdom = $srch->{'srchdomain'};
 9646:         }
 9647:         $srchterm = $srch->{'srchterm'};
 9648:     }
 9649:     my %html_lt=&Apache::lonlocal::texthash(
 9650:                     'usr'       => 'Search criteria',
 9651:                     'doma'      => 'Domain/institution to search',
 9652:                     'uname'     => 'username',
 9653:                     'lastname'  => 'last name',
 9654:                     'lastfirst' => 'last name, first name',
 9655:                     'crs'       => 'in this course',
 9656:                     'dom'       => 'in selected LON-CAPA domain', 
 9657:                     'alc'       => 'all LON-CAPA',
 9658:                     'instd'     => 'in institutional directory for selected domain',
 9659:                     'exact'     => 'is',
 9660:                     'contains'  => 'contains',
 9661:                     'begins'    => 'begins with',
 9662:                                        );
 9663:     my %js_lt=&Apache::lonlocal::texthash(
 9664:                     'youm'      => "You must include some text to search for.",
 9665:                     'thte'      => "The text you are searching for must contain at least two characters when using a 'begins' type search.",
 9666:                     'thet'      => "The text you are searching for must contain at least three characters when using a 'contains' type search.",
 9667:                     'yomc'      => "You must choose a domain when using an institutional directory search.",
 9668:                     'ymcd'      => "You must choose a domain when using a domain search.",
 9669:                     'whus'      => "When using searching by last,first you must include a comma as separator between last name and first name.",
 9670:                     'whse'      => "When searching by last,first you must include at least one character in the first name.",
 9671:                      'thfo'     => "The following need to be corrected before the search can be run:",
 9672:                                        );
 9673:     &html_escape(\%html_lt);
 9674:     &js_escape(\%js_lt);
 9675:     my $domform;
 9676:     my $allow_blank = 1;
 9677:     if ($fixeddom) {
 9678:         $allow_blank = 0;
 9679:         $domform = &select_dom_form($currdom,'srchdomain',$allow_blank,1,undef,[$currdom]);
 9680:     } else {
 9681:         $domform = &select_dom_form($currdom,'srchdomain',$allow_blank,1);
 9682:     }
 9683:     my $srchinsel = ' <select name="srchin">';
 9684: 
 9685:     my @srchins = ('crs','dom','alc','instd');
 9686: 
 9687:     foreach my $option (@srchins) {
 9688:         # FIXME 'alc' option unavailable until 
 9689:         #       loncreateuser::print_user_query_page()
 9690:         #       has been completed.
 9691:         next if ($option eq 'alc');
 9692:         next if (($option eq 'crs') && ($env{'form.form'} eq 'requestcrs'));  
 9693:         next if ($option eq 'crs' && !$env{'request.course.id'});
 9694:         next if (($option eq 'instd') && ($noinstd));
 9695:         if ($curr_selected{'srchin'} eq $option) {
 9696:             $srchinsel .= ' 
 9697:    <option value="'.$option.'" selected="selected">'.$html_lt{$option}.'</option>';
 9698:         } else {
 9699:             $srchinsel .= '
 9700:    <option value="'.$option.'">'.$html_lt{$option}.'</option>';
 9701:         }
 9702:     }
 9703:     $srchinsel .= "\n  </select>\n";
 9704: 
 9705:     my $srchbysel =  ' <select name="srchby">';
 9706:     foreach my $option ('lastname','lastfirst','uname') {
 9707:         if ($curr_selected{'srchby'} eq $option) {
 9708:             $srchbysel .= '
 9709:    <option value="'.$option.'" selected="selected">'.$html_lt{$option}.'</option>';
 9710:         } else {
 9711:             $srchbysel .= '
 9712:    <option value="'.$option.'">'.$html_lt{$option}.'</option>';
 9713:          }
 9714:     }
 9715:     $srchbysel .= "\n  </select>\n";
 9716: 
 9717:     my $srchtypesel = ' <select name="srchtype">';
 9718:     foreach my $option ('begins','contains','exact') {
 9719:         if ($curr_selected{'srchtype'} eq $option) {
 9720:             $srchtypesel .= '
 9721:    <option value="'.$option.'" selected="selected">'.$html_lt{$option}.'</option>';
 9722:         } else {
 9723:             $srchtypesel .= '
 9724:    <option value="'.$option.'">'.$html_lt{$option}.'</option>';
 9725:         }
 9726:     }
 9727:     $srchtypesel .= "\n  </select>\n";
 9728: 
 9729:     my ($newuserscript,$new_user_create);
 9730:     my $context_dom = $env{'request.role.domain'};
 9731:     if ($context eq 'requestcrs') {
 9732:         if ($env{'form.coursedom'} ne '') { 
 9733:             $context_dom = $env{'form.coursedom'};
 9734:         }
 9735:     }
 9736:     if ($forcenewuser) {
 9737:         if (ref($srch) eq 'HASH') {
 9738:             if ($srch->{'srchby'} eq 'uname' && $srch->{'srchtype'} eq 'exact' && $srch->{'srchin'} eq 'dom' && $srch->{'srchdomain'} eq $context_dom) {
 9739:                 if ($cancreate) {
 9740:                     $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>';
 9741:                 } else {
 9742:                     my $helplink = 'javascript:helpMenu('."'display'".')';
 9743:                     my %usertypetext = (
 9744:                         official   => 'institutional',
 9745:                         unofficial => 'non-institutional',
 9746:                     );
 9747:                     $new_user_create = '<p class="LC_warning">'
 9748:                                       .&mt("You are not authorized to create new $usertypetext{$usertype} users in this domain.")
 9749:                                       .' '
 9750:                                       .&mt('Please contact the [_1]helpdesk[_2] for assistance.'
 9751:                                           ,'<a href="'.$helplink.'">','</a>')
 9752:                                       .'</p><br />';
 9753:                 }
 9754:             }
 9755:         }
 9756: 
 9757:         $newuserscript = <<"ENDSCRIPT";
 9758: 
 9759: function setSearch(createnew,callingForm) {
 9760:     if (createnew == 1) {
 9761:         for (var i=0; i<callingForm.srchby.length; i++) {
 9762:             if (callingForm.srchby.options[i].value == 'uname') {
 9763:                 callingForm.srchby.selectedIndex = i;
 9764:             }
 9765:         }
 9766:         for (var i=0; i<callingForm.srchin.length; i++) {
 9767:             if ( callingForm.srchin.options[i].value == 'dom') {
 9768: 		callingForm.srchin.selectedIndex = i;
 9769:             }
 9770:         }
 9771:         for (var i=0; i<callingForm.srchtype.length; i++) {
 9772:             if (callingForm.srchtype.options[i].value == 'exact') {
 9773:                 callingForm.srchtype.selectedIndex = i;
 9774:             }
 9775:         }
 9776:         for (var i=0; i<callingForm.srchdomain.length; i++) {
 9777:             if (callingForm.srchdomain.options[i].value == '$context_dom') {
 9778:                 callingForm.srchdomain.selectedIndex = i;
 9779:             }
 9780:         }
 9781:     }
 9782: }
 9783: ENDSCRIPT
 9784: 
 9785:     }
 9786: 
 9787:     my $output = <<"END_BLOCK";
 9788: <script type="text/javascript">
 9789: // <![CDATA[
 9790: function validateEntry(callingForm) {
 9791: 
 9792:     var checkok = 1;
 9793:     var srchin;
 9794:     for (var i=0; i<callingForm.srchin.length; i++) {
 9795: 	if ( callingForm.srchin[i].checked ) {
 9796: 	    srchin = callingForm.srchin[i].value;
 9797: 	}
 9798:     }
 9799: 
 9800:     var srchtype = callingForm.srchtype.options[callingForm.srchtype.selectedIndex].value;
 9801:     var srchby = callingForm.srchby.options[callingForm.srchby.selectedIndex].value;
 9802:     var srchdomain = callingForm.srchdomain.options[callingForm.srchdomain.selectedIndex].value;
 9803:     var srchterm =  callingForm.srchterm.value;
 9804:     var srchin = callingForm.srchin.options[callingForm.srchin.selectedIndex].value;
 9805:     var msg = "";
 9806: 
 9807:     if (srchterm == "") {
 9808:         checkok = 0;
 9809:         msg += "$js_lt{'youm'}\\n";
 9810:     }
 9811: 
 9812:     if (srchtype== 'begins') {
 9813:         if (srchterm.length < 2) {
 9814:             checkok = 0;
 9815:             msg += "$js_lt{'thte'}\\n";
 9816:         }
 9817:     }
 9818: 
 9819:     if (srchtype== 'contains') {
 9820:         if (srchterm.length < 3) {
 9821:             checkok = 0;
 9822:             msg += "$js_lt{'thet'}\\n";
 9823:         }
 9824:     }
 9825:     if (srchin == 'instd') {
 9826:         if (srchdomain == '') {
 9827:             checkok = 0;
 9828:             msg += "$js_lt{'yomc'}\\n";
 9829:         }
 9830:     }
 9831:     if (srchin == 'dom') {
 9832:         if (srchdomain == '') {
 9833:             checkok = 0;
 9834:             msg += "$js_lt{'ymcd'}\\n";
 9835:         }
 9836:     }
 9837:     if (srchby == 'lastfirst') {
 9838:         if (srchterm.indexOf(",") == -1) {
 9839:             checkok = 0;
 9840:             msg += "$js_lt{'whus'}\\n";
 9841:         }
 9842:         if (srchterm.indexOf(",") == srchterm.length -1) {
 9843:             checkok = 0;
 9844:             msg += "$js_lt{'whse'}\\n";
 9845:         }
 9846:     }
 9847:     if (checkok == 0) {
 9848:         alert("$js_lt{'thfo'}\\n"+msg);
 9849:         return;
 9850:     }
 9851:     if (checkok == 1) {
 9852:         callingForm.submit();
 9853:     }
 9854: }
 9855: 
 9856: $newuserscript
 9857: 
 9858: // ]]>
 9859: </script>
 9860: 
 9861: $new_user_create
 9862: 
 9863: END_BLOCK
 9864: 
 9865:     $output .= &Apache::lonhtmlcommon::start_pick_box().
 9866:                &Apache::lonhtmlcommon::row_title($html_lt{'doma'}).
 9867:                $domform.
 9868:                &Apache::lonhtmlcommon::row_closure().
 9869:                &Apache::lonhtmlcommon::row_title($html_lt{'usr'}).
 9870:                $srchbysel.
 9871:                $srchtypesel. 
 9872:                '<input type="text" size="15" name="srchterm" value="'.$srchterm.'" />'.
 9873:                $srchinsel.
 9874:                &Apache::lonhtmlcommon::row_closure(1). 
 9875:                &Apache::lonhtmlcommon::end_pick_box().
 9876:                '<br />';
 9877:     return ($output,1);
 9878: }
 9879: 
 9880: sub user_rule_check {
 9881:     my ($usershash,$checks,$alerts,$rulematch,$inst_results,$curr_rules,$got_rules) = @_;
 9882:     my ($response,%inst_response);
 9883:     if (ref($usershash) eq 'HASH') {
 9884:         if (keys(%{$usershash}) > 1) {
 9885:             my (%by_username,%by_id,%userdoms);
 9886:             my $checkid;
 9887:             if (ref($checks) eq 'HASH') {
 9888:                 if ((!defined($checks->{'username'})) && (defined($checks->{'id'}))) {
 9889:                     $checkid = 1;
 9890:                 }
 9891:             }
 9892:             foreach my $user (keys(%{$usershash})) {
 9893:                 my ($uname,$udom) = split(/:/,$user);
 9894:                 if ($checkid) {
 9895:                     if (ref($usershash->{$user}) eq 'HASH') {
 9896:                         if ($usershash->{$user}->{'id'} ne '') {
 9897:                             $by_id{$udom}{$usershash->{$user}->{'id'}} = $uname;
 9898:                             $userdoms{$udom} = 1;
 9899:                             if (ref($inst_results) eq 'HASH') {
 9900:                                 $inst_results->{$uname.':'.$udom} = {};
 9901:                             }
 9902:                         }
 9903:                     }
 9904:                 } else {
 9905:                     $by_username{$udom}{$uname} = 1;
 9906:                     $userdoms{$udom} = 1;
 9907:                     if (ref($inst_results) eq 'HASH') {
 9908:                         $inst_results->{$uname.':'.$udom} = {};
 9909:                     }
 9910:                 }
 9911:             }
 9912:             foreach my $udom (keys(%userdoms)) {
 9913:                 if (!$got_rules->{$udom}) {
 9914:                     my %domconfig = &Apache::lonnet::get_dom('configuration',
 9915:                                                              ['usercreation'],$udom);
 9916:                     if (ref($domconfig{'usercreation'}) eq 'HASH') {
 9917:                         foreach my $item ('username','id') {
 9918:                             if (ref($domconfig{'usercreation'}{$item.'_rule'}) eq 'ARRAY') {
 9919:                                 $$curr_rules{$udom}{$item} =
 9920:                                     $domconfig{'usercreation'}{$item.'_rule'};
 9921:                             }
 9922:                         }
 9923:                     }
 9924:                     $got_rules->{$udom} = 1;
 9925:                 }
 9926:             }
 9927:             if ($checkid) {
 9928:                 foreach my $udom (keys(%by_id)) {
 9929:                     my ($outcome,$results) = &Apache::lonnet::get_multiple_instusers($udom,$by_id{$udom},'id');
 9930:                     if ($outcome eq 'ok') {
 9931:                         foreach my $id (keys(%{$by_id{$udom}})) {
 9932:                             my $uname = $by_id{$udom}{$id};
 9933:                             $inst_response{$uname.':'.$udom} = $outcome;
 9934:                         }
 9935:                         if (ref($results) eq 'HASH') {
 9936:                             foreach my $uname (keys(%{$results})) {
 9937:                                 if (exists($inst_response{$uname.':'.$udom})) {
 9938:                                     $inst_response{$uname.':'.$udom} = $outcome;
 9939:                                     $inst_results->{$uname.':'.$udom} = $results->{$uname};
 9940:                                 }
 9941:                             }
 9942:                         }
 9943:                     }
 9944:                 }
 9945:             } else {
 9946:                 foreach my $udom (keys(%by_username)) {
 9947:                     my ($outcome,$results) = &Apache::lonnet::get_multiple_instusers($udom,$by_username{$udom});
 9948:                     if ($outcome eq 'ok') {
 9949:                         foreach my $uname (keys(%{$by_username{$udom}})) {
 9950:                             $inst_response{$uname.':'.$udom} = $outcome;
 9951:                         }
 9952:                         if (ref($results) eq 'HASH') {
 9953:                             foreach my $uname (keys(%{$results})) {
 9954:                                 $inst_results->{$uname.':'.$udom} = $results->{$uname};
 9955:                             }
 9956:                         }
 9957:                     }
 9958:                 }
 9959:             }
 9960:         } elsif (keys(%{$usershash}) == 1) {
 9961:             my $user = (keys(%{$usershash}))[0];
 9962:             my ($uname,$udom) = split(/:/,$user);
 9963:             if (($udom ne '') && ($uname ne '')) {
 9964:                 if (ref($usershash->{$user}) eq 'HASH') {
 9965:                     if (ref($checks) eq 'HASH') {
 9966:                         if (defined($checks->{'username'})) {
 9967:                             ($inst_response{$user},%{$inst_results->{$user}}) =
 9968:                                 &Apache::lonnet::get_instuser($udom,$uname);
 9969:                         } elsif (defined($checks->{'id'})) {
 9970:                             if ($usershash->{$user}->{'id'} ne '') {
 9971:                                 ($inst_response{$user},%{$inst_results->{$user}}) =
 9972:                                     &Apache::lonnet::get_instuser($udom,undef,
 9973:                                                                   $usershash->{$user}->{'id'});
 9974:                             } else {
 9975:                                 ($inst_response{$user},%{$inst_results->{$user}}) =
 9976:                                     &Apache::lonnet::get_instuser($udom,$uname);
 9977:                             }
 9978:                         }
 9979:                     } else {
 9980:                        ($inst_response{$user},%{$inst_results->{$user}}) =
 9981:                             &Apache::lonnet::get_instuser($udom,$uname);
 9982:                        return;
 9983:                     }
 9984:                     if (!$got_rules->{$udom}) {
 9985:                         my %domconfig = &Apache::lonnet::get_dom('configuration',
 9986:                                                                  ['usercreation'],$udom);
 9987:                         if (ref($domconfig{'usercreation'}) eq 'HASH') {
 9988:                             foreach my $item ('username','id') {
 9989:                                 if (ref($domconfig{'usercreation'}{$item.'_rule'}) eq 'ARRAY') {
 9990:                                    $$curr_rules{$udom}{$item} =
 9991:                                        $domconfig{'usercreation'}{$item.'_rule'};
 9992:                                 }
 9993:                             }
 9994:                         }
 9995:                         $got_rules->{$udom} = 1;
 9996:                     }
 9997:                 }
 9998:             } else {
 9999:                 return;
10000:             }
10001:         } else {
10002:             return;
10003:         }
10004:         foreach my $user (keys(%{$usershash})) {
10005:             my ($uname,$udom) = split(/:/,$user);
10006:             next if (($udom eq '') || ($uname eq ''));
10007:             my $id;
10008:             if (ref($inst_results) eq 'HASH') {
10009:                 if (ref($inst_results->{$user}) eq 'HASH') {
10010:                     $id = $inst_results->{$user}->{'id'};
10011:                 }
10012:             }
10013:             if ($id eq '') {
10014:                 if (ref($usershash->{$user})) {
10015:                     $id = $usershash->{$user}->{'id'};
10016:                 }
10017:             }
10018:             foreach my $item (keys(%{$checks})) {
10019:                 if (ref($$curr_rules{$udom}) eq 'HASH') {
10020:                     if (ref($$curr_rules{$udom}{$item}) eq 'ARRAY') {
10021:                         if (@{$$curr_rules{$udom}{$item}} > 0) {
10022:                             my %rule_check = &Apache::lonnet::inst_rulecheck($udom,$uname,$id,$item,
10023:                                                                              $$curr_rules{$udom}{$item});
10024:                             foreach my $rule (@{$$curr_rules{$udom}{$item}}) {
10025:                                 if ($rule_check{$rule}) {
10026:                                     $$rulematch{$user}{$item} = $rule;
10027:                                     if ($inst_response{$user} eq 'ok') {
10028:                                         if (ref($inst_results) eq 'HASH') {
10029:                                             if (ref($inst_results->{$user}) eq 'HASH') {
10030:                                                 if (keys(%{$inst_results->{$user}}) == 0) {
10031:                                                     $$alerts{$item}{$udom}{$uname} = 1;
10032:                                                 } elsif ($item eq 'id') {
10033:                                                     if ($inst_results->{$user}->{'id'} eq '') {
10034:                                                         $$alerts{$item}{$udom}{$uname} = 1;
10035:                                                     }
10036:                                                 }
10037:                                             }
10038:                                         }
10039:                                     }
10040:                                     last;
10041:                                 }
10042:                             }
10043:                         }
10044:                     }
10045:                 }
10046:             }
10047:         }
10048:     }
10049:     return;
10050: }
10051: 
10052: sub user_rule_formats {
10053:     my ($domain,$domdesc,$curr_rules,$check) = @_;
10054:     my %text = ( 
10055:                  'username' => 'Usernames',
10056:                  'id'       => 'IDs',
10057:                );
10058:     my $output;
10059:     my ($rules,$ruleorder) = &Apache::lonnet::inst_userrules($domain,$check);
10060:     if ((ref($rules) eq 'HASH') && (ref($ruleorder) eq 'ARRAY')) {
10061:         if (@{$ruleorder} > 0) {
10062:             $output = '<br />'.
10063:                       &mt($text{$check}.' with the following format(s) may [_1]only[_2] be used for verified users at [_3]:',
10064:                           '<span class="LC_cusr_emph">','</span>',$domdesc).
10065:                       ' <ul>';
10066:             foreach my $rule (@{$ruleorder}) {
10067:                 if (ref($curr_rules) eq 'ARRAY') {
10068:                     if (grep(/^\Q$rule\E$/,@{$curr_rules})) {
10069:                         if (ref($rules->{$rule}) eq 'HASH') {
10070:                             $output .= '<li>'.$rules->{$rule}{'name'}.': '.
10071:                                         $rules->{$rule}{'desc'}.'</li>';
10072:                         }
10073:                     }
10074:                 }
10075:             }
10076:             $output .= '</ul>';
10077:         }
10078:     }
10079:     return $output;
10080: }
10081: 
10082: sub instrule_disallow_msg {
10083:     my ($checkitem,$domdesc,$count,$mode) = @_;
10084:     my $response;
10085:     my %text = (
10086:                   item   => 'username',
10087:                   items  => 'usernames',
10088:                   match  => 'matches',
10089:                   do     => 'does',
10090:                   action => 'a username',
10091:                   one    => 'one',
10092:                );
10093:     if ($count > 1) {
10094:         $text{'item'} = 'usernames';
10095:         $text{'match'} ='match';
10096:         $text{'do'} = 'do';
10097:         $text{'action'} = 'usernames',
10098:         $text{'one'} = 'ones';
10099:     }
10100:     if ($checkitem eq 'id') {
10101:         $text{'items'} = 'IDs';
10102:         $text{'item'} = 'ID';
10103:         $text{'action'} = 'an ID';
10104:         if ($count > 1) {
10105:             $text{'item'} = 'IDs';
10106:             $text{'action'} = 'IDs';
10107:         }
10108:     }
10109:     $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 />';
10110:     if ($mode eq 'upload') {
10111:         if ($checkitem eq 'username') {
10112:             $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'}.");
10113:         } elsif ($checkitem eq 'id') {
10114:             $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.");
10115:         }
10116:     } elsif ($mode eq 'selfcreate') {
10117:         if ($checkitem eq 'id') {
10118:             $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.");
10119:         }
10120:     } else {
10121:         if ($checkitem eq 'username') {
10122:             $response .= &mt("You must choose $text{'action'} with a different format --  $text{'one'} that will not conflict with 'official' institutional $text{'items'}.");
10123:         } elsif ($checkitem eq 'id') {
10124:             $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.");
10125:         }
10126:     }
10127:     return $response;
10128: }
10129: 
10130: sub personal_data_fieldtitles {
10131:     my %fieldtitles = &Apache::lonlocal::texthash (
10132:                         id => 'Student/Employee ID',
10133:                         permanentemail => 'E-mail address',
10134:                         lastname => 'Last Name',
10135:                         firstname => 'First Name',
10136:                         middlename => 'Middle Name',
10137:                         generation => 'Generation',
10138:                         gen => 'Generation',
10139:                         inststatus => 'Affiliation',
10140:                    );
10141:     return %fieldtitles;
10142: }
10143: 
10144: sub sorted_inst_types {
10145:     my ($dom) = @_;
10146:     my ($usertypes,$order);
10147:     my %domdefaults = &Apache::lonnet::get_domain_defaults($dom);
10148:     if (ref($domdefaults{'inststatus'}) eq 'HASH') {
10149:         $usertypes = $domdefaults{'inststatus'}{'inststatustypes'};
10150:         $order = $domdefaults{'inststatus'}{'inststatusorder'};
10151:     } else {
10152:         ($usertypes,$order) = &Apache::lonnet::retrieve_inst_usertypes($dom);
10153:     }
10154:     my $othertitle = &mt('All users');
10155:     if ($env{'request.course.id'}) {
10156:         $othertitle  = &mt('Any users');
10157:     }
10158:     my @types;
10159:     if (ref($order) eq 'ARRAY') {
10160:         @types = @{$order};
10161:     }
10162:     if (@types == 0) {
10163:         if (ref($usertypes) eq 'HASH') {
10164:             @types = sort(keys(%{$usertypes}));
10165:         }
10166:     }
10167:     if (keys(%{$usertypes}) > 0) {
10168:         $othertitle = &mt('Other users');
10169:     }
10170:     return ($othertitle,$usertypes,\@types);
10171: }
10172: 
10173: sub get_institutional_codes {
10174:     my ($settings,$allcourses,$LC_code) = @_;
10175: # Get complete list of course sections to update
10176:     my @currsections = ();
10177:     my @currxlists = ();
10178:     my $coursecode = $$settings{'internal.coursecode'};
10179: 
10180:     if ($$settings{'internal.sectionnums'} ne '') {
10181:         @currsections = split(/,/,$$settings{'internal.sectionnums'});
10182:     }
10183: 
10184:     if ($$settings{'internal.crosslistings'} ne '') {
10185:         @currxlists = split(/,/,$$settings{'internal.crosslistings'});
10186:     }
10187: 
10188:     if (@currxlists > 0) {
10189:         foreach (@currxlists) {
10190:             if (m/^([^:]+):(\w*)$/) {
10191:                 unless (grep/^$1$/,@{$allcourses}) {
10192:                     push(@{$allcourses},$1);
10193:                     $$LC_code{$1} = $2;
10194:                 }
10195:             }
10196:         }
10197:     }
10198:  
10199:     if (@currsections > 0) {
10200:         foreach (@currsections) {
10201:             if (m/^(\w+):(\w*)$/) {
10202:                 my $sec = $coursecode.$1;
10203:                 my $lc_sec = $2;
10204:                 unless (grep/^$sec$/,@{$allcourses}) {
10205:                     push(@{$allcourses},$sec);
10206:                     $$LC_code{$sec} = $lc_sec;
10207:                 }
10208:             }
10209:         }
10210:     }
10211:     return;
10212: }
10213: 
10214: sub get_standard_codeitems {
10215:     return ('Year','Semester','Department','Number','Section');
10216: }
10217: 
10218: =pod
10219: 
10220: =head1 Slot Helpers
10221: 
10222: =over 4
10223: 
10224: =item * sorted_slots()
10225: 
10226: Sorts an array of slot names in order of an optional sort key,
10227: default sort is by slot start time (earliest first). 
10228: 
10229: Inputs:
10230: 
10231: =over 4
10232: 
10233: slotsarr  - Reference to array of unsorted slot names.
10234: 
10235: slots     - Reference to hash of hash, where outer hash keys are slot names.
10236: 
10237: sortkey   - Name of key in inner hash to be sorted on (e.g., starttime).
10238: 
10239: =back
10240: 
10241: Returns:
10242: 
10243: =over 4
10244: 
10245: sorted   - An array of slot names sorted by a specified sort key 
10246:            (default sort key is start time of the slot).
10247: 
10248: =back
10249: 
10250: =cut
10251: 
10252: 
10253: sub sorted_slots {
10254:     my ($slotsarr,$slots,$sortkey) = @_;
10255:     if ($sortkey eq '') {
10256:         $sortkey = 'starttime';
10257:     }
10258:     my @sorted;
10259:     if ((ref($slotsarr) eq 'ARRAY') && (ref($slots) eq 'HASH')) {
10260:         @sorted =
10261:             sort {
10262:                      if (ref($slots->{$a}) && ref($slots->{$b})) {
10263:                          return $slots->{$a}{$sortkey} <=> $slots->{$b}{$sortkey}
10264:                      }
10265:                      if (ref($slots->{$a})) { return -1;}
10266:                      if (ref($slots->{$b})) { return 1;}
10267:                      return 0;
10268:                  } @{$slotsarr};
10269:     }
10270:     return @sorted;
10271: }
10272: 
10273: =pod
10274: 
10275: =item * get_future_slots()
10276: 
10277: Inputs:
10278: 
10279: =over 4
10280: 
10281: cnum - course number
10282: 
10283: cdom - course domain
10284: 
10285: now - current UNIX time
10286: 
10287: symb - optional symb
10288: 
10289: =back
10290: 
10291: Returns:
10292: 
10293: =over 4
10294: 
10295: sorted_reservable - ref to array of student_schedulable slots currently 
10296:                     reservable, ordered by end date of reservation period.
10297: 
10298: reservable_now - ref to hash of student_schedulable slots currently
10299:                  reservable.
10300: 
10301:     Keys in inner hash are:
10302:     (a) symb: either blank or symb to which slot use is restricted.
10303:     (b) endreserve: end date of reservation period.
10304:     (c) uniqueperiod: start,end dates when slot is to be uniquely
10305:         selected.
10306: 
10307: sorted_future - ref to array of student_schedulable slots reservable in
10308:                 the future, ordered by start date of reservation period.
10309: 
10310: future_reservable - ref to hash of student_schedulable slots reservable
10311:                     in the future.
10312: 
10313:     Keys in inner hash are:
10314:     (a) symb: either blank or symb to which slot use is restricted.
10315:     (b) startreserve:  start date of reservation period.
10316:     (c) uniqueperiod: start,end dates when slot is to be uniquely
10317:         selected.
10318: 
10319: =back
10320: 
10321: =cut
10322: 
10323: sub get_future_slots {
10324:     my ($cnum,$cdom,$now,$symb) = @_;
10325:     my (%reservable_now,%future_reservable,@sorted_reservable,@sorted_future);
10326:     my %slots = &Apache::lonnet::get_course_slots($cnum,$cdom);
10327:     foreach my $slot (keys(%slots)) {
10328:         next unless($slots{$slot}->{'type'} eq 'schedulable_student');
10329:         if ($symb) {
10330:             next if (($slots{$slot}->{'symb'} ne '') && 
10331:                      ($slots{$slot}->{'symb'} ne $symb));
10332:         }
10333:         if (($slots{$slot}->{'starttime'} > $now) &&
10334:             ($slots{$slot}->{'endtime'} > $now)) {
10335:             if (($slots{$slot}->{'allowedsections'}) || ($slots{$slot}->{'allowedusers'})) {
10336:                 my $userallowed = 0;
10337:                 if ($slots{$slot}->{'allowedsections'}) {
10338:                     my @allowed_sec = split(',',$slots{$slot}->{'allowedsections'});
10339:                     if (!defined($env{'request.role.sec'})
10340:                         && grep(/^No section assigned$/,@allowed_sec)) {
10341:                         $userallowed=1;
10342:                     } else {
10343:                         if (grep(/^\Q$env{'request.role.sec'}\E$/,@allowed_sec)) {
10344:                             $userallowed=1;
10345:                         }
10346:                     }
10347:                     unless ($userallowed) {
10348:                         if (defined($env{'request.course.groups'})) {
10349:                             my @groups = split(/:/,$env{'request.course.groups'});
10350:                             foreach my $group (@groups) {
10351:                                 if (grep(/^\Q$group\E$/,@allowed_sec)) {
10352:                                     $userallowed=1;
10353:                                     last;
10354:                                 }
10355:                             }
10356:                         }
10357:                     }
10358:                 }
10359:                 if ($slots{$slot}->{'allowedusers'}) {
10360:                     my @allowed_users = split(',',$slots{$slot}->{'allowedusers'});
10361:                     my $user = $env{'user.name'}.':'.$env{'user.domain'};
10362:                     if (grep(/^\Q$user\E$/,@allowed_users)) {
10363:                         $userallowed = 1;
10364:                     }
10365:                 }
10366:                 next unless($userallowed);
10367:             }
10368:             my $startreserve = $slots{$slot}->{'startreserve'};
10369:             my $endreserve = $slots{$slot}->{'endreserve'};
10370:             my $symb = $slots{$slot}->{'symb'};
10371:             my $uniqueperiod;
10372:             if (ref($slots{$slot}->{'uniqueperiod'}) eq 'ARRAY') {
10373:                 $uniqueperiod = join(',',@{$slots{$slot}->{'uniqueperiod'}});
10374:             }
10375:             if (($startreserve < $now) &&
10376:                 (!$endreserve || $endreserve > $now)) {
10377:                 my $lastres = $endreserve;
10378:                 if (!$lastres) {
10379:                     $lastres = $slots{$slot}->{'starttime'};
10380:                 }
10381:                 $reservable_now{$slot} = {
10382:                                            symb       => $symb,
10383:                                            endreserve => $lastres,
10384:                                            uniqueperiod => $uniqueperiod,   
10385:                                          };
10386:             } elsif (($startreserve > $now) &&
10387:                      (!$endreserve || $endreserve > $startreserve)) {
10388:                 $future_reservable{$slot} = {
10389:                                               symb         => $symb,
10390:                                               startreserve => $startreserve,
10391:                                               uniqueperiod => $uniqueperiod,
10392:                                             };
10393:             }
10394:         }
10395:     }
10396:     my @unsorted_reservable = keys(%reservable_now);
10397:     if (@unsorted_reservable > 0) {
10398:         @sorted_reservable = 
10399:             &sorted_slots(\@unsorted_reservable,\%reservable_now,'endreserve');
10400:     }
10401:     my @unsorted_future = keys(%future_reservable);
10402:     if (@unsorted_future > 0) {
10403:         @sorted_future =
10404:             &sorted_slots(\@unsorted_future,\%future_reservable,'startreserve');
10405:     }
10406:     return (\@sorted_reservable,\%reservable_now,\@sorted_future,\%future_reservable);
10407: }
10408: 
10409: =pod
10410: 
10411: =back
10412: 
10413: =head1 HTTP Helpers
10414: 
10415: =over 4
10416: 
10417: =item * &get_unprocessed_cgi($query,$possible_names)
10418: 
10419: Modify the %env hash to contain unprocessed CGI form parameters held in
10420: $query.  The parameters listed in $possible_names (an array reference),
10421: will be set in $env{'form.name'} if they do not already exist.
10422: 
10423: Typically called with $ENV{'QUERY_STRING'} as the first parameter.  
10424: $possible_names is an ref to an array of form element names.  As an example:
10425: get_unprocessed_cgi($ENV{'QUERY_STRING'},['uname','udom']);
10426: will result in $env{'form.uname'} and $env{'form.udom'} being set.
10427: 
10428: =cut
10429: 
10430: sub get_unprocessed_cgi {
10431:   my ($query,$possible_names)= @_;
10432:   # $Apache::lonxml::debug=1;
10433:   foreach my $pair (split(/&/,$query)) {
10434:     my ($name, $value) = split(/=/,$pair);
10435:     $name = &unescape($name);
10436:     if (!defined($possible_names) || (grep {$_ eq $name} @$possible_names)) {
10437:       $value =~ tr/+/ /;
10438:       $value =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack("C",hex($1))/eg;
10439:       unless (defined($env{'form.'.$name})) { &add_to_env('form.'.$name,$value) };
10440:     }
10441:   }
10442: }
10443: 
10444: =pod
10445: 
10446: =item * &cacheheader() 
10447: 
10448: returns cache-controlling header code
10449: 
10450: =cut
10451: 
10452: sub cacheheader {
10453:     unless ($env{'request.method'} eq 'GET') { return ''; }
10454:     my $date=strftime("%a, %d %b %Y %H:%M:%S GMT",gmtime);
10455:     my $output .='<meta HTTP-EQUIV="Expires" CONTENT="'.$date.'" />
10456:                 <meta HTTP-EQUIV="Cache-control" CONTENT="no-cache" />
10457:                 <meta HTTP-EQUIV="Pragma" CONTENT="no-cache" />';
10458:     return $output;
10459: }
10460: 
10461: =pod
10462: 
10463: =item * &no_cache($r) 
10464: 
10465: specifies header code to not have cache
10466: 
10467: =cut
10468: 
10469: sub no_cache {
10470:     my ($r) = @_;
10471:     if ($ENV{'REQUEST_METHOD'} ne 'GET' &&
10472: 	$env{'request.method'} ne 'GET') { return ''; }
10473:     my $date=strftime("%a, %d %b %Y %H:%M:%S GMT",gmtime(time));
10474:     $r->no_cache(1);
10475:     $r->header_out("Expires" => $date);
10476:     $r->header_out("Pragma" => "no-cache");
10477: }
10478: 
10479: sub content_type {
10480:     my ($r,$type,$charset) = @_;
10481:     if ($r) {
10482: 	#  Note that printout.pl calls this with undef for $r.
10483: 	&no_cache($r);
10484:     }
10485:     if ($env{'browser.mathml'} && $type eq 'text/html') { $type='text/xml'; }
10486:     unless ($charset) {
10487: 	$charset=&Apache::lonlocal::current_encoding;
10488:     }
10489:     if ($charset) { $type.='; charset='.$charset; }
10490:     if ($r) {
10491: 	$r->content_type($type);
10492:     } else {
10493: 	print("Content-type: $type\n\n");
10494:     }
10495: }
10496: 
10497: =pod
10498: 
10499: =item * &add_to_env($name,$value) 
10500: 
10501: adds $name to the %env hash with value
10502: $value, if $name already exists, the entry is converted to an array
10503: reference and $value is added to the array.
10504: 
10505: =cut
10506: 
10507: sub add_to_env {
10508:   my ($name,$value)=@_;
10509:   if (defined($env{$name})) {
10510:     if (ref($env{$name})) {
10511:       #already have multiple values
10512:       push(@{ $env{$name} },$value);
10513:     } else {
10514:       #first time seeing multiple values, convert hash entry to an arrayref
10515:       my $first=$env{$name};
10516:       undef($env{$name});
10517:       push(@{ $env{$name} },$first,$value);
10518:     }
10519:   } else {
10520:     $env{$name}=$value;
10521:   }
10522: }
10523: 
10524: =pod
10525: 
10526: =item * &get_env_multiple($name) 
10527: 
10528: gets $name from the %env hash, it seemlessly handles the cases where multiple
10529: values may be defined and end up as an array ref.
10530: 
10531: returns an array of values
10532: 
10533: =cut
10534: 
10535: sub get_env_multiple {
10536:     my ($name) = @_;
10537:     my @values;
10538:     if (defined($env{$name})) {
10539:         # exists is it an array
10540:         if (ref($env{$name})) {
10541:             @values=@{ $env{$name} };
10542:         } else {
10543:             $values[0]=$env{$name};
10544:         }
10545:     }
10546:     return(@values);
10547: }
10548: 
10549: sub ask_for_embedded_content {
10550:     my ($actionurl,$state,$allfiles,$codebase,$args)=@_;
10551:     my (%subdependencies,%dependencies,%mapping,%existing,%newfiles,%pathchanges,
10552:         %currsubfile,%unused,$rem);
10553:     my $counter = 0;
10554:     my $numnew = 0;
10555:     my $numremref = 0;
10556:     my $numinvalid = 0;
10557:     my $numpathchg = 0;
10558:     my $numexisting = 0;
10559:     my $numunused = 0;
10560:     my ($output,$upload_output,$toplevel,$url,$udom,$uname,$getpropath,$cdom,$cnum,
10561:         $fileloc,$filename,$delete_output,$modify_output,$title,$symb,$path,$navmap);
10562:     my $heading = &mt('Upload embedded files');
10563:     my $buttontext = &mt('Upload');
10564: 
10565:     if ($env{'request.course.id'}) {
10566:         if ($actionurl eq '/adm/dependencies') {
10567:             $navmap = Apache::lonnavmaps::navmap->new();
10568:         }
10569:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
10570:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
10571:     }
10572:     if (($actionurl eq '/adm/portfolio') ||
10573:         ($actionurl eq '/adm/coursegrp_portfolio')) {
10574:         my $current_path='/';
10575:         if ($env{'form.currentpath'}) {
10576:             $current_path = $env{'form.currentpath'};
10577:         }
10578:         if ($actionurl eq '/adm/coursegrp_portfolio') {
10579:             $udom = $cdom;
10580:             $uname = $cnum;
10581:             $url = '/userfiles/groups/'.$env{'form.group'}.'/portfolio';
10582:         } else {
10583:             $udom = $env{'user.domain'};
10584:             $uname = $env{'user.name'};
10585:             $url = '/userfiles/portfolio';
10586:         }
10587:         $toplevel = $url.'/';
10588:         $url .= $current_path;
10589:         $getpropath = 1;
10590:     } elsif (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank') ||
10591:              ($actionurl eq '/adm/imsimport')) { 
10592:         my ($udom,$uname,$rest) = ($args->{'current_path'} =~ m{/priv/($match_domain)/($match_username)/?(.*)$});
10593:         $url = $Apache::lonnet::perlvar{'lonDocRoot'}."/priv/$udom/$uname/";
10594:         $toplevel = $url;
10595:         if ($rest ne '') {
10596:             $url .= $rest;
10597:         }
10598:     } elsif ($actionurl eq '/adm/coursedocs') {
10599:         if (ref($args) eq 'HASH') {
10600:             $url = $args->{'docs_url'};
10601:             $toplevel = $url;
10602:             if ($args->{'context'} eq 'paste') {
10603:                 ($cdom,$cnum) = ($url =~ m{^\Q/uploaded/\E($match_domain)/($match_courseid)/});
10604:                 ($path) =
10605:                     ($toplevel =~ m{^(\Q/uploaded/$cdom/$cnum/\E(?:docs|supplemental)/(?:default|\d+)/\d+)/});
10606:                 $fileloc = &Apache::lonnet::filelocation('',$toplevel);
10607:                 $fileloc =~ s{^/}{};
10608:             }
10609:         }
10610:     } elsif ($actionurl eq '/adm/dependencies') {
10611:         if ($env{'request.course.id'} ne '') {
10612:             if (ref($args) eq 'HASH') {
10613:                 $url = $args->{'docs_url'};
10614:                 $title = $args->{'docs_title'};
10615:                 $toplevel = $url;
10616:                 unless ($toplevel =~ m{^/}) {
10617:                     $toplevel = "/$url";
10618:                 }
10619:                 ($rem) = ($toplevel =~ m{^(.+/)[^/]+$});
10620:                 if ($toplevel =~ m{^(\Q/uploaded/$cdom/$cnum/portfolio/syllabus\E)}) {
10621:                     $path = $1;
10622:                 } else {
10623:                     ($path) =
10624:                         ($toplevel =~ m{^(\Q/uploaded/$cdom/$cnum/\E(?:docs|supplemental)/(?:default|\d+)/\d+)/});
10625:                 }
10626:                 if ($toplevel=~/^\/*(uploaded|editupload)/) {
10627:                     $fileloc = $toplevel;
10628:                     $fileloc=~ s/^\s*(\S+)\s*$/$1/;
10629:                     my ($udom,$uname,$fname) =
10630:                         ($fileloc=~ m{^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$});
10631:                     $fileloc = propath($udom,$uname).'/userfiles/'.$fname;
10632:                 } else {
10633:                     $fileloc = &Apache::lonnet::filelocation('',$toplevel);
10634:                 }
10635:                 $fileloc =~ s{^/}{};
10636:                 ($filename) = ($fileloc =~ m{.+/([^/]+)$});
10637:                 $heading = &mt('Status of dependencies in [_1]',"$title ($filename)");
10638:             }
10639:         }
10640:     } elsif ($actionurl eq "/public/$cdom/$cnum/syllabus") {
10641:         $udom = $cdom;
10642:         $uname = $cnum;
10643:         $url = "/uploaded/$cdom/$cnum/portfolio/syllabus";
10644:         $toplevel = $url;
10645:         $path = $url;
10646:         $fileloc = &Apache::lonnet::filelocation('',$toplevel).'/';
10647:         $fileloc =~ s{^/}{};
10648:     }
10649:     foreach my $file (keys(%{$allfiles})) {
10650:         my $embed_file;
10651:         if (($path eq "/uploaded/$cdom/$cnum/portfolio/syllabus") && ($file =~ m{^\Q$path/\E(.+)$})) {
10652:             $embed_file = $1;
10653:         } else {
10654:             $embed_file = $file;
10655:         }
10656:         my ($absolutepath,$cleaned_file);
10657:         if ($embed_file =~ m{^\w+://}) {
10658:             $cleaned_file = $embed_file;
10659:             $newfiles{$cleaned_file} = 1;
10660:             $mapping{$cleaned_file} = $embed_file;
10661:         } else {
10662:             $cleaned_file = &clean_path($embed_file);
10663:             if ($embed_file =~ m{^/}) {
10664:                 $absolutepath = $embed_file;
10665:             }
10666:             if ($cleaned_file =~ m{/}) {
10667:                 my ($path,$fname) = ($cleaned_file =~ m{^(.+)/([^/]*)$});
10668:                 $path = &check_for_traversal($path,$url,$toplevel);
10669:                 my $item = $fname;
10670:                 if ($path ne '') {
10671:                     $item = $path.'/'.$fname;
10672:                     $subdependencies{$path}{$fname} = 1;
10673:                 } else {
10674:                     $dependencies{$item} = 1;
10675:                 }
10676:                 if ($absolutepath) {
10677:                     $mapping{$item} = $absolutepath;
10678:                 } else {
10679:                     $mapping{$item} = $embed_file;
10680:                 }
10681:             } else {
10682:                 $dependencies{$embed_file} = 1;
10683:                 if ($absolutepath) {
10684:                     $mapping{$cleaned_file} = $absolutepath;
10685:                 } else {
10686:                     $mapping{$cleaned_file} = $embed_file;
10687:                 }
10688:             }
10689:         }
10690:     }
10691:     my $dirptr = 16384;
10692:     foreach my $path (keys(%subdependencies)) {
10693:         $currsubfile{$path} = {};
10694:         if (($actionurl eq '/adm/portfolio') ||
10695:             ($actionurl eq '/adm/coursegrp_portfolio')) { 
10696:             my ($sublistref,$listerror) =
10697:                 &Apache::lonnet::dirlist($url.$path,$udom,$uname,$getpropath);
10698:             if (ref($sublistref) eq 'ARRAY') {
10699:                 foreach my $line (@{$sublistref}) {
10700:                     my ($file_name,$rest) = split(/\&/,$line,2);
10701:                     $currsubfile{$path}{$file_name} = 1;
10702:                 }
10703:             }
10704:         } elsif (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank')) {
10705:             if (opendir(my $dir,$url.'/'.$path)) {
10706:                 my @subdir_list = grep(!/^\./,readdir($dir));
10707:                 map {$currsubfile{$path}{$_} = 1;} @subdir_list;
10708:             }
10709:         } elsif (($actionurl eq '/adm/dependencies') ||
10710:                  (($actionurl eq '/adm/coursedocs') && (ref($args) eq 'HASH') &&
10711:                   ($args->{'context'} eq 'paste')) ||
10712:                  ($actionurl eq "/public/$cdom/$cnum/syllabus")) {
10713:             if ($env{'request.course.id'} ne '') {
10714:                 my $dir;
10715:                 if ($actionurl eq "/public/$cdom/$cnum/syllabus") {
10716:                     $dir = $fileloc;
10717:                 } else {
10718:                     ($dir) = ($fileloc =~ m{^(.+/)[^/]+$});
10719:                 }
10720:                 if ($dir ne '') {
10721:                     my ($sublistref,$listerror) =
10722:                         &Apache::lonnet::dirlist($dir.$path,$cdom,$cnum,$getpropath,undef,'/');
10723:                     if (ref($sublistref) eq 'ARRAY') {
10724:                         foreach my $line (@{$sublistref}) {
10725:                             my ($file_name,$dom,undef,$testdir,undef,undef,undef,undef,$size,
10726:                                 undef,$mtime)=split(/\&/,$line,12);
10727:                             unless (($testdir&$dirptr) ||
10728:                                     ($file_name =~ /^\.\.?$/)) {
10729:                                 $currsubfile{$path}{$file_name} = [$size,$mtime];
10730:                             }
10731:                         }
10732:                     }
10733:                 }
10734:             }
10735:         }
10736:         foreach my $file (keys(%{$subdependencies{$path}})) {
10737:             if (exists($currsubfile{$path}{$file})) {
10738:                 my $item = $path.'/'.$file;
10739:                 unless ($mapping{$item} eq $item) {
10740:                     $pathchanges{$item} = 1;
10741:                 }
10742:                 $existing{$item} = 1;
10743:                 $numexisting ++;
10744:             } else {
10745:                 $newfiles{$path.'/'.$file} = 1;
10746:             }
10747:         }
10748:         if ($actionurl eq '/adm/dependencies') {
10749:             foreach my $path (keys(%currsubfile)) {
10750:                 if (ref($currsubfile{$path}) eq 'HASH') {
10751:                     foreach my $file (keys(%{$currsubfile{$path}})) {
10752:                          unless ($subdependencies{$path}{$file}) {
10753:                              next if (($rem ne '') &&
10754:                                       (($env{"httpref.$rem"."$path/$file"} ne '') ||
10755:                                        (ref($navmap) &&
10756:                                        (($navmap->getResourceByUrl($rem."$path/$file") ne '') ||
10757:                                         (($file =~ /^(.*\.s?html?)\.bak$/i) &&
10758:                                          ($navmap->getResourceByUrl($rem."$path/$1")))))));
10759:                              $unused{$path.'/'.$file} = 1; 
10760:                          }
10761:                     }
10762:                 }
10763:             }
10764:         }
10765:     }
10766:     my %currfile;
10767:     if (($actionurl eq '/adm/portfolio') ||
10768:         ($actionurl eq '/adm/coursegrp_portfolio')) {
10769:         my ($dirlistref,$listerror) =
10770:             &Apache::lonnet::dirlist($url,$udom,$uname,$getpropath);
10771:         if (ref($dirlistref) eq 'ARRAY') {
10772:             foreach my $line (@{$dirlistref}) {
10773:                 my ($file_name,$rest) = split(/\&/,$line,2);
10774:                 $currfile{$file_name} = 1;
10775:             }
10776:         }
10777:     } elsif (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank')) {
10778:         if (opendir(my $dir,$url)) {
10779:             my @dir_list = grep(!/^\./,readdir($dir));
10780:             map {$currfile{$_} = 1;} @dir_list;
10781:         }
10782:     } elsif (($actionurl eq '/adm/dependencies') ||
10783:              (($actionurl eq '/adm/coursedocs') && (ref($args) eq 'HASH') &&
10784:               ($args->{'context'} eq 'paste')) ||
10785:              ($actionurl eq "/public/$cdom/$cnum/syllabus")) {
10786:         if ($env{'request.course.id'} ne '') {
10787:             my ($dir) = ($fileloc =~ m{^(.+/)[^/]+$});
10788:             if ($dir ne '') {
10789:                 my ($dirlistref,$listerror) =
10790:                     &Apache::lonnet::dirlist($dir,$cdom,$cnum,$getpropath,undef,'/');
10791:                 if (ref($dirlistref) eq 'ARRAY') {
10792:                     foreach my $line (@{$dirlistref}) {
10793:                         my ($file_name,$dom,undef,$testdir,undef,undef,undef,undef,
10794:                             $size,undef,$mtime)=split(/\&/,$line,12);
10795:                         unless (($testdir&$dirptr) ||
10796:                                 ($file_name =~ /^\.\.?$/)) {
10797:                             $currfile{$file_name} = [$size,$mtime];
10798:                         }
10799:                     }
10800:                 }
10801:             }
10802:         }
10803:     }
10804:     foreach my $file (keys(%dependencies)) {
10805:         if (exists($currfile{$file})) {
10806:             unless ($mapping{$file} eq $file) {
10807:                 $pathchanges{$file} = 1;
10808:             }
10809:             $existing{$file} = 1;
10810:             $numexisting ++;
10811:         } else {
10812:             $newfiles{$file} = 1;
10813:         }
10814:     }
10815:     foreach my $file (keys(%currfile)) {
10816:         unless (($file eq $filename) ||
10817:                 ($file eq $filename.'.bak') ||
10818:                 ($dependencies{$file})) {
10819:             if ($actionurl eq '/adm/dependencies') {
10820:                 unless ($toplevel =~ m{^\Q/uploaded/$cdom/$cnum/portfolio/syllabus\E}) {
10821:                     next if (($rem ne '') &&
10822:                              (($env{"httpref.$rem".$file} ne '') ||
10823:                               (ref($navmap) &&
10824:                               (($navmap->getResourceByUrl($rem.$file) ne '') ||
10825:                                (($file =~ /^(.*\.s?html?)\.bak$/i) &&
10826:                                 ($navmap->getResourceByUrl($rem.$1)))))));
10827:                 }
10828:             }
10829:             $unused{$file} = 1;
10830:         }
10831:     }
10832:     if (($actionurl eq '/adm/coursedocs') && (ref($args) eq 'HASH') &&
10833:         ($args->{'context'} eq 'paste')) {
10834:         $counter = scalar(keys(%existing));
10835:         $numpathchg = scalar(keys(%pathchanges));
10836:         return ($output,$counter,$numpathchg,\%existing);
10837:     } elsif (($actionurl eq "/public/$cdom/$cnum/syllabus") &&
10838:              (ref($args) eq 'HASH') && ($args->{'context'} eq 'rewrites')) {
10839:         $counter = scalar(keys(%existing));
10840:         $numpathchg = scalar(keys(%pathchanges));
10841:         return ($output,$counter,$numpathchg,\%existing,\%mapping);
10842:     }
10843:     foreach my $embed_file (sort {lc($a) cmp lc($b)} keys(%newfiles)) {
10844:         if ($actionurl eq '/adm/dependencies') {
10845:             next if ($embed_file =~ m{^\w+://});
10846:         }
10847:         $upload_output .= &start_data_table_row().
10848:                           '<td valign="top"><img src="'.&icon($embed_file).'" />&nbsp;'.
10849:                           '<span class="LC_filename">'.$embed_file.'</span>';
10850:         unless ($mapping{$embed_file} eq $embed_file) {
10851:             $upload_output .= '<br /><span class="LC_info" style="font-size:smaller;">'.
10852:                               &mt('changed from: [_1]',$mapping{$embed_file}).'</span>';
10853:         }
10854:         $upload_output .= '</td>';
10855:         if ($args->{'ignore_remote_references'} && $embed_file =~ m{^\w+://}) { 
10856:             $upload_output.='<td align="right">'.
10857:                             '<span class="LC_info LC_fontsize_medium">'.
10858:                             &mt("URL points to web address").'</span>';
10859:             $numremref++;
10860:         } elsif ($args->{'error_on_invalid_names'}
10861:             && $embed_file ne &Apache::lonnet::clean_filename($embed_file,{'keep_path' => 1,})) {
10862:             $upload_output.='<td align="right"><span class="LC_warning">'.
10863:                             &mt('Invalid characters').'</span>';
10864:             $numinvalid++;
10865:         } else {
10866:             $upload_output .= '<td>'.
10867:                               &embedded_file_element('upload_embedded',$counter,
10868:                                                      $embed_file,\%mapping,
10869:                                                      $allfiles,$codebase,'upload');
10870:             $counter ++;
10871:             $numnew ++;
10872:         }
10873:         $upload_output .= '</td>'.&Apache::loncommon::end_data_table_row()."\n";
10874:     }
10875:     foreach my $embed_file (sort {lc($a) cmp lc($b)} keys(%existing)) {
10876:         if ($actionurl eq '/adm/dependencies') {
10877:             my ($size,$mtime) = &get_dependency_details(\%currfile,\%currsubfile,$embed_file);
10878:             $modify_output .= &start_data_table_row().
10879:                               '<td><a href="'.$path.'/'.$embed_file.'" style="text-decoration:none;">'.
10880:                               '<img src="'.&icon($embed_file).'" border="0" />'.
10881:                               '&nbsp;<span class="LC_filename">'.$embed_file.'</span></a></td>'.
10882:                               '<td>'.$size.'</td>'.
10883:                               '<td>'.$mtime.'</td>'.
10884:                               '<td><label><input type="checkbox" name="mod_upload_dep" '.
10885:                               'onclick="toggleBrowse('."'$counter'".')" id="mod_upload_dep_'.
10886:                               $counter.'" value="'.$counter.'" />'.&mt('Yes').'</label>'.
10887:                               '<div id="moduploaddep_'.$counter.'" style="display:none;">'.
10888:                               &embedded_file_element('upload_embedded',$counter,
10889:                                                      $embed_file,\%mapping,
10890:                                                      $allfiles,$codebase,'modify').
10891:                               '</div></td>'.
10892:                               &end_data_table_row()."\n";
10893:             $counter ++;
10894:         } else {
10895:             $upload_output .= &start_data_table_row().
10896:                               '<td valign="top"><img src="'.&icon($embed_file).'" />&nbsp;'.
10897:                               '<span class="LC_filename">'.$embed_file.'</span></td>'.
10898:                               '<td align="right"><span class="LC_info LC_fontsize_medium">'.&mt('Already exists').'</span></td>'.
10899:                               &Apache::loncommon::end_data_table_row()."\n";
10900:         }
10901:     }
10902:     my $delidx = $counter;
10903:     foreach my $oldfile (sort {lc($a) cmp lc($b)} keys(%unused)) {
10904:         my ($size,$mtime) = &get_dependency_details(\%currfile,\%currsubfile,$oldfile);
10905:         $delete_output .= &start_data_table_row().
10906:                           '<td><img src="'.&icon($oldfile).'" />'.
10907:                           '&nbsp;<span class="LC_filename">'.$oldfile.'</span></td>'.
10908:                           '<td>'.$size.'</td>'.
10909:                           '<td>'.$mtime.'</td>'.
10910:                           '<td><label><input type="checkbox" name="del_upload_dep" '.
10911:                           ' value="'.$delidx.'" />'.&mt('Yes').'</label>'.
10912:                           &embedded_file_element('upload_embedded',$delidx,
10913:                                                  $oldfile,\%mapping,$allfiles,
10914:                                                  $codebase,'delete').'</td>'.
10915:                           &end_data_table_row()."\n"; 
10916:         $numunused ++;
10917:         $delidx ++;
10918:     }
10919:     if ($upload_output) {
10920:         $upload_output = &start_data_table().
10921:                          $upload_output.
10922:                          &end_data_table()."\n";
10923:     }
10924:     if ($modify_output) {
10925:         $modify_output = &start_data_table().
10926:                          &start_data_table_header_row().
10927:                          '<th>'.&mt('File').'</th>'.
10928:                          '<th>'.&mt('Size (KB)').'</th>'.
10929:                          '<th>'.&mt('Modified').'</th>'.
10930:                          '<th>'.&mt('Upload replacement?').'</th>'.
10931:                          &end_data_table_header_row().
10932:                          $modify_output.
10933:                          &end_data_table()."\n";
10934:     }
10935:     if ($delete_output) {
10936:         $delete_output = &start_data_table().
10937:                          &start_data_table_header_row().
10938:                          '<th>'.&mt('File').'</th>'.
10939:                          '<th>'.&mt('Size (KB)').'</th>'.
10940:                          '<th>'.&mt('Modified').'</th>'.
10941:                          '<th>'.&mt('Delete?').'</th>'.
10942:                          &end_data_table_header_row().
10943:                          $delete_output.
10944:                          &end_data_table()."\n";
10945:     }
10946:     my $applies = 0;
10947:     if ($numremref) {
10948:         $applies ++;
10949:     }
10950:     if ($numinvalid) {
10951:         $applies ++;
10952:     }
10953:     if ($numexisting) {
10954:         $applies ++;
10955:     }
10956:     if ($counter || $numunused) {
10957:         $output = '<form name="upload_embedded" action="'.$actionurl.'"'.
10958:                   ' method="post" enctype="multipart/form-data">'."\n".
10959:                   $state.'<h3>'.$heading.'</h3>'; 
10960:         if ($actionurl eq '/adm/dependencies') {
10961:             if ($numnew) {
10962:                 $output .= '<h4>'.&mt('Missing dependencies').'</h4>'.
10963:                            '<p>'.&mt('The following files need to be uploaded.').'</p>'."\n".
10964:                            $upload_output.'<br />'."\n";
10965:             }
10966:             if ($numexisting) {
10967:                 $output .= '<h4>'.&mt('Uploaded dependencies (in use)').'</h4>'.
10968:                            '<p>'.&mt('Upload a new file to replace the one currently in use.').'</p>'."\n".
10969:                            $modify_output.'<br />'."\n";
10970:                            $buttontext = &mt('Save changes');
10971:             }
10972:             if ($numunused) {
10973:                 $output .= '<h4>'.&mt('Unused files').'</h4>'.
10974:                            '<p>'.&mt('The following uploaded files are no longer used.').'</p>'."\n".
10975:                            $delete_output.'<br />'."\n";
10976:                            $buttontext = &mt('Save changes');
10977:             }
10978:         } else {
10979:             $output .= $upload_output.'<br />'."\n";
10980:         }
10981:         $output .= '<input type ="hidden" name="number_embedded_items" value="'.
10982:                    $counter.'" />'."\n";
10983:         if ($actionurl eq '/adm/dependencies') { 
10984:             $output .= '<input type ="hidden" name="number_newemb_items" value="'.
10985:                        $numnew.'" />'."\n";
10986:         } elsif ($actionurl eq '') {
10987:             $output .=  '<input type="hidden" name="phase" value="three" />';
10988:         }
10989:     } elsif ($applies) {
10990:         $output = '<b>'.&mt('Referenced files').'</b>:<br />';
10991:         if ($applies > 1) {
10992:             $output .=  
10993:                 &mt('No dependencies need to be uploaded, as one of the following applies to each reference:').'<ul>';
10994:             if ($numremref) {
10995:                 $output .= '<li>'.&mt('reference is to a URL which points to another server').'</li>'."\n";
10996:             }
10997:             if ($numinvalid) {
10998:                 $output .= '<li>'.&mt('reference is to file with a name containing invalid characters').'</li>'."\n";
10999:             }
11000:             if ($numexisting) {
11001:                 $output .= '<li>'.&mt('reference is to an existing file at the specified location').'</li>'."\n";
11002:             }
11003:             $output .= '</ul><br />';
11004:         } elsif ($numremref) {
11005:             $output .= '<p>'.&mt('None to upload, as all references are to URLs pointing to another server.').'</p>';
11006:         } elsif ($numinvalid) {
11007:             $output .= '<p>'.&mt('None to upload, as all references are to files with names containing invalid characters.').'</p>';
11008:         } elsif ($numexisting) {
11009:             $output .= '<p>'.&mt('None to upload, as all references are to existing files.').'</p>';
11010:         }
11011:         $output .= $upload_output.'<br />';
11012:     }
11013:     my ($pathchange_output,$chgcount);
11014:     $chgcount = $counter;
11015:     if (keys(%pathchanges) > 0) {
11016:         foreach my $embed_file (sort {lc($a) cmp lc($b)} keys(%pathchanges)) {
11017:             if ($counter) {
11018:                 $output .= &embedded_file_element('pathchange',$chgcount,
11019:                                                   $embed_file,\%mapping,
11020:                                                   $allfiles,$codebase,'change');
11021:             } else {
11022:                 $pathchange_output .= 
11023:                     &start_data_table_row().
11024:                     '<td><input type ="checkbox" name="namechange" value="'.
11025:                     $chgcount.'" checked="checked" /></td>'.
11026:                     '<td>'.$mapping{$embed_file}.'</td>'.
11027:                     '<td>'.$embed_file.
11028:                     &embedded_file_element('pathchange',$numpathchg,$embed_file,
11029:                                            \%mapping,$allfiles,$codebase,'change').
11030:                     '</td>'.&end_data_table_row();
11031:             }
11032:             $numpathchg ++;
11033:             $chgcount ++;
11034:         }
11035:     }
11036:     if (($counter) || ($numunused)) {
11037:         if ($numpathchg) {
11038:             $output .= '<input type ="hidden" name="number_pathchange_items" value="'.
11039:                        $numpathchg.'" />'."\n";
11040:         }
11041:         if (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank') || 
11042:             ($actionurl eq '/adm/imsimport')) {
11043:             $output .= '<input type="hidden" name="phase" value="three" />'."\n";
11044:         } elsif ($actionurl eq '/adm/portfolio' || $actionurl eq '/adm/coursegrp_portfolio') {
11045:             $output .= '<input type="hidden" name="action" value="upload_embedded" />';
11046:         } elsif ($actionurl eq '/adm/dependencies') {
11047:             $output .= '<input type="hidden" name="action" value="process_changes" />';
11048:         }
11049:         $output .= '<input type ="submit" value="'.$buttontext.'" />'."\n".'</form>'."\n";
11050:     } elsif ($numpathchg) {
11051:         my %pathchange = ();
11052:         $output .= &modify_html_form('pathchange',$actionurl,$state,\%pathchange,$pathchange_output);
11053:         if (($actionurl eq '/adm/portfolio') || ($actionurl eq '/adm/coursegrp_portfolio')) {
11054:             $output .= '<p>'.&mt('or').'</p>'; 
11055:         }
11056:     }
11057:     return ($output,$counter,$numpathchg);
11058: }
11059: 
11060: =pod
11061: 
11062: =item * clean_path($name)
11063: 
11064: Performs clean-up of directories, subdirectories and filename in an
11065: embedded object, referenced in an HTML file which is being uploaded
11066: to a course or portfolio, where
11067: "Upload embedded images/multimedia files if HTML file" checkbox was
11068: checked.
11069: 
11070: Clean-up is similar to replacements in lonnet::clean_filename()
11071: except each / between sub-directory and next level is preserved.
11072: 
11073: =cut
11074: 
11075: sub clean_path {
11076:     my ($embed_file) = @_;
11077:     $embed_file =~s{^/+}{};
11078:     my @contents;
11079:     if ($embed_file =~ m{/}) {
11080:         @contents = split(/\//,$embed_file);
11081:     } else {
11082:         @contents = ($embed_file);
11083:     }
11084:     my $lastidx = scalar(@contents)-1;
11085:     for (my $i=0; $i<=$lastidx; $i++) {
11086:         $contents[$i]=~s{\\}{/}g;
11087:         $contents[$i]=~s/\s+/\_/g;
11088:         $contents[$i]=~s{[^/\w\.\-]}{}g;
11089:         if ($i == $lastidx) {
11090:             $contents[$i]=~s/\.(\d+)(?=\.)/_$1/g;
11091:         }
11092:     }
11093:     if ($lastidx > 0) {
11094:         return join('/',@contents);
11095:     } else {
11096:         return $contents[0];
11097:     }
11098: }
11099: 
11100: sub embedded_file_element {
11101:     my ($context,$num,$embed_file,$mapping,$allfiles,$codebase,$type) = @_;
11102:     return unless ((ref($mapping) eq 'HASH') && (ref($allfiles) eq 'HASH') &&
11103:                    (ref($codebase) eq 'HASH'));
11104:     my $output;
11105:     if (($context eq 'upload_embedded') && ($type ne 'delete')) {
11106:        $output = '<input name="embedded_item_'.$num.'" type="file" value="" />'."\n";
11107:     }
11108:     $output .= '<input name="embedded_orig_'.$num.'" type="hidden" value="'.
11109:                &escape($embed_file).'" />';
11110:     unless (($context eq 'upload_embedded') && 
11111:             ($mapping->{$embed_file} eq $embed_file)) {
11112:         $output .='
11113:         <input name="embedded_ref_'.$num.'" type="hidden" value="'.&escape($mapping->{$embed_file}).'" />';
11114:     }
11115:     my $attrib;
11116:     if (ref($allfiles->{$mapping->{$embed_file}}) eq 'ARRAY') {
11117:         $attrib = &escape(join(':',@{$allfiles->{$mapping->{$embed_file}}}));
11118:     }
11119:     $output .=
11120:         "\n\t\t".
11121:         '<input name="embedded_attrib_'.$num.'" type="hidden" value="'.
11122:         $attrib.'" />';
11123:     if (exists($codebase->{$mapping->{$embed_file}})) {
11124:         $output .=
11125:             "\n\t\t".
11126:             '<input name="codebase_'.$num.'" type="hidden" value="'.
11127:             &escape($codebase->{$mapping->{$embed_file}}).'" />';
11128:     }
11129:     return $output;
11130: }
11131: 
11132: sub get_dependency_details {
11133:     my ($currfile,$currsubfile,$embed_file) = @_;
11134:     my ($size,$mtime,$showsize,$showmtime);
11135:     if ((ref($currfile) eq 'HASH') && (ref($currsubfile))) {
11136:         if ($embed_file =~ m{/}) {
11137:             my ($path,$fname) = split(/\//,$embed_file);
11138:             if (ref($currsubfile->{$path}{$fname}) eq 'ARRAY') {
11139:                 ($size,$mtime) = @{$currsubfile->{$path}{$fname}};
11140:             }
11141:         } else {
11142:             if (ref($currfile->{$embed_file}) eq 'ARRAY') {
11143:                 ($size,$mtime) = @{$currfile->{$embed_file}};
11144:             }
11145:         }
11146:         $showsize = $size/1024.0;
11147:         $showsize = sprintf("%.1f",$showsize);
11148:         if ($mtime > 0) {
11149:             $showmtime = &Apache::lonlocal::locallocaltime($mtime);
11150:         }
11151:     }
11152:     return ($showsize,$showmtime);
11153: }
11154: 
11155: sub ask_embedded_js {
11156:     return <<"END";
11157: <script type="text/javascript"">
11158: // <![CDATA[
11159: function toggleBrowse(counter) {
11160:     var chkboxid = document.getElementById('mod_upload_dep_'+counter);
11161:     var fileid = document.getElementById('embedded_item_'+counter);
11162:     var uploaddivid = document.getElementById('moduploaddep_'+counter);
11163:     if (chkboxid.checked == true) {
11164:         uploaddivid.style.display='block';
11165:     } else {
11166:         uploaddivid.style.display='none';
11167:         fileid.value = '';
11168:     }
11169: }
11170: // ]]>
11171: </script>
11172: 
11173: END
11174: }
11175: 
11176: sub upload_embedded {
11177:     my ($context,$dirpath,$uname,$udom,$dir_root,$url_root,$group,$disk_quota,
11178:         $current_disk_usage,$hiddenstate,$actionurl) = @_;
11179:     my (%pathchange,$output,$modifyform,$footer,$returnflag);
11180:     for (my $i=0; $i<$env{'form.number_embedded_items'}; $i++) {
11181:         next if (!exists($env{'form.embedded_item_'.$i.'.filename'}));
11182:         my $orig_uploaded_filename =
11183:             $env{'form.embedded_item_'.$i.'.filename'};
11184:         foreach my $type ('orig','ref','attrib','codebase') {
11185:             if ($env{'form.embedded_'.$type.'_'.$i} ne '') {
11186:                 $env{'form.embedded_'.$type.'_'.$i} =
11187:                     &unescape($env{'form.embedded_'.$type.'_'.$i});
11188:             }
11189:         }
11190:         my ($path,$fname) =
11191:             ($env{'form.embedded_orig_'.$i} =~ m{(.*/)([^/]*)});
11192:         # no path, whole string is fname
11193:         if (!$fname) { $fname = $env{'form.embedded_orig_'.$i} };
11194:         $fname = &Apache::lonnet::clean_filename($fname);
11195:         # See if there is anything left
11196:         next if ($fname eq '');
11197: 
11198:         # Check if file already exists as a file or directory.
11199:         my ($state,$msg);
11200:         if ($context eq 'portfolio') {
11201:             my $port_path = $dirpath;
11202:             if ($group ne '') {
11203:                 $port_path = "groups/$group/$port_path";
11204:             }
11205:             ($state,$msg) = &check_for_upload($env{'form.currentpath'}.$path,
11206:                                               $fname,$group,'embedded_item_'.$i,
11207:                                               $dir_root,$port_path,$disk_quota,
11208:                                               $current_disk_usage,$uname,$udom);
11209:             if ($state eq 'will_exceed_quota'
11210:                 || $state eq 'file_locked') {
11211:                 $output .= $msg;
11212:                 next;
11213:             }
11214:         } elsif (($context eq 'author') || ($context eq 'testbank')) {
11215:             ($state,$msg) = &check_for_existing($path,$fname,'embedded_item_'.$i);
11216:             if ($state eq 'exists') {
11217:                 $output .= $msg;
11218:                 next;
11219:             }
11220:         }
11221:         # Check if extension is valid
11222:         if (($fname =~ /\.(\w+)$/) &&
11223:             (&Apache::loncommon::fileembstyle($1) eq 'hdn')) {
11224:             $output .= &mt('Invalid file extension ([_1]) - reserved for internal use.',$1)
11225:                       .' '.&mt('Rename the file with a different extension and re-upload.').'<br />';
11226:             next;
11227:         } elsif (($fname =~ /\.(\w+)$/) &&
11228:                  (!defined(&Apache::loncommon::fileembstyle($1)))) {
11229:             $output .= &mt('Unrecognized file extension ([_1]) - rename the file with a proper extension and re-upload.',$1).'<br />';
11230:             next;
11231:         } elsif ($fname=~/\.(\d+)\.(\w+)$/) {
11232:             $output .= &mt('Filename not allowed - rename the file to remove the number immediately before the file extension([_1]) and re-upload.',$2).'<br />';
11233:             next;
11234:         }
11235:         $env{'form.embedded_item_'.$i.'.filename'}=$fname;
11236:         my $subdir = $path;
11237:         $subdir =~ s{/+$}{};
11238:         if ($context eq 'portfolio') {
11239:             my $result;
11240:             if ($state eq 'existingfile') {
11241:                 $result=
11242:                     &Apache::lonnet::userfileupload('embedded_item_'.$i,'existingfile',
11243:                                                     $dirpath.$env{'form.currentpath'}.$subdir);
11244:             } else {
11245:                 $result=
11246:                     &Apache::lonnet::userfileupload('embedded_item_'.$i,'',
11247:                                                     $dirpath.
11248:                                                     $env{'form.currentpath'}.$subdir);
11249:                 if ($result !~ m|^/uploaded/|) {
11250:                     $output .= '<span class="LC_error">'
11251:                                .&mt('An error occurred ([_1]) while trying to upload [_2] for embedded element [_3].'
11252:                                ,$result,$orig_uploaded_filename,$env{'form.embedded_orig_'.$i})
11253:                                .'</span><br />';
11254:                     next;
11255:                 } else {
11256:                     $output .= &mt('Uploaded [_1]','<span class="LC_filename">'.
11257:                                $path.$fname.'</span>').'<br />';     
11258:                 }
11259:             }
11260:         } elsif (($context eq 'coursedoc') || ($context eq 'syllabus')) {
11261:             my $extendedsubdir = $dirpath.'/'.$subdir;
11262:             $extendedsubdir =~ s{/+$}{};
11263:             my $result =
11264:                 &Apache::lonnet::userfileupload('embedded_item_'.$i,$context,$extendedsubdir);
11265:             if ($result !~ m|^/uploaded/|) {
11266:                 $output .= '<span class="LC_error">'
11267:                            .&mt('An error occurred ([_1]) while trying to upload [_2] for embedded element [_3].'
11268:                            ,$result,$orig_uploaded_filename,$env{'form.embedded_orig_'.$i})
11269:                            .'</span><br />';
11270:                     next;
11271:             } else {
11272:                 $output .= &mt('Uploaded [_1]','<span class="LC_filename">'.
11273:                            $path.$fname.'</span>').'<br />';
11274:                 if ($context eq 'syllabus') {
11275:                     &Apache::lonnet::make_public_indefinitely($result);
11276:                 }
11277:             }
11278:         } else {
11279: # Save the file
11280:             my $target = $env{'form.embedded_item_'.$i};
11281:             my $fullpath = $dir_root.$dirpath.'/'.$path;
11282:             my $dest = $fullpath.$fname;
11283:             my $url = $url_root.$dirpath.'/'.$path.$fname;
11284:             my @parts=split(/\//,"$dirpath/$path");
11285:             my $count;
11286:             my $filepath = $dir_root;
11287:             foreach my $subdir (@parts) {
11288:                 $filepath .= "/$subdir";
11289:                 if (!-e $filepath) {
11290:                     mkdir($filepath,0770);
11291:                 }
11292:             }
11293:             my $fh;
11294:             if (!open($fh,'>'.$dest)) {
11295:                 &Apache::lonnet::logthis('Failed to create '.$dest);
11296:                 $output .= '<span class="LC_error">'.
11297:                            &mt('An error occurred while trying to upload [_1] for embedded element [_2].',
11298:                                $orig_uploaded_filename,$env{'form.embedded_orig_'.$i}).
11299:                            '</span><br />';
11300:             } else {
11301:                 if (!print $fh $env{'form.embedded_item_'.$i}) {
11302:                     &Apache::lonnet::logthis('Failed to write to '.$dest);
11303:                     $output .= '<span class="LC_error">'.
11304:                               &mt('An error occurred while writing the file [_1] for embedded element [_2].',
11305:                                   $orig_uploaded_filename,$env{'form.embedded_orig_'.$i}).
11306:                               '</span><br />';
11307:                 } else {
11308:                     $output .= &mt('Uploaded [_1]','<span class="LC_filename">'.
11309:                                $url.'</span>').'<br />';
11310:                     unless ($context eq 'testbank') {
11311:                         $footer .= &mt('View embedded file: [_1]',
11312:                                        '<a href="'.$url.'">'.$fname.'</a>').'<br />';
11313:                     }
11314:                 }
11315:                 close($fh);
11316:             }
11317:         }
11318:         if ($env{'form.embedded_ref_'.$i}) {
11319:             $pathchange{$i} = 1;
11320:         }
11321:     }
11322:     if ($output) {
11323:         $output = '<p>'.$output.'</p>';
11324:     }
11325:     $output .= &modify_html_form('upload_embedded',$actionurl,$hiddenstate,\%pathchange);
11326:     $returnflag = 'ok';
11327:     my $numpathchgs = scalar(keys(%pathchange));
11328:     if ($numpathchgs > 0) {
11329:         if ($context eq 'portfolio') {
11330:             $output .= '<p>'.&mt('or').'</p>';
11331:         } elsif ($context eq 'testbank') {
11332:             $output .=  '<p>'.&mt('Or [_1]continue[_2] the testbank import without modifying the reference(s).',
11333:                                   '<a href="javascript:document.testbankForm.submit();">','</a>').'</p>';
11334:             $returnflag = 'modify_orightml';
11335:         }
11336:     }
11337:     return ($output.$footer,$returnflag,$numpathchgs);
11338: }
11339: 
11340: sub modify_html_form {
11341:     my ($context,$actionurl,$hiddenstate,$pathchange,$pathchgtable) = @_;
11342:     my $end = 0;
11343:     my $modifyform;
11344:     if ($context eq 'upload_embedded') {
11345:         return unless (ref($pathchange) eq 'HASH');
11346:         if ($env{'form.number_embedded_items'}) {
11347:             $end += $env{'form.number_embedded_items'};
11348:         }
11349:         if ($env{'form.number_pathchange_items'}) {
11350:             $end += $env{'form.number_pathchange_items'};
11351:         }
11352:         if ($end) {
11353:             for (my $i=0; $i<$end; $i++) {
11354:                 if ($i < $env{'form.number_embedded_items'}) {
11355:                     next unless($pathchange->{$i});
11356:                 }
11357:                 $modifyform .=
11358:                     &start_data_table_row().
11359:                     '<td><input type ="checkbox" name="namechange" value="'.$i.'" '.
11360:                     'checked="checked" /></td>'.
11361:                     '<td>'.$env{'form.embedded_ref_'.$i}.
11362:                     '<input type="hidden" name="embedded_ref_'.$i.'" value="'.
11363:                     &escape($env{'form.embedded_ref_'.$i}).'" />'.
11364:                     '<input type="hidden" name="embedded_codebase_'.$i.'" value="'.
11365:                     &escape($env{'form.embedded_codebase_'.$i}).'" />'.
11366:                     '<input type="hidden" name="embedded_attrib_'.$i.'" value="'.
11367:                     &escape($env{'form.embedded_attrib_'.$i}).'" /></td>'.
11368:                     '<td>'.$env{'form.embedded_orig_'.$i}.
11369:                     '<input type="hidden" name="embedded_orig_'.$i.'" value="'.
11370:                     &escape($env{'form.embedded_orig_'.$i}).'" /></td>'.
11371:                     &end_data_table_row();
11372:             }
11373:         }
11374:     } else {
11375:         $modifyform = $pathchgtable;
11376:         if (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank')) {
11377:             $hiddenstate .= '<input type="hidden" name="phase" value="four" />';
11378:         } elsif (($actionurl eq '/adm/portfolio') || ($actionurl eq '/adm/coursegrp_portfolio')) {
11379:             $hiddenstate .= '<input type="hidden" name="action" value="modify_orightml" />';
11380:         }
11381:     }
11382:     if ($modifyform) {
11383:         if ($actionurl eq '/adm/dependencies') {
11384:             $hiddenstate .= '<input type="hidden" name="action" value="modifyhrefs" />';
11385:         }
11386:         return '<h3>'.&mt('Changes in content of HTML file required').'</h3>'."\n".
11387:                '<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".
11388:                '<li>'.&mt('For consistency between the reference(s) and the location of the corresponding stored file within LON-CAPA.').'</li>'."\n".
11389:                '<li>'.&mt('To change absolute paths to relative paths, or replace directory traversal via "../" within the original reference.').'</li>'."\n".
11390:                '</ol></p>'."\n".'<p>'.
11391:                &mt('LON-CAPA can make the required changes to your HTML file.').'</p>'."\n".
11392:                '<form method="post" name="refchanger" action="'.$actionurl.'">'.
11393:                &start_data_table()."\n".
11394:                &start_data_table_header_row().
11395:                '<th>'.&mt('Change?').'</th>'.
11396:                '<th>'.&mt('Current reference').'</th>'.
11397:                '<th>'.&mt('Required reference').'</th>'.
11398:                &end_data_table_header_row()."\n".
11399:                $modifyform.
11400:                &end_data_table().'<br />'."\n".$hiddenstate.
11401:                '<input type="submit" name="pathchanges" value="'.&mt('Modify HTML file').'" />'.
11402:                '</form>'."\n";
11403:     }
11404:     return;
11405: }
11406: 
11407: sub modify_html_refs {
11408:     my ($context,$dirpath,$uname,$udom,$dir_root,$url) = @_;
11409:     my $container;
11410:     if ($context eq 'portfolio') {
11411:         $container = $env{'form.container'};
11412:     } elsif ($context eq 'coursedoc') {
11413:         $container = $env{'form.primaryurl'};
11414:     } elsif ($context eq 'manage_dependencies') {
11415:         (undef,undef,$container) = &Apache::lonnet::decode_symb($env{'form.symb'});
11416:         $container = "/$container";
11417:     } elsif ($context eq 'syllabus') {
11418:         $container = $url;
11419:     } else {
11420:         $container = $Apache::lonnet::perlvar{'lonDocRoot'}.$env{'form.filename'};
11421:     }
11422:     my (%allfiles,%codebase,$output,$content);
11423:     my @changes = &get_env_multiple('form.namechange');
11424:     unless ((@changes > 0)  || ($context eq 'syllabus')) {
11425:         if (wantarray) {
11426:             return ('',0,0); 
11427:         } else {
11428:             return;
11429:         }
11430:     }
11431:     if (($context eq 'portfolio') || ($context eq 'coursedoc') || 
11432:         ($context eq 'manage_dependencies') || ($context eq 'syllabus')) {
11433:         unless ($container =~ m{^/uploaded/\Q$udom\E/\Q$uname\E/}) {
11434:             if (wantarray) {
11435:                 return ('',0,0);
11436:             } else {
11437:                 return;
11438:             }
11439:         } 
11440:         $content = &Apache::lonnet::getfile($container);
11441:         if ($content eq '-1') {
11442:             if (wantarray) {
11443:                 return ('',0,0);
11444:             } else {
11445:                 return;
11446:             }
11447:         }
11448:     } else {
11449:         unless ($container =~ /^\Q$dir_root\E/) {
11450:             if (wantarray) {
11451:                 return ('',0,0);
11452:             } else {
11453:                 return;
11454:             }
11455:         } 
11456:         if (open(my $fh,"<$container")) {
11457:             $content = join('', <$fh>);
11458:             close($fh);
11459:         } else {
11460:             if (wantarray) {
11461:                 return ('',0,0);
11462:             } else {
11463:                 return;
11464:             }
11465:         }
11466:     }
11467:     my ($count,$codebasecount) = (0,0);
11468:     my $mm = new File::MMagic;
11469:     my $mime_type = $mm->checktype_contents($content);
11470:     if ($mime_type eq 'text/html') {
11471:         my $parse_result = 
11472:             &Apache::lonnet::extract_embedded_items($container,\%allfiles,
11473:                                                     \%codebase,\$content);
11474:         if ($parse_result eq 'ok') {
11475:             foreach my $i (@changes) {
11476:                 my $orig = &unescape($env{'form.embedded_orig_'.$i});
11477:                 my $ref = &unescape($env{'form.embedded_ref_'.$i});
11478:                 if ($allfiles{$ref}) {
11479:                     my $newname =  $orig;
11480:                     my ($attrib_regexp,$codebase);
11481:                     $attrib_regexp = &unescape($env{'form.embedded_attrib_'.$i});
11482:                     if ($attrib_regexp =~ /:/) {
11483:                         $attrib_regexp =~ s/\:/|/g;
11484:                     }
11485:                     if ($content =~ m{($attrib_regexp\s*=\s*['"]?)\Q$ref\E(['"]?)}) {
11486:                         my $numchg = ($content =~ s{($attrib_regexp\s*=\s*['"]?)\Q$ref\E(['"]?)}{$1$newname$2}gi);
11487:                         $count += $numchg;
11488:                         $allfiles{$newname} = $allfiles{$ref};
11489:                         delete($allfiles{$ref});
11490:                     }
11491:                     if ($env{'form.embedded_codebase_'.$i} ne '') {
11492:                         $codebase = &unescape($env{'form.embedded_codebase_'.$i});
11493:                         my $numchg = ($content =~ s/(codebase\s*=\s*["']?)\Q$codebase\E(["']?)/$1.$2/i); #' stupid emacs
11494:                         $codebasecount ++;
11495:                     }
11496:                 }
11497:             }
11498:             my $skiprewrites;
11499:             if ($count || $codebasecount) {
11500:                 my $saveresult;
11501:                 if (($context eq 'portfolio') || ($context eq 'coursedoc') || 
11502:                     ($context eq 'manage_dependencies') || ($context eq 'syllabus')) {
11503:                     my $url = &Apache::lonnet::store_edited_file($container,$content,$udom,$uname,\$saveresult);
11504:                     if ($url eq $container) {
11505:                         my ($fname) = ($container =~ m{/([^/]+)$});
11506:                         $output = '<p>'.&mt('Updated [quant,_1,reference] in [_2].',
11507:                                             $count,'<span class="LC_filename">'.
11508:                                             $fname.'</span>').'</p>';
11509:                     } else {
11510:                          $output = '<p class="LC_error">'.
11511:                                    &mt('Error: update failed for: [_1].',
11512:                                    '<span class="LC_filename">'.
11513:                                    $container.'</span>').'</p>';
11514:                     }
11515:                     if ($context eq 'syllabus') {
11516:                         unless ($saveresult eq 'ok') {
11517:                             $skiprewrites = 1;
11518:                         }
11519:                     }
11520:                 } else {
11521:                     if (open(my $fh,">$container")) {
11522:                         print $fh $content;
11523:                         close($fh);
11524:                         $output = '<p>'.&mt('Updated [quant,_1,reference] in [_2].',
11525:                                   $count,'<span class="LC_filename">'.
11526:                                   $container.'</span>').'</p>';
11527:                     } else {
11528:                          $output = '<p class="LC_error">'.
11529:                                    &mt('Error: could not update [_1].',
11530:                                    '<span class="LC_filename">'.
11531:                                    $container.'</span>').'</p>';
11532:                     }
11533:                 }
11534:             }
11535:             if (($context eq 'syllabus') && (!$skiprewrites)) {
11536:                 my ($actionurl,$state);
11537:                 $actionurl = "/public/$udom/$uname/syllabus";
11538:                 my ($ignore,$num,$numpathchanges,$existing,$mapping) =
11539:                     &ask_for_embedded_content($actionurl,$state,\%allfiles,
11540:                                               \%codebase,
11541:                                               {'context' => 'rewrites',
11542:                                                'ignore_remote_references' => 1,});
11543:                 if (ref($mapping) eq 'HASH') {
11544:                     my $rewrites = 0;
11545:                     foreach my $key (keys(%{$mapping})) {
11546:                         next if ($key =~ m{^https?://});
11547:                         my $ref = $mapping->{$key};
11548:                         my $newname = "/uploaded/$udom/$uname/portfolio/syllabus/$key";
11549:                         my $attrib;
11550:                         if (ref($allfiles{$mapping->{$key}}) eq 'ARRAY') {
11551:                             $attrib = join('|',@{$allfiles{$mapping->{$key}}});
11552:                         }
11553:                         if ($content =~ m{($attrib\s*=\s*['"]?)\Q$ref\E(['"]?)}) {
11554:                             my $numchg = ($content =~ s{($attrib\s*=\s*['"]?)\Q$ref\E(['"]?)}{$1$newname$2}gi);
11555:                             $rewrites += $numchg;
11556:                         }
11557:                     }
11558:                     if ($rewrites) {
11559:                         my $saveresult;
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('Rewrote [quant,_1,link] as [quant,_1,absolute link] in [_2].',
11564:                                             $count,'<span class="LC_filename">'.
11565:                                             $fname.'</span>').'</p>';
11566:                         } else {
11567:                             $output .= '<p class="LC_error">'.
11568:                                        &mt('Error: could not update links in [_1].',
11569:                                        '<span class="LC_filename">'.
11570:                                        $container.'</span>').'</p>';
11571: 
11572:                         }
11573:                     }
11574:                 }
11575:             }
11576:         } else {
11577:             &logthis('Failed to parse '.$container.
11578:                      ' to modify references: '.$parse_result);
11579:         }
11580:     }
11581:     if (wantarray) {
11582:         return ($output,$count,$codebasecount);
11583:     } else {
11584:         return $output;
11585:     }
11586: }
11587: 
11588: sub check_for_existing {
11589:     my ($path,$fname,$element) = @_;
11590:     my ($state,$msg);
11591:     if (-d $path.'/'.$fname) {
11592:         $state = 'exists';
11593:         $msg = &mt('Unable to upload [_1]. A directory by that name was found in [_2].','<span class="LC_filename">'.$fname.'</span>',$path);
11594:     } elsif (-e $path.'/'.$fname) {
11595:         $state = 'exists';
11596:         $msg = &mt('Unable to upload [_1]. A file by that name was found in [_2].','<span class="LC_filename">'.$fname.'</span>',$path);
11597:     }
11598:     if ($state eq 'exists') {
11599:         $msg = '<span class="LC_error">'.$msg.'</span><br />';
11600:     }
11601:     return ($state,$msg);
11602: }
11603: 
11604: sub check_for_upload {
11605:     my ($path,$fname,$group,$element,$portfolio_root,$port_path,
11606:         $disk_quota,$current_disk_usage,$uname,$udom) = @_;
11607:     my $filesize = length($env{'form.'.$element});
11608:     if (!$filesize) {
11609:         my $msg = '<span class="LC_error">'.
11610:                   &mt('Unable to upload [_1]. (size = [_2] bytes)', 
11611:                       '<span class="LC_filename">'.$fname.'</span>',
11612:                       $filesize).'<br />'.
11613:                   &mt('Either the file you attempted to upload was empty, or your web browser was unable to read its contents.').'<br />'.
11614:                   '</span>';
11615:         return ('zero_bytes',$msg);
11616:     }
11617:     $filesize =  $filesize/1000; #express in k (1024?)
11618:     my $getpropath = 1;
11619:     my ($dirlistref,$listerror) =
11620:          &Apache::lonnet::dirlist($portfolio_root.$path,$udom,$uname,$getpropath);
11621:     my $found_file = 0;
11622:     my $locked_file = 0;
11623:     my @lockers;
11624:     my $navmap;
11625:     if ($env{'request.course.id'}) {
11626:         $navmap = Apache::lonnavmaps::navmap->new();
11627:     }
11628:     if (ref($dirlistref) eq 'ARRAY') {
11629:         foreach my $line (@{$dirlistref}) {
11630:             my ($file_name,$rest)=split(/\&/,$line,2);
11631:             if ($file_name eq $fname){
11632:                 $file_name = $path.$file_name;
11633:                 if ($group ne '') {
11634:                     $file_name = $group.$file_name;
11635:                 }
11636:                 $found_file = 1;
11637:                 if (&Apache::lonnet::is_locked($file_name,$udom,$uname,\@lockers) eq 'true') {
11638:                     foreach my $lock (@lockers) {
11639:                         if (ref($lock) eq 'ARRAY') {
11640:                             my ($symb,$crsid) = @{$lock};
11641:                             if ($crsid eq $env{'request.course.id'}) {
11642:                                 if (ref($navmap)) {
11643:                                     my $res = $navmap->getBySymb($symb);
11644:                                     foreach my $part (@{$res->parts()}) { 
11645:                                         my ($slot_status,$slot_time,$slot_name)=$res->check_for_slot($part);
11646:                                         unless (($slot_status == $res->RESERVED) ||
11647:                                                 ($slot_status == $res->RESERVED_LOCATION)) {
11648:                                             $locked_file = 1;
11649:                                         }
11650:                                     }
11651:                                 } else {
11652:                                     $locked_file = 1;
11653:                                 }
11654:                             } else {
11655:                                 $locked_file = 1;
11656:                             }
11657:                         }
11658:                    }
11659:                 } else {
11660:                     my @info = split(/\&/,$rest);
11661:                     my $currsize = $info[6]/1000;
11662:                     if ($currsize < $filesize) {
11663:                         my $extra = $filesize - $currsize;
11664:                         if (($current_disk_usage + $extra) > $disk_quota) {
11665:                             my $msg = '<p class="LC_warning">'.
11666:                                       &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.',
11667:                                           '<span class="LC_filename">'.$fname.'</span>',$filesize,$currsize).'</p>'.
11668:                                       '<p>'.&mt('Disk quota is [_1] kilobytes. Your current disk usage is [_2] kilobytes.',
11669:                                                    $disk_quota,$current_disk_usage).'</p>';
11670:                             return ('will_exceed_quota',$msg);
11671:                         }
11672:                     }
11673:                 }
11674:             }
11675:         }
11676:     }
11677:     if (($current_disk_usage + $filesize) > $disk_quota){
11678:         my $msg = '<p class="LC_warning">'.
11679:                 &mt('Unable to upload [_1]. (size = [_2] kilobytes). Disk quota will be exceeded.','<span class="LC_filename">'.$fname.'</span>',$filesize).'</p>'.
11680:                   '<p>'.&mt('Disk quota is [_1] kilobytes. Your current disk usage is [_2] kilobytes.',$disk_quota,$current_disk_usage).'</p>';
11681:         return ('will_exceed_quota',$msg);
11682:     } elsif ($found_file) {
11683:         if ($locked_file) {
11684:             my $msg = '<p class="LC_warning">';
11685:             $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>');
11686:             $msg .= '</p>';
11687:             $msg .= &mt('You will be able to rename or delete existing [_1] after a grade has been assigned.','<span class="LC_filename">'.$fname.'</span>');
11688:             return ('file_locked',$msg);
11689:         } else {
11690:             my $msg = '<p class="LC_error">';
11691:             $msg .= &mt(' A file by that name: [_1] was found in [_2].','<span class="LC_filename">'.$fname.'</span>',$port_path.$env{'form.currentpath'});
11692:             $msg .= '</p>';
11693:             return ('existingfile',$msg);
11694:         }
11695:     }
11696: }
11697: 
11698: sub check_for_traversal {
11699:     my ($path,$url,$toplevel) = @_;
11700:     my @parts=split(/\//,$path);
11701:     my $cleanpath;
11702:     my $fullpath = $url;
11703:     for (my $i=0;$i<@parts;$i++) {
11704:         next if ($parts[$i] eq '.');
11705:         if ($parts[$i] eq '..') {
11706:             $fullpath =~ s{([^/]+/)$}{};
11707:         } else {
11708:             $fullpath .= $parts[$i].'/';
11709:         }
11710:     }
11711:     if ($fullpath =~ /^\Q$url\E(.*)$/) {
11712:         $cleanpath = $1;
11713:     } elsif ($fullpath =~ /^\Q$toplevel\E(.*)$/) {
11714:         my $curr_toprel = $1;
11715:         my @parts = split(/\//,$curr_toprel);
11716:         my ($url_toprel) = ($url =~ /^\Q$toplevel\E(.*)$/);
11717:         my @urlparts = split(/\//,$url_toprel);
11718:         my $doubledots;
11719:         my $startdiff = -1;
11720:         for (my $i=0; $i<@urlparts; $i++) {
11721:             if ($startdiff == -1) {
11722:                 unless ($urlparts[$i] eq $parts[$i]) {
11723:                     $startdiff = $i;
11724:                     $doubledots .= '../';
11725:                 }
11726:             } else {
11727:                 $doubledots .= '../';
11728:             }
11729:         }
11730:         if ($startdiff > -1) {
11731:             $cleanpath = $doubledots;
11732:             for (my $i=$startdiff; $i<@parts; $i++) {
11733:                 $cleanpath .= $parts[$i].'/';
11734:             }
11735:         }
11736:     }
11737:     $cleanpath =~ s{(/)$}{};
11738:     return $cleanpath;
11739: }
11740: 
11741: sub is_archive_file {
11742:     my ($mimetype) = @_;
11743:     if (($mimetype eq 'application/octet-stream') ||
11744:         ($mimetype eq 'application/x-stuffit') ||
11745:         ($mimetype =~ m{^application/(x\-)?(compressed|tar|zip|tgz|gz|gtar|gzip|gunzip|bz|bz2|bzip2)})) {
11746:         return 1;
11747:     }
11748:     return;
11749: }
11750: 
11751: sub decompress_form {
11752:     my ($mimetype,$archiveurl,$action,$noextract,$hiddenelements,$dirlist) = @_;
11753:     my %lt = &Apache::lonlocal::texthash (
11754:         this => 'This file is an archive file.',
11755:         camt => 'This file is a Camtasia archive file.',
11756:         itsc => 'Its contents are as follows:',
11757:         youm => 'You may wish to extract its contents.',
11758:         extr => 'Extract contents',
11759:         auto => 'LON-CAPA can process the files automatically, or you can decide how each should be handled.',
11760:         proa => 'Process automatically?',
11761:         yes  => 'Yes',
11762:         no   => 'No',
11763:         fold => 'Title for folder containing movie',
11764:         movi => 'Title for page containing embedded movie', 
11765:     );
11766:     my $fileloc = &Apache::lonnet::filelocation(undef,$archiveurl);
11767:     my ($is_camtasia,$topdir,%toplevel,@paths);
11768:     my $info = &list_archive_contents($fileloc,\@paths);
11769:     if (@paths) {
11770:         foreach my $path (@paths) {
11771:             $path =~ s{^/}{};
11772:             if ($path =~ m{^([^/]+)/$}) {
11773:                 $topdir = $1;
11774:             }
11775:             if ($path =~ m{^([^/]+)/}) {
11776:                 $toplevel{$1} = $path;
11777:             } else {
11778:                 $toplevel{$path} = $path;
11779:             }
11780:         }
11781:     }
11782:     if ($mimetype =~ m{^application/(x\-)?(compressed|zip)}) {
11783:         my @camtasia6 = ("$topdir/","$topdir/index.html",
11784:                         "$topdir/media/",
11785:                         "$topdir/media/$topdir.mp4",
11786:                         "$topdir/media/FirstFrame.png",
11787:                         "$topdir/media/player.swf",
11788:                         "$topdir/media/swfobject.js",
11789:                         "$topdir/media/expressInstall.swf");
11790:         my @camtasia8_1 = ("$topdir/","$topdir/$topdir.html",
11791:                          "$topdir/$topdir.mp4",
11792:                          "$topdir/$topdir\_config.xml",
11793:                          "$topdir/$topdir\_controller.swf",
11794:                          "$topdir/$topdir\_embed.css",
11795:                          "$topdir/$topdir\_First_Frame.png",
11796:                          "$topdir/$topdir\_player.html",
11797:                          "$topdir/$topdir\_Thumbnails.png",
11798:                          "$topdir/playerProductInstall.swf",
11799:                          "$topdir/scripts/",
11800:                          "$topdir/scripts/config_xml.js",
11801:                          "$topdir/scripts/handlebars.js",
11802:                          "$topdir/scripts/jquery-1.7.1.min.js",
11803:                          "$topdir/scripts/jquery-ui-1.8.15.custom.min.js",
11804:                          "$topdir/scripts/modernizr.js",
11805:                          "$topdir/scripts/player-min.js",
11806:                          "$topdir/scripts/swfobject.js",
11807:                          "$topdir/skins/",
11808:                          "$topdir/skins/configuration_express.xml",
11809:                          "$topdir/skins/express_show/",
11810:                          "$topdir/skins/express_show/player-min.css",
11811:                          "$topdir/skins/express_show/spritesheet.png");
11812:         my @camtasia8_4 = ("$topdir/","$topdir/$topdir.html",
11813:                          "$topdir/$topdir.mp4",
11814:                          "$topdir/$topdir\_config.xml",
11815:                          "$topdir/$topdir\_controller.swf",
11816:                          "$topdir/$topdir\_embed.css",
11817:                          "$topdir/$topdir\_First_Frame.png",
11818:                          "$topdir/$topdir\_player.html",
11819:                          "$topdir/$topdir\_Thumbnails.png",
11820:                          "$topdir/playerProductInstall.swf",
11821:                          "$topdir/scripts/",
11822:                          "$topdir/scripts/config_xml.js",
11823:                          "$topdir/scripts/techsmith-smart-player.min.js",
11824:                          "$topdir/skins/",
11825:                          "$topdir/skins/configuration_express.xml",
11826:                          "$topdir/skins/express_show/",
11827:                          "$topdir/skins/express_show/spritesheet.min.css",
11828:                          "$topdir/skins/express_show/spritesheet.png",
11829:                          "$topdir/skins/express_show/techsmith-smart-player.min.css");
11830:         my @diffs = &compare_arrays(\@paths,\@camtasia6);
11831:         if (@diffs == 0) {
11832:             $is_camtasia = 6;
11833:         } else {
11834:             @diffs = &compare_arrays(\@paths,\@camtasia8_1);
11835:             if (@diffs == 0) {
11836:                 $is_camtasia = 8;
11837:             } else {
11838:                 @diffs = &compare_arrays(\@paths,\@camtasia8_4);
11839:                 if (@diffs == 0) {
11840:                     $is_camtasia = 8;
11841:                 }
11842:             }
11843:         }
11844:     }
11845:     my $output;
11846:     if ($is_camtasia) {
11847:         $output = <<"ENDCAM";
11848: <script type="text/javascript" language="Javascript">
11849: // <![CDATA[
11850: 
11851: function camtasiaToggle() {
11852:     for (var i=0; i<document.uploaded_decompress.autoextract_camtasia.length; i++) {
11853:         if (document.uploaded_decompress.autoextract_camtasia[i].checked) {
11854:             if (document.uploaded_decompress.autoextract_camtasia[i].value == $is_camtasia) {
11855:                 document.getElementById('camtasia_titles').style.display='block';
11856:             } else {
11857:                 document.getElementById('camtasia_titles').style.display='none';
11858:             }
11859:         }
11860:     }
11861:     return;
11862: }
11863: 
11864: // ]]>
11865: </script>
11866: <p>$lt{'camt'}</p>
11867: ENDCAM
11868:     } else {
11869:         $output = '<p>'.$lt{'this'};
11870:         if ($info eq '') {
11871:             $output .= ' '.$lt{'youm'}.'</p>'."\n";
11872:         } else {
11873:             $output .= ' '.$lt{'itsc'}.'</p>'."\n".
11874:                        '<div><pre>'.$info.'</pre></div>';
11875:         }
11876:     }
11877:     $output .= '<form name="uploaded_decompress" action="'.$action.'" method="post">'."\n";
11878:     my $duplicates;
11879:     my $num = 0;
11880:     if (ref($dirlist) eq 'ARRAY') {
11881:         foreach my $item (@{$dirlist}) {
11882:             if (ref($item) eq 'ARRAY') {
11883:                 if (exists($toplevel{$item->[0]})) {
11884:                     $duplicates .= 
11885:                         &start_data_table_row().
11886:                         '<td><label><input type="radio" name="archive_overwrite_'.$num.'" '.
11887:                         'value="0" checked="checked" />'.&mt('No').'</label>'.
11888:                         '&nbsp;<label><input type="radio" name="archive_overwrite_'.$num.'" '.
11889:                         'value="1" />'.&mt('Yes').'</label>'.
11890:                         '<input type="hidden" name="archive_overwrite_name_'.$num.'" value="'.$item->[0].'" /></td>'."\n".
11891:                         '<td>'.$item->[0].'</td>';
11892:                     if ($item->[2]) {
11893:                         $duplicates .= '<td>'.&mt('Directory').'</td>';
11894:                     } else {
11895:                         $duplicates .= '<td>'.&mt('File').'</td>';
11896:                     }
11897:                     $duplicates .= '<td>'.$item->[3].'</td>'.
11898:                                    '<td>'.
11899:                                    &Apache::lonlocal::locallocaltime($item->[4]).
11900:                                    '</td>'.
11901:                                    &end_data_table_row();
11902:                     $num ++;
11903:                 }
11904:             }
11905:         }
11906:     }
11907:     my $itemcount;
11908:     if (@paths > 0) {
11909:         $itemcount = scalar(@paths);
11910:     } else {
11911:         $itemcount = 1;
11912:     }
11913:     if ($is_camtasia) {
11914:         $output .= $lt{'auto'}.'<br />'.
11915:                    '<span class="LC_nobreak">'.$lt{'proa'}.'<label>'.
11916:                    '<input type="radio" name="autoextract_camtasia" value="'.$is_camtasia.'" onclick="javascript:camtasiaToggle();" checked="checked" />'.
11917:                    $lt{'yes'}.'</label>&nbsp;<label>'.
11918:                    '<input type="radio" name="autoextract_camtasia" value="0" onclick="javascript:camtasiaToggle();" />'.
11919:                    $lt{'no'}.'</label></span><br />'.
11920:                    '<div id="camtasia_titles" style="display:block">'.
11921:                    &Apache::lonhtmlcommon::start_pick_box().
11922:                    &Apache::lonhtmlcommon::row_title($lt{'fold'}).
11923:                    '<input type="textbox" name="camtasia_foldername" value="'.$env{'form.comment'}.'" />'."\n".
11924:                    &Apache::lonhtmlcommon::row_closure().
11925:                    &Apache::lonhtmlcommon::row_title($lt{'movi'}).
11926:                    '<input type="textbox" name="camtasia_moviename" value="" />'."\n".
11927:                    &Apache::lonhtmlcommon::row_closure(1).
11928:                    &Apache::lonhtmlcommon::end_pick_box().
11929:                    '</div>';
11930:     }
11931:     $output .= 
11932:         '<input type="hidden" name="archive_overwrite_total" value="'.$num.'" />'.
11933:         '<input type="hidden" name="archive_itemcount" value="'.$itemcount.'" />'.
11934:         "\n";
11935:     if ($duplicates ne '') {
11936:         $output .= '<p><span class="LC_warning">'.
11937:                    &mt('Warning: decompression of the archive will overwrite the following items which already exist:').'</span><br />'.  
11938:                    &start_data_table().
11939:                    &start_data_table_header_row().
11940:                    '<th>'.&mt('Overwrite?').'</th>'.
11941:                    '<th>'.&mt('Name').'</th>'.
11942:                    '<th>'.&mt('Type').'</th>'.
11943:                    '<th>'.&mt('Size').'</th>'.
11944:                    '<th>'.&mt('Last modified').'</th>'.
11945:                    &end_data_table_header_row().
11946:                    $duplicates.
11947:                    &end_data_table().
11948:                    '</p>';
11949:     }
11950:     $output .= '<input type="hidden" name="archiveurl" value="'.$archiveurl.'" />'."\n";
11951:     if (ref($hiddenelements) eq 'HASH') {
11952:         foreach my $hidden (sort(keys(%{$hiddenelements}))) {
11953:             $output .= '<input type="hidden" name="'.$hidden.'" value="'.$hiddenelements->{$hidden}.'" />'."\n";
11954:         }
11955:     }
11956:     $output .= <<"END";
11957: <br />
11958: <input type="submit" name="decompress" value="$lt{'extr'}" />
11959: </form>
11960: $noextract
11961: END
11962:     return $output;
11963: }
11964: 
11965: sub decompression_utility {
11966:     my ($program) = @_;
11967:     my @utilities = ('tar','gunzip','bunzip2','unzip'); 
11968:     my $location;
11969:     if (grep(/^\Q$program\E$/,@utilities)) { 
11970:         foreach my $dir ('/bin/','/usr/bin/','/usr/local/bin/','/sbin/',
11971:                          '/usr/sbin/') {
11972:             if (-x $dir.$program) {
11973:                 $location = $dir.$program;
11974:                 last;
11975:             }
11976:         }
11977:     }
11978:     return $location;
11979: }
11980: 
11981: sub list_archive_contents {
11982:     my ($file,$pathsref) = @_;
11983:     my (@cmd,$output);
11984:     my $needsregexp;
11985:     if ($file =~ /\.zip$/) {
11986:         @cmd = (&decompression_utility('unzip'),"-l");
11987:         $needsregexp = 1;
11988:     } elsif (($file =~ m/\.tar\.gz$/) ||
11989:              ($file =~ /\.tgz$/)) {
11990:         @cmd = (&decompression_utility('tar'),"-ztf");
11991:     } elsif ($file =~ /\.tar\.bz2$/) {
11992:         @cmd = (&decompression_utility('tar'),"-jtf");
11993:     } elsif ($file =~ m|\.tar$|) {
11994:         @cmd = (&decompression_utility('tar'),"-tf");
11995:     }
11996:     if (@cmd) {
11997:         undef($!);
11998:         undef($@);
11999:         if (open(my $fh,"-|", @cmd, $file)) {
12000:             while (my $line = <$fh>) {
12001:                 $output .= $line;
12002:                 chomp($line);
12003:                 my $item;
12004:                 if ($needsregexp) {
12005:                     ($item) = ($line =~ /^\s*\d+\s+[\d\-]+\s+[\d:]+\s*(.+)$/); 
12006:                 } else {
12007:                     $item = $line;
12008:                 }
12009:                 if ($item ne '') {
12010:                     unless (grep(/^\Q$item\E$/,@{$pathsref})) {
12011:                         push(@{$pathsref},$item);
12012:                     } 
12013:                 }
12014:             }
12015:             close($fh);
12016:         }
12017:     }
12018:     return $output;
12019: }
12020: 
12021: sub decompress_uploaded_file {
12022:     my ($file,$dir) = @_;
12023:     &Apache::lonnet::appenv({'cgi.file' => $file});
12024:     &Apache::lonnet::appenv({'cgi.dir' => $dir});
12025:     my $result = &Apache::lonnet::ssi_body('/cgi-bin/decompress.pl');
12026:     my ($handle) = ($env{'user.environment'} =~m{/([^/]+)\.id$});
12027:     my $lonidsdir = $Apache::lonnet::perlvar{'lonIDsDir'};
12028:     &Apache::lonnet::transfer_profile_to_env($lonidsdir,$handle,1);
12029:     my $decompressed = $env{'cgi.decompressed'};
12030:     &Apache::lonnet::delenv('cgi.file');
12031:     &Apache::lonnet::delenv('cgi.dir');
12032:     &Apache::lonnet::delenv('cgi.decompressed');
12033:     return ($decompressed,$result);
12034: }
12035: 
12036: sub process_decompression {
12037:     my ($docudom,$docuname,$file,$destination,$dir_root,$hiddenelem) = @_;
12038:     my ($dir,$error,$warning,$output);
12039:     if ($file !~ /\.(zip|tar|bz2|gz|tar.gz|tar.bz2|tgz)$/i) {
12040:         $error = &mt('Filename not a supported archive file type.').
12041:                  '<br />'.&mt('Filename should end with one of: [_1].',
12042:                               '.zip, .tar, .bz2, .gz, .tar.gz, .tar.bz2, .tgz');
12043:     } else {
12044:         my $docuhome = &Apache::lonnet::homeserver($docuname,$docudom);
12045:         if ($docuhome eq 'no_host') {
12046:             $error = &mt('Could not determine home server for course.');
12047:         } else {
12048:             my @ids=&Apache::lonnet::current_machine_ids();
12049:             my $currdir = "$dir_root/$destination";
12050:             if (grep(/^\Q$docuhome\E$/,@ids)) {
12051:                 $dir = &LONCAPA::propath($docudom,$docuname).
12052:                        "$dir_root/$destination";
12053:             } else {
12054:                 $dir = $Apache::lonnet::perlvar{'lonDocRoot'}.
12055:                        "$dir_root/$docudom/$docuname/$destination";
12056:                 unless (&Apache::lonnet::repcopy_userfile("$dir/$file") eq 'ok') {
12057:                     $error = &mt('Archive file not found.');
12058:                 }
12059:             }
12060:             my (@to_overwrite,@to_skip);
12061:             if ($env{'form.archive_overwrite_total'} > 0) {
12062:                 my $total = $env{'form.archive_overwrite_total'};
12063:                 for (my $i=0; $i<$total; $i++) {
12064:                     if ($env{'form.archive_overwrite_'.$i} == 1) {
12065:                         push(@to_overwrite,$env{'form.archive_overwrite_name_'.$i});
12066:                     } elsif ($env{'form.archive_overwrite_'.$i} == 0) {
12067:                         push(@to_skip,$env{'form.archive_overwrite_name_'.$i});
12068:                     }
12069:                 }
12070:             }
12071:             my $numskip = scalar(@to_skip);
12072:             if (($numskip > 0) && 
12073:                 ($numskip == $env{'form.archive_itemcount'})) {
12074:                 $warning = &mt('All items in the archive file already exist, and no overwriting of existing files has been requested.');         
12075:             } elsif ($dir eq '') {
12076:                 $error = &mt('Directory containing archive file unavailable.');
12077:             } elsif (!$error) {
12078:                 my ($decompressed,$display);
12079:                 if ($numskip > 0) {
12080:                     my $tempdir = time.'_'.$$.int(rand(10000));
12081:                     mkdir("$dir/$tempdir",0755);
12082:                     system("mv $dir/$file $dir/$tempdir/$file");
12083:                     ($decompressed,$display) = 
12084:                         &decompress_uploaded_file($file,"$dir/$tempdir");
12085:                     foreach my $item (@to_skip) {
12086:                         if (($item ne '') && ($item !~ /\.\./)) {
12087:                             if (-f "$dir/$tempdir/$item") { 
12088:                                 unlink("$dir/$tempdir/$item");
12089:                             } elsif (-d "$dir/$tempdir/$item") {
12090:                                 system("rm -rf $dir/$tempdir/$item");
12091:                             }
12092:                         }
12093:                     }
12094:                     system("mv $dir/$tempdir/* $dir");
12095:                     rmdir("$dir/$tempdir");   
12096:                 } else {
12097:                     ($decompressed,$display) = 
12098:                         &decompress_uploaded_file($file,$dir);
12099:                 }
12100:                 if ($decompressed eq 'ok') {
12101:                     $output = '<p class="LC_info">'.
12102:                               &mt('Files extracted successfully from archive.').
12103:                               '</p>'."\n";
12104:                     my ($warning,$result,@contents);
12105:                     my ($newdirlistref,$newlisterror) =
12106:                         &Apache::lonnet::dirlist($currdir,$docudom,
12107:                                                  $docuname,1);
12108:                     my (%is_dir,%changes,@newitems);
12109:                     my $dirptr = 16384;
12110:                     if (ref($newdirlistref) eq 'ARRAY') {
12111:                         foreach my $dir_line (@{$newdirlistref}) {
12112:                             my ($item,undef,undef,$testdir)=split(/\&/,$dir_line,5);
12113:                             unless (($item =~ /^\.+$/) || ($item eq $file) || 
12114:                                     ((@to_skip > 0) && (grep(/^\Q$item\E$/,@to_skip)))) {
12115:                                 push(@newitems,$item);
12116:                                 if ($dirptr&$testdir) {
12117:                                     $is_dir{$item} = 1;
12118:                                 }
12119:                                 $changes{$item} = 1;
12120:                             }
12121:                         }
12122:                     }
12123:                     if (keys(%changes) > 0) {
12124:                         foreach my $item (sort(@newitems)) {
12125:                             if ($changes{$item}) {
12126:                                 push(@contents,$item);
12127:                             }
12128:                         }
12129:                     }
12130:                     if (@contents > 0) {
12131:                         my $wantform;
12132:                         unless ($env{'form.autoextract_camtasia'}) {
12133:                             $wantform = 1;
12134:                         }
12135:                         my (%children,%parent,%dirorder,%titles);
12136:                         my ($count,$datatable) = &get_extracted($docudom,$docuname,
12137:                                                                 $currdir,\%is_dir,
12138:                                                                 \%children,\%parent,
12139:                                                                 \@contents,\%dirorder,
12140:                                                                 \%titles,$wantform);
12141:                         if ($datatable ne '') {
12142:                             $output .= &archive_options_form('decompressed',$datatable,
12143:                                                              $count,$hiddenelem);
12144:                             my $startcount = 6;
12145:                             $output .= &archive_javascript($startcount,$count,
12146:                                                            \%titles,\%children);
12147:                         }
12148:                         if ($env{'form.autoextract_camtasia'}) {
12149:                             my $version = $env{'form.autoextract_camtasia'};
12150:                             my %displayed;
12151:                             my $total = 1;
12152:                             $env{'form.archive_directory'} = [];
12153:                             foreach my $i (sort { $a <=> $b } keys(%dirorder)) {
12154:                                 my $path = join('/',map { $titles{$_}; } @{$dirorder{$i}});
12155:                                 $path =~ s{/$}{};
12156:                                 my $item;
12157:                                 if ($path ne '') {
12158:                                     $item = "$path/$titles{$i}";
12159:                                 } else {
12160:                                     $item = $titles{$i};
12161:                                 }
12162:                                 $env{'form.archive_content_'.$i} = "$dir_root/$destination/$item";
12163:                                 if ($item eq $contents[0]) {
12164:                                     push(@{$env{'form.archive_directory'}},$i);
12165:                                     $env{'form.archive_'.$i} = 'display';
12166:                                     $env{'form.archive_title_'.$i} = $env{'form.camtasia_foldername'};
12167:                                     $displayed{'folder'} = $i;
12168:                                 } elsif ((($item eq "$contents[0]/index.html") && ($version == 6)) ||
12169:                                          (($item eq "$contents[0]/$contents[0]".'.html') && ($version == 8))) {
12170:                                     $env{'form.archive_'.$i} = 'display';
12171:                                     $env{'form.archive_title_'.$i} = $env{'form.camtasia_moviename'};
12172:                                     $displayed{'web'} = $i;
12173:                                 } else {
12174:                                     if ((($item eq "$contents[0]/media") && ($version == 6)) ||
12175:                                         ((($item eq "$contents[0]/scripts") || ($item eq "$contents[0]/skins") ||
12176:                                              ($item eq "$contents[0]/skins/express_show")) && ($version == 8))) {
12177:                                         push(@{$env{'form.archive_directory'}},$i);
12178:                                     }
12179:                                     $env{'form.archive_'.$i} = 'dependency';
12180:                                 }
12181:                                 $total ++;
12182:                             }
12183:                             for (my $i=1; $i<$total; $i++) {
12184:                                 next if ($i == $displayed{'web'});
12185:                                 next if ($i == $displayed{'folder'});
12186:                                 $env{'form.archive_dependent_on_'.$i} = $displayed{'web'};
12187:                             }
12188:                             $env{'form.phase'} = 'decompress_cleanup';
12189:                             $env{'form.archivedelete'} = 1;
12190:                             $env{'form.archive_count'} = $total-1;
12191:                             $output .=
12192:                                 &process_extracted_files('coursedocs',$docudom,
12193:                                                          $docuname,$destination,
12194:                                                          $dir_root,$hiddenelem);
12195:                         }
12196:                     } else {
12197:                         $warning = &mt('No new items extracted from archive file.');
12198:                     }
12199:                 } else {
12200:                     $output = $display;
12201:                     $error = &mt('An error occurred during extraction from the archive file.');
12202:                 }
12203:             }
12204:         }
12205:     }
12206:     if ($error) {
12207:         $output .= '<p class="LC_error">'.&mt('Not extracted.').'<br />'.
12208:                    $error.'</p>'."\n";
12209:     }
12210:     if ($warning) {
12211:         $output .= '<p class="LC_warning">'.$warning.'</p>'."\n";
12212:     }
12213:     return $output;
12214: }
12215: 
12216: sub get_extracted {
12217:     my ($docudom,$docuname,$currdir,$is_dir,$children,$parent,$contents,$dirorder,
12218:         $titles,$wantform) = @_;
12219:     my $count = 0;
12220:     my $depth = 0;
12221:     my $datatable;
12222:     my @hierarchy;
12223:     return unless ((ref($is_dir) eq 'HASH') && (ref($children) eq 'HASH') &&
12224:                    (ref($parent) eq 'HASH') && (ref($contents) eq 'ARRAY') &&
12225:                    (ref($dirorder) eq 'HASH') && (ref($titles) eq 'HASH'));
12226:     foreach my $item (@{$contents}) {
12227:         $count ++;
12228:         @{$dirorder->{$count}} = @hierarchy;
12229:         $titles->{$count} = $item;
12230:         &archive_hierarchy($depth,$count,$parent,$children);
12231:         if ($wantform) {
12232:             $datatable .= &archive_row($is_dir->{$item},$item,
12233:                                        $currdir,$depth,$count);
12234:         }
12235:         if ($is_dir->{$item}) {
12236:             $depth ++;
12237:             push(@hierarchy,$count);
12238:             $parent->{$depth} = $count;
12239:             $datatable .=
12240:                 &recurse_extracted_archive("$currdir/$item",$docudom,$docuname,
12241:                                            \$depth,\$count,\@hierarchy,$dirorder,
12242:                                            $children,$parent,$titles,$wantform);
12243:             $depth --;
12244:             pop(@hierarchy);
12245:         }
12246:     }
12247:     return ($count,$datatable);
12248: }
12249: 
12250: sub recurse_extracted_archive {
12251:     my ($currdir,$docudom,$docuname,$depth,$count,$hierarchy,$dirorder,
12252:         $children,$parent,$titles,$wantform) = @_;
12253:     my $result='';
12254:     unless ((ref($depth)) && (ref($count)) && (ref($hierarchy) eq 'ARRAY') &&
12255:             (ref($children) eq 'HASH') && (ref($parent) eq 'HASH') &&
12256:             (ref($dirorder) eq 'HASH')) {
12257:         return $result;
12258:     }
12259:     my $dirptr = 16384;
12260:     my ($newdirlistref,$newlisterror) =
12261:         &Apache::lonnet::dirlist($currdir,$docudom,$docuname,1);
12262:     if (ref($newdirlistref) eq 'ARRAY') {
12263:         foreach my $dir_line (@{$newdirlistref}) {
12264:             my ($item,undef,undef,$testdir)=split(/\&/,$dir_line,5);
12265:             unless ($item =~ /^\.+$/) {
12266:                 $$count ++;
12267:                 @{$dirorder->{$$count}} = @{$hierarchy};
12268:                 $titles->{$$count} = $item;
12269:                 &archive_hierarchy($$depth,$$count,$parent,$children);
12270: 
12271:                 my $is_dir;
12272:                 if ($dirptr&$testdir) {
12273:                     $is_dir = 1;
12274:                 }
12275:                 if ($wantform) {
12276:                     $result .= &archive_row($is_dir,$item,$currdir,$$depth,$$count);
12277:                 }
12278:                 if ($is_dir) {
12279:                     $$depth ++;
12280:                     push(@{$hierarchy},$$count);
12281:                     $parent->{$$depth} = $$count;
12282:                     $result .=
12283:                         &recurse_extracted_archive("$currdir/$item",$docudom,
12284:                                                    $docuname,$depth,$count,
12285:                                                    $hierarchy,$dirorder,$children,
12286:                                                    $parent,$titles,$wantform);
12287:                     $$depth --;
12288:                     pop(@{$hierarchy});
12289:                 }
12290:             }
12291:         }
12292:     }
12293:     return $result;
12294: }
12295: 
12296: sub archive_hierarchy {
12297:     my ($depth,$count,$parent,$children) =@_;
12298:     if ((ref($parent) eq 'HASH') && (ref($children) eq 'HASH')) {
12299:         if (exists($parent->{$depth})) {
12300:              $children->{$parent->{$depth}} .= $count.':';
12301:         }
12302:     }
12303:     return;
12304: }
12305: 
12306: sub archive_row {
12307:     my ($is_dir,$item,$currdir,$depth,$count) = @_;
12308:     my ($name) = ($item =~ m{([^/]+)$});
12309:     my %choices = &Apache::lonlocal::texthash (
12310:                                        'display'    => 'Add as file',
12311:                                        'dependency' => 'Include as dependency',
12312:                                        'discard'    => 'Discard',
12313:                                       );
12314:     if ($is_dir) {
12315:         $choices{'display'} = &mt('Add as folder'); 
12316:     }
12317:     my $output = &start_data_table_row().'<td align="right">'.$count.'</td>'."\n";
12318:     my $offset = 0;
12319:     foreach my $action ('display','dependency','discard') {
12320:         $offset ++;
12321:         if ($action ne 'display') {
12322:             $offset ++;
12323:         }  
12324:         $output .= '<td><span class="LC_nobreak">'.
12325:                    '<label><input type="radio" name="archive_'.$count.
12326:                    '" id="archive_'.$action.'_'.$count.'" value="'.$action.'"';
12327:         my $text = $choices{$action};
12328:         if ($is_dir) {
12329:             $output .= ' onclick="javascript:propagateCheck(this.form,'."'$count'".');"';
12330:             if ($action eq 'display') {
12331:                 $text = &mt('Add as folder');
12332:             }
12333:         } else {
12334:             $output .= ' onclick="javascript:dependencyCheck(this.form,'."$count,$offset".');"';
12335: 
12336:         }
12337:         $output .= ' />&nbsp;'.$choices{$action}.'</label></span>';
12338:         if ($action eq 'dependency') {
12339:             $output .= '<div id="arc_depon_'.$count.'" style="display:none;">'."\n".
12340:                        &mt('Used by:').'&nbsp;<select name="archive_dependent_on_'.$count.'" '.
12341:                        'onchange="propagateSelect(this.form,'."$count,$offset".')">'."\n".
12342:                        '<option value=""></option>'."\n".
12343:                        '</select>'."\n".
12344:                        '</div>';
12345:         } elsif ($action eq 'display') {
12346:             $output .= '<div id="arc_title_'.$count.'" style="display:none;">'."\n".
12347:                        &mt('Title:').'&nbsp;<input type="text" name="archive_title_'.$count.'" id="archive_title_'.$count.'" />'."\n".
12348:                        '</div>';
12349:         }
12350:         $output .= '</td>';
12351:     }
12352:     $output .= '<td><input type="hidden" name="archive_content_'.$count.'" value="'.
12353:                &HTML::Entities::encode("$currdir/$item",'"<>&').'" />'.('&nbsp;' x 2);
12354:     for (my $i=0; $i<$depth; $i++) {
12355:         $output .= ('<img src="/adm/lonIcons/whitespace1.gif" class="LC_docs_spacer" alt="" />' x2)."\n";
12356:     }
12357:     if ($is_dir) {
12358:         $output .= '<img src="/adm/lonIcons/navmap.folder.open.gif" alt="" />&nbsp;'."\n".
12359:                    '<input type="hidden" name="archive_directory" value="'.$count.'" />'."\n";
12360:     } else {
12361:         $output .= '<input type="hidden" name="archive_file" value="'.$count.'" />'."\n";
12362:     }
12363:     $output .= '&nbsp;'.$name.'</td>'."\n".
12364:                &end_data_table_row();
12365:     return $output;
12366: }
12367: 
12368: sub archive_options_form {
12369:     my ($form,$display,$count,$hiddenelem) = @_;
12370:     my %lt = &Apache::lonlocal::texthash(
12371:                perm => 'Permanently remove archive file?',
12372:                hows => 'How should each extracted item be incorporated in the course?',
12373:                cont => 'Content actions for all',
12374:                addf => 'Add as folder/file',
12375:                incd => 'Include as dependency for a displayed file',
12376:                disc => 'Discard',
12377:                no   => 'No',
12378:                yes  => 'Yes',
12379:                save => 'Save',
12380:     );
12381:     my $output = <<"END";
12382: <form name="$form" method="post" action="">
12383: <p><span class="LC_nobreak">$lt{'perm'}&nbsp;
12384: <label>
12385:   <input type="radio" name="archivedelete" value="0" checked="checked" />$lt{'no'}
12386: </label>
12387: &nbsp;
12388: <label>
12389:   <input type="radio" name="archivedelete" value="1" />$lt{'yes'}</label>
12390: </span>
12391: </p>
12392: <input type="hidden" name="phase" value="decompress_cleanup" />
12393: <br />$lt{'hows'}
12394: <div class="LC_columnSection">
12395:   <fieldset>
12396:     <legend>$lt{'cont'}</legend>
12397:     <input type="button" value="$lt{'addf'}" onclick="javascript:checkAll(document.$form,'display');" /> 
12398:     &nbsp;&nbsp;<input type="button" value="$lt{'incd'}" onclick="javascript:checkAll(document.$form,'dependency');" />
12399:     &nbsp;&nbsp;<input type="button" value="$lt{'disc'}" onclick="javascript:checkAll(document.$form,'discard');" />
12400:   </fieldset>
12401: </div>
12402: END
12403:     return $output.
12404:            &start_data_table()."\n".
12405:            $display."\n".
12406:            &end_data_table()."\n".
12407:            '<input type="hidden" name="archive_count" value="'.$count.'" />'.
12408:            $hiddenelem.
12409:            '<br /><input type="submit" name="archive_submit" value="'.$lt{'save'}.'" />'.
12410:            '</form>';
12411: }
12412: 
12413: sub archive_javascript {
12414:     my ($startcount,$numitems,$titles,$children) = @_;
12415:     return unless ((ref($titles) eq 'HASH') && (ref($children) eq 'HASH'));
12416:     my $maintitle = $env{'form.comment'};
12417:     my $scripttag = <<START;
12418: <script type="text/javascript">
12419: // <![CDATA[
12420: 
12421: function checkAll(form,prefix) {
12422:     var idstr =  new RegExp("^archive_"+prefix+"_\\\\d+\$");
12423:     for (var i=0; i < form.elements.length; i++) {
12424:         var id = form.elements[i].id;
12425:         if ((id != '') && (id != undefined)) {
12426:             if (idstr.test(id)) {
12427:                 if (form.elements[i].type == 'radio') {
12428:                     form.elements[i].checked = true;
12429:                     var nostart = i-$startcount;
12430:                     var offset = nostart%7;
12431:                     var count = (nostart-offset)/7;    
12432:                     dependencyCheck(form,count,offset);
12433:                 }
12434:             }
12435:         }
12436:     }
12437: }
12438: 
12439: function propagateCheck(form,count) {
12440:     if (count > 0) {
12441:         var startelement = $startcount + ((count-1) * 7);
12442:         for (var j=1; j<6; j++) {
12443:             if ((j != 2) && (j != 4)) {
12444:                 var item = startelement + j; 
12445:                 if (form.elements[item].type == 'radio') {
12446:                     if (form.elements[item].checked) {
12447:                         containerCheck(form,count,j);
12448:                         break;
12449:                     }
12450:                 }
12451:             }
12452:         }
12453:     }
12454: }
12455: 
12456: numitems = $numitems
12457: var titles = new Array(numitems);
12458: var parents = new Array(numitems);
12459: for (var i=0; i<numitems; i++) {
12460:     parents[i] = new Array;
12461: }
12462: var maintitle = '$maintitle';
12463: 
12464: START
12465: 
12466:     foreach my $container (sort { $a <=> $b } (keys(%{$children}))) {
12467:         my @contents = split(/:/,$children->{$container});
12468:         for (my $i=0; $i<@contents; $i ++) {
12469:             $scripttag .= 'parents['.$container.']['.$i.'] = '.$contents[$i]."\n";
12470:         }
12471:     }
12472: 
12473:     foreach my $key (sort { $a <=> $b } (keys(%{$titles}))) {
12474:         $scripttag .= "titles[$key] = '".$titles->{$key}."';\n";
12475:     }
12476: 
12477:     $scripttag .= <<END;
12478: 
12479: function containerCheck(form,count,offset) {
12480:     if (count > 0) {
12481:         dependencyCheck(form,count,offset);
12482:         var item = (offset+$startcount)+7*(count-1);
12483:         form.elements[item].checked = true;
12484:         if(Object.prototype.toString.call(parents[count]) === '[object Array]') {
12485:             if (parents[count].length > 0) {
12486:                 for (var j=0; j<parents[count].length; j++) {
12487:                     containerCheck(form,parents[count][j],offset);
12488:                 }
12489:             }
12490:         }
12491:     }
12492: }
12493: 
12494: function dependencyCheck(form,count,offset) {
12495:     if (count > 0) {
12496:         var chosen = (offset+$startcount)+7*(count-1);
12497:         var depitem = $startcount + ((count-1) * 7) + 4;
12498:         var currtype = form.elements[depitem].type;
12499:         if (form.elements[chosen].value == 'dependency') {
12500:             document.getElementById('arc_depon_'+count).style.display='block'; 
12501:             form.elements[depitem].options.length = 0;
12502:             form.elements[depitem].options[0] = new Option('Select','',true,true);
12503:             for (var i=1; i<=numitems; i++) {
12504:                 if (i == count) {
12505:                     continue;
12506:                 }
12507:                 var startelement = $startcount + (i-1) * 7;
12508:                 for (var j=1; j<6; j++) {
12509:                     if ((j != 2) && (j!= 4)) {
12510:                         var item = startelement + j;
12511:                         if (form.elements[item].type == 'radio') {
12512:                             if (form.elements[item].checked) {
12513:                                 if (form.elements[item].value == 'display') {
12514:                                     var n = form.elements[depitem].options.length;
12515:                                     form.elements[depitem].options[n] = new Option(titles[i],i,false,false);
12516:                                 }
12517:                             }
12518:                         }
12519:                     }
12520:                 }
12521:             }
12522:         } else {
12523:             document.getElementById('arc_depon_'+count).style.display='none';
12524:             form.elements[depitem].options.length = 0;
12525:             form.elements[depitem].options[0] = new Option('Select','',true,true);
12526:         }
12527:         titleCheck(form,count,offset);
12528:     }
12529: }
12530: 
12531: function propagateSelect(form,count,offset) {
12532:     if (count > 0) {
12533:         var item = (1+offset+$startcount)+7*(count-1);
12534:         var picked = form.elements[item].options[form.elements[item].selectedIndex].value; 
12535:         if (Object.prototype.toString.call(parents[count]) === '[object Array]') {
12536:             if (parents[count].length > 0) {
12537:                 for (var j=0; j<parents[count].length; j++) {
12538:                     containerSelect(form,parents[count][j],offset,picked);
12539:                 }
12540:             }
12541:         }
12542:     }
12543: }
12544: 
12545: function containerSelect(form,count,offset,picked) {
12546:     if (count > 0) {
12547:         var item = (offset+$startcount)+7*(count-1);
12548:         if (form.elements[item].type == 'radio') {
12549:             if (form.elements[item].value == 'dependency') {
12550:                 if (form.elements[item+1].type == 'select-one') {
12551:                     for (var i=0; i<form.elements[item+1].options.length; i++) {
12552:                         if (form.elements[item+1].options[i].value == picked) {
12553:                             form.elements[item+1].selectedIndex = i;
12554:                             break;
12555:                         }
12556:                     }
12557:                 }
12558:                 if (Object.prototype.toString.call(parents[count]) === '[object Array]') {
12559:                     if (parents[count].length > 0) {
12560:                         for (var j=0; j<parents[count].length; j++) {
12561:                             containerSelect(form,parents[count][j],offset,picked);
12562:                         }
12563:                     }
12564:                 }
12565:             }
12566:         }
12567:     }
12568: }
12569: 
12570: function titleCheck(form,count,offset) {
12571:     if (count > 0) {
12572:         var chosen = (offset+$startcount)+7*(count-1);
12573:         var depitem = $startcount + ((count-1) * 7) + 2;
12574:         var currtype = form.elements[depitem].type;
12575:         if (form.elements[chosen].value == 'display') {
12576:             document.getElementById('arc_title_'+count).style.display='block';
12577:             if ((count==1) && ((parents[count].length > 0) || (numitems == 1))) {
12578:                 document.getElementById('archive_title_'+count).value=maintitle;
12579:             }
12580:         } else {
12581:             document.getElementById('arc_title_'+count).style.display='none';
12582:             if (currtype == 'text') { 
12583:                 document.getElementById('archive_title_'+count).value='';
12584:             }
12585:         }
12586:     }
12587:     return;
12588: }
12589: 
12590: // ]]>
12591: </script>
12592: END
12593:     return $scripttag;
12594: }
12595: 
12596: sub process_extracted_files {
12597:     my ($context,$docudom,$docuname,$destination,$dir_root,$hiddenelem) = @_;
12598:     my $numitems = $env{'form.archive_count'};
12599:     return unless ($numitems);
12600:     my @ids=&Apache::lonnet::current_machine_ids();
12601:     my ($prefix,$pathtocheck,$dir,$ishome,$error,$warning,%toplevelitems,%is_dir,
12602:         %folders,%containers,%mapinner,%prompttofetch);
12603:     my $docuhome = &Apache::lonnet::homeserver($docuname,$docudom);
12604:     if (grep(/^\Q$docuhome\E$/,@ids)) {
12605:         $prefix = &LONCAPA::propath($docudom,$docuname);
12606:         $pathtocheck = "$dir_root/$destination";
12607:         $dir = $dir_root;
12608:         $ishome = 1;
12609:     } else {
12610:         $prefix = $Apache::lonnet::perlvar{'lonDocRoot'};
12611:         $pathtocheck = "$dir_root/$docudom/$docuname/$destination";
12612:         $dir = "$dir_root/$docudom/$docuname";    
12613:     }
12614:     my $currdir = "$dir_root/$destination";
12615:     (my $docstype,$mapinner{'0'}) = ($destination =~ m{^(docs|supplemental)/(\w+)/});
12616:     if ($env{'form.folderpath'}) {
12617:         my @items = split('&',$env{'form.folderpath'});
12618:         $folders{'0'} = $items[-2];
12619:         if ($env{'form.folderpath'} =~ /\:1$/) {
12620:             $containers{'0'}='page';
12621:         } else {
12622:             $containers{'0'}='sequence';
12623:         }
12624:     }
12625:     my @archdirs = &get_env_multiple('form.archive_directory');
12626:     if ($numitems) {
12627:         for (my $i=1; $i<=$numitems; $i++) {
12628:             my $path = $env{'form.archive_content_'.$i};
12629:             if ($path =~ m{^\Q$pathtocheck\E/([^/]+)$}) {
12630:                 my $item = $1;
12631:                 $toplevelitems{$item} = $i;
12632:                 if (grep(/^\Q$i\E$/,@archdirs)) {
12633:                     $is_dir{$item} = 1;
12634:                 }
12635:             }
12636:         }
12637:     }
12638:     my ($output,%children,%parent,%titles,%dirorder,$result);
12639:     if (keys(%toplevelitems) > 0) {
12640:         my @contents = sort(keys(%toplevelitems));
12641:         (my $count,undef) = &get_extracted($docudom,$docuname,$currdir,\%is_dir,\%children,
12642:                                            \%parent,\@contents,\%dirorder,\%titles);
12643:     }
12644:     my (%referrer,%orphaned,%todelete,%todeletedir,%newdest,%newseqid);
12645:     if ($numitems) {
12646:         for (my $i=1; $i<=$numitems; $i++) {
12647:             next if ($env{'form.archive_'.$i} eq 'dependency');
12648:             my $path = $env{'form.archive_content_'.$i};
12649:             if ($path =~ /^\Q$pathtocheck\E/) {
12650:                 if ($env{'form.archive_'.$i} eq 'discard') {
12651:                     if ($prefix ne '' && $path ne '') {
12652:                         if (-e $prefix.$path) {
12653:                             if ((@archdirs > 0) && 
12654:                                 (grep(/^\Q$i\E$/,@archdirs))) {
12655:                                 $todeletedir{$prefix.$path} = 1;
12656:                             } else {
12657:                                 $todelete{$prefix.$path} = 1;
12658:                             }
12659:                         }
12660:                     }
12661:                 } elsif ($env{'form.archive_'.$i} eq 'display') {
12662:                     my ($docstitle,$title,$url,$outer);
12663:                     ($title) = ($path =~ m{/([^/]+)$});
12664:                     $docstitle = $env{'form.archive_title_'.$i};
12665:                     if ($docstitle eq '') {
12666:                         $docstitle = $title;
12667:                     }
12668:                     $outer = 0;
12669:                     if (ref($dirorder{$i}) eq 'ARRAY') {
12670:                         if (@{$dirorder{$i}} > 0) {
12671:                             foreach my $item (reverse(@{$dirorder{$i}})) {
12672:                                 if ($env{'form.archive_'.$item} eq 'display') {
12673:                                     $outer = $item;
12674:                                     last;
12675:                                 }
12676:                             }
12677:                         }
12678:                     }
12679:                     my ($errtext,$fatal) = 
12680:                         &LONCAPA::map::mapread('/uploaded/'.$docudom.'/'.$docuname.
12681:                                                '/'.$folders{$outer}.'.'.
12682:                                                $containers{$outer});
12683:                     next if ($fatal);
12684:                     if ((@archdirs > 0) && (grep(/^\Q$i\E$/,@archdirs))) {
12685:                         if ($context eq 'coursedocs') {
12686:                             $mapinner{$i} = time;
12687:                             $folders{$i} = 'default_'.$mapinner{$i};
12688:                             $containers{$i} = 'sequence';
12689:                             my $url = '/uploaded/'.$docudom.'/'.$docuname.'/'.
12690:                                       $folders{$i}.'.'.$containers{$i};
12691:                             my $newidx = &LONCAPA::map::getresidx();
12692:                             $LONCAPA::map::resources[$newidx]=
12693:                                 $docstitle.':'.$url.':false:normal:res';
12694:                             push(@LONCAPA::map::order,$newidx);
12695:                             my ($outtext,$errtext) =
12696:                                 &LONCAPA::map::storemap('/uploaded/'.$docudom.'/'.
12697:                                                         $docuname.'/'.$folders{$outer}.
12698:                                                         '.'.$containers{$outer},1,1);
12699:                             $newseqid{$i} = $newidx;
12700:                             unless ($errtext) {
12701:                                 $result .=  '<li>'.&mt('Folder: [_1] added to course',$docstitle).'</li>'."\n";
12702:                             }
12703:                         }
12704:                     } else {
12705:                         if ($context eq 'coursedocs') {
12706:                             my $newidx=&LONCAPA::map::getresidx();
12707:                             my $url = '/uploaded/'.$docudom.'/'.$docuname.'/'.
12708:                                       $docstype.'/'.$mapinner{$outer}.'/'.$newidx.'/'.
12709:                                       $title;
12710:                             if (!-e "$prefix$dir/$docstype/$mapinner{$outer}") {
12711:                                 mkdir("$prefix$dir/$docstype/$mapinner{$outer}",0755);
12712:                             }
12713:                             if (!-e "$prefix$dir/$docstype/$mapinner{$outer}/$newidx") {
12714:                                 mkdir("$prefix$dir/$docstype/$mapinner{$outer}/$newidx");
12715:                             }
12716:                             if (-e "$prefix$dir/$docstype/$mapinner{$outer}/$newidx") {
12717:                                 system("mv $prefix$path $prefix$dir/$docstype/$mapinner{$outer}/$newidx/$title");
12718:                                 $newdest{$i} = "$prefix$dir/$docstype/$mapinner{$outer}/$newidx";
12719:                                 unless ($ishome) {
12720:                                     my $fetch = "$newdest{$i}/$title";
12721:                                     $fetch =~ s/^\Q$prefix$dir\E//;
12722:                                     $prompttofetch{$fetch} = 1;
12723:                                 }
12724:                             }
12725:                             $LONCAPA::map::resources[$newidx]=
12726:                                 $docstitle.':'.$url.':false:normal:res';
12727:                             push(@LONCAPA::map::order, $newidx);
12728:                             my ($outtext,$errtext)=
12729:                                 &LONCAPA::map::storemap('/uploaded/'.$docudom.'/'.
12730:                                                         $docuname.'/'.$folders{$outer}.
12731:                                                         '.'.$containers{$outer},1,1);
12732:                             unless ($errtext) {
12733:                                 if (-e "$prefix$dir/$docstype/$mapinner{$outer}/$newidx/$title") {
12734:                                     $result .= '<li>'.&mt('File: [_1] added to course',$docstitle).'</li>'."\n";
12735:                                 }
12736:                             }
12737:                         }
12738:                     }
12739:                 }
12740:             } else {
12741:                 $warning .= &mt('Item extracted from archive: [_1] has unexpected path.',$path).'<br />';
12742:             }
12743:         }
12744:         for (my $i=1; $i<=$numitems; $i++) {
12745:             next unless ($env{'form.archive_'.$i} eq 'dependency');
12746:             my $path = $env{'form.archive_content_'.$i};
12747:             if ($path =~ /^\Q$pathtocheck\E/) {
12748:                 my ($title) = ($path =~ m{/([^/]+)$});
12749:                 $referrer{$i} = $env{'form.archive_dependent_on_'.$i};
12750:                 if ($env{'form.archive_'.$referrer{$i}} eq 'display') {
12751:                     if (ref($dirorder{$i}) eq 'ARRAY') {
12752:                         my ($itemidx,$fullpath,$relpath);
12753:                         if (ref($dirorder{$referrer{$i}}) eq 'ARRAY') {
12754:                             my $container = $dirorder{$referrer{$i}}->[-1];
12755:                             for (my $j=0; $j<@{$dirorder{$i}}; $j++) {
12756:                                 if ($dirorder{$i}->[$j] eq $container) {
12757:                                     $itemidx = $j;
12758:                                 }
12759:                             }
12760:                         }
12761:                         if ($itemidx eq '') {
12762:                             $itemidx =  0;
12763:                         }
12764:                         if (grep(/^\Q$referrer{$i}\E$/,@archdirs)) {
12765:                             if ($mapinner{$referrer{$i}}) {
12766:                                 $fullpath = "$prefix$dir/$docstype/$mapinner{$referrer{$i}}";
12767:                                 for (my $j=$itemidx; $j<@{$dirorder{$i}}; $j++) {
12768:                                     if (grep(/^\Q$dirorder{$i}->[$j]\E$/,@archdirs)) {
12769:                                         unless (defined($newseqid{$dirorder{$i}->[$j]})) {
12770:                                             $fullpath .= '/'.$titles{$dirorder{$i}->[$j]};
12771:                                             $relpath .= '/'.$titles{$dirorder{$i}->[$j]};
12772:                                             if (!-e $fullpath) {
12773:                                                 mkdir($fullpath,0755);
12774:                                             }
12775:                                         }
12776:                                     } else {
12777:                                         last;
12778:                                     }
12779:                                 }
12780:                             }
12781:                         } elsif ($newdest{$referrer{$i}}) {
12782:                             $fullpath = $newdest{$referrer{$i}};
12783:                             for (my $j=$itemidx; $j<@{$dirorder{$i}}; $j++) {
12784:                                 if ($env{'form.archive_'.$dirorder{$i}->[$j]} eq 'discard') {
12785:                                     $orphaned{$i} = $env{'form.archive_'.$dirorder{$i}->[$j]};
12786:                                     last;
12787:                                 } elsif (grep(/^\Q$dirorder{$i}->[$j]\E$/,@archdirs)) {
12788:                                     unless (defined($newseqid{$dirorder{$i}->[$j]})) {
12789:                                         $fullpath .= '/'.$titles{$dirorder{$i}->[$j]};
12790:                                         $relpath .= '/'.$titles{$dirorder{$i}->[$j]};
12791:                                         if (!-e $fullpath) {
12792:                                             mkdir($fullpath,0755);
12793:                                         }
12794:                                     }
12795:                                 } else {
12796:                                     last;
12797:                                 }
12798:                             }
12799:                         }
12800:                         if ($fullpath ne '') {
12801:                             if (-e "$prefix$path") {
12802:                                 system("mv $prefix$path $fullpath/$title");
12803:                             }
12804:                             if (-e "$fullpath/$title") {
12805:                                 my $showpath;
12806:                                 if ($relpath ne '') {
12807:                                     $showpath = "$relpath/$title";
12808:                                 } else {
12809:                                     $showpath = "/$title";
12810:                                 }
12811:                                 $result .= '<li>'.&mt('[_1] included as a dependency',$showpath).'</li>'."\n";
12812:                             }
12813:                             unless ($ishome) {
12814:                                 my $fetch = "$fullpath/$title";
12815:                                 $fetch =~ s/^\Q$prefix$dir\E//;
12816:                                 $prompttofetch{$fetch} = 1;
12817:                             }
12818:                         }
12819:                     }
12820:                 } elsif ($env{'form.archive_'.$referrer{$i}} eq 'discard') {
12821:                     $warning .= &mt('[_1] is a dependency of [_2], which was discarded.',
12822:                                     $path,$env{'form.archive_content_'.$referrer{$i}}).'<br />';
12823:                 }
12824:             } else {
12825:                 $warning .= &mt('Item extracted from archive: [_1] has unexpected path.',$path).'<br />';
12826:             }
12827:         }
12828:         if (keys(%todelete)) {
12829:             foreach my $key (keys(%todelete)) {
12830:                 unlink($key);
12831:             }
12832:         }
12833:         if (keys(%todeletedir)) {
12834:             foreach my $key (keys(%todeletedir)) {
12835:                 rmdir($key);
12836:             }
12837:         }
12838:         foreach my $dir (sort(keys(%is_dir))) {
12839:             if (($pathtocheck ne '') && ($dir ne ''))  {
12840:                 &cleanup_empty_dirs($prefix."$pathtocheck/$dir");
12841:             }
12842:         }
12843:         if ($result ne '') {
12844:             $output .= '<ul>'."\n".
12845:                        $result."\n".
12846:                        '</ul>';
12847:         }
12848:         unless ($ishome) {
12849:             my $replicationfail;
12850:             foreach my $item (keys(%prompttofetch)) {
12851:                 my $fetchresult= &Apache::lonnet::reply('fetchuserfile:'.$item,$docuhome);
12852:                 unless ($fetchresult eq 'ok') {
12853:                     $replicationfail .= '<li>'.$item.'</li>'."\n";
12854:                 }
12855:             }
12856:             if ($replicationfail) {
12857:                 $output .= '<p class="LC_error">'.
12858:                            &mt('Course home server failed to retrieve:').'<ul>'.
12859:                            $replicationfail.
12860:                            '</ul></p>';
12861:             }
12862:         }
12863:     } else {
12864:         $warning = &mt('No items found in archive.');
12865:     }
12866:     if ($error) {
12867:         $output .= '<p class="LC_error">'.&mt('Not extracted.').'<br />'.
12868:                    $error.'</p>'."\n";
12869:     }
12870:     if ($warning) {
12871:         $output .= '<p class="LC_warning">'.$warning.'</p>'."\n";
12872:     }
12873:     return $output;
12874: }
12875: 
12876: sub cleanup_empty_dirs {
12877:     my ($path) = @_;
12878:     if (($path ne '') && (-d $path)) {
12879:         if (opendir(my $dirh,$path)) {
12880:             my @dircontents = grep(!/^\./,readdir($dirh));
12881:             my $numitems = 0;
12882:             foreach my $item (@dircontents) {
12883:                 if (-d "$path/$item") {
12884:                     &cleanup_empty_dirs("$path/$item");
12885:                     if (-e "$path/$item") {
12886:                         $numitems ++;
12887:                     }
12888:                 } else {
12889:                     $numitems ++;
12890:                 }
12891:             }
12892:             if ($numitems == 0) {
12893:                 rmdir($path);
12894:             }
12895:             closedir($dirh);
12896:         }
12897:     }
12898:     return;
12899: }
12900: 
12901: =pod
12902: 
12903: =item * &get_folder_hierarchy()
12904: 
12905: Provides hierarchy of names of folders/sub-folders containing the current
12906: item,
12907: 
12908: Inputs: 3
12909:      - $navmap - navmaps object
12910: 
12911:      - $map - url for map (either the trigger itself, or map containing
12912:                            the resource, which is the trigger).
12913: 
12914:      - $showitem - 1 => show title for map itself; 0 => do not show.
12915: 
12916: Outputs: 1 @pathitems - array of folder/subfolder names.
12917: 
12918: =cut
12919: 
12920: sub get_folder_hierarchy {
12921:     my ($navmap,$map,$showitem) = @_;
12922:     my @pathitems;
12923:     if (ref($navmap)) {
12924:         my $mapres = $navmap->getResourceByUrl($map);
12925:         if (ref($mapres)) {
12926:             my $pcslist = $mapres->map_hierarchy();
12927:             if ($pcslist ne '') {
12928:                 my @pcs = split(/,/,$pcslist);
12929:                 foreach my $pc (@pcs) {
12930:                     if ($pc == 1) {
12931:                         push(@pathitems,&mt('Main Content'));
12932:                     } else {
12933:                         my $res = $navmap->getByMapPc($pc);
12934:                         if (ref($res)) {
12935:                             my $title = $res->compTitle();
12936:                             $title =~ s/\W+/_/g;
12937:                             if ($title ne '') {
12938:                                 push(@pathitems,$title);
12939:                             }
12940:                         }
12941:                     }
12942:                 }
12943:             }
12944:             if ($showitem) {
12945:                 if ($mapres->{ID} eq '0.0') {
12946:                     push(@pathitems,&mt('Main Content'));
12947:                 } else {
12948:                     my $maptitle = $mapres->compTitle();
12949:                     $maptitle =~ s/\W+/_/g;
12950:                     if ($maptitle ne '') {
12951:                         push(@pathitems,$maptitle);
12952:                     }
12953:                 }
12954:             }
12955:         }
12956:     }
12957:     return @pathitems;
12958: }
12959: 
12960: =pod
12961: 
12962: =item * &get_turnedin_filepath()
12963: 
12964: Determines path in a user's portfolio file for storage of files uploaded
12965: to a specific essayresponse or dropbox item.
12966: 
12967: Inputs: 3 required + 1 optional.
12968: $symb is symb for resource, $uname and $udom are for current user (required).
12969: $caller is optional (can be "submission", if routine is called when storing
12970: an upoaded file when "Submit Answer" button was pressed).
12971: 
12972: Returns array containing $path and $multiresp. 
12973: $path is path in portfolio.  $multiresp is 1 if this resource contains more
12974: than one file upload item.  Callers of routine should append partid as a 
12975: subdirectory to $path in cases where $multiresp is 1.
12976: 
12977: Called by: homework/essayresponse.pm and homework/structuretags.pm
12978: 
12979: =cut
12980: 
12981: sub get_turnedin_filepath {
12982:     my ($symb,$uname,$udom,$caller) = @_;
12983:     my ($map,$resid,$resurl)=&Apache::lonnet::decode_symb($symb);
12984:     my $turnindir;
12985:     my %userhash = &Apache::lonnet::userenvironment($udom,$uname,'turnindir');
12986:     $turnindir = $userhash{'turnindir'};
12987:     my ($path,$multiresp);
12988:     if ($turnindir eq '') {
12989:         if ($caller eq 'submission') {
12990:             $turnindir = &mt('turned in');
12991:             $turnindir =~ s/\W+/_/g;
12992:             my %newhash = (
12993:                             'turnindir' => $turnindir,
12994:                           );
12995:             &Apache::lonnet::put('environment',\%newhash,$udom,$uname);
12996:         }
12997:     }
12998:     if ($turnindir ne '') {
12999:         $path = '/'.$turnindir.'/';
13000:         my ($multipart,$turnin,@pathitems);
13001:         my $navmap = Apache::lonnavmaps::navmap->new();
13002:         if (defined($navmap)) {
13003:             my $mapres = $navmap->getResourceByUrl($map);
13004:             if (ref($mapres)) {
13005:                 my $pcslist = $mapres->map_hierarchy();
13006:                 if ($pcslist ne '') {
13007:                     foreach my $pc (split(/,/,$pcslist)) {
13008:                         my $res = $navmap->getByMapPc($pc);
13009:                         if (ref($res)) {
13010:                             my $title = $res->compTitle();
13011:                             $title =~ s/\W+/_/g;
13012:                             if ($title ne '') {
13013:                                 if (($pc > 1) && (length($title) > 12)) {
13014:                                     $title = substr($title,0,12);
13015:                                 }
13016:                                 push(@pathitems,$title);
13017:                             }
13018:                         }
13019:                     }
13020:                 }
13021:                 my $maptitle = $mapres->compTitle();
13022:                 $maptitle =~ s/\W+/_/g;
13023:                 if ($maptitle ne '') {
13024:                     if (length($maptitle) > 12) {
13025:                         $maptitle = substr($maptitle,0,12);
13026:                     }
13027:                     push(@pathitems,$maptitle);
13028:                 }
13029:                 unless ($env{'request.state'} eq 'construct') {
13030:                     my $res = $navmap->getBySymb($symb);
13031:                     if (ref($res)) {
13032:                         my $partlist = $res->parts();
13033:                         my $totaluploads = 0;
13034:                         if (ref($partlist) eq 'ARRAY') {
13035:                             foreach my $part (@{$partlist}) {
13036:                                 my @types = $res->responseType($part);
13037:                                 my @ids = $res->responseIds($part);
13038:                                 for (my $i=0; $i < scalar(@ids); $i++) {
13039:                                     if ($types[$i] eq 'essay') {
13040:                                         my $partid = $part.'_'.$ids[$i];
13041:                                         if (&Apache::lonnet::EXT("resource.$partid.uploadedfiletypes") ne '') {
13042:                                             $totaluploads ++;
13043:                                         }
13044:                                     }
13045:                                 }
13046:                             }
13047:                             if ($totaluploads > 1) {
13048:                                 $multiresp = 1;
13049:                             }
13050:                         }
13051:                     }
13052:                 }
13053:             } else {
13054:                 return;
13055:             }
13056:         } else {
13057:             return;
13058:         }
13059:         my $restitle=&Apache::lonnet::gettitle($symb);
13060:         $restitle =~ s/\W+/_/g;
13061:         if ($restitle eq '') {
13062:             $restitle = ($resurl =~ m{/[^/]+$});
13063:             if ($restitle eq '') {
13064:                 $restitle = time;
13065:             }
13066:         }
13067:         if (length($restitle) > 12) {
13068:             $restitle = substr($restitle,0,12);
13069:         }
13070:         push(@pathitems,$restitle);
13071:         $path .= join('/',@pathitems);
13072:     }
13073:     return ($path,$multiresp);
13074: }
13075: 
13076: =pod
13077: 
13078: =back
13079: 
13080: =head1 CSV Upload/Handling functions
13081: 
13082: =over 4
13083: 
13084: =item * &upfile_store($r)
13085: 
13086: Store uploaded file, $r should be the HTTP Request object,
13087: needs $env{'form.upfile'}
13088: returns $datatoken to be put into hidden field
13089: 
13090: =cut
13091: 
13092: sub upfile_store {
13093:     my $r=shift;
13094:     $env{'form.upfile'}=~s/\r/\n/gs;
13095:     $env{'form.upfile'}=~s/\f/\n/gs;
13096:     $env{'form.upfile'}=~s/\n+/\n/gs;
13097:     $env{'form.upfile'}=~s/\n+$//gs;
13098: 
13099:     my $datatoken=$env{'user.name'}.'_'.$env{'user.domain'}.
13100: 	'_enroll_'.$env{'request.course.id'}.'_'.time.'_'.$$;
13101:     {
13102:         my $datafile = $r->dir_config('lonDaemons').
13103:                            '/tmp/'.$datatoken.'.tmp';
13104:         if ( open(my $fh,">$datafile") ) {
13105:             print $fh $env{'form.upfile'};
13106:             close($fh);
13107:         }
13108:     }
13109:     return $datatoken;
13110: }
13111: 
13112: =pod
13113: 
13114: =item * &load_tmp_file($r)
13115: 
13116: Load uploaded file from tmp, $r should be the HTTP Request object,
13117: needs $env{'form.datatoken'},
13118: sets $env{'form.upfile'} to the contents of the file
13119: 
13120: =cut
13121: 
13122: sub load_tmp_file {
13123:     my $r=shift;
13124:     my @studentdata=();
13125:     {
13126:         my $studentfile = $r->dir_config('lonDaemons').
13127:                               '/tmp/'.$env{'form.datatoken'}.'.tmp';
13128:         if ( open(my $fh,"<$studentfile") ) {
13129:             @studentdata=<$fh>;
13130:             close($fh);
13131:         }
13132:     }
13133:     $env{'form.upfile'}=join('',@studentdata);
13134: }
13135: 
13136: =pod
13137: 
13138: =item * &upfile_record_sep()
13139: 
13140: Separate uploaded file into records
13141: returns array of records,
13142: needs $env{'form.upfile'} and $env{'form.upfiletype'}
13143: 
13144: =cut
13145: 
13146: sub upfile_record_sep {
13147:     if ($env{'form.upfiletype'} eq 'xml') {
13148:     } else {
13149: 	my @records;
13150: 	foreach my $line (split(/\n/,$env{'form.upfile'})) {
13151: 	    if ($line=~/^\s*$/) { next; }
13152: 	    push(@records,$line);
13153: 	}
13154: 	return @records;
13155:     }
13156: }
13157: 
13158: =pod
13159: 
13160: =item * &record_sep($record)
13161: 
13162: Separate a record into fields $record should be an item from the upfile_record_sep(), needs $env{'form.upfiletype'}
13163: 
13164: =cut
13165: 
13166: sub takeleft {
13167:     my $index=shift;
13168:     return substr('0000'.$index,-4,4);
13169: }
13170: 
13171: sub record_sep {
13172:     my $record=shift;
13173:     my %components=();
13174:     if ($env{'form.upfiletype'} eq 'xml') {
13175:     } elsif ($env{'form.upfiletype'} eq 'space') {
13176:         my $i=0;
13177:         foreach my $field (split(/\s+/,$record)) {
13178:             $field=~s/^(\"|\')//;
13179:             $field=~s/(\"|\')$//;
13180:             $components{&takeleft($i)}=$field;
13181:             $i++;
13182:         }
13183:     } elsif ($env{'form.upfiletype'} eq 'tab') {
13184:         my $i=0;
13185:         foreach my $field (split(/\t/,$record)) {
13186:             $field=~s/^(\"|\')//;
13187:             $field=~s/(\"|\')$//;
13188:             $components{&takeleft($i)}=$field;
13189:             $i++;
13190:         }
13191:     } else {
13192:         my $separator=',';
13193:         if ($env{'form.upfiletype'} eq 'semisv') {
13194:             $separator=';';
13195:         }
13196:         my $i=0;
13197: # the character we are looking for to indicate the end of a quote or a record 
13198:         my $looking_for=$separator;
13199: # do not add the characters to the fields
13200:         my $ignore=0;
13201: # we just encountered a separator (or the beginning of the record)
13202:         my $just_found_separator=1;
13203: # store the field we are working on here
13204:         my $field='';
13205: # work our way through all characters in record
13206:         foreach my $character ($record=~/(.)/g) {
13207:             if ($character eq $looking_for) {
13208:                if ($character ne $separator) {
13209: # Found the end of a quote, again looking for separator
13210:                   $looking_for=$separator;
13211:                   $ignore=1;
13212:                } else {
13213: # Found a separator, store away what we got
13214:                   $components{&takeleft($i)}=$field;
13215: 	          $i++;
13216:                   $just_found_separator=1;
13217:                   $ignore=0;
13218:                   $field='';
13219:                }
13220:                next;
13221:             }
13222: # single or double quotation marks after a separator indicate beginning of a quote
13223: # we are now looking for the end of the quote and need to ignore separators
13224:             if ((($character eq '"') || ($character eq "'")) && ($just_found_separator))  {
13225:                $looking_for=$character;
13226:                next;
13227:             }
13228: # ignore would be true after we reached the end of a quote
13229:             if ($ignore) { next; }
13230:             if (($just_found_separator) && ($character=~/\s/)) { next; }
13231:             $field.=$character;
13232:             $just_found_separator=0; 
13233:         }
13234: # catch the very last entry, since we never encountered the separator
13235:         $components{&takeleft($i)}=$field;
13236:     }
13237:     return %components;
13238: }
13239: 
13240: ######################################################
13241: ######################################################
13242: 
13243: =pod
13244: 
13245: =item * &upfile_select_html()
13246: 
13247: Return HTML code to select a file from the users machine and specify 
13248: the file type.
13249: 
13250: =cut
13251: 
13252: ######################################################
13253: ######################################################
13254: sub upfile_select_html {
13255:     my %Types = (
13256:                  csv   => &mt('CSV (comma separated values, spreadsheet)'),
13257:                  semisv => &mt('Semicolon separated values'),
13258:                  space => &mt('Space separated'),
13259:                  tab   => &mt('Tabulator separated'),
13260: #                 xml   => &mt('HTML/XML'),
13261:                  );
13262:     my $Str = '<input type="file" name="upfile" size="50" />'.
13263:         '<br />'.&mt('Type').': <select name="upfiletype">';
13264:     foreach my $type (sort(keys(%Types))) {
13265:         $Str .= '<option value="'.$type.'" >'.$Types{$type}."</option>\n";
13266:     }
13267:     $Str .= "</select>\n";
13268:     return $Str;
13269: }
13270: 
13271: sub get_samples {
13272:     my ($records,$toget) = @_;
13273:     my @samples=({});
13274:     my $got=0;
13275:     foreach my $rec (@$records) {
13276: 	my %temp = &record_sep($rec);
13277: 	if (! grep(/\S/, values(%temp))) { next; }
13278: 	if (%temp) {
13279: 	    $samples[$got]=\%temp;
13280: 	    $got++;
13281: 	    if ($got == $toget) { last; }
13282: 	}
13283:     }
13284:     return \@samples;
13285: }
13286: 
13287: ######################################################
13288: ######################################################
13289: 
13290: =pod
13291: 
13292: =item * &csv_print_samples($r,$records)
13293: 
13294: Prints a table of sample values from each column uploaded $r is an
13295: Apache Request ref, $records is an arrayref from
13296: &Apache::loncommon::upfile_record_sep
13297: 
13298: =cut
13299: 
13300: ######################################################
13301: ######################################################
13302: sub csv_print_samples {
13303:     my ($r,$records) = @_;
13304:     my $samples = &get_samples($records,5);
13305: 
13306:     $r->print(&mt('Samples').'<br />'.&start_data_table().
13307:               &start_data_table_header_row());
13308:     foreach my $sample (sort({$a <=> $b} keys(%{ $samples->[0] }))) { 
13309:         $r->print('<th>'.&mt('Column [_1]',($sample+1)).'</th>'); }
13310:     $r->print(&end_data_table_header_row());
13311:     foreach my $hash (@$samples) {
13312: 	$r->print(&start_data_table_row());
13313: 	foreach my $sample (sort({$a <=> $b} keys(%{ $samples->[0] }))) {
13314: 	    $r->print('<td>');
13315: 	    if (defined($$hash{$sample})) { $r->print($$hash{$sample}); }
13316: 	    $r->print('</td>');
13317: 	}
13318: 	$r->print(&end_data_table_row());
13319:     }
13320:     $r->print(&end_data_table().'<br />'."\n");
13321: }
13322: 
13323: ######################################################
13324: ######################################################
13325: 
13326: =pod
13327: 
13328: =item * &csv_print_select_table($r,$records,$d)
13329: 
13330: Prints a table to create associations between values and table columns.
13331: 
13332: $r is an Apache Request ref,
13333: $records is an arrayref from &Apache::loncommon::upfile_record_sep,
13334: $d is an array of 2 element arrays (internal name, displayed name,defaultcol)
13335: 
13336: =cut
13337: 
13338: ######################################################
13339: ######################################################
13340: sub csv_print_select_table {
13341:     my ($r,$records,$d) = @_;
13342:     my $i=0;
13343:     my $samples = &get_samples($records,1);
13344:     $r->print(&mt('Associate columns with student attributes.')."\n".
13345: 	      &start_data_table().&start_data_table_header_row().
13346:               '<th>'.&mt('Attribute').'</th>'.
13347:               '<th>'.&mt('Column').'</th>'.
13348:               &end_data_table_header_row()."\n");
13349:     foreach my $array_ref (@$d) {
13350: 	my ($value,$display,$defaultcol)=@{ $array_ref };
13351: 	$r->print(&start_data_table_row().'<td>'.$display.'</td>');
13352: 
13353: 	$r->print('<td><select name="f'.$i.'"'.
13354: 		  ' onchange="javascript:flip(this.form,'.$i.');">');
13355: 	$r->print('<option value="none"></option>');
13356: 	foreach my $sample (sort({$a <=> $b} keys(%{ $samples->[0] }))) {
13357: 	    $r->print('<option value="'.$sample.'"'.
13358:                       ($sample eq $defaultcol ? ' selected="selected" ' : '').
13359:                       '>'.&mt('Column [_1]',($sample+1)).'</option>');
13360: 	}
13361: 	$r->print('</select></td>'.&end_data_table_row()."\n");
13362: 	$i++;
13363:     }
13364:     $r->print(&end_data_table());
13365:     $i--;
13366:     return $i;
13367: }
13368: 
13369: ######################################################
13370: ######################################################
13371: 
13372: =pod
13373: 
13374: =item * &csv_samples_select_table($r,$records,$d)
13375: 
13376: Prints a table of sample values from the upload and can make associate samples to internal names.
13377: 
13378: $r is an Apache Request ref,
13379: $records is an arrayref from &Apache::loncommon::upfile_record_sep,
13380: $d is an array of 2 element arrays (internal name, displayed name)
13381: 
13382: =cut
13383: 
13384: ######################################################
13385: ######################################################
13386: sub csv_samples_select_table {
13387:     my ($r,$records,$d) = @_;
13388:     my $i=0;
13389:     #
13390:     my $max_samples = 5;
13391:     my $samples = &get_samples($records,$max_samples);
13392:     $r->print(&start_data_table().
13393:               &start_data_table_header_row().'<th>'.
13394:               &mt('Field').'</th><th>'.&mt('Samples').'</th>'.
13395:               &end_data_table_header_row());
13396: 
13397:     foreach my $key (sort(keys(%{ $samples->[0] }))) {
13398: 	$r->print(&start_data_table_row().'<td><select name="f'.$i.'"'.
13399: 		  ' onchange="javascript:flip(this.form,'.$i.');">');
13400: 	foreach my $option (@$d) {
13401: 	    my ($value,$display,$defaultcol)=@{ $option };
13402: 	    $r->print('<option value="'.$value.'"'.
13403:                       ($i eq $defaultcol ? ' selected="selected" ':'').'>'.
13404:                       $display.'</option>');
13405: 	}
13406: 	$r->print('</select></td><td>');
13407: 	foreach my $line (0..($max_samples-1)) {
13408: 	    if (defined($samples->[$line]{$key})) { 
13409: 		$r->print($samples->[$line]{$key}."<br />\n"); 
13410: 	    }
13411: 	}
13412: 	$r->print('</td>'.&end_data_table_row());
13413: 	$i++;
13414:     }
13415:     $r->print(&end_data_table());
13416:     $i--;
13417:     return($i);
13418: }
13419: 
13420: ######################################################
13421: ######################################################
13422: 
13423: =pod
13424: 
13425: =item * &clean_excel_name($name)
13426: 
13427: Returns a replacement for $name which does not contain any illegal characters.
13428: 
13429: =cut
13430: 
13431: ######################################################
13432: ######################################################
13433: sub clean_excel_name {
13434:     my ($name) = @_;
13435:     $name =~ s/[:\*\?\/\\]//g;
13436:     if (length($name) > 31) {
13437:         $name = substr($name,0,31);
13438:     }
13439:     return $name;
13440: }
13441: 
13442: =pod
13443: 
13444: =item * &check_if_partid_hidden($id,$symb,$udom,$uname)
13445: 
13446: Returns either 1 or undef
13447: 
13448: 1 if the part is to be hidden, undef if it is to be shown
13449: 
13450: Arguments are:
13451: 
13452: $id the id of the part to be checked
13453: $symb, optional the symb of the resource to check
13454: $udom, optional the domain of the user to check for
13455: $uname, optional the username of the user to check for
13456: 
13457: =cut
13458: 
13459: sub check_if_partid_hidden {
13460:     my ($id,$symb,$udom,$uname) = @_;
13461:     my $hiddenparts=&Apache::lonnet::EXT('resource.0.hiddenparts',
13462: 					 $symb,$udom,$uname);
13463:     my $truth=1;
13464:     #if the string starts with !, then the list is the list to show not hide
13465:     if ($hiddenparts=~s/^\s*!//) { $truth=undef; }
13466:     my @hiddenlist=split(/,/,$hiddenparts);
13467:     foreach my $checkid (@hiddenlist) {
13468: 	if ($checkid =~ /^\s*\Q$id\E\s*$/) { return $truth; }
13469:     }
13470:     return !$truth;
13471: }
13472: 
13473: 
13474: ############################################################
13475: ############################################################
13476: 
13477: =pod
13478: 
13479: =back 
13480: 
13481: =head1 cgi-bin script and graphing routines
13482: 
13483: =over 4
13484: 
13485: =item * &get_cgi_id()
13486: 
13487: Inputs: none
13488: 
13489: Returns an id which can be used to pass environment variables
13490: to various cgi-bin scripts.  These environment variables will
13491: be removed from the users environment after a given time by
13492: the routine &Apache::lonnet::transfer_profile_to_env.
13493: 
13494: =cut
13495: 
13496: ############################################################
13497: ############################################################
13498: my $uniq=0;
13499: sub get_cgi_id {
13500:     $uniq=($uniq+1)%100000;
13501:     return (time.'_'.$$.'_'.$uniq);
13502: }
13503: 
13504: ############################################################
13505: ############################################################
13506: 
13507: =pod
13508: 
13509: =item * &DrawBarGraph()
13510: 
13511: Facilitates the plotting of data in a (stacked) bar graph.
13512: Puts plot definition data into the users environment in order for 
13513: graph.png to plot it.  Returns an <img> tag for the plot.
13514: The bars on the plot are labeled '1','2',...,'n'.
13515: 
13516: Inputs:
13517: 
13518: =over 4
13519: 
13520: =item $Title: string, the title of the plot
13521: 
13522: =item $xlabel: string, text describing the X-axis of the plot
13523: 
13524: =item $ylabel: string, text describing the Y-axis of the plot
13525: 
13526: =item $Max: scalar, the maximum Y value to use in the plot
13527: If $Max is < any data point, the graph will not be rendered.
13528: 
13529: =item $colors: array ref holding the colors to be used for the data sets when
13530: they are plotted.  If undefined, default values will be used.
13531: 
13532: =item $labels: array ref holding the labels to use on the x-axis for the bars.
13533: 
13534: =item @Values: An array of array references.  Each array reference holds data
13535: to be plotted in a stacked bar chart.
13536: 
13537: =item If the final element of @Values is a hash reference the key/value
13538: pairs will be added to the graph definition.
13539: 
13540: =back
13541: 
13542: Returns:
13543: 
13544: An <img> tag which references graph.png and the appropriate identifying
13545: information for the plot.
13546: 
13547: =cut
13548: 
13549: ############################################################
13550: ############################################################
13551: sub DrawBarGraph {
13552:     my ($Title,$xlabel,$ylabel,$Max,$colors,$labels,@Values)=@_;
13553:     #
13554:     if (! defined($colors)) {
13555:         $colors = ['#33ff00', 
13556:                   '#0033cc', '#990000', '#aaaa66', '#663399', '#ff9933',
13557:                   '#66ccff', '#ff9999', '#cccc33', '#660000', '#33cc66',
13558:                   ]; 
13559:     }
13560:     my $extra_settings = {};
13561:     if (ref($Values[-1]) eq 'HASH') {
13562:         $extra_settings = pop(@Values);
13563:     }
13564:     #
13565:     my $identifier = &get_cgi_id();
13566:     my $id = 'cgi.'.$identifier;        
13567:     if (! @Values || ref($Values[0]) ne 'ARRAY') {
13568:         return '';
13569:     }
13570:     #
13571:     my @Labels;
13572:     if (defined($labels)) {
13573:         @Labels = @$labels;
13574:     } else {
13575:         for (my $i=0;$i<@{$Values[0]};$i++) {
13576:             push(@Labels,$i+1);
13577:         }
13578:     }
13579:     #
13580:     my $NumBars = scalar(@{$Values[0]});
13581:     if ($NumBars < scalar(@Labels)) { $NumBars = scalar(@Labels); }
13582:     my %ValuesHash;
13583:     my $NumSets=1;
13584:     foreach my $array (@Values) {
13585:         next if (! ref($array));
13586:         $ValuesHash{$id.'.data.'.$NumSets++} = 
13587:             join(',',@$array);
13588:     }
13589:     #
13590:     my ($height,$width,$xskip,$bar_width) = (200,120,1,15);
13591:     if ($NumBars < 3) {
13592:         $width = 120+$NumBars*32;
13593:         $xskip = 1;
13594:         $bar_width = 30;
13595:     } elsif ($NumBars < 5) {
13596:         $width = 120+$NumBars*20;
13597:         $xskip = 1;
13598:         $bar_width = 20;
13599:     } elsif ($NumBars < 10) {
13600:         $width = 120+$NumBars*15;
13601:         $xskip = 1;
13602:         $bar_width = 15;
13603:     } elsif ($NumBars <= 25) {
13604:         $width = 120+$NumBars*11;
13605:         $xskip = 5;
13606:         $bar_width = 8;
13607:     } elsif ($NumBars <= 50) {
13608:         $width = 120+$NumBars*8;
13609:         $xskip = 5;
13610:         $bar_width = 4;
13611:     } else {
13612:         $width = 120+$NumBars*8;
13613:         $xskip = 5;
13614:         $bar_width = 4;
13615:     }
13616:     #
13617:     $Max = 1 if ($Max < 1);
13618:     if ( int($Max) < $Max ) {
13619:         $Max++;
13620:         $Max = int($Max);
13621:     }
13622:     $Title  = '' if (! defined($Title));
13623:     $xlabel = '' if (! defined($xlabel));
13624:     $ylabel = '' if (! defined($ylabel));
13625:     $ValuesHash{$id.'.title'}    = &escape($Title);
13626:     $ValuesHash{$id.'.xlabel'}   = &escape($xlabel);
13627:     $ValuesHash{$id.'.ylabel'}   = &escape($ylabel);
13628:     $ValuesHash{$id.'.y_max_value'} = $Max;
13629:     $ValuesHash{$id.'.NumBars'}  = $NumBars;
13630:     $ValuesHash{$id.'.NumSets'}  = $NumSets;
13631:     $ValuesHash{$id.'.PlotType'} = 'bar';
13632:     $ValuesHash{$id.'.Colors'}   = join(',',@{$colors});
13633:     $ValuesHash{$id.'.height'}   = $height;
13634:     $ValuesHash{$id.'.width'}    = $width;
13635:     $ValuesHash{$id.'.xskip'}    = $xskip;
13636:     $ValuesHash{$id.'.bar_width'} = $bar_width;
13637:     $ValuesHash{$id.'.labels'} = join(',',@Labels);
13638:     #
13639:     # Deal with other parameters
13640:     while (my ($key,$value) = each(%$extra_settings)) {
13641:         $ValuesHash{$id.'.'.$key} = $value;
13642:     }
13643:     #
13644:     &Apache::lonnet::appenv(\%ValuesHash);
13645:     return '<img src="/cgi-bin/graph.png?'.$identifier.'" border="1" />';
13646: }
13647: 
13648: ############################################################
13649: ############################################################
13650: 
13651: =pod
13652: 
13653: =item * &DrawXYGraph()
13654: 
13655: Facilitates the plotting of data in an XY graph.
13656: Puts plot definition data into the users environment in order for 
13657: graph.png to plot it.  Returns an <img> tag for the plot.
13658: 
13659: Inputs:
13660: 
13661: =over 4
13662: 
13663: =item $Title: string, the title of the plot
13664: 
13665: =item $xlabel: string, text describing the X-axis of the plot
13666: 
13667: =item $ylabel: string, text describing the Y-axis of the plot
13668: 
13669: =item $Max: scalar, the maximum Y value to use in the plot
13670: If $Max is < any data point, the graph will not be rendered.
13671: 
13672: =item $colors: Array ref containing the hex color codes for the data to be 
13673: plotted in.  If undefined, default values will be used.
13674: 
13675: =item $Xlabels: Array ref containing the labels to be used for the X-axis.
13676: 
13677: =item $Ydata: Array ref containing Array refs.  
13678: Each of the contained arrays will be plotted as a separate curve.
13679: 
13680: =item %Values: hash indicating or overriding any default values which are 
13681: passed to graph.png.  
13682: Possible values are: width, xskip, x_ticks, x_tick_offset, among others.
13683: 
13684: =back
13685: 
13686: Returns:
13687: 
13688: An <img> tag which references graph.png and the appropriate identifying
13689: information for the plot.
13690: 
13691: =cut
13692: 
13693: ############################################################
13694: ############################################################
13695: sub DrawXYGraph {
13696:     my ($Title,$xlabel,$ylabel,$Max,$colors,$Xlabels,$Ydata,%Values)=@_;
13697:     #
13698:     # Create the identifier for the graph
13699:     my $identifier = &get_cgi_id();
13700:     my $id = 'cgi.'.$identifier;
13701:     #
13702:     $Title  = '' if (! defined($Title));
13703:     $xlabel = '' if (! defined($xlabel));
13704:     $ylabel = '' if (! defined($ylabel));
13705:     my %ValuesHash = 
13706:         (
13707:          $id.'.title'  => &escape($Title),
13708:          $id.'.xlabel' => &escape($xlabel),
13709:          $id.'.ylabel' => &escape($ylabel),
13710:          $id.'.y_max_value'=> $Max,
13711:          $id.'.labels'     => join(',',@$Xlabels),
13712:          $id.'.PlotType'   => 'XY',
13713:          );
13714:     #
13715:     if (defined($colors) && ref($colors) eq 'ARRAY') {
13716:         $ValuesHash{$id.'.Colors'}   = join(',',@{$colors});
13717:     }
13718:     #
13719:     if (! ref($Ydata) || ref($Ydata) ne 'ARRAY') {
13720:         return '';
13721:     }
13722:     my $NumSets=1;
13723:     foreach my $array (@{$Ydata}){
13724:         next if (! ref($array));
13725:         $ValuesHash{$id.'.data.'.$NumSets++} = join(',',@$array);
13726:     }
13727:     $ValuesHash{$id.'.NumSets'} = $NumSets-1;
13728:     #
13729:     # Deal with other parameters
13730:     while (my ($key,$value) = each(%Values)) {
13731:         $ValuesHash{$id.'.'.$key} = $value;
13732:     }
13733:     #
13734:     &Apache::lonnet::appenv(\%ValuesHash);
13735:     return '<img src="/cgi-bin/graph.png?'.$identifier.'" border="1" />';
13736: }
13737: 
13738: ############################################################
13739: ############################################################
13740: 
13741: =pod
13742: 
13743: =item * &DrawXYYGraph()
13744: 
13745: Facilitates the plotting of data in an XY graph with two Y axes.
13746: Puts plot definition data into the users environment in order for 
13747: graph.png to plot it.  Returns an <img> tag for the plot.
13748: 
13749: Inputs:
13750: 
13751: =over 4
13752: 
13753: =item $Title: string, the title of the plot
13754: 
13755: =item $xlabel: string, text describing the X-axis of the plot
13756: 
13757: =item $ylabel: string, text describing the Y-axis of the plot
13758: 
13759: =item $colors: Array ref containing the hex color codes for the data to be 
13760: plotted in.  If undefined, default values will be used.
13761: 
13762: =item $Xlabels: Array ref containing the labels to be used for the X-axis.
13763: 
13764: =item $Ydata1: The first data set
13765: 
13766: =item $Min1: The minimum value of the left Y-axis
13767: 
13768: =item $Max1: The maximum value of the left Y-axis
13769: 
13770: =item $Ydata2: The second data set
13771: 
13772: =item $Min2: The minimum value of the right Y-axis
13773: 
13774: =item $Max2: The maximum value of the left Y-axis
13775: 
13776: =item %Values: hash indicating or overriding any default values which are 
13777: passed to graph.png.  
13778: Possible values are: width, xskip, x_ticks, x_tick_offset, among others.
13779: 
13780: =back
13781: 
13782: Returns:
13783: 
13784: An <img> tag which references graph.png and the appropriate identifying
13785: information for the plot.
13786: 
13787: =cut
13788: 
13789: ############################################################
13790: ############################################################
13791: sub DrawXYYGraph {
13792:     my ($Title,$xlabel,$ylabel,$colors,$Xlabels,$Ydata1,$Min1,$Max1,
13793:                                         $Ydata2,$Min2,$Max2,%Values)=@_;
13794:     #
13795:     # Create the identifier for the graph
13796:     my $identifier = &get_cgi_id();
13797:     my $id = 'cgi.'.$identifier;
13798:     #
13799:     $Title  = '' if (! defined($Title));
13800:     $xlabel = '' if (! defined($xlabel));
13801:     $ylabel = '' if (! defined($ylabel));
13802:     my %ValuesHash = 
13803:         (
13804:          $id.'.title'  => &escape($Title),
13805:          $id.'.xlabel' => &escape($xlabel),
13806:          $id.'.ylabel' => &escape($ylabel),
13807:          $id.'.labels' => join(',',@$Xlabels),
13808:          $id.'.PlotType' => 'XY',
13809:          $id.'.NumSets' => 2,
13810:          $id.'.two_axes' => 1,
13811:          $id.'.y1_max_value' => $Max1,
13812:          $id.'.y1_min_value' => $Min1,
13813:          $id.'.y2_max_value' => $Max2,
13814:          $id.'.y2_min_value' => $Min2,
13815:          );
13816:     #
13817:     if (defined($colors) && ref($colors) eq 'ARRAY') {
13818:         $ValuesHash{$id.'.Colors'}   = join(',',@{$colors});
13819:     }
13820:     #
13821:     if (! ref($Ydata1) || ref($Ydata1) ne 'ARRAY' ||
13822:         ! ref($Ydata2) || ref($Ydata2) ne 'ARRAY'){
13823:         return '';
13824:     }
13825:     my $NumSets=1;
13826:     foreach my $array ($Ydata1,$Ydata2){
13827:         next if (! ref($array));
13828:         $ValuesHash{$id.'.data.'.$NumSets++} = join(',',@$array);
13829:     }
13830:     #
13831:     # Deal with other parameters
13832:     while (my ($key,$value) = each(%Values)) {
13833:         $ValuesHash{$id.'.'.$key} = $value;
13834:     }
13835:     #
13836:     &Apache::lonnet::appenv(\%ValuesHash);
13837:     return '<img src="/cgi-bin/graph.png?'.$identifier.'" border="1" />';
13838: }
13839: 
13840: ############################################################
13841: ############################################################
13842: 
13843: =pod
13844: 
13845: =back 
13846: 
13847: =head1 Statistics helper routines?  
13848: 
13849: Bad place for them but what the hell.
13850: 
13851: =over 4
13852: 
13853: =item * &chartlink()
13854: 
13855: Returns a link to the chart for a specific student.  
13856: 
13857: Inputs:
13858: 
13859: =over 4
13860: 
13861: =item $linktext: The text of the link
13862: 
13863: =item $sname: The students username
13864: 
13865: =item $sdomain: The students domain
13866: 
13867: =back
13868: 
13869: =back
13870: 
13871: =cut
13872: 
13873: ############################################################
13874: ############################################################
13875: sub chartlink {
13876:     my ($linktext, $sname, $sdomain) = @_;
13877:     my $link = '<a href="/adm/statistics?reportSelected=student_assessment'.
13878:         '&amp;SelectedStudent='.&escape($sname.':'.$sdomain).
13879:         '&amp;chartoutputmode='.HTML::Entities::encode('html, with all links').
13880:        '">'.$linktext.'</a>';
13881: }
13882: 
13883: #######################################################
13884: #######################################################
13885: 
13886: =pod
13887: 
13888: =head1 Course Environment Routines
13889: 
13890: =over 4
13891: 
13892: =item * &restore_course_settings()
13893: 
13894: =item * &store_course_settings()
13895: 
13896: Restores/Store indicated form parameters from the course environment.
13897: Will not overwrite existing values of the form parameters.
13898: 
13899: Inputs: 
13900: a scalar describing the data (e.g. 'chart', 'problem_analysis')
13901: 
13902: a hash ref describing the data to be stored.  For example:
13903:    
13904: %Save_Parameters = ('Status' => 'scalar',
13905:     'chartoutputmode' => 'scalar',
13906:     'chartoutputdata' => 'scalar',
13907:     'Section' => 'array',
13908:     'Group' => 'array',
13909:     'StudentData' => 'array',
13910:     'Maps' => 'array');
13911: 
13912: Returns: both routines return nothing
13913: 
13914: =back
13915: 
13916: =cut
13917: 
13918: #######################################################
13919: #######################################################
13920: sub store_course_settings {
13921:     return &store_settings($env{'request.course.id'},@_);
13922: }
13923: 
13924: sub store_settings {
13925:     # save to the environment
13926:     # appenv the same items, just to be safe
13927:     my $udom  = $env{'user.domain'};
13928:     my $uname = $env{'user.name'};
13929:     my ($context,$prefix,$Settings) = @_;
13930:     my %SaveHash;
13931:     my %AppHash;
13932:     while (my ($setting,$type) = each(%$Settings)) {
13933:         my $basename = join('.','internal',$context,$prefix,$setting);
13934:         my $envname = 'environment.'.$basename;
13935:         if (exists($env{'form.'.$setting})) {
13936:             # Save this value away
13937:             if ($type eq 'scalar' &&
13938:                 (! exists($env{$envname}) || 
13939:                  $env{$envname} ne $env{'form.'.$setting})) {
13940:                 $SaveHash{$basename} = $env{'form.'.$setting};
13941:                 $AppHash{$envname}   = $env{'form.'.$setting};
13942:             } elsif ($type eq 'array') {
13943:                 my $stored_form;
13944:                 if (ref($env{'form.'.$setting})) {
13945:                     $stored_form = join(',',
13946:                                         map {
13947:                                             &escape($_);
13948:                                         } sort(@{$env{'form.'.$setting}}));
13949:                 } else {
13950:                     $stored_form = 
13951:                         &escape($env{'form.'.$setting});
13952:                 }
13953:                 # Determine if the array contents are the same.
13954:                 if ($stored_form ne $env{$envname}) {
13955:                     $SaveHash{$basename} = $stored_form;
13956:                     $AppHash{$envname}   = $stored_form;
13957:                 }
13958:             }
13959:         }
13960:     }
13961:     my $put_result = &Apache::lonnet::put('environment',\%SaveHash,
13962:                                           $udom,$uname);
13963:     if ($put_result !~ /^(ok|delayed)/) {
13964:         &Apache::lonnet::logthis('unable to save form parameters, '.
13965:                                  'got error:'.$put_result);
13966:     }
13967:     # Make sure these settings stick around in this session, too
13968:     &Apache::lonnet::appenv(\%AppHash);
13969:     return;
13970: }
13971: 
13972: sub restore_course_settings {
13973:     return &restore_settings($env{'request.course.id'},@_);
13974: }
13975: 
13976: sub restore_settings {
13977:     my ($context,$prefix,$Settings) = @_;
13978:     while (my ($setting,$type) = each(%$Settings)) {
13979:         next if (exists($env{'form.'.$setting}));
13980:         my $envname = 'environment.internal.'.$context.'.'.$prefix.
13981:             '.'.$setting;
13982:         if (exists($env{$envname})) {
13983:             if ($type eq 'scalar') {
13984:                 $env{'form.'.$setting} = $env{$envname};
13985:             } elsif ($type eq 'array') {
13986:                 $env{'form.'.$setting} = [ 
13987:                                            map { 
13988:                                                &unescape($_); 
13989:                                            } split(',',$env{$envname})
13990:                                            ];
13991:             }
13992:         }
13993:     }
13994: }
13995: 
13996: #######################################################
13997: #######################################################
13998: 
13999: =pod
14000: 
14001: =head1 Domain E-mail Routines  
14002: 
14003: =over 4
14004: 
14005: =item * &build_recipient_list()
14006: 
14007: Build recipient lists for following types of e-mail:
14008: (a) Error Reports, (b) Package Updates, (c) lonstatus warnings/errors
14009: (d) Help requests, (e) Course requests needing approval, (f) loncapa
14010: module change checking, student/employee ID conflict checks, as
14011: generated by lonerrorhandler.pm, CHECKRPMS, loncron,
14012: lonsupportreq.pm, loncoursequeueadmin.pm, searchcat.pl respectively.
14013: 
14014: Inputs:
14015: defmail (scalar - email address of default recipient),
14016: mailing type (scalar: errormail, packagesmail, helpdeskmail,
14017: requestsmail, updatesmail, or idconflictsmail).
14018: 
14019: defdom (domain for which to retrieve configuration settings),
14020: 
14021: origmail (scalar - email address of recipient from loncapa.conf,
14022: i.e., predates configuration by DC via domainprefs.pm
14023: 
14024: Returns: comma separated list of addresses to which to send e-mail.
14025: 
14026: =back
14027: 
14028: =cut
14029: 
14030: ############################################################
14031: ############################################################
14032: sub build_recipient_list {
14033:     my ($defmail,$mailing,$defdom,$origmail) = @_;
14034:     my @recipients;
14035:     my ($otheremails,$lastresort,$allbcc,$addtext);
14036:     my %domconfig =
14037:         &Apache::lonnet::get_dom('configuration',['contacts'],$defdom);
14038:     if (ref($domconfig{'contacts'}) eq 'HASH') {
14039:         if (exists($domconfig{'contacts'}{$mailing})) {
14040:             if (ref($domconfig{'contacts'}{$mailing}) eq 'HASH') {
14041:                 my @contacts = ('adminemail','supportemail');
14042:                 foreach my $item (@contacts) {
14043:                     if ($domconfig{'contacts'}{$mailing}{$item}) {
14044:                         my $addr = $domconfig{'contacts'}{$item}; 
14045:                         if (!grep(/^\Q$addr\E$/,@recipients)) {
14046:                             push(@recipients,$addr);
14047:                         }
14048:                     }
14049:                 }
14050:                 $otheremails = $domconfig{'contacts'}{$mailing}{'others'};
14051:                 if ($mailing eq 'helpdeskmail') {
14052:                     if ($domconfig{'contacts'}{$mailing}{'bcc'}) {
14053:                         my @bccs = split(/,/,$domconfig{'contacts'}{$mailing}{'bcc'});
14054:                         my @ok_bccs;
14055:                         foreach my $bcc (@bccs) {
14056:                             $bcc =~ s/^\s+//g;
14057:                             $bcc =~ s/\s+$//g;
14058:                             if ($bcc =~ m/^[^\@]+\@[^\@]+$/) {
14059:                                 if (!(grep(/^\Q$bcc\E$/,@ok_bccs))) {
14060:                                     push(@ok_bccs,$bcc);
14061:                                 }
14062:                             }
14063:                         }
14064:                         if (@ok_bccs > 0) {
14065:                             $allbcc = join(', ',@ok_bccs);
14066:                         }
14067:                     }
14068:                     $addtext = $domconfig{'contacts'}{$mailing}{'include'};
14069:                 }
14070:             }
14071:         } elsif ($origmail ne '') {
14072:             $lastresort = $origmail;
14073:         }
14074:     } elsif ($origmail ne '') {
14075:         $lastresort = $origmail;
14076:     }
14077: 
14078:     if (($mailing eq 'helpdesk') && ($lastresort ne '')) {
14079:         unless (grep(/^\Q$defdom\E$/,&Apache::lonnet::current_machine_domains())) {
14080:             my $lonhost = $Apache::lonnet::perlvar{'lonHostID'};
14081:             my $machinedom = $Apache::lonnet::perlvar{'lonDefDomain'};
14082:             my %what = (
14083:                           perlvar => 1,
14084:                        );
14085:             my $primary = &Apache::lonnet::domain($defdom,'primary');
14086:             if ($primary) {
14087:                 my $gotaddr;
14088:                 my ($result,$returnhash) =
14089:                     &Apache::lonnet::get_remote_globals($primary,{ perlvar => 1 });
14090:                 if (($result eq 'ok') && (ref($returnhash) eq 'HASH')) {
14091:                     if ($returnhash->{'lonSupportEMail'} =~ /^[^\@]+\@[^\@]+$/) {
14092:                         $lastresort = $returnhash->{'lonSupportEMail'};
14093:                         $gotaddr = 1;
14094:                     }
14095:                 }
14096:                 unless ($gotaddr) {
14097:                     my $uintdom = &Apache::lonnet::internet_dom($primary);
14098:                     my $intdom = &Apache::lonnet::internet_dom($lonhost);
14099:                     unless ($uintdom eq $intdom) {
14100:                         my %domconfig =
14101:                             &Apache::lonnet::get_dom('configuration',['contacts'],$machinedom);
14102:                         if (ref($domconfig{'contacts'}) eq 'HASH') {
14103:                             if (ref($domconfig{'contacts'}{'otherdomsmail'}) eq 'HASH') {
14104:                                 my @contacts = ('adminemail','supportemail');
14105:                                 foreach my $item (@contacts) {
14106:                                     if ($domconfig{'contacts'}{'otherdomsmail'}{$item}) {
14107:                                         my $addr = $domconfig{'contacts'}{$item};
14108:                                         if (!grep(/^\Q$addr\E$/,@recipients)) {
14109:                                             push(@recipients,$addr);
14110:                                         }
14111:                                     }
14112:                                 }
14113:                                 if ($domconfig{'contacts'}{'otherdomsmail'}{'others'}) {
14114:                                     $otheremails = $domconfig{'contacts'}{'otherdomsmail'}{'others'};
14115:                                 }
14116:                                 if ($domconfig{'contacts'}{'otherdomsmail'}{'bcc'}) {
14117:                                     my @bccs = split(/,/,$domconfig{'contacts'}{'otherdomsmail'}{'bcc'});
14118:                                     my @ok_bccs;
14119:                                     foreach my $bcc (@bccs) {
14120:                                         $bcc =~ s/^\s+//g;
14121:                                         $bcc =~ s/\s+$//g;
14122:                                         if ($bcc =~ m/^[^\@]+\@[^\@]+$/) {
14123:                                             if (!(grep(/^\Q$bcc\E$/,@ok_bccs))) {
14124:                                                 push(@ok_bccs,$bcc);
14125:                                             }
14126:                                         }
14127:                                     }
14128:                                     if (@ok_bccs > 0) {
14129:                                         $allbcc = join(', ',@ok_bccs);
14130:                                     }
14131:                                 }
14132:                                 $addtext = $domconfig{'contacts'}{'otherdomsmail'}{'include'};
14133:                             }
14134:                         }
14135:                     }
14136:                 }
14137:             }
14138:         }
14139:     }
14140:     if (defined($defmail)) {
14141:         if ($defmail ne '') {
14142:             push(@recipients,$defmail);
14143:         }
14144:     }
14145:     if ($otheremails) {
14146:         my @others;
14147:         if ($otheremails =~ /,/) {
14148:             @others = split(/,/,$otheremails);
14149:         } else {
14150:             push(@others,$otheremails);
14151:         }
14152:         foreach my $addr (@others) {
14153:             if (!grep(/^\Q$addr\E$/,@recipients)) {
14154:                 push(@recipients,$addr);
14155:             }
14156:         }
14157:     }
14158:     if ($mailing eq 'helpdesk') {
14159:         if ((!@recipients) && ($lastresort ne '')) {
14160:             push(@recipients,$lastresort);
14161:         }
14162:     } elsif ($lastresort ne '') {
14163:         if (!grep(/^\Q$lastresort\E$/,@recipients)) {
14164:             push(@recipients,$lastresort);
14165:         }
14166:     }
14167:     my $recipientlist = join(',',@recipients);
14168:     if (wantarray) {
14169:         return ($recipientlist,$allbcc,$addtext);
14170:     } else {
14171:         return $recipientlist;
14172:     }
14173: }
14174: 
14175: ############################################################
14176: ############################################################
14177: 
14178: =pod
14179: 
14180: =head1 Course Catalog Routines
14181: 
14182: =over 4
14183: 
14184: =item * &gather_categories()
14185: 
14186: Converts category definitions - keys of categories hash stored in  
14187: coursecategories in configuration.db on the primary library server in a 
14188: domain - to an array.  Also generates javascript and idx hash used to 
14189: generate Domain Coordinator interface for editing Course Categories.
14190: 
14191: Inputs:
14192: 
14193: categories (reference to hash of category definitions).
14194: 
14195: cats (reference to array of arrays/hashes which encapsulates hierarchy of
14196:       categories and subcategories).
14197: 
14198: idx (reference to hash of counters used in Domain Coordinator interface for 
14199:       editing Course Categories).
14200: 
14201: jsarray (reference to array of categories used to create Javascript arrays for
14202:          Domain Coordinator interface for editing Course Categories).
14203: 
14204: Returns: nothing
14205: 
14206: Side effects: populates cats, idx and jsarray. 
14207: 
14208: =cut
14209: 
14210: sub gather_categories {
14211:     my ($categories,$cats,$idx,$jsarray) = @_;
14212:     my %counters;
14213:     my $num = 0;
14214:     foreach my $item (keys(%{$categories})) {
14215:         my ($cat,$container,$depth) = map { &unescape($_); } split(/:/,$item);
14216:         if ($container eq '' && $depth == 0) {
14217:             $cats->[$depth][$categories->{$item}] = $cat;
14218:         } else {
14219:             $cats->[$depth]{$container}[$categories->{$item}] = $cat;
14220:         }
14221:         my ($escitem,$tail) = split(/:/,$item,2);
14222:         if ($counters{$tail} eq '') {
14223:             $counters{$tail} = $num;
14224:             $num ++;
14225:         }
14226:         if (ref($idx) eq 'HASH') {
14227:             $idx->{$item} = $counters{$tail};
14228:         }
14229:         if (ref($jsarray) eq 'ARRAY') {
14230:             push(@{$jsarray->[$counters{$tail}]},$item);
14231:         }
14232:     }
14233:     return;
14234: }
14235: 
14236: =pod
14237: 
14238: =item * &extract_categories()
14239: 
14240: Used to generate breadcrumb trails for course categories.
14241: 
14242: Inputs:
14243: 
14244: categories (reference to hash of category definitions).
14245: 
14246: cats (reference to array of arrays/hashes which encapsulates hierarchy of
14247:       categories and subcategories).
14248: 
14249: trails (reference to array of breacrumb trails for each category).
14250: 
14251: allitems (reference to hash - key is category key 
14252:          (format: escaped(name):escaped(parent category):depth in hierarchy).
14253: 
14254: idx (reference to hash of counters used in Domain Coordinator interface for
14255:       editing Course Categories).
14256: 
14257: jsarray (reference to array of categories used to create Javascript arrays for
14258:          Domain Coordinator interface for editing Course Categories).
14259: 
14260: subcats (reference to hash of arrays containing all subcategories within each 
14261:          category, -recursive)
14262: 
14263: Returns: nothing
14264: 
14265: Side effects: populates trails and allitems hash references.
14266: 
14267: =cut
14268: 
14269: sub extract_categories {
14270:     my ($categories,$cats,$trails,$allitems,$idx,$jsarray,$subcats) = @_;
14271:     if (ref($categories) eq 'HASH') {
14272:         &gather_categories($categories,$cats,$idx,$jsarray);
14273:         if (ref($cats->[0]) eq 'ARRAY') {
14274:             for (my $i=0; $i<@{$cats->[0]}; $i++) {
14275:                 my $name = $cats->[0][$i];
14276:                 my $item = &escape($name).'::0';
14277:                 my $trailstr;
14278:                 if ($name eq 'instcode') {
14279:                     $trailstr = &mt('Official courses (with institutional codes)');
14280:                 } elsif ($name eq 'communities') {
14281:                     $trailstr = &mt('Communities');
14282:                 } else {
14283:                     $trailstr = $name;
14284:                 }
14285:                 if ($allitems->{$item} eq '') {
14286:                     push(@{$trails},$trailstr);
14287:                     $allitems->{$item} = scalar(@{$trails})-1;
14288:                 }
14289:                 my @parents = ($name);
14290:                 if (ref($cats->[1]{$name}) eq 'ARRAY') {
14291:                     for (my $j=0; $j<@{$cats->[1]{$name}}; $j++) {
14292:                         my $category = $cats->[1]{$name}[$j];
14293:                         if (ref($subcats) eq 'HASH') {
14294:                             push(@{$subcats->{$item}},&escape($category).':'.&escape($name).':1');
14295:                         }
14296:                         &recurse_categories($cats,2,$category,$trails,$allitems,\@parents,$subcats);
14297:                     }
14298:                 } else {
14299:                     if (ref($subcats) eq 'HASH') {
14300:                         $subcats->{$item} = [];
14301:                     }
14302:                 }
14303:             }
14304:         }
14305:     }
14306:     return;
14307: }
14308: 
14309: =pod
14310: 
14311: =item * &recurse_categories()
14312: 
14313: Recursively used to generate breadcrumb trails for course categories.
14314: 
14315: Inputs:
14316: 
14317: cats (reference to array of arrays/hashes which encapsulates hierarchy of
14318:       categories and subcategories).
14319: 
14320: depth (current depth in hierarchy of categories and sub-categories - 0 indexed).
14321: 
14322: category (current course category, for which breadcrumb trail is being generated).
14323: 
14324: trails (reference to array of breadcrumb trails for each category).
14325: 
14326: allitems (reference to hash - key is category key
14327:          (format: escaped(name):escaped(parent category):depth in hierarchy).
14328: 
14329: parents (array containing containers directories for current category, 
14330:          back to top level). 
14331: 
14332: Returns: nothing
14333: 
14334: Side effects: populates trails and allitems hash references
14335: 
14336: =cut
14337: 
14338: sub recurse_categories {
14339:     my ($cats,$depth,$category,$trails,$allitems,$parents,$subcats) = @_;
14340:     my $shallower = $depth - 1;
14341:     if (ref($cats->[$depth]{$category}) eq 'ARRAY') {
14342:         for (my $k=0; $k<@{$cats->[$depth]{$category}}; $k++) {
14343:             my $name = $cats->[$depth]{$category}[$k];
14344:             my $item = &escape($category).':'.&escape($parents->[-1]).':'.$shallower;
14345:             my $trailstr = join(' -&gt; ',(@{$parents},$category));
14346:             if ($allitems->{$item} eq '') {
14347:                 push(@{$trails},$trailstr);
14348:                 $allitems->{$item} = scalar(@{$trails})-1;
14349:             }
14350:             my $deeper = $depth+1;
14351:             push(@{$parents},$category);
14352:             if (ref($subcats) eq 'HASH') {
14353:                 my $subcat = &escape($name).':'.$category.':'.$depth;
14354:                 for (my $j=@{$parents}; $j>=0; $j--) {
14355:                     my $higher;
14356:                     if ($j > 0) {
14357:                         $higher = &escape($parents->[$j]).':'.
14358:                                   &escape($parents->[$j-1]).':'.$j;
14359:                     } else {
14360:                         $higher = &escape($parents->[$j]).'::'.$j;
14361:                     }
14362:                     push(@{$subcats->{$higher}},$subcat);
14363:                 }
14364:             }
14365:             &recurse_categories($cats,$deeper,$name,$trails,$allitems,$parents,
14366:                                 $subcats);
14367:             pop(@{$parents});
14368:         }
14369:     } else {
14370:         my $item = &escape($category).':'.&escape($parents->[-1]).':'.$shallower;
14371:         my $trailstr = join(' -&gt; ',(@{$parents},$category));
14372:         if ($allitems->{$item} eq '') {
14373:             push(@{$trails},$trailstr);
14374:             $allitems->{$item} = scalar(@{$trails})-1;
14375:         }
14376:     }
14377:     return;
14378: }
14379: 
14380: =pod
14381: 
14382: =item * &assign_categories_table()
14383: 
14384: Create a datatable for display of hierarchical categories in a domain,
14385: with checkboxes to allow a course to be categorized. 
14386: 
14387: Inputs:
14388: 
14389: cathash - reference to hash of categories defined for the domain (from
14390:           configuration.db)
14391: 
14392: currcat - scalar with an & separated list of categories assigned to a course. 
14393: 
14394: type    - scalar contains course type (Course or Community).
14395: 
14396: disabled - scalar (optional) contains disabled="disabled" if input elements are
14397:            to be readonly (e.g., Domain Helpdesk role viewing course settings).
14398: 
14399: Returns: $output (markup to be displayed) 
14400: 
14401: =cut
14402: 
14403: sub assign_categories_table {
14404:     my ($cathash,$currcat,$type,$disabled) = @_;
14405:     my $output;
14406:     if (ref($cathash) eq 'HASH') {
14407:         my (@cats,@trails,%allitems,%idx,@jsarray,@path,$maxdepth);
14408:         &extract_categories($cathash,\@cats,\@trails,\%allitems,\%idx,\@jsarray);
14409:         $maxdepth = scalar(@cats);
14410:         if (@cats > 0) {
14411:             my $itemcount = 0;
14412:             if (ref($cats[0]) eq 'ARRAY') {
14413:                 my @currcategories;
14414:                 if ($currcat ne '') {
14415:                     @currcategories = split('&',$currcat);
14416:                 }
14417:                 my $table;
14418:                 for (my $i=0; $i<@{$cats[0]}; $i++) {
14419:                     my $parent = $cats[0][$i];
14420:                     next if ($parent eq 'instcode');
14421:                     if ($type eq 'Community') {
14422:                         next unless ($parent eq 'communities');
14423:                     } else {
14424:                         next if ($parent eq 'communities');
14425:                     }
14426:                     my $css_class = $itemcount%2?' class="LC_odd_row"':'';
14427:                     my $item = &escape($parent).'::0';
14428:                     my $checked = '';
14429:                     if (@currcategories > 0) {
14430:                         if (grep(/^\Q$item\E$/,@currcategories)) {
14431:                             $checked = ' checked="checked"';
14432:                         }
14433:                     }
14434:                     my $parent_title = $parent;
14435:                     if ($parent eq 'communities') {
14436:                         $parent_title = &mt('Communities');
14437:                     }
14438:                     $table .= '<tr '.$css_class.'><td><span class="LC_nobreak">'.
14439:                               '<input type="checkbox" name="usecategory" value="'.
14440:                               $item.'"'.$checked.$disabled.' />'.$parent_title.'</span>'.
14441:                               '<input type="hidden" name="catname" value="'.$parent.'" /></td>';
14442:                     my $depth = 1;
14443:                     push(@path,$parent);
14444:                     $table .= &assign_category_rows($itemcount,\@cats,$depth,$parent,\@path,\@currcategories,$disabled);
14445:                     pop(@path);
14446:                     $table .= '</tr><tr><td colspan="'.$maxdepth.'" class="LC_row_separator"></td></tr>';
14447:                     $itemcount ++;
14448:                 }
14449:                 if ($itemcount) {
14450:                     $output = &Apache::loncommon::start_data_table().
14451:                               $table.
14452:                               &Apache::loncommon::end_data_table();
14453:                 }
14454:             }
14455:         }
14456:     }
14457:     return $output;
14458: }
14459: 
14460: =pod
14461: 
14462: =item * &assign_category_rows()
14463: 
14464: Create a datatable row for display of nested categories in a domain,
14465: with checkboxes to allow a course to be categorized,called recursively.
14466: 
14467: Inputs:
14468: 
14469: itemcount - track row number for alternating colors
14470: 
14471: cats - reference to array of arrays/hashes which encapsulates hierarchy of
14472:       categories and subcategories.
14473: 
14474: depth - current depth in hierarchy of categories and sub-categories - 0 indexed.
14475: 
14476: parent - parent of current category item
14477: 
14478: path - Array containing all categories back up through the hierarchy from the
14479:        current category to the top level.
14480: 
14481: currcategories - reference to array of current categories assigned to the course
14482: 
14483: disabled - scalar (optional) contains disabled="disabled" if input elements are
14484:            to be readonly (e.g., Domain Helpdesk role viewing course settings).
14485: 
14486: Returns: $output (markup to be displayed).
14487: 
14488: =cut
14489: 
14490: sub assign_category_rows {
14491:     my ($itemcount,$cats,$depth,$parent,$path,$currcategories,$disabled) = @_;
14492:     my ($text,$name,$item,$chgstr);
14493:     if (ref($cats) eq 'ARRAY') {
14494:         my $maxdepth = scalar(@{$cats});
14495:         if (ref($cats->[$depth]) eq 'HASH') {
14496:             if (ref($cats->[$depth]{$parent}) eq 'ARRAY') {
14497:                 my $numchildren = @{$cats->[$depth]{$parent}};
14498:                 my $css_class = $itemcount%2?' class="LC_odd_row"':'';
14499:                 $text .= '<td><table class="LC_data_table">';
14500:                 for (my $j=0; $j<$numchildren; $j++) {
14501:                     $name = $cats->[$depth]{$parent}[$j];
14502:                     $item = &escape($name).':'.&escape($parent).':'.$depth;
14503:                     my $deeper = $depth+1;
14504:                     my $checked = '';
14505:                     if (ref($currcategories) eq 'ARRAY') {
14506:                         if (@{$currcategories} > 0) {
14507:                             if (grep(/^\Q$item\E$/,@{$currcategories})) {
14508:                                 $checked = ' checked="checked"';
14509:                             }
14510:                         }
14511:                     }
14512:                     $text .= '<tr><td><span class="LC_nobreak"><label>'.
14513:                              '<input type="checkbox" name="usecategory" value="'.
14514:                              $item.'"'.$checked.$disabled.' />'.$name.'</label></span>'.
14515:                              '<input type="hidden" name="catname" value="'.$name.'" />'.
14516:                              '</td><td>';
14517:                     if (ref($path) eq 'ARRAY') {
14518:                         push(@{$path},$name);
14519:                         $text .= &assign_category_rows($itemcount,$cats,$deeper,$name,$path,$currcategories,$disabled);
14520:                         pop(@{$path});
14521:                     }
14522:                     $text .= '</td></tr>';
14523:                 }
14524:                 $text .= '</table></td>';
14525:             }
14526:         }
14527:     }
14528:     return $text;
14529: }
14530: 
14531: =pod
14532: 
14533: =back
14534: 
14535: =cut
14536: 
14537: ############################################################
14538: ############################################################
14539: 
14540: 
14541: sub commit_customrole {
14542:     my ($udom,$uname,$url,$three,$four,$five,$start,$end,$context) = @_;
14543:     my $output = &mt('Assigning custom role').' "'.$five.'" by '.$four.':'.$three.' in '.$url.
14544:                          ($start?', '.&mt('starting').' '.localtime($start):'').
14545:                          ($end?', ending '.localtime($end):'').': <b>'.
14546:               &Apache::lonnet::assigncustomrole(
14547:                  $udom,$uname,$url,$three,$four,$five,$end,$start,undef,undef,$context).
14548:                  '</b><br />';
14549:     return $output;
14550: }
14551: 
14552: sub commit_standardrole {
14553:     my ($udom,$uname,$url,$three,$start,$end,$one,$two,$sec,$context,$credits) = @_;
14554:     my ($output,$logmsg,$linefeed);
14555:     if ($context eq 'auto') {
14556:         $linefeed = "\n";
14557:     } else {
14558:         $linefeed = "<br />\n";
14559:     }  
14560:     if ($three eq 'st') {
14561:         my $result = &commit_studentrole(\$logmsg,$udom,$uname,$url,$three,$start,$end,
14562:                                          $one,$two,$sec,$context,$credits);
14563:         if (($result =~ /^error/) || ($result eq 'not_in_class') || 
14564:             ($result eq 'unknown_course') || ($result eq 'refused')) {
14565:             $output = $logmsg.' '.&mt('Error: ').$result."\n"; 
14566:         } else {
14567:             $output = $logmsg.$linefeed.&mt('Assigning').' '.$three.' in '.$url.
14568:                ($start?', '.&mt('starting').' '.localtime($start):'').
14569:                ($end?', '.&mt('ending').' '.localtime($end):'').': ';
14570:             if ($context eq 'auto') {
14571:                 $output .= $result.$linefeed.&mt('Add to classlist').': ok';
14572:             } else {
14573:                $output .= '<b>'.$result.'</b>'.$linefeed.
14574:                &mt('Add to classlist').': <b>ok</b>';
14575:             }
14576:             $output .= $linefeed;
14577:         }
14578:     } else {
14579:         $output = &mt('Assigning').' '.$three.' in '.$url.
14580:                ($start?', '.&mt('starting').' '.localtime($start):'').
14581:                ($end?', '.&mt('ending').' '.localtime($end):'').': ';
14582:         my $result = &Apache::lonnet::assignrole($udom,$uname,$url,$three,$end,$start,'','',$context);
14583:         if ($context eq 'auto') {
14584:             $output .= $result.$linefeed;
14585:         } else {
14586:             $output .= '<b>'.$result.'</b>'.$linefeed;
14587:         }
14588:     }
14589:     return $output;
14590: }
14591: 
14592: sub commit_studentrole {
14593:     my ($logmsg,$udom,$uname,$url,$three,$start,$end,$one,$two,$sec,$context,
14594:         $credits) = @_;
14595:     my ($result,$linefeed,$oldsecurl,$newsecurl);
14596:     if ($context eq 'auto') {
14597:         $linefeed = "\n";
14598:     } else {
14599:         $linefeed = '<br />'."\n";
14600:     }
14601:     if (defined($one) && defined($two)) {
14602:         my $cid=$one.'_'.$two;
14603:         my $oldsec=&Apache::lonnet::getsection($udom,$uname,$cid);
14604:         my $secchange = 0;
14605:         my $expire_role_result;
14606:         my $modify_section_result;
14607:         if ($oldsec ne '-1') { 
14608:             if ($oldsec ne $sec) {
14609:                 $secchange = 1;
14610:                 my $now = time;
14611:                 my $uurl='/'.$cid;
14612:                 $uurl=~s/\_/\//g;
14613:                 if ($oldsec) {
14614:                     $uurl.='/'.$oldsec;
14615:                 }
14616:                 $oldsecurl = $uurl;
14617:                 $expire_role_result = 
14618:                     &Apache::lonnet::assignrole($udom,$uname,$uurl,'st',$now,'','',$context);
14619:                 if ($env{'request.course.sec'} ne '') { 
14620:                     if ($expire_role_result eq 'refused') {
14621:                         my @roles = ('st');
14622:                         my @statuses = ('previous');
14623:                         my @roledoms = ($one);
14624:                         my $withsec = 1;
14625:                         my %roleshash = 
14626:                             &Apache::lonnet::get_my_roles($uname,$udom,'userroles',
14627:                                               \@statuses,\@roles,\@roledoms,$withsec);
14628:                         if (defined ($roleshash{$two.':'.$one.':st:'.$oldsec})) {
14629:                             my ($oldstart,$oldend) = 
14630:                                 split(':',$roleshash{$two.':'.$one.':st:'.$oldsec});
14631:                             if ($oldend > 0 && $oldend <= $now) {
14632:                                 $expire_role_result = 'ok';
14633:                             }
14634:                         }
14635:                     }
14636:                 }
14637:                 $result = $expire_role_result;
14638:             }
14639:         }
14640:         if (($expire_role_result eq 'ok') || ($secchange == 0)) {
14641:             $modify_section_result = 
14642:                 &Apache::lonnet::modify_student_enrollment($udom,$uname,undef,undef,
14643:                                                            undef,undef,undef,$sec,
14644:                                                            $end,$start,'','',$cid,
14645:                                                            '',$context,$credits);
14646:             if ($modify_section_result =~ /^ok/) {
14647:                 if ($secchange == 1) {
14648:                     if ($sec eq '') {
14649:                         $$logmsg .= &mt('Section for [_1] switched from (possibly expired) old section: [_2] to student role without a section.',$uname,$oldsec).$linefeed;
14650:                     } else {
14651:                         $$logmsg .= &mt('Section for [_1] switched from (possibly expired) old section: [_2] to new section: [_3].',$uname,$oldsec,$sec).$linefeed;
14652:                     }
14653:                 } elsif ($oldsec eq '-1') {
14654:                     if ($sec eq '') {
14655:                         $$logmsg .= &mt('New student role without a section for [_1] in course [_2].',$uname,$cid).$linefeed;
14656:                     } else {
14657:                         $$logmsg .= &mt('New student role for [_1] in section [_2] in course [_3].',$uname,$sec,$cid).$linefeed;
14658:                     }
14659:                 } else {
14660:                     if ($sec eq '') {
14661:                         $$logmsg .= &mt('Student [_1] assigned to course [_2] without a section.',$uname,$cid).$linefeed;
14662:                     } else {
14663:                         $$logmsg .= &mt('Student [_1] assigned to section [_2] in course [_3].',$uname,$sec,$cid).$linefeed;
14664:                     }
14665:                 }
14666:             } else {
14667:                 if ($secchange) {       
14668:                     $$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;
14669:                 } else {
14670:                     $$logmsg .= &mt('Error when attempting to modify role for [_1] for section: "[_2]" in course [_3] -error:',$uname,$sec,$cid).' '.$modify_section_result.$linefeed;
14671:                 }
14672:             }
14673:             $result = $modify_section_result;
14674:         } elsif ($secchange == 1) {
14675:             if ($oldsec eq '') {
14676:                 $$logmsg .= &mt('Error when attempting to expire existing role without a section for [_1] in course [_2] -error: ',$uname,$cid).' '.$expire_role_result.$linefeed;
14677:             } else {
14678:                 $$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;
14679:             }
14680:             if ($expire_role_result eq 'refused') {
14681:                 my $newsecurl = '/'.$cid;
14682:                 $newsecurl =~ s/\_/\//g;
14683:                 if ($sec ne '') {
14684:                     $newsecurl.='/'.$sec;
14685:                 }
14686:                 if (&Apache::lonnet::allowed('cst',$newsecurl) && !(&Apache::lonnet::allowed('cst',$oldsecurl))) {
14687:                     if ($sec eq '') {
14688:                         $$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;
14689:                     } else {
14690:                         $$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;
14691:                     }
14692:                 }
14693:             }
14694:         }
14695:     } else {
14696:         $$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;
14697:         $result = "error: incomplete course id\n";
14698:     }
14699:     return $result;
14700: }
14701: 
14702: sub show_role_extent {
14703:     my ($scope,$context,$role) = @_;
14704:     $scope =~ s{^/}{};
14705:     my @courseroles = &Apache::lonuserutils::roles_by_context('course',1);
14706:     push(@courseroles,'co');
14707:     my @authorroles = &Apache::lonuserutils::roles_by_context('author');
14708:     if (($context eq 'course') || (grep(/^\Q$role\E/,@courseroles))) {
14709:         $scope =~ s{/}{_};
14710:         return '<span class="LC_cusr_emph">'.$env{'course.'.$scope.'.description'}.'</span>';
14711:     } elsif (($context eq 'author') || (grep(/^\Q$role\E/,@authorroles))) {
14712:         my ($audom,$auname) = split(/\//,$scope);
14713:         return &mt('[_1] Author Space','<span class="LC_cusr_emph">'.
14714:                    &Apache::loncommon::plainname($auname,$audom).'</span>');
14715:     } else {
14716:         $scope =~ s{/$}{};
14717:         return &mt('Domain: [_1]','<span class="LC_cusr_emph">'.
14718:                    &Apache::lonnet::domain($scope,'description').'</span>');
14719:     }
14720: }
14721: 
14722: ############################################################
14723: ############################################################
14724: 
14725: sub check_clone {
14726:     my ($args,$linefeed) = @_;
14727:     my $cloneid='/'.$args->{'clonedomain'}.'/'.$args->{'clonecourse'};
14728:     my ($clonecrsudom,$clonecrsunum)= &LONCAPA::split_courseid($cloneid);
14729:     my $clonehome=&Apache::lonnet::homeserver($clonecrsunum,$clonecrsudom);
14730:     my $clonemsg;
14731:     my $can_clone = 0;
14732:     my $lctype = lc($args->{'crstype'});
14733:     if ($lctype ne 'community') {
14734:         $lctype = 'course';
14735:     }
14736:     if ($clonehome eq 'no_host') {
14737:         if ($args->{'crstype'} eq 'Community') {
14738:             $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'});
14739:         } else {
14740:             $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'});
14741:         }     
14742:     } else {
14743: 	my %clonedesc = &Apache::lonnet::coursedescription($cloneid,{'one_time' => 1});
14744:         if ($args->{'crstype'} eq 'Community') {
14745:             if ($clonedesc{'type'} ne 'Community') {
14746:                  $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'});
14747:                 return ($can_clone, $clonemsg, $cloneid, $clonehome);
14748:             }
14749:         }
14750: 	if (($env{'request.role.domain'} eq $args->{'clonedomain'}) &&
14751:             (&Apache::lonnet::allowed('ccc',$env{'request.role.domain'}))) {
14752: 	    $can_clone = 1;
14753: 	} else {
14754: 	    my %clonehash = &Apache::lonnet::get('environment',['cloners','internal.coursecode'],
14755: 						 $args->{'clonedomain'},$args->{'clonecourse'});
14756:             if ($clonehash{'cloners'} eq '') {
14757:                 my %domdefs = &Apache::lonnet::get_domain_defaults($args->{'course_domain'});
14758:                 if ($domdefs{'canclone'}) {
14759:                     unless ($domdefs{'canclone'} eq 'none') {
14760:                         if ($domdefs{'canclone'} eq 'domain') {
14761:                             if ($args->{'ccdomain'} eq $args->{'clonedomain'}) {
14762:                                 $can_clone = 1;
14763:                             }
14764:                         } elsif (($clonehash{'internal.coursecode'}) && ($args->{'crscode'}) &&
14765:                                  ($args->{'clonedomain'} eq  $args->{'course_domain'})) {
14766:                             if (&Apache::lonnet::default_instcode_cloning($args->{'clonedomain'},$domdefs{'canclone'},
14767:                                                                           $clonehash{'internal.coursecode'},$args->{'crscode'})) {
14768:                                 $can_clone = 1;
14769:                             }
14770:                         }
14771:                     }
14772:                 }
14773:             } else {
14774: 	        my @cloners = split(/,/,$clonehash{'cloners'});
14775:                 if (grep(/^\*$/,@cloners)) {
14776:                     $can_clone = 1;
14777:                 } elsif (grep(/^\*\:\Q$args->{'ccdomain'}\E$/,@cloners)) {
14778:                     $can_clone = 1;
14779:                 } elsif (grep(/^\Q$args->{'ccuname'}\E:\Q$args->{'ccdomain'}\E$/,@cloners)) {
14780:                     $can_clone = 1;
14781:                 }
14782:                 unless ($can_clone) {
14783:                     if (($clonehash{'internal.coursecode'}) && ($args->{'crscode'}) &&
14784:                         ($args->{'clonedomain'} eq  $args->{'course_domain'})) {
14785:                         my (%gotdomdefaults,%gotcodedefaults);
14786:                         foreach my $cloner (@cloners) {
14787:                             if (($cloner ne '*') && ($cloner !~ /^\*\:$match_domain$/) &&
14788:                                 ($cloner !~ /^$match_username\:$match_domain$/) && ($cloner ne '')) {
14789:                                 my (%codedefaults,@code_order);
14790:                                 if (ref($gotcodedefaults{$args->{'clonedomain'}}) eq 'HASH') {
14791:                                     if (ref($gotcodedefaults{$args->{'clonedomain'}}{'defaults'}) eq 'HASH') {
14792:                                         %codedefaults = %{$gotcodedefaults{$args->{'clonedomain'}}{'defaults'}};
14793:                                     }
14794:                                     if (ref($gotcodedefaults{$args->{'clonedomain'}}{'order'}) eq 'ARRAY') {
14795:                                         @code_order = @{$gotcodedefaults{$args->{'clonedomain'}}{'order'}};
14796:                                     }
14797:                                 } else {
14798:                                     &Apache::lonnet::auto_instcode_defaults($args->{'clonedomain'},
14799:                                                                             \%codedefaults,
14800:                                                                             \@code_order);
14801:                                     $gotcodedefaults{$args->{'clonedomain'}}{'defaults'} = \%codedefaults;
14802:                                     $gotcodedefaults{$args->{'clonedomain'}}{'order'} = \@code_order;
14803:                                 }
14804:                                 if (@code_order > 0) {
14805:                                     if (&Apache::lonnet::check_instcode_cloning(\%codedefaults,\@code_order,
14806:                                                                                 $cloner,$clonehash{'internal.coursecode'},
14807:                                                                                 $args->{'crscode'})) {
14808:                                         $can_clone = 1;
14809:                                         last;
14810:                                     }
14811:                                 }
14812:                             }
14813:                         }
14814:                     }
14815:                 }
14816:             }
14817:             unless ($can_clone) {
14818:                 my $ccrole = 'cc';
14819:                 if ($args->{'crstype'} eq 'Community') {
14820:                     $ccrole = 'co';
14821:                 }
14822:                 my %roleshash =
14823:                     &Apache::lonnet::get_my_roles($args->{'ccuname'},
14824:                                                   $args->{'ccdomain'},
14825:                                                   'userroles',['active'],[$ccrole],
14826:                                                   [$args->{'clonedomain'}]);
14827:                 if ($roleshash{$args->{'clonecourse'}.':'.$args->{'clonedomain'}.':'.$ccrole}) {
14828:                     $can_clone = 1;
14829:                 } elsif (&Apache::lonnet::is_course_owner($args->{'clonedomain'},$args->{'clonecourse'},
14830:                                                           $args->{'ccuname'},$args->{'ccdomain'})) {
14831:                     $can_clone = 1;
14832:                 }
14833:             }
14834:             unless ($can_clone) {
14835:                 if ($args->{'crstype'} eq 'Community') {
14836:                     $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'});
14837:                 } else {
14838:                     $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'});
14839: 	        }
14840: 	    }
14841:         }
14842:     }
14843:     return ($can_clone, $clonemsg, $cloneid, $clonehome);
14844: }
14845: 
14846: sub construct_course {
14847:     my ($args,$logmsg,$courseid,$crsudom,$crsunum,$udom,$uname,$context,
14848:         $cnum,$category,$coderef) = @_;
14849:     my $outcome;
14850:     my $linefeed =  '<br />'."\n";
14851:     if ($context eq 'auto') {
14852:         $linefeed = "\n";
14853:     }
14854: 
14855: #
14856: # Are we cloning?
14857: #
14858:     my ($can_clone, $clonemsg, $cloneid, $clonehome);
14859:     if (($args->{'clonecourse'}) && ($args->{'clonedomain'})) {
14860: 	($can_clone, $clonemsg, $cloneid, $clonehome) = &check_clone($args,$linefeed);
14861: 	if ($context ne 'auto') {
14862:             if ($clonemsg ne '') {
14863: 	        $clonemsg = '<span class="LC_error">'.$clonemsg.'</span>';
14864:             }
14865: 	}
14866: 	$outcome .= $clonemsg.$linefeed;
14867: 
14868:         if (!$can_clone) {
14869: 	    return (0,$outcome);
14870: 	}
14871:     }
14872: 
14873: #
14874: # Open course
14875: #
14876:     my $crstype = lc($args->{'crstype'});
14877:     my %cenv=();
14878:     $$courseid=&Apache::lonnet::createcourse($args->{'course_domain'},
14879:                                              $args->{'cdescr'},
14880:                                              $args->{'curl'},
14881:                                              $args->{'course_home'},
14882:                                              $args->{'nonstandard'},
14883:                                              $args->{'crscode'},
14884:                                              $args->{'ccuname'}.':'.
14885:                                              $args->{'ccdomain'},
14886:                                              $args->{'crstype'},
14887:                                              $cnum,$context,$category);
14888: 
14889:     # Note: The testing routines depend on this being output; see 
14890:     # Utils::Course. This needs to at least be output as a comment
14891:     # if anyone ever decides to not show this, and Utils::Course::new
14892:     # will need to be suitably modified.
14893:     $outcome .= &mt('New LON-CAPA [_1] ID: [_2]',$crstype,$$courseid).$linefeed;
14894:     if ($$courseid =~ /^error:/) {
14895:         return (0,$outcome);
14896:     }
14897: 
14898: #
14899: # Check if created correctly
14900: #
14901:     ($$crsudom,$$crsunum)= &LONCAPA::split_courseid($$courseid);
14902:     my $crsuhome=&Apache::lonnet::homeserver($$crsunum,$$crsudom);
14903:     if ($crsuhome eq 'no_host') {
14904:         $outcome .= &mt('Course creation failed, unrecognized course home server.').$linefeed;
14905:         return (0,$outcome);
14906:     }
14907:     $outcome .= &mt('Created on').': '.$crsuhome.$linefeed;
14908: 
14909: #
14910: # Do the cloning
14911: #   
14912:     if ($can_clone && $cloneid) {
14913: 	$clonemsg = &mt('Cloning [_1] from [_2]',$crstype,$clonehome);
14914: 	if ($context ne 'auto') {
14915: 	    $clonemsg = '<span class="LC_success">'.$clonemsg.'</span>';
14916: 	}
14917: 	$outcome .= $clonemsg.$linefeed;
14918: 	my %oldcenv=&Apache::lonnet::dump('environment',$$crsudom,$$crsunum);
14919: # Copy all files
14920: 	&Apache::lonclonecourse::copycoursefiles($cloneid,$$courseid,$args->{'datemode'},
14921: 	                                         $args->{'dateshift'},$args->{'crscode'});
14922: # Restore URL
14923: 	$cenv{'url'}=$oldcenv{'url'};
14924: # Restore title
14925: 	$cenv{'description'}=$oldcenv{'description'};
14926: # Restore creation date, creator and creation context.
14927:         $cenv{'internal.created'}=$oldcenv{'internal.created'};
14928:         $cenv{'internal.creator'}=$oldcenv{'internal.creator'};
14929:         $cenv{'internal.creationcontext'}=$oldcenv{'internal.creationcontext'};
14930: # Mark as cloned
14931: 	$cenv{'clonedfrom'}=$cloneid;
14932: # Need to clone grading mode
14933:         my %newenv=&Apache::lonnet::get('environment',['grading'],$$crsudom,$$crsunum);
14934:         $cenv{'grading'}=$newenv{'grading'};
14935: # Do not clone these environment entries
14936:         &Apache::lonnet::del('environment',
14937:                   ['default_enrollment_start_date',
14938:                    'default_enrollment_end_date',
14939:                    'question.email',
14940:                    'policy.email',
14941:                    'comment.email',
14942:                    'pch.users.denied',
14943:                    'plc.users.denied',
14944:                    'hidefromcat',
14945:                    'checkforpriv',
14946:                    'categories',
14947:                    'internal.uniquecode'],
14948:                    $$crsudom,$$crsunum);
14949:         if ($args->{'textbook'}) {
14950:             $cenv{'internal.textbook'} = $args->{'textbook'};
14951:         }
14952:     }
14953: 
14954: #
14955: # Set environment (will override cloned, if existing)
14956: #
14957:     my @sections = ();
14958:     my @xlists = ();
14959:     if ($args->{'crstype'}) {
14960:         $cenv{'type'}=$args->{'crstype'};
14961:     }
14962:     if ($args->{'crsid'}) {
14963:         $cenv{'courseid'}=$args->{'crsid'};
14964:     }
14965:     if ($args->{'crscode'}) {
14966:         $cenv{'internal.coursecode'}=$args->{'crscode'};
14967:     }
14968:     if ($args->{'crsquota'} ne '') {
14969:         $cenv{'internal.coursequota'}=$args->{'crsquota'};
14970:     } else {
14971:         $cenv{'internal.coursequota'}=$args->{'crsquota'} = 20;
14972:     }
14973:     if ($args->{'ccuname'}) {
14974:         $cenv{'internal.courseowner'} = $args->{'ccuname'}.
14975:                                         ':'.$args->{'ccdomain'};
14976:     } else {
14977:         $cenv{'internal.courseowner'} = $args->{'curruser'};
14978:     }
14979:     if ($args->{'defaultcredits'}) {
14980:         $cenv{'internal.defaultcredits'} = $args->{'defaultcredits'};
14981:     }
14982:     my @badclasses = (); # Used to accumulate sections/crosslistings that did not pass classlist access check for course owner.
14983:     if ($args->{'crssections'}) {
14984:         $cenv{'internal.sectionnums'} = '';
14985:         if ($args->{'crssections'} =~ m/,/) {
14986:             @sections = split/,/,$args->{'crssections'};
14987:         } else {
14988:             $sections[0] = $args->{'crssections'};
14989:         }
14990:         if (@sections > 0) {
14991:             foreach my $item (@sections) {
14992:                 my ($sec,$gp) = split/:/,$item;
14993:                 my $class = $args->{'crscode'}.$sec;
14994:                 my $addcheck = &Apache::lonnet::auto_new_course($$crsunum,$$crsudom,$class,$cenv{'internal.courseowner'});
14995:                 $cenv{'internal.sectionnums'} .= $item.',';
14996:                 unless ($addcheck eq 'ok') {
14997:                     push(@badclasses,$class);
14998:                 }
14999:             }
15000:             $cenv{'internal.sectionnums'} =~ s/,$//;
15001:         }
15002:     }
15003: # do not hide course coordinator from staff listing, 
15004: # even if privileged
15005:     $cenv{'nothideprivileged'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
15006: # add course coordinator's domain to domains to check for privileged users
15007: # if different to course domain
15008:     if ($$crsudom ne $args->{'ccdomain'}) {
15009:         $cenv{'checkforpriv'} = $args->{'ccdomain'};
15010:     }
15011: # add crosslistings
15012:     if ($args->{'crsxlist'}) {
15013:         $cenv{'internal.crosslistings'}='';
15014:         if ($args->{'crsxlist'} =~ m/,/) {
15015:             @xlists = split/,/,$args->{'crsxlist'};
15016:         } else {
15017:             $xlists[0] = $args->{'crsxlist'};
15018:         }
15019:         if (@xlists > 0) {
15020:             foreach my $item (@xlists) {
15021:                 my ($xl,$gp) = split/:/,$item;
15022:                 my $addcheck =  &Apache::lonnet::auto_new_course($$crsunum,$$crsudom,$xl,$cenv{'internal.courseowner'});
15023:                 $cenv{'internal.crosslistings'} .= $item.',';
15024:                 unless ($addcheck eq 'ok') {
15025:                     push(@badclasses,$xl);
15026:                 }
15027:             }
15028:             $cenv{'internal.crosslistings'} =~ s/,$//;
15029:         }
15030:     }
15031:     if ($args->{'autoadds'}) {
15032:         $cenv{'internal.autoadds'}=$args->{'autoadds'};
15033:     }
15034:     if ($args->{'autodrops'}) {
15035:         $cenv{'internal.autodrops'}=$args->{'autodrops'};
15036:     }
15037: # check for notification of enrollment changes
15038:     my @notified = ();
15039:     if ($args->{'notify_owner'}) {
15040:         if ($args->{'ccuname'} ne '') {
15041:             push(@notified,$args->{'ccuname'}.':'.$args->{'ccdomain'});
15042:         }
15043:     }
15044:     if ($args->{'notify_dc'}) {
15045:         if ($uname ne '') { 
15046:             push(@notified,$uname.':'.$udom);
15047:         }
15048:     }
15049:     if (@notified > 0) {
15050:         my $notifylist;
15051:         if (@notified > 1) {
15052:             $notifylist = join(',',@notified);
15053:         } else {
15054:             $notifylist = $notified[0];
15055:         }
15056:         $cenv{'internal.notifylist'} = $notifylist;
15057:     }
15058:     if (@badclasses > 0) {
15059:         my %lt=&Apache::lonlocal::texthash(
15060:                 'tclb' => 'The courses listed below were included as sections or crosslistings affiliated with your new LON-CAPA course.',
15061:                 'howi' => 'However, if automated course roster updates are enabled for this class, these particular sections/crosslistings are not guaranteed to contribute towards enrollment.',
15062:                 'itis' => 'It is possible that rights to access enrollment for these classes will be available through assignment of co-owners.',
15063:         );
15064:         my $badclass_msg = $lt{'tclb'}.$linefeed.$lt{'howi'}.$linefeed.
15065:                            &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'};
15066:         if ($context eq 'auto') {
15067:             $outcome .= $badclass_msg.$linefeed;
15068:         } else {
15069:             $outcome .= '<div class="LC_warning">'.$badclass_msg.$linefeed.'<ul>'."\n";
15070:         }
15071:         foreach my $item (@badclasses) {
15072:             if ($context eq 'auto') {
15073:                 $outcome .= " - $item\n";
15074:             } else {
15075:                 $outcome .= "<li>$item</li>\n";
15076:             }
15077:         }
15078:         if ($context eq 'auto') {
15079:             $outcome .= $linefeed;
15080:         } else {
15081:             $outcome .= "</ul><br /><br /></div>\n";
15082:         }
15083:     }
15084:     if ($args->{'no_end_date'}) {
15085:         $args->{'endaccess'} = 0;
15086:     }
15087:     $cenv{'internal.autostart'}=$args->{'enrollstart'};
15088:     $cenv{'internal.autoend'}=$args->{'enrollend'};
15089:     $cenv{'default_enrollment_start_date'}=$args->{'startaccess'};
15090:     $cenv{'default_enrollment_end_date'}=$args->{'endaccess'};
15091:     if ($args->{'showphotos'}) {
15092:       $cenv{'internal.showphotos'}=$args->{'showphotos'};
15093:     }
15094:     $cenv{'internal.authtype'} = $args->{'authtype'};
15095:     $cenv{'internal.autharg'} = $args->{'autharg'}; 
15096:     if ( ($cenv{'internal.authtype'} =~ /^krb/) && ($cenv{'internal.autoadds'} == 1)) {
15097:         if (! defined($cenv{'internal.autharg'}) || $cenv{'internal.autharg'}  eq '') {
15098:             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'); 
15099:             if ($context eq 'auto') {
15100:                 $outcome .= $krb_msg;
15101:             } else {
15102:                 $outcome .= '<span class="LC_error">'.$krb_msg.'</span>';
15103:             }
15104:             $outcome .= $linefeed;
15105:         }
15106:     }
15107:     if (($args->{'ccdomain'}) && ($args->{'ccuname'})) {
15108:        if ($args->{'setpolicy'}) {
15109:            $cenv{'policy.email'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
15110:        }
15111:        if ($args->{'setcontent'}) {
15112:            $cenv{'question.email'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
15113:        }
15114:        if ($args->{'setcomment'}) {
15115:            $cenv{'comment.email'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
15116:        }
15117:     }
15118:     if ($args->{'reshome'}) {
15119: 	$cenv{'reshome'}=$args->{'reshome'}.'/';
15120: 	$cenv{'reshome'}=~s/\/+$/\//;
15121:     }
15122: #
15123: # course has keyed access
15124: #
15125:     if ($args->{'setkeys'}) {
15126:        $cenv{'keyaccess'}='yes';
15127:     }
15128: # if specified, key authority is not course, but user
15129: # only active if keyaccess is yes
15130:     if ($args->{'keyauth'}) {
15131: 	my ($user,$domain) = split(':',$args->{'keyauth'});
15132: 	$user = &LONCAPA::clean_username($user);
15133: 	$domain = &LONCAPA::clean_username($domain);
15134: 	if ($user ne '' && $domain ne '') {
15135: 	    $cenv{'keyauth'}=$user.':'.$domain;
15136: 	}
15137:     }
15138: 
15139: #
15140: #  generate and store uniquecode (available to course requester), if course should have one.
15141: #
15142:     if ($args->{'uniquecode'}) {
15143:         my ($code,$error) = &make_unique_code($$crsudom,$$crsunum);
15144:         if ($code) {
15145:             $cenv{'internal.uniquecode'} = $code;
15146:             my %crsinfo =
15147:                 &Apache::lonnet::courseiddump($$crsudom,'.',1,'.','.',$$crsunum,undef,undef,'.');
15148:             if (ref($crsinfo{$$crsudom.'_'.$$crsunum}) eq 'HASH') {
15149:                 $crsinfo{$$crsudom.'_'.$$crsunum}{'uniquecode'} = $code;
15150:                 my $putres = &Apache::lonnet::courseidput($$crsudom,\%crsinfo,$crsuhome,'notime');
15151:             }
15152:             if (ref($coderef)) {
15153:                 $$coderef = $code;
15154:             }
15155:         }
15156:     }
15157: 
15158:     if ($args->{'disresdis'}) {
15159:         $cenv{'pch.roles.denied'}='st';
15160:     }
15161:     if ($args->{'disablechat'}) {
15162:         $cenv{'plc.roles.denied'}='st';
15163:     }
15164: 
15165:     # Record we've not yet viewed the Course Initialization Helper for this 
15166:     # course
15167:     $cenv{'course.helper.not.run'} = 1;
15168:     #
15169:     # Use new Randomseed
15170:     #
15171:     $cenv{'rndseed'}=&Apache::lonnet::latest_rnd_algorithm_id();;
15172:     $cenv{'receiptalg'}=&Apache::lonnet::latest_receipt_algorithm_id();;
15173:     #
15174:     # The encryption code and receipt prefix for this course
15175:     #
15176:     $cenv{'internal.encseed'}=$Apache::lonnet::perlvar{'lonReceipt'}.$$.time.int(rand(9999));
15177:     $cenv{'internal.encpref'}=100+int(9*rand(99));
15178:     #
15179:     # By default, use standard grading
15180:     if (!defined($cenv{'grading'})) { $cenv{'grading'} = 'standard'; }
15181: 
15182:     $outcome .= $linefeed.&mt('Setting environment').': '.                 
15183:           &Apache::lonnet::put('environment',\%cenv,$$crsudom,$$crsunum).$linefeed;
15184: #
15185: # Open all assignments
15186: #
15187:     if ($args->{'openall'}) {
15188:        my $opendate = time;
15189:        if ($args->{'openallfrom'} =~ /^\d+$/) {
15190:            $opendate = $args->{'openallfrom'};
15191:        }
15192:        my $storeunder=$$crsudom.'_'.$$crsunum.'.0.opendate';
15193:        my %storecontent = ($storeunder         => $opendate,
15194:                            $storeunder.'.type' => 'date_start');
15195:        $outcome .= &mt('All assignments open starting [_1]',
15196:                        &Apache::lonlocal::locallocaltime($opendate)).': '.
15197:                    &Apache::lonnet::cput
15198:                        ('resourcedata',\%storecontent,$$crsudom,$$crsunum).$linefeed;
15199:    }
15200: #
15201: # Set first page
15202: #
15203:     unless (($args->{'nonstandard'}) || ($args->{'firstres'} eq 'blank')
15204: 	    || ($cloneid)) {
15205: 	use LONCAPA::map;
15206: 	$outcome .= &mt('Setting first resource').': ';
15207: 
15208: 	my $map = '/uploaded/'.$$crsudom.'/'.$$crsunum.'/default.sequence';
15209:         my ($errtext,$fatal)=&LONCAPA::map::mapread($map);
15210: 
15211:         $outcome .= ($fatal?$errtext:'read ok').' - ';
15212:         my $title; my $url;
15213:         if ($args->{'firstres'} eq 'syl') {
15214: 	    $title=&mt('Syllabus');
15215:             $url='/public/'.$$crsudom.'/'.$$crsunum.'/syllabus';
15216:         } else {
15217:             $title=&mt('Table of Contents');
15218:             $url='/adm/navmaps';
15219:         }
15220: 
15221:         $LONCAPA::map::resources[1]=$title.':'.$url.':false:start:res';
15222: 	(my $outtext,$errtext) = &LONCAPA::map::storemap($map,1);
15223: 
15224: 	if ($errtext) { $fatal=2; }
15225:         $outcome .= ($fatal?$errtext:'write ok').$linefeed;
15226:     }
15227: 
15228:     return (1,$outcome);
15229: }
15230: 
15231: sub make_unique_code {
15232:     my ($cdom,$cnum) = @_;
15233:     # get lock on uniquecodes db
15234:     my $lockhash = {
15235:                       $cnum."\0".'uniquecodes' => $env{'user.name'}.
15236:                                                   ':'.$env{'user.domain'},
15237:                    };
15238:     my $tries = 0;
15239:     my $gotlock = &Apache::lonnet::newput_dom('uniquecodes',$lockhash,$cdom);
15240:     my ($code,$error);
15241: 
15242:     while (($gotlock ne 'ok') && ($tries<3)) {
15243:         $tries ++;
15244:         sleep 1;
15245:         $gotlock = &Apache::lonnet::newput_dom('uniquecodes',$lockhash,$cdom);
15246:     }
15247:     if ($gotlock eq 'ok') {
15248:         my %currcodes = &Apache::lonnet::dump_dom('uniquecodes',$cdom);
15249:         my $gotcode;
15250:         my $attempts = 0;
15251:         while ((!$gotcode) && ($attempts < 100)) {
15252:             $code = &generate_code();
15253:             if (!exists($currcodes{$code})) {
15254:                 $gotcode = 1;
15255:                 unless (&Apache::lonnet::newput_dom('uniquecodes',{ $code => $cnum },$cdom) eq 'ok') {
15256:                     $error = 'nostore';
15257:                 }
15258:             }
15259:             $attempts ++;
15260:         }
15261:         my @del_lock = ($cnum."\0".'uniquecodes');
15262:         my $dellockoutcome = &Apache::lonnet::del_dom('uniquecodes',\@del_lock,$cdom);
15263:     } else {
15264:         $error = 'nolock';
15265:     }
15266:     return ($code,$error);
15267: }
15268: 
15269: sub generate_code {
15270:     my $code;
15271:     my @letts = qw(B C D G H J K M N P Q R S T V W X Z);
15272:     for (my $i=0; $i<6; $i++) {
15273:         my $lettnum = int (rand 2);
15274:         my $item = '';
15275:         if ($lettnum) {
15276:             $item = $letts[int( rand(18) )];
15277:         } else {
15278:             $item = 1+int( rand(8) );
15279:         }
15280:         $code .= $item;
15281:     }
15282:     return $code;
15283: }
15284: 
15285: ############################################################
15286: ############################################################
15287: 
15288: #SD
15289: # only Community and Course, or anything else?
15290: sub course_type {
15291:     my ($cid) = @_;
15292:     if (!defined($cid)) {
15293:         $cid = $env{'request.course.id'};
15294:     }
15295:     if (defined($env{'course.'.$cid.'.type'})) {
15296:         return $env{'course.'.$cid.'.type'};
15297:     } else {
15298:         return 'Course';
15299:     }
15300: }
15301: 
15302: sub group_term {
15303:     my $crstype = &course_type();
15304:     my %names = (
15305:                   'Course' => 'group',
15306:                   'Community' => 'group',
15307:                 );
15308:     return $names{$crstype};
15309: }
15310: 
15311: sub course_types {
15312:     my @types = ('official','unofficial','community','textbook');
15313:     my %typename = (
15314:                          official   => 'Official course',
15315:                          unofficial => 'Unofficial course',
15316:                          community  => 'Community',
15317:                          textbook   => 'Textbook course',
15318:                    );
15319:     return (\@types,\%typename);
15320: }
15321: 
15322: sub icon {
15323:     my ($file)=@_;
15324:     my $curfext = lc((split(/\./,$file))[-1]);
15325:     my $iconname=$Apache::lonnet::perlvar{'lonIconsURL'}.'/unknown.gif';
15326:     my $embstyle = &Apache::loncommon::fileembstyle($curfext);
15327:     if (!(!defined($embstyle) || $embstyle eq 'unk' || $embstyle eq 'hdn')) {
15328: 	if (-e  $Apache::lonnet::perlvar{'lonDocRoot'}.'/'.
15329: 	          $Apache::lonnet::perlvar{'lonIconsURL'}.'/'.
15330: 	            $curfext.".gif") {
15331: 	    $iconname=$Apache::lonnet::perlvar{'lonIconsURL'}.'/'.
15332: 		$curfext.".gif";
15333: 	}
15334:     }
15335:     return &lonhttpdurl($iconname);
15336: } 
15337: 
15338: sub lonhttpdurl {
15339: #
15340: # Had been used for "small fry" static images on separate port 8080.
15341: # Modify here if lightweight http functionality desired again.
15342: # Currently eliminated due to increasing firewall issues.
15343: #
15344:     my ($url)=@_;
15345:     return $url;
15346: }
15347: 
15348: sub connection_aborted {
15349:     my ($r)=@_;
15350:     $r->print(" ");$r->rflush();
15351:     my $c = $r->connection;
15352:     return $c->aborted();
15353: }
15354: 
15355: #    Escapes strings that may have embedded 's that will be put into
15356: #    strings as 'strings'.
15357: sub escape_single {
15358:     my ($input) = @_;
15359:     $input =~ s/\\/\\\\/g;	# Escape the \'s..(must be first)>
15360:     $input =~ s/\'/\\\'/g;	# Esacpe the 's....
15361:     return $input;
15362: }
15363: 
15364: #  Same as escape_single, but escape's "'s  This 
15365: #  can be used for  "strings"
15366: sub escape_double {
15367:     my ($input) = @_;
15368:     $input =~ s/\\/\\\\/g;	# Escape the /'s..(must be first)>
15369:     $input =~ s/\"/\\\"/g;	# Esacpe the "s....
15370:     return $input;
15371: }
15372:  
15373: #   Escapes the last element of a full URL.
15374: sub escape_url {
15375:     my ($url)   = @_;
15376:     my @urlslices = split(/\//, $url,-1);
15377:     my $lastitem = &escape(pop(@urlslices));
15378:     return &HTML::Entities::encode(join('/',@urlslices),"'").'/'.$lastitem;
15379: }
15380: 
15381: sub compare_arrays {
15382:     my ($arrayref1,$arrayref2) = @_;
15383:     my (@difference,%count);
15384:     @difference = ();
15385:     %count = ();
15386:     if ((ref($arrayref1) eq 'ARRAY') && (ref($arrayref2) eq 'ARRAY')) {
15387:         foreach my $element (@{$arrayref1}, @{$arrayref2}) { $count{$element}++; }
15388:         foreach my $element (keys(%count)) {
15389:             if ($count{$element} == 1) {
15390:                 push(@difference,$element);
15391:             }
15392:         }
15393:     }
15394:     return @difference;
15395: }
15396: 
15397: # -------------------------------------------------------- Initialize user login
15398: sub init_user_environment {
15399:     my ($r, $username, $domain, $authhost, $form, $args) = @_;
15400:     my $lonids=$Apache::lonnet::perlvar{'lonIDsDir'};
15401: 
15402:     my $public=($username eq 'public' && $domain eq 'public');
15403: 
15404: # See if old ID present, if so, remove
15405: 
15406:     my ($filename,$cookie,$userroles,$firstaccenv,$timerintenv);
15407:     my $now=time;
15408: 
15409:     if ($public) {
15410: 	my $max_public=100;
15411: 	my $oldest;
15412: 	my $oldest_time=0;
15413: 	for(my $next=1;$next<=$max_public;$next++) {
15414: 	    if (-e $lonids."/publicuser_$next.id") {
15415: 		my $mtime=(stat($lonids."/publicuser_$next.id"))[9];
15416: 		if ($mtime<$oldest_time || !$oldest_time) {
15417: 		    $oldest_time=$mtime;
15418: 		    $oldest=$next;
15419: 		}
15420: 	    } else {
15421: 		$cookie="publicuser_$next";
15422: 		last;
15423: 	    }
15424: 	}
15425: 	if (!$cookie) { $cookie="publicuser_$oldest"; }
15426:     } else {
15427: 	# if this isn't a robot, kill any existing non-robot sessions
15428: 	if (!$args->{'robot'}) {
15429: 	    opendir(DIR,$lonids);
15430: 	    while ($filename=readdir(DIR)) {
15431: 		if ($filename=~/^$username\_\d+\_$domain\_$authhost\.id$/) {
15432: 		    unlink($lonids.'/'.$filename);
15433: 		}
15434: 	    }
15435: 	    closedir(DIR);
15436: # If there is a undeleted lockfile for the user's paste buffer remove it.
15437:             my $namespace = 'nohist_courseeditor';
15438:             my $lockingkey = 'paste'."\0".'locked_num';
15439:             my %lockhash = &Apache::lonnet::get($namespace,[$lockingkey],
15440:                                                 $domain,$username);
15441:             if (exists($lockhash{$lockingkey})) {
15442:                 my $delresult = &Apache::lonnet::del($namespace,[$lockingkey],$domain,$username);
15443:                 unless ($delresult eq 'ok') {
15444:                     &Apache::lonnet::logthis("Failed to delete paste buffer locking key in $namespace for ".$username.":".$domain." Result was: $delresult");
15445:                 }
15446:             }
15447: 	}
15448: # Give them a new cookie
15449: 	my $id = ($args->{'robot'} ? 'robot'.$args->{'robot'}
15450: 		                   : $now.$$.int(rand(10000)));
15451: 	$cookie="$username\_$id\_$domain\_$authhost";
15452:     
15453: # Initialize roles
15454: 
15455: 	($userroles,$firstaccenv,$timerintenv) = 
15456:             &Apache::lonnet::rolesinit($domain,$username,$authhost);
15457:     }
15458: # ------------------------------------ Check browser type and MathML capability
15459: 
15460:     my ($httpbrowser,$clientbrowser,$clientversion,$clientmathml,$clientunicode,
15461:         $clientos,$clientmobile,$clientinfo,$clientosversion) = &decode_user_agent($r);
15462: 
15463: # ------------------------------------------------------------- Get environment
15464: 
15465:     my %userenv = &Apache::lonnet::dump('environment',$domain,$username);
15466:     my ($tmp) = keys(%userenv);
15467:     if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
15468:     } else {
15469: 	undef(%userenv);
15470:     }
15471:     if (($userenv{'interface'}) && (!$form->{'interface'})) {
15472: 	$form->{'interface'}=$userenv{'interface'};
15473:     }
15474:     if ($userenv{'texengine'} eq 'ttm') { $clientmathml=1; }
15475: 
15476: # --------------- Do not trust query string to be put directly into environment
15477:     foreach my $option ('interface','localpath','localres') {
15478:         $form->{$option}=~s/[\n\r\=]//gs;
15479:     }
15480: # --------------------------------------------------------- Write first profile
15481: 
15482:     {
15483: 	my %initial_env = 
15484: 	    ("user.name"          => $username,
15485: 	     "user.domain"        => $domain,
15486: 	     "user.home"          => $authhost,
15487: 	     "browser.type"       => $clientbrowser,
15488: 	     "browser.version"    => $clientversion,
15489: 	     "browser.mathml"     => $clientmathml,
15490: 	     "browser.unicode"    => $clientunicode,
15491: 	     "browser.os"         => $clientos,
15492:              "browser.mobile"     => $clientmobile,
15493:              "browser.info"       => $clientinfo,
15494:              "browser.osversion"  => $clientosversion,
15495: 	     "server.domain"      => $Apache::lonnet::perlvar{'lonDefDomain'},
15496: 	     "request.course.fn"  => '',
15497: 	     "request.course.uri" => '',
15498: 	     "request.course.sec" => '',
15499: 	     "request.role"       => 'cm',
15500: 	     "request.role.adv"   => $env{'user.adv'},
15501: 	     "request.host"       => $ENV{'REMOTE_ADDR'},);
15502: 
15503:         if ($form->{'localpath'}) {
15504: 	    $initial_env{"browser.localpath"}  = $form->{'localpath'};
15505: 	    $initial_env{"browser.localres"}   = $form->{'localres'};
15506:         }
15507: 	
15508: 	if ($form->{'interface'}) {
15509: 	    $form->{'interface'}=~s/\W//gs;
15510: 	    $initial_env{"browser.interface"} = $form->{'interface'};
15511: 	    $env{'browser.interface'}=$form->{'interface'};
15512: 	}
15513: 
15514:         if ($form->{'iptoken'}) {
15515:             my $lonhost = $r->dir_config('lonHostID');
15516:             $initial_env{"user.noloadbalance"} = $lonhost;
15517:             $env{'user.noloadbalance'} = $lonhost;
15518:         }
15519: 
15520:         if ($form->{'noloadbalance'}) {
15521:             my @hosts = &Apache::lonnet::current_machine_ids();
15522:             my $hosthere = $form->{'noloadbalance'};
15523:             if (grep(/^\Q$hosthere\E$/,@hosts)) {
15524:                 $initial_env{"user.noloadbalance"} = $hosthere;
15525:                 $env{'user.noloadbalance'} = $hosthere;
15526:             }
15527:         }
15528: 
15529:         unless ($domain eq 'public') {
15530:             my %is_adv = ( is_adv => $env{'user.adv'} );
15531:             my %domdef = &Apache::lonnet::get_domain_defaults($domain);
15532: 
15533:             foreach my $tool ('aboutme','blog','webdav','portfolio') {
15534:                 $userenv{'availabletools.'.$tool} = 
15535:                     &Apache::lonnet::usertools_access($username,$domain,$tool,'reload',
15536:                                                       undef,\%userenv,\%domdef,\%is_adv);
15537:             }
15538: 
15539:             foreach my $crstype ('official','unofficial','community','textbook') {
15540:                 $userenv{'canrequest.'.$crstype} =
15541:                     &Apache::lonnet::usertools_access($username,$domain,$crstype,
15542:                                                       'reload','requestcourses',
15543:                                                       \%userenv,\%domdef,\%is_adv);
15544:             }
15545: 
15546:             $userenv{'canrequest.author'} =
15547:                 &Apache::lonnet::usertools_access($username,$domain,'requestauthor',
15548:                                                   'reload','requestauthor',
15549:                                                   \%userenv,\%domdef,\%is_adv);
15550:             my %reqauthor = &Apache::lonnet::get('requestauthor',['author_status','author'],
15551:                                                  $domain,$username);
15552:             my $reqstatus = $reqauthor{'author_status'};
15553:             if ($reqstatus eq 'approval' || $reqstatus eq 'approved') {
15554:                 if (ref($reqauthor{'author'}) eq 'HASH') {
15555:                     $userenv{'requestauthorqueued'} = $reqstatus.':'.
15556:                                                       $reqauthor{'author'}{'timestamp'};
15557:                 }
15558:             }
15559:         }
15560: 
15561: 	$env{'user.environment'} = "$lonids/$cookie.id";
15562: 
15563: 	if (tie(my %disk_env,'GDBM_File',"$lonids/$cookie.id",
15564: 		 &GDBM_WRCREAT(),0640)) {
15565: 	    &_add_to_env(\%disk_env,\%initial_env);
15566: 	    &_add_to_env(\%disk_env,\%userenv,'environment.');
15567: 	    &_add_to_env(\%disk_env,$userroles);
15568:             if (ref($firstaccenv) eq 'HASH') {
15569:                 &_add_to_env(\%disk_env,$firstaccenv);
15570:             }
15571:             if (ref($timerintenv) eq 'HASH') {
15572:                 &_add_to_env(\%disk_env,$timerintenv);
15573:             }
15574: 	    if (ref($args->{'extra_env'})) {
15575: 		&_add_to_env(\%disk_env,$args->{'extra_env'});
15576: 	    }
15577: 	    untie(%disk_env);
15578: 	} else {
15579: 	    &Apache::lonnet::logthis("<span style=\"color:blue;\">WARNING: ".
15580: 			   'Could not create environment storage in lonauth: '.$!.'</span>');
15581: 	    return 'error: '.$!;
15582: 	}
15583:     }
15584:     $env{'request.role'}='cm';
15585:     $env{'request.role.adv'}=$env{'user.adv'};
15586:     $env{'browser.type'}=$clientbrowser;
15587: 
15588:     return $cookie;
15589: 
15590: }
15591: 
15592: sub _add_to_env {
15593:     my ($idf,$env_data,$prefix) = @_;
15594:     if (ref($env_data) eq 'HASH') {
15595:         while (my ($key,$value) = each(%$env_data)) {
15596: 	    $idf->{$prefix.$key} = $value;
15597: 	    $env{$prefix.$key}   = $value;
15598:         }
15599:     }
15600: }
15601: 
15602: # --- Get the symbolic name of a problem and the url
15603: sub get_symb {
15604:     my ($request,$silent) = @_;
15605:     (my $url=$env{'form.url'}) =~ s-^https?\://($ENV{'SERVER_NAME'}|$ENV{'HTTP_HOST'})--;
15606:     my $symb=($env{'form.symb'} ne '' ? $env{'form.symb'} : (&Apache::lonnet::symbread($url)));
15607:     if ($symb eq '') {
15608:         if (!$silent) {
15609:             if (ref($request)) { 
15610:                 $request->print("Unable to handle ambiguous references:$url:.");
15611:             }
15612:             return ();
15613:         }
15614:     }
15615:     &Apache::lonenc::check_decrypt(\$symb);
15616:     return ($symb);
15617: }
15618: 
15619: # --------------------------------------------------------------Get annotation
15620: 
15621: sub get_annotation {
15622:     my ($symb,$enc) = @_;
15623: 
15624:     my $key = $symb;
15625:     if (!$enc) {
15626:         $key =
15627:             &Apache::lonnet::clutter((&Apache::lonnet::decode_symb($symb))[2]);
15628:     }
15629:     my %annotation=&Apache::lonnet::get('nohist_annotations',[$key]);
15630:     return $annotation{$key};
15631: }
15632: 
15633: sub clean_symb {
15634:     my ($symb,$delete_enc) = @_;
15635: 
15636:     &Apache::lonenc::check_decrypt(\$symb);
15637:     my $enc = $env{'request.enc'};
15638:     if ($delete_enc) {
15639:         delete($env{'request.enc'});
15640:     }
15641: 
15642:     return ($symb,$enc);
15643: }
15644: 
15645: ############################################################
15646: ############################################################
15647: 
15648: =pod
15649: 
15650: =head1 Routines for building display used to search for courses
15651: 
15652: 
15653: =over 4
15654: 
15655: =item * &build_filters()
15656: 
15657: Create markup for a table used to set filters to use when selecting
15658: courses in a domain.  Used by lonpickcourse.pm, lonmodifycourse.pm
15659: and quotacheck.pl
15660: 
15661: 
15662: Inputs:
15663: 
15664: filterlist - anonymous array of fields to include as potential filters
15665: 
15666: crstype - course type
15667: 
15668: roleelement - fifth arg in selectcourse_link() populates fifth arg in javascript: opencrsbrowser() function, used
15669:               to pop-open a course selector (will contain "extra element").
15670: 
15671: multelement - if multiple course selections will be allowed, this will be a hidden form element: name: multiple; value: 1
15672: 
15673: filter - anonymous hash of criteria and their values
15674: 
15675: action - form action
15676: 
15677: numfiltersref - ref to scalar (count of number of elements in institutional codes -- e.g., 4 for year, semester, department, and number)
15678: 
15679: caller - caller context (e.g., set to 'modifycourse' when routine is called from lonmodifycourse.pm)
15680: 
15681: cloneruname - username of owner of new course who wants to clone
15682: 
15683: clonerudom - domain of owner of new course who wants to clone
15684: 
15685: typeelem - text to use for left column in row containing course type (i.e., Course, Community or Course/Community)
15686: 
15687: codetitlesref - reference to array of titles of components in institutional codes (official courses)
15688: 
15689: codedom - domain
15690: 
15691: formname - value of form element named "form".
15692: 
15693: fixeddom - domain, if fixed.
15694: 
15695: prevphase - value to assign to form element named "phase" when going back to the previous screen
15696: 
15697: cnameelement - name of form element in form on opener page which will receive title of selected course
15698: 
15699: cnumelement - name of form element in form on opener page which will receive courseID  of selected course
15700: 
15701: cdomelement - name of form element in form on opener page which will receive domain of selected course
15702: 
15703: setroles - includes access constraint identifier when setting a roles-based condition for acces to a portfolio file
15704: 
15705: clonetext - hidden form elements containing list of courses cloneable by intended course owner when DC creates a course
15706: 
15707: clonewarning - warning message about missing information for intended course owner when DC creates a course
15708: 
15709: 
15710: Returns: $output - HTML for display of search criteria, and hidden form elements.
15711: 
15712: 
15713: Side Effects: None
15714: 
15715: =cut
15716: 
15717: # ---------------------------------------------- search for courses based on last activity etc.
15718: 
15719: sub build_filters {
15720:     my ($filterlist,$crstype,$roleelement,$multelement,$filter,$action,
15721:         $numtitlesref,$caller,$cloneruname,$clonerudom,$typeelement,
15722:         $codetitlesref,$codedom,$formname,$fixeddom,$prevphase,
15723:         $cnameelement,$cnumelement,$cdomelement,$setroles,
15724:         $clonetext,$clonewarning) = @_;
15725:     my ($list,$jscript);
15726:     my $onchange = 'javascript:updateFilters(this)';
15727:     my ($domainselectform,$sincefilterform,$createdfilterform,
15728:         $ownerdomselectform,$persondomselectform,$instcodeform,
15729:         $typeselectform,$instcodetitle);
15730:     if ($formname eq '') {
15731:         $formname = $caller;
15732:     }
15733:     foreach my $item (@{$filterlist}) {
15734:         unless (($item eq 'descriptfilter') || ($item eq 'instcodefilter') ||
15735:                 ($item eq 'sincefilter') || ($item eq 'createdfilter')) {
15736:             if ($item eq 'domainfilter') {
15737:                 $filter->{$item} = &LONCAPA::clean_domain($filter->{$item});
15738:             } elsif ($item eq 'coursefilter') {
15739:                 $filter->{$item} = &LONCAPA::clean_courseid($filter->{$item});
15740:             } elsif ($item eq 'ownerfilter') {
15741:                 $filter->{$item} = &LONCAPA::clean_username($filter->{$item});
15742:             } elsif ($item eq 'ownerdomfilter') {
15743:                 $filter->{'ownerdomfilter'} =
15744:                     &LONCAPA::clean_domain($filter->{$item});
15745:                 $ownerdomselectform = &select_dom_form($filter->{'ownerdomfilter'},
15746:                                                        'ownerdomfilter',1);
15747:             } elsif ($item eq 'personfilter') {
15748:                 $filter->{$item} = &LONCAPA::clean_username($filter->{$item});
15749:             } elsif ($item eq 'persondomfilter') {
15750:                 $persondomselectform = &select_dom_form($filter->{'persondomfilter'},
15751:                                                         'persondomfilter',1);
15752:             } else {
15753:                 $filter->{$item} =~ s/\W//g;
15754:             }
15755:             if (!$filter->{$item}) {
15756:                 $filter->{$item} = '';
15757:             }
15758:         }
15759:         if ($item eq 'domainfilter') {
15760:             my $allow_blank = 1;
15761:             if ($formname eq 'portform') {
15762:                 $allow_blank=0;
15763:             } elsif ($formname eq 'studentform') {
15764:                 $allow_blank=0;
15765:             }
15766:             if ($fixeddom) {
15767:                 $domainselectform = '<input type="hidden" name="domainfilter"'.
15768:                                     ' value="'.$codedom.'" />'.
15769:                                     &Apache::lonnet::domain($codedom,'description');
15770:             } else {
15771:                 $domainselectform = &select_dom_form($filter->{$item},
15772:                                                      'domainfilter',
15773:                                                       $allow_blank,'',$onchange);
15774:             }
15775:         } else {
15776:             $list->{$item} = &HTML::Entities::encode($filter->{$item},'<>&"');
15777:         }
15778:     }
15779: 
15780:     # last course activity filter and selection
15781:     $sincefilterform = &timebased_select_form('sincefilter',$filter);
15782: 
15783:     # course created filter and selection
15784:     if (exists($filter->{'createdfilter'})) {
15785:         $createdfilterform = &timebased_select_form('createdfilter',$filter);
15786:     }
15787: 
15788:     my %lt = &Apache::lonlocal::texthash(
15789:                 'cac' => "$crstype Activity",
15790:                 'ccr' => "$crstype Created",
15791:                 'cde' => "$crstype Title",
15792:                 'cdo' => "$crstype Domain",
15793:                 'ins' => 'Institutional Code',
15794:                 'inc' => 'Institutional Categorization',
15795:                 'cow' => "$crstype Owner/Co-owner",
15796:                 'cop' => "$crstype Personnel Includes",
15797:                 'cog' => 'Type',
15798:              );
15799: 
15800:     if (($formname eq 'ccrs') || ($formname eq 'requestcrs')) {
15801:         my $typeval = 'Course';
15802:         if ($crstype eq 'Community') {
15803:             $typeval = 'Community';
15804:         }
15805:         $typeselectform = '<input type="hidden" name="type" value="'.$typeval.'" />';
15806:     } else {
15807:         $typeselectform =  '<select name="type" size="1"';
15808:         if ($onchange) {
15809:             $typeselectform .= ' onchange="'.$onchange.'"';
15810:         }
15811:         $typeselectform .= '>'."\n";
15812:         foreach my $posstype ('Course','Community') {
15813:             $typeselectform.='<option value="'.$posstype.'"'.
15814:                 ($posstype eq $crstype ? ' selected="selected" ' : ''). ">".&mt($posstype)."</option>\n";
15815:         }
15816:         $typeselectform.="</select>";
15817:     }
15818: 
15819:     my ($cloneableonlyform,$cloneabletitle);
15820:     if (exists($filter->{'cloneableonly'})) {
15821:         my $cloneableon = '';
15822:         my $cloneableoff = ' checked="checked"';
15823:         if ($filter->{'cloneableonly'}) {
15824:             $cloneableon = $cloneableoff;
15825:             $cloneableoff = '';
15826:         }
15827:         $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>';
15828:         if ($formname eq 'ccrs') {
15829:             $cloneabletitle = &mt('Cloneable for [_1]',$cloneruname.':'.$clonerudom);
15830:         } else {
15831:             $cloneabletitle = &mt('Cloneable by you');
15832:         }
15833:     }
15834:     my $officialjs;
15835:     if ($crstype eq 'Course') {
15836:         if (exists($filter->{'instcodefilter'})) {
15837: #            if (($fixeddom) || ($formname eq 'requestcrs') ||
15838: #                ($formname eq 'modifycourse') || ($formname eq 'filterpicker')) {
15839:             if ($codedom) {
15840:                 $officialjs = 1;
15841:                 ($instcodeform,$jscript,$$numtitlesref) =
15842:                     &Apache::courseclassifier::instcode_selectors($codedom,'filterpicker',
15843:                                                                   $officialjs,$codetitlesref);
15844:                 if ($jscript) {
15845:                     $jscript = '<script type="text/javascript">'."\n".
15846:                                '// <![CDATA['."\n".
15847:                                $jscript."\n".
15848:                                '// ]]>'."\n".
15849:                                '</script>'."\n";
15850:                 }
15851:             }
15852:             if ($instcodeform eq '') {
15853:                 $instcodeform =
15854:                     '<input type="text" name="instcodefilter" size="10" value="'.
15855:                     $list->{'instcodefilter'}.'" />';
15856:                 $instcodetitle = $lt{'ins'};
15857:             } else {
15858:                 $instcodetitle = $lt{'inc'};
15859:             }
15860:             if ($fixeddom) {
15861:                 $instcodetitle .= '<br />('.$codedom.')';
15862:             }
15863:         }
15864:     }
15865:     my $output = qq|
15866: <form method="post" name="filterpicker" action="$action">
15867: <input type="hidden" name="form" value="$formname" />
15868: |;
15869:     if ($formname eq 'modifycourse') {
15870:         $output .= '<input type="hidden" name="phase" value="courselist" />'."\n".
15871:                    '<input type="hidden" name="prevphase" value="'.
15872:                    $prevphase.'" />'."\n";
15873:     } elsif ($formname eq 'quotacheck') {
15874:         $output .= qq|
15875: <input type="hidden" name="sortby" value="" />
15876: <input type="hidden" name="sortorder" value="" />
15877: |;
15878:     } else {
15879:         my $name_input;
15880:         if ($cnameelement ne '') {
15881:             $name_input = '<input type="hidden" name="cnameelement" value="'.
15882:                           $cnameelement.'" />';
15883:         }
15884:         $output .= qq|
15885: <input type="hidden" name="cnumelement" value="$cnumelement" />
15886: <input type="hidden" name="cdomelement" value="$cdomelement" />
15887: $name_input
15888: $roleelement
15889: $multelement
15890: $typeelement
15891: |;
15892:         if ($formname eq 'portform') {
15893:             $output .= '<input type="hidden" name="setroles" value="'.$setroles.'" />'."\n";
15894:         }
15895:     }
15896:     if ($fixeddom) {
15897:         $output .= '<input type="hidden" name="fixeddom" value="'.$fixeddom.'" />'."\n";
15898:     }
15899:     $output .= "<br />\n".&Apache::lonhtmlcommon::start_pick_box();
15900:     if ($sincefilterform) {
15901:         $output .= &Apache::lonhtmlcommon::row_title($lt{'cac'})
15902:                   .$sincefilterform
15903:                   .&Apache::lonhtmlcommon::row_closure();
15904:     }
15905:     if ($createdfilterform) {
15906:         $output .= &Apache::lonhtmlcommon::row_title($lt{'ccr'})
15907:                   .$createdfilterform
15908:                   .&Apache::lonhtmlcommon::row_closure();
15909:     }
15910:     if ($domainselectform) {
15911:         $output .= &Apache::lonhtmlcommon::row_title($lt{'cdo'})
15912:                   .$domainselectform
15913:                   .&Apache::lonhtmlcommon::row_closure();
15914:     }
15915:     if ($typeselectform) {
15916:         if (($formname eq 'ccrs') || ($formname eq 'requestcrs')) {
15917:             $output .= $typeselectform;
15918:         } else {
15919:             $output .= &Apache::lonhtmlcommon::row_title($lt{'cog'})
15920:                       .$typeselectform
15921:                       .&Apache::lonhtmlcommon::row_closure();
15922:         }
15923:     }
15924:     if ($instcodeform) {
15925:         $output .= &Apache::lonhtmlcommon::row_title($instcodetitle)
15926:                   .$instcodeform
15927:                   .&Apache::lonhtmlcommon::row_closure();
15928:     }
15929:     if (exists($filter->{'ownerfilter'})) {
15930:         $output .= &Apache::lonhtmlcommon::row_title($lt{'cow'}).
15931:                    '<table><tr><td>'.&mt('Username').'<br />'.
15932:                    '<input type="text" name="ownerfilter" size="20" value="'.
15933:                    $list->{'ownerfilter'}.'" /></td><td>'.&mt('Domain').'<br />'.
15934:                    $ownerdomselectform.'</td></tr></table>'.
15935:                    &Apache::lonhtmlcommon::row_closure();
15936:     }
15937:     if (exists($filter->{'personfilter'})) {
15938:         $output .= &Apache::lonhtmlcommon::row_title($lt{'cop'}).
15939:                    '<table><tr><td>'.&mt('Username').'<br />'.
15940:                    '<input type="text" name="personfilter" size="20" value="'.
15941:                    $list->{'personfilter'}.'" /></td><td>'.&mt('Domain').'<br />'.
15942:                    $persondomselectform.'</td></tr></table>'.
15943:                    &Apache::lonhtmlcommon::row_closure();
15944:     }
15945:     if (exists($filter->{'coursefilter'})) {
15946:         $output .= &Apache::lonhtmlcommon::row_title(&mt('LON-CAPA course ID'))
15947:                   .'<input type="text" name="coursefilter" size="25" value="'
15948:                   .$list->{'coursefilter'}.'" />'
15949:                   .&Apache::lonhtmlcommon::row_closure();
15950:     }
15951:     if ($cloneableonlyform) {
15952:         $output .= &Apache::lonhtmlcommon::row_title($cloneabletitle).
15953:                    $cloneableonlyform.&Apache::lonhtmlcommon::row_closure();
15954:     }
15955:     if (exists($filter->{'descriptfilter'})) {
15956:         $output .= &Apache::lonhtmlcommon::row_title($lt{'cde'})
15957:                   .'<input type="text" name="descriptfilter" size="40" value="'
15958:                   .$list->{'descriptfilter'}.'" />'
15959:                   .&Apache::lonhtmlcommon::row_closure(1);
15960:     }
15961:     $output .= &Apache::lonhtmlcommon::end_pick_box().'<p>'.$clonetext."\n".
15962:                '<input type="hidden" name="updater" value="" />'."\n".
15963:                '<input type="submit" name="gosearch" value="'.
15964:                &mt('Search').'" /></p>'."\n".'</form>'."\n".'<hr />'."\n";
15965:     return $jscript.$clonewarning.$output;
15966: }
15967: 
15968: =pod
15969: 
15970: =item * &timebased_select_form()
15971: 
15972: Create markup for a dropdown list used to select a time-based
15973: filter e.g., Course Activity, Course Created, when searching for courses
15974: or communities
15975: 
15976: Inputs:
15977: 
15978: item - name of form element (sincefilter or createdfilter)
15979: 
15980: filter - anonymous hash of criteria and their values
15981: 
15982: Returns: HTML for a select box contained a blank, then six time selections,
15983:          with value set in incoming form variables currently selected.
15984: 
15985: Side Effects: None
15986: 
15987: =cut
15988: 
15989: sub timebased_select_form {
15990:     my ($item,$filter) = @_;
15991:     if (ref($filter) eq 'HASH') {
15992:         $filter->{$item} =~ s/[^\d-]//g;
15993:         if (!$filter->{$item}) { $filter->{$item}=-1; }
15994:         return &select_form(
15995:                             $filter->{$item},
15996:                             $item,
15997:                             {      '-1' => '',
15998:                                 '86400' => &mt('today'),
15999:                                '604800' => &mt('last week'),
16000:                               '2592000' => &mt('last month'),
16001:                               '7776000' => &mt('last three months'),
16002:                              '15552000' => &mt('last six months'),
16003:                              '31104000' => &mt('last year'),
16004:                     'select_form_order' =>
16005:                            ['-1','86400','604800','2592000','7776000',
16006:                             '15552000','31104000']});
16007:     }
16008: }
16009: 
16010: =pod
16011: 
16012: =item * &js_changer()
16013: 
16014: Create script tag containing Javascript used to submit course search form
16015: when course type or domain is changed, and also to hide 'Searching ...' on
16016: page load completion for page showing search result.
16017: 
16018: Inputs: None
16019: 
16020: Returns: markup containing updateFilters() and hideSearching() javascript functions.
16021: 
16022: Side Effects: None
16023: 
16024: =cut
16025: 
16026: sub js_changer {
16027:     return <<ENDJS;
16028: <script type="text/javascript">
16029: // <![CDATA[
16030: function updateFilters(caller) {
16031:     if (typeof(caller) != "undefined") {
16032:         document.filterpicker.updater.value = caller.name;
16033:     }
16034:     document.filterpicker.submit();
16035: }
16036: 
16037: function hideSearching() {
16038:     if (document.getElementById('searching')) {
16039:         document.getElementById('searching').style.display = 'none';
16040:     }
16041:     return;
16042: }
16043: 
16044: // ]]>
16045: </script>
16046: 
16047: ENDJS
16048: }
16049: 
16050: =pod
16051: 
16052: =item * &search_courses()
16053: 
16054: Process selected filters form course search form and pass to lonnet::courseiddump
16055: to retrieve a hash for which keys are courseIDs which match the selected filters.
16056: 
16057: Inputs:
16058: 
16059: dom - domain being searched
16060: 
16061: type - course type ('Course' or 'Community' or '.' if any).
16062: 
16063: filter - anonymous hash of criteria and their values
16064: 
16065: numtitles - for institutional codes - number of categories
16066: 
16067: cloneruname - optional username of new course owner
16068: 
16069: clonerudom - optional domain of new course owner
16070: 
16071: domcloner - optional "domcloner" flag; has value=1 if user has ccc priv in domain being filtered by,
16072:             (used when DC is using course creation form)
16073: 
16074: codetitles - reference to array of titles of components in institutional codes (official courses).
16075: 
16076: cc_clone - escaped comma separated list of courses for which course cloner has active CC role
16077:            (and so can clone automatically)
16078: 
16079: reqcrsdom - domain of new course, where search_courses is used to identify potential courses to clone
16080: 
16081: reqinstcode - institutional code of new course, where search_courses is used to identify potential
16082:               courses to clone
16083: 
16084: Returns: %courses - hash of courses satisfying search criteria, keys = course IDs, values are corresponding colon-separated escaped description, institutional code, owner and type.
16085: 
16086: 
16087: Side Effects: None
16088: 
16089: =cut
16090: 
16091: 
16092: sub search_courses {
16093:     my ($dom,$type,$filter,$numtitles,$cloneruname,$clonerudom,$domcloner,$codetitles,
16094:         $cc_clone,$reqcrsdom,$reqinstcode) = @_;
16095:     my (%courses,%showcourses,$cloner);
16096:     if (($filter->{'ownerfilter'} ne '') ||
16097:         ($filter->{'ownerdomfilter'} ne '')) {
16098:         $filter->{'combownerfilter'} = $filter->{'ownerfilter'}.':'.
16099:                                        $filter->{'ownerdomfilter'};
16100:     }
16101:     foreach my $item ('descriptfilter','coursefilter','combownerfilter') {
16102:         if (!$filter->{$item}) {
16103:             $filter->{$item}='.';
16104:         }
16105:     }
16106:     my $now = time;
16107:     my $timefilter =
16108:        ($filter->{'sincefilter'}==-1?1:$now-$filter->{'sincefilter'});
16109:     my ($createdbefore,$createdafter);
16110:     if (($filter->{'createdfilter'} ne '') && ($filter->{'createdfilter'} !=-1)) {
16111:         $createdbefore = $now;
16112:         $createdafter = $now-$filter->{'createdfilter'};
16113:     }
16114:     my ($instcodefilter,$regexpok);
16115:     if ($numtitles) {
16116:         if ($env{'form.official'} eq 'on') {
16117:             $instcodefilter =
16118:                 &Apache::courseclassifier::instcode_search_str($dom,$numtitles,$codetitles);
16119:             $regexpok = 1;
16120:         } elsif ($env{'form.official'} eq 'off') {
16121:             $instcodefilter = &Apache::courseclassifier::instcode_search_str($dom,$numtitles,$codetitles);
16122:             unless ($instcodefilter eq '') {
16123:                 $regexpok = -1;
16124:             }
16125:         }
16126:     } else {
16127:         $instcodefilter = $filter->{'instcodefilter'};
16128:     }
16129:     if ($instcodefilter eq '') { $instcodefilter = '.'; }
16130:     if ($type eq '') { $type = '.'; }
16131: 
16132:     if (($clonerudom ne '') && ($cloneruname ne '')) {
16133:         $cloner = $cloneruname.':'.$clonerudom;
16134:     }
16135:     %courses = &Apache::lonnet::courseiddump($dom,
16136:                                              $filter->{'descriptfilter'},
16137:                                              $timefilter,
16138:                                              $instcodefilter,
16139:                                              $filter->{'combownerfilter'},
16140:                                              $filter->{'coursefilter'},
16141:                                              undef,undef,$type,$regexpok,undef,undef,
16142:                                              undef,undef,$cloner,$cc_clone,
16143:                                              $filter->{'cloneableonly'},
16144:                                              $createdbefore,$createdafter,undef,
16145:                                              $domcloner,undef,$reqcrsdom,$reqinstcode);
16146:     if (($filter->{'personfilter'} ne '') && ($filter->{'persondomfilter'} ne '')) {
16147:         my $ccrole;
16148:         if ($type eq 'Community') {
16149:             $ccrole = 'co';
16150:         } else {
16151:             $ccrole = 'cc';
16152:         }
16153:         my %rolehash = &Apache::lonnet::get_my_roles($filter->{'personfilter'},
16154:                                                      $filter->{'persondomfilter'},
16155:                                                      'userroles',undef,
16156:                                                      [$ccrole,'in','ad','ep','ta','cr'],
16157:                                                      $dom);
16158:         foreach my $role (keys(%rolehash)) {
16159:             my ($cnum,$cdom,$courserole) = split(':',$role);
16160:             my $cid = $cdom.'_'.$cnum;
16161:             if (exists($courses{$cid})) {
16162:                 if (ref($courses{$cid}) eq 'HASH') {
16163:                     if (ref($courses{$cid}{roles}) eq 'ARRAY') {
16164:                         if (!grep(/^\Q$courserole\E$/,@{$courses{$cid}{roles}})) {
16165:                             push(@{$courses{$cid}{roles}},$courserole);
16166:                         }
16167:                     } else {
16168:                         $courses{$cid}{roles} = [$courserole];
16169:                     }
16170:                     $showcourses{$cid} = $courses{$cid};
16171:                 }
16172:             }
16173:         }
16174:         %courses = %showcourses;
16175:     }
16176:     return %courses;
16177: }
16178: 
16179: =pod
16180: 
16181: =back
16182: 
16183: =head1 Routines for version requirements for current course.
16184: 
16185: =over 4
16186: 
16187: =item * &check_release_required()
16188: 
16189: Compares required LON-CAPA version with version on server, and
16190: if required version is newer looks for a server with the required version.
16191: 
16192: Looks first at servers in user's owen domain; if none suitable, looks at
16193: servers in course's domain are permitted to host sessions for user's domain.
16194: 
16195: Inputs:
16196: 
16197: $loncaparev - Version on current server (format: Major.Minor.Subrelease-datestamp)
16198: 
16199: $courseid - Course ID of current course
16200: 
16201: $rolecode - User's current role in course (for switchserver query string).
16202: 
16203: $required - LON-CAPA version needed by course (format: Major.Minor).
16204: 
16205: 
16206: Returns:
16207: 
16208: $switchserver - query string tp append to /adm/switchserver call (if
16209:                 current server's LON-CAPA version is too old.
16210: 
16211: $warning - Message is displayed if no suitable server could be found.
16212: 
16213: =cut
16214: 
16215: sub check_release_required {
16216:     my ($loncaparev,$courseid,$rolecode,$required) = @_;
16217:     my ($switchserver,$warning);
16218:     if ($required ne '') {
16219:         my ($reqdmajor,$reqdminor) = ($required =~ /^(\d+)\.(\d+)$/);
16220:         my ($major,$minor) = ($loncaparev =~ /^\'?(\d+)\.(\d+)\.[\w.\-]+\'?$/);
16221:         if ($reqdmajor ne '' && $reqdminor ne '') {
16222:             my $otherserver;
16223:             if (($major eq '' && $minor eq '') ||
16224:                 (($reqdmajor > $major) || (($reqdmajor == $major) && ($reqdminor > $minor)))) {
16225:                 my ($userdomserver) = &Apache::lonnet::choose_server($env{'user.domain'},undef,$required,1);
16226:                 my $switchlcrev =
16227:                     &Apache::lonnet::get_server_loncaparev($env{'user.domain'},
16228:                                                            $userdomserver);
16229:                 my ($swmajor,$swminor) = ($switchlcrev =~ /^\'?(\d+)\.(\d+)\.[\w.\-]+\'?$/);
16230:                 if (($swmajor eq '' && $swminor eq '') || ($reqdmajor > $swmajor) ||
16231:                     (($reqdmajor == $swmajor) && ($reqdminor > $swminor))) {
16232:                     my $cdom = $env{'course.'.$courseid.'.domain'};
16233:                     if ($cdom ne $env{'user.domain'}) {
16234:                         my ($coursedomserver,$coursehostname) = &Apache::lonnet::choose_server($cdom,undef,$required,1);
16235:                         my $serverhomeID = &Apache::lonnet::get_server_homeID($coursehostname);
16236:                         my $serverhomedom = &Apache::lonnet::host_domain($serverhomeID);
16237:                         my %defdomdefaults = &Apache::lonnet::get_domain_defaults($serverhomedom);
16238:                         my %udomdefaults = &Apache::lonnet::get_domain_defaults($env{'user.domain'});
16239:                         my $remoterev = &Apache::lonnet::get_server_loncaparev($serverhomedom,$coursedomserver);
16240:                         my $canhost =
16241:                             &Apache::lonnet::can_host_session($env{'user.domain'},
16242:                                                               $coursedomserver,
16243:                                                               $remoterev,
16244:                                                               $udomdefaults{'remotesessions'},
16245:                                                               $defdomdefaults{'hostedsessions'});
16246: 
16247:                         if ($canhost) {
16248:                             $otherserver = $coursedomserver;
16249:                         } else {
16250:                             $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.");
16251:                         }
16252:                     } else {
16253:                         $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).");
16254:                     }
16255:                 } else {
16256:                     $otherserver = $userdomserver;
16257:                 }
16258:             }
16259:             if ($otherserver ne '') {
16260:                 $switchserver = 'otherserver='.$otherserver.'&amp;role='.$rolecode;
16261:             }
16262:         }
16263:     }
16264:     return ($switchserver,$warning);
16265: }
16266: 
16267: =pod
16268: 
16269: =item * &check_release_result()
16270: 
16271: Inputs:
16272: 
16273: $switchwarning - Warning message if no suitable server found to host session.
16274: 
16275: $switchserver - query string to append to /adm/switchserver containing lonHostID
16276:                 and current role.
16277: 
16278: Returns: HTML to display with information about requirement to switch server.
16279:          Either displaying warning with link to Roles/Courses screen or
16280:          display link to switchserver.
16281: 
16282: =cut
16283: 
16284: sub check_release_result {
16285:     my ($switchwarning,$switchserver) = @_;
16286:     my $output = &start_page('Selected course unavailable on this server').
16287:                  '<p class="LC_warning">';
16288:     if ($switchwarning) {
16289:         $output .= $switchwarning.'<br /><a href="/adm/roles">';
16290:         if (&show_course()) {
16291:             $output .= &mt('Display courses');
16292:         } else {
16293:             $output .= &mt('Display roles');
16294:         }
16295:         $output .= '</a>';
16296:     } elsif ($switchserver) {
16297:         $output .= &mt('This course requires a newer version of LON-CAPA than is installed on this server.').
16298:                    '<br />'.
16299:                    '<a href="/adm/switchserver?'.$switchserver.'">'.
16300:                    &mt('Switch Server').
16301:                    '</a>';
16302:     }
16303:     $output .= '</p>'.&end_page();
16304:     return $output;
16305: }
16306: 
16307: =pod
16308: 
16309: =item * &needs_coursereinit()
16310: 
16311: Determine if course contents stored for user's session needs to be
16312: refreshed, because content has changed since "Big Hash" last tied.
16313: 
16314: Check for change is made if time last checked is more than 10 minutes ago
16315: (by default).
16316: 
16317: Inputs:
16318: 
16319: $loncaparev - Version on current server (format: Major.Minor.Subrelease-datestamp)
16320: 
16321: $interval (optional) - Time which may elapse (in s) between last check for content
16322:                        change in current course. (default: 600 s).
16323: 
16324: Returns: an array; first element is:
16325: 
16326: =over 4
16327: 
16328: 'switch' - if content updates mean user's session
16329:            needs to be switched to a server running a newer LON-CAPA version
16330: 
16331: 'update' - if course session needs to be refreshed (i.e., Big Hash needs to be reloaded)
16332:            on current server hosting user's session
16333: 
16334: ''       - if no action required.
16335: 
16336: =back
16337: 
16338: If first item element is 'switch':
16339: 
16340: second item is $switchwarning - Warning message if no suitable server found to host session.
16341: 
16342: third item is $switchserver - query string to append to /adm/switchserver containing lonHostID
16343:                               and current role.
16344: 
16345: otherwise: no other elements returned.
16346: 
16347: =back
16348: 
16349: =cut
16350: 
16351: sub needs_coursereinit {
16352:     my ($loncaparev,$interval) = @_;
16353:     return() unless ($env{'request.course.id'} && $env{'request.course.tied'});
16354:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
16355:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
16356:     my $now = time;
16357:     if ($interval eq '') {
16358:         $interval = 600;
16359:     }
16360:     if (($now-$env{'request.course.timechecked'})>$interval) {
16361:         my $lastchange = &Apache::lonnet::get_coursechange($cdom,$cnum);
16362:         &Apache::lonnet::appenv({'request.course.timechecked'=>$now});
16363:         if ($lastchange > $env{'request.course.tied'}) {
16364:             my %curr_reqd_hash = &Apache::lonnet::userenvironment($cdom,$cnum,'internal.releaserequired');
16365:             if ($curr_reqd_hash{'internal.releaserequired'} ne '') {
16366:                 my $required = $env{'course.'.$cdom.'_'.$cnum.'.internal.releaserequired'};
16367:                 if ($curr_reqd_hash{'internal.releaserequired'} ne $required) {
16368:                     &Apache::lonnet::appenv({'course.'.$cdom.'_'.$cnum.'.internal.releaserequired' =>
16369:                                              $curr_reqd_hash{'internal.releaserequired'}});
16370:                     my ($switchserver,$switchwarning) =
16371:                         &check_release_required($loncaparev,$cdom.'_'.$cnum,$env{'request.role'},
16372:                                                 $curr_reqd_hash{'internal.releaserequired'});
16373:                     if ($switchwarning ne '' || $switchserver ne '') {
16374:                         return ('switch',$switchwarning,$switchserver);
16375:                     }
16376:                 }
16377:             }
16378:             return ('update');
16379:         }
16380:     }
16381:     return ();
16382: }
16383: 
16384: sub update_content_constraints {
16385:     my ($cdom,$cnum,$chome,$cid) = @_;
16386:     my %curr_reqd_hash = &Apache::lonnet::userenvironment($cdom,$cnum,'internal.releaserequired');
16387:     my ($reqdmajor,$reqdminor) = split(/\./,$curr_reqd_hash{'internal.releaserequired'});
16388:     my %checkresponsetypes;
16389:     foreach my $key (keys(%Apache::lonnet::needsrelease)) {
16390:         my ($item,$name,$value) = split(/:/,$key);
16391:         if ($item eq 'resourcetag') {
16392:             if ($name eq 'responsetype') {
16393:                 $checkresponsetypes{$value} = $Apache::lonnet::needsrelease{$key}
16394:             }
16395:         }
16396:     }
16397:     my $navmap = Apache::lonnavmaps::navmap->new();
16398:     if (defined($navmap)) {
16399:         my %allresponses;
16400:         foreach my $res ($navmap->retrieveResources(undef,sub { $_[0]->is_problem() },1,0)) {
16401:             my %responses = $res->responseTypes();
16402:             foreach my $key (keys(%responses)) {
16403:                 next unless(exists($checkresponsetypes{$key}));
16404:                 $allresponses{$key} += $responses{$key};
16405:             }
16406:         }
16407:         foreach my $key (keys(%allresponses)) {
16408:             my ($major,$minor) = split(/\./,$checkresponsetypes{$key});
16409:             if (($major > $reqdmajor) || ($major == $reqdmajor && $minor > $reqdminor)) {
16410:                 ($reqdmajor,$reqdminor) = ($major,$minor);
16411:             }
16412:         }
16413:         undef($navmap);
16414:     }
16415:     unless (($reqdmajor eq '') && ($reqdminor eq '')) {
16416:         &Apache::lonnet::update_released_required($reqdmajor.'.'.$reqdminor,$cdom,$cnum,$chome,$cid);
16417:     }
16418:     return;
16419: }
16420: 
16421: sub allmaps_incourse {
16422:     my ($cdom,$cnum,$chome,$cid) = @_;
16423:     if ($cdom eq '' || $cnum eq '' || $chome eq '' || $cid eq '') {
16424:         $cid = $env{'request.course.id'};
16425:         $cdom = $env{'course.'.$cid.'.domain'};
16426:         $cnum = $env{'course.'.$cid.'.num'};
16427:         $chome = $env{'course.'.$cid.'.home'};
16428:     }
16429:     my %allmaps = ();
16430:     my $lastchange =
16431:         &Apache::lonnet::get_coursechange($cdom,$cnum);
16432:     if ($lastchange > $env{'request.course.tied'}) {
16433:         my ($furl,$ferr) = &Apache::lonuserstate::readmap("$cdom/$cnum");
16434:         unless ($ferr) {
16435:             &update_content_constraints($cdom,$cnum,$chome,$cid);
16436:         }
16437:     }
16438:     my $navmap = Apache::lonnavmaps::navmap->new();
16439:     if (defined($navmap)) {
16440:         foreach my $res ($navmap->retrieveResources(undef,sub { $_[0]->is_map() },1,0,1)) {
16441:             $allmaps{$res->src()} = 1;
16442:         }
16443:     }
16444:     return \%allmaps;
16445: }
16446: 
16447: sub parse_supplemental_title {
16448:     my ($title) = @_;
16449: 
16450:     my ($foldertitle,$renametitle);
16451:     if ($title =~ /&amp;&amp;&amp;/) {
16452:         $title = &HTML::Entites::decode($title);
16453:     }
16454:     if ($title =~ m/^(\d+)___&&&___($match_username)___&&&___($match_domain)___&&&___(.*)$/) {
16455:         $renametitle=$4;
16456:         my ($time,$uname,$udom) = ($1,$2,$3);
16457:         $foldertitle=&Apache::lontexconvert::msgtexconverted($4);
16458:         my $name =  &plainname($uname,$udom);
16459:         $name = &HTML::Entities::encode($name,'"<>&\'');
16460:         $renametitle = &HTML::Entities::encode($renametitle,'"<>&\'');
16461:         $title='<i>'.&Apache::lonlocal::locallocaltime($time).'</i> '.
16462:             $name.': <br />'.$foldertitle;
16463:     }
16464:     if (wantarray) {
16465:         return ($title,$foldertitle,$renametitle);
16466:     }
16467:     return $title;
16468: }
16469: 
16470: sub recurse_supplemental {
16471:     my ($cnum,$cdom,$suppmap,$numfiles,$errors) = @_;
16472:     if ($suppmap) {
16473:         my ($errtext,$fatal) = &LONCAPA::map::mapread('/uploaded/'.$cdom.'/'.$cnum.'/'.$suppmap);
16474:         if ($fatal) {
16475:             $errors ++;
16476:         } else {
16477:             if ($#LONCAPA::map::resources > 0) {
16478:                 foreach my $res (@LONCAPA::map::resources) {
16479:                     my ($title,$src,$ext,$type,$status)=split(/\:/,$res);
16480:                     if (($src ne '') && ($status eq 'res')) {
16481:                         if ($src =~ m{^\Q/uploaded/$cdom/$cnum/\E(supplemental_\d+\.sequence)$}) {
16482:                             ($numfiles,$errors) = &recurse_supplemental($cnum,$cdom,$1,$numfiles,$errors);
16483:                         } else {
16484:                             $numfiles ++;
16485:                         }
16486:                     }
16487:                 }
16488:             }
16489:         }
16490:     }
16491:     return ($numfiles,$errors);
16492: }
16493: 
16494: sub symb_to_docspath {
16495:     my ($symb,$navmapref) = @_;
16496:     return unless ($symb && ref($navmapref));
16497:     my ($mapurl,$id,$resurl) = &Apache::lonnet::decode_symb($symb);
16498:     if ($resurl=~/\.(sequence|page)$/) {
16499:         $mapurl=$resurl;
16500:     } elsif ($resurl eq 'adm/navmaps') {
16501:         $mapurl=$env{'course.'.$env{'request.course.id'}.'.url'};
16502:     }
16503:     my $mapresobj;
16504:     unless (ref($$navmapref)) {
16505:         $$navmapref = Apache::lonnavmaps::navmap->new();
16506:     }
16507:     if (ref($$navmapref)) {
16508:         $mapresobj = $$navmapref->getResourceByUrl($mapurl);
16509:     }
16510:     $mapurl=~s{^.*/([^/]+)\.(\w+)$}{$1};
16511:     my $type=$2;
16512:     my $path;
16513:     if (ref($mapresobj)) {
16514:         my $pcslist = $mapresobj->map_hierarchy();
16515:         if ($pcslist ne '') {
16516:             foreach my $pc (split(/,/,$pcslist)) {
16517:                 next if ($pc <= 1);
16518:                 my $res = $$navmapref->getByMapPc($pc);
16519:                 if (ref($res)) {
16520:                     my $thisurl = $res->src();
16521:                     $thisurl=~s{^.*/([^/]+)\.\w+$}{$1};
16522:                     my $thistitle = $res->title();
16523:                     $path .= '&'.
16524:                              &Apache::lonhtmlcommon::entity_encode($thisurl).'&'.
16525:                              &escape($thistitle).
16526:                              ':'.$res->randompick().
16527:                              ':'.$res->randomout().
16528:                              ':'.$res->encrypted().
16529:                              ':'.$res->randomorder().
16530:                              ':'.$res->is_page();
16531:                 }
16532:             }
16533:         }
16534:         $path =~ s/^\&//;
16535:         my $maptitle = $mapresobj->title();
16536:         if ($mapurl eq 'default') {
16537:             $maptitle = 'Main Content';
16538:         }
16539:         $path .= (($path ne '')? '&' : '').
16540:                  &Apache::lonhtmlcommon::entity_encode($mapurl).'&'.
16541:                  &escape($maptitle).
16542:                  ':'.$mapresobj->randompick().
16543:                  ':'.$mapresobj->randomout().
16544:                  ':'.$mapresobj->encrypted().
16545:                  ':'.$mapresobj->randomorder().
16546:                  ':'.$mapresobj->is_page();
16547:     } else {
16548:         my $maptitle = &Apache::lonnet::gettitle($mapurl);
16549:         my $ispage = (($type eq 'page')? 1 : '');
16550:         if ($mapurl eq 'default') {
16551:             $maptitle = 'Main Content';
16552:         }
16553:         $path = &Apache::lonhtmlcommon::entity_encode($mapurl).'&'.
16554:                 &escape($maptitle).':::::'.$ispage;
16555:     }
16556:     unless ($mapurl eq 'default') {
16557:         $path = 'default&'.
16558:                 &escape('Main Content').
16559:                 ':::::&'.$path;
16560:     }
16561:     return $path;
16562: }
16563: 
16564: sub captcha_display {
16565:     my ($context,$lonhost) = @_;
16566:     my ($output,$error);
16567:     my ($captcha,$pubkey,$privkey,$version) =
16568:         &get_captcha_config($context,$lonhost);
16569:     if ($captcha eq 'original') {
16570:         $output = &create_captcha();
16571:         unless ($output) {
16572:             $error = 'captcha';
16573:         }
16574:     } elsif ($captcha eq 'recaptcha') {
16575:         $output = &create_recaptcha($pubkey,$version);
16576:         unless ($output) {
16577:             $error = 'recaptcha';
16578:         }
16579:     }
16580:     return ($output,$error,$captcha,$version);
16581: }
16582: 
16583: sub captcha_response {
16584:     my ($context,$lonhost) = @_;
16585:     my ($captcha_chk,$captcha_error);
16586:     my ($captcha,$pubkey,$privkey,$version) = &get_captcha_config($context,$lonhost);
16587:     if ($captcha eq 'original') {
16588:         ($captcha_chk,$captcha_error) = &check_captcha();
16589:     } elsif ($captcha eq 'recaptcha') {
16590:         $captcha_chk = &check_recaptcha($privkey,$version);
16591:     } else {
16592:         $captcha_chk = 1;
16593:     }
16594:     return ($captcha_chk,$captcha_error);
16595: }
16596: 
16597: sub get_captcha_config {
16598:     my ($context,$lonhost) = @_;
16599:     my ($captcha,$pubkey,$privkey,$version,$hashtocheck);
16600:     my $hostname = &Apache::lonnet::hostname($lonhost);
16601:     my $serverhomeID = &Apache::lonnet::get_server_homeID($hostname);
16602:     my $serverhomedom = &Apache::lonnet::host_domain($serverhomeID);
16603:     if ($context eq 'usercreation') {
16604:         my %domconfig = &Apache::lonnet::get_dom('configuration',[$context],$serverhomedom);
16605:         if (ref($domconfig{$context}) eq 'HASH') {
16606:             $hashtocheck = $domconfig{$context}{'cancreate'};
16607:             if (ref($hashtocheck) eq 'HASH') {
16608:                 if ($hashtocheck->{'captcha'} eq 'recaptcha') {
16609:                     if (ref($hashtocheck->{'recaptchakeys'}) eq 'HASH') {
16610:                         $pubkey = $hashtocheck->{'recaptchakeys'}{'public'};
16611:                         $privkey = $hashtocheck->{'recaptchakeys'}{'private'};
16612:                     }
16613:                     if ($privkey && $pubkey) {
16614:                         $captcha = 'recaptcha';
16615:                         $version = $hashtocheck->{'recaptchaversion'};
16616:                         if ($version ne '2') {
16617:                             $version = 1;
16618:                         }
16619:                     } else {
16620:                         $captcha = 'original';
16621:                     }
16622:                 } elsif ($hashtocheck->{'captcha'} ne 'notused') {
16623:                     $captcha = 'original';
16624:                 }
16625:             }
16626:         } else {
16627:             $captcha = 'captcha';
16628:         }
16629:     } elsif ($context eq 'login') {
16630:         my %domconfhash = &Apache::loncommon::get_domainconf($serverhomedom);
16631:         if ($domconfhash{$serverhomedom.'.login.captcha'} eq 'recaptcha') {
16632:             $pubkey = $domconfhash{$serverhomedom.'.login.recaptchakeys_public'};
16633:             $privkey = $domconfhash{$serverhomedom.'.login.recaptchakeys_private'};
16634:             if ($privkey && $pubkey) {
16635:                 $captcha = 'recaptcha';
16636:                 $version = $domconfhash{$serverhomedom.'.login.recaptchaversion'};
16637:                 if ($version ne '2') {
16638:                     $version = 1;
16639:                 }
16640:             } else {
16641:                 $captcha = 'original';
16642:             }
16643:         } elsif ($domconfhash{$serverhomedom.'.login.captcha'} eq 'original') {
16644:             $captcha = 'original';
16645:         }
16646:     }
16647:     return ($captcha,$pubkey,$privkey,$version);
16648: }
16649: 
16650: sub create_captcha {
16651:     my %captcha_params = &captcha_settings();
16652:     my ($output,$maxtries,$tries) = ('',10,0);
16653:     while ($tries < $maxtries) {
16654:         $tries ++;
16655:         my $captcha = Authen::Captcha->new (
16656:                                            output_folder => $captcha_params{'output_dir'},
16657:                                            data_folder   => $captcha_params{'db_dir'},
16658:                                           );
16659:         my $md5sum = $captcha->generate_code($captcha_params{'numchars'});
16660: 
16661:         if (-e $Apache::lonnet::perlvar{'lonCaptchaDir'}.'/'.$md5sum.'.png') {
16662:             $output = '<input type="hidden" name="crypt" value="'.$md5sum.'" />'."\n".
16663:                       &mt('Type in the letters/numbers shown below').'&nbsp;'.
16664:                       '<input type="text" size="5" name="code" value="" autocomplete="off" />'.
16665:                       '<br />'.
16666:                       '<img src="'.$captcha_params{'www_output_dir'}.'/'.$md5sum.'.png" alt="captcha" />';
16667:             last;
16668:         }
16669:     }
16670:     return $output;
16671: }
16672: 
16673: sub captcha_settings {
16674:     my %captcha_params = (
16675:                            output_dir     => $Apache::lonnet::perlvar{'lonCaptchaDir'},
16676:                            www_output_dir => "/captchaspool",
16677:                            db_dir         => $Apache::lonnet::perlvar{'lonCaptchaDb'},
16678:                            numchars       => '5',
16679:                          );
16680:     return %captcha_params;
16681: }
16682: 
16683: sub check_captcha {
16684:     my ($captcha_chk,$captcha_error);
16685:     my $code = $env{'form.code'};
16686:     my $md5sum = $env{'form.crypt'};
16687:     my %captcha_params = &captcha_settings();
16688:     my $captcha = Authen::Captcha->new(
16689:                       output_folder => $captcha_params{'output_dir'},
16690:                       data_folder   => $captcha_params{'db_dir'},
16691:                   );
16692:     $captcha_chk = $captcha->check_code($code,$md5sum);
16693:     my %captcha_hash = (
16694:                         0       => 'Code not checked (file error)',
16695:                        -1      => 'Failed: code expired',
16696:                        -2      => 'Failed: invalid code (not in database)',
16697:                        -3      => 'Failed: invalid code (code does not match crypt)',
16698:     );
16699:     if ($captcha_chk != 1) {
16700:         $captcha_error = $captcha_hash{$captcha_chk}
16701:     }
16702:     return ($captcha_chk,$captcha_error);
16703: }
16704: 
16705: sub create_recaptcha {
16706:     my ($pubkey,$version) = @_;
16707:     if ($version >= 2) {
16708:         return '<div class="g-recaptcha" data-sitekey="'.$pubkey.'"></div>';
16709:     } else {
16710:         my $use_ssl;
16711:         if ($ENV{'SERVER_PORT'} == 443) {
16712:             $use_ssl = 1;
16713:         }
16714:         my $captcha = Captcha::reCAPTCHA->new;
16715:         return $captcha->get_options_setter({theme => 'white'})."\n".
16716:                $captcha->get_html($pubkey,undef,$use_ssl).
16717:                &mt('If the text is hard to read, [_1] will replace them.',
16718:                    '<img src="/res/adm/pages/refresh.gif" alt="reCAPTCHA refresh" />').
16719:                '<br /><br />';
16720:      }
16721: }
16722: 
16723: sub check_recaptcha {
16724:     my ($privkey,$version) = @_;
16725:     my $captcha_chk;
16726:     if ($version >= 2) {
16727:         my $ua = LWP::UserAgent->new;
16728:         $ua->timeout(10);
16729:         my %info = (
16730:                      secret   => $privkey,
16731:                      response => $env{'form.g-recaptcha-response'},
16732:                      remoteip => $ENV{'REMOTE_ADDR'},
16733:                    );
16734:         my $response = $ua->post('https://www.google.com/recaptcha/api/siteverify',\%info);
16735:         if ($response->is_success)  {
16736:             my $data = JSON::DWIW->from_json($response->decoded_content);
16737:             if (ref($data) eq 'HASH') {
16738:                 if ($data->{'success'}) {
16739:                     $captcha_chk = 1;
16740:                 }
16741:             }
16742:         }
16743:     } else {
16744:         my $captcha = Captcha::reCAPTCHA->new;
16745:         my $captcha_result =
16746:             $captcha->check_answer(
16747:                                     $privkey,
16748:                                     $ENV{'REMOTE_ADDR'},
16749:                                     $env{'form.recaptcha_challenge_field'},
16750:                                     $env{'form.recaptcha_response_field'},
16751:                                   );
16752:         if ($captcha_result->{is_valid}) {
16753:             $captcha_chk = 1;
16754:         }
16755:     }
16756:     return $captcha_chk;
16757: }
16758: 
16759: sub emailusername_info {
16760:     my @fields = ('firstname','lastname','institution','web','location','officialemail','id');
16761:     my %titles = &Apache::lonlocal::texthash (
16762:                      lastname      => 'Last Name',
16763:                      firstname     => 'First Name',
16764:                      institution   => 'School/college/university',
16765:                      location      => "School's city, state/province, country",
16766:                      web           => "School's web address",
16767:                      officialemail => 'E-mail address at institution (if different)',
16768:                      id            => 'Student/Employee ID',
16769:                  );
16770:     return (\@fields,\%titles);
16771: }
16772: 
16773: sub cleanup_html {
16774:     my ($incoming) = @_;
16775:     my $outgoing;
16776:     if ($incoming ne '') {
16777:         $outgoing = $incoming;
16778:         $outgoing =~ s/;/&#059;/g;
16779:         $outgoing =~ s/\#/&#035;/g;
16780:         $outgoing =~ s/\&/&#038;/g;
16781:         $outgoing =~ s/</&#060;/g;
16782:         $outgoing =~ s/>/&#062;/g;
16783:         $outgoing =~ s/\(/&#040/g;
16784:         $outgoing =~ s/\)/&#041;/g;
16785:         $outgoing =~ s/"/&#034;/g;
16786:         $outgoing =~ s/'/&#039;/g;
16787:         $outgoing =~ s/\$/&#036;/g;
16788:         $outgoing =~ s{/}{&#047;}g;
16789:         $outgoing =~ s/=/&#061;/g;
16790:         $outgoing =~ s/\\/&#092;/g
16791:     }
16792:     return $outgoing;
16793: }
16794: 
16795: # Checks for critical messages and returns a redirect url if one exists.
16796: # $interval indicates how often to check for messages.
16797: sub critical_redirect {
16798:     my ($interval) = @_;
16799:     if ((time-$env{'user.criticalcheck.time'})>$interval) {
16800:         my @what=&Apache::lonnet::dump('critical', $env{'user.domain'},
16801:                                         $env{'user.name'});
16802:         &Apache::lonnet::appenv({'user.criticalcheck.time'=>time});
16803:         my $redirecturl;
16804:         if ($what[0]) {
16805:             if (($what[0] ne 'con_lost') && ($what[0]!~/^error\:/)) {
16806:                 $redirecturl='/adm/email?critical=display';
16807:                 my $url=&Apache::lonnet::absolute_url().$redirecturl;
16808:                 return (1, $url);
16809:             }
16810:         }
16811:     }
16812:     return ();
16813: }
16814: 
16815: # Use:
16816: #   my $answer=reply("encrypt:passwd:$udom:$uname:$upass",$tryserver);
16817: #
16818: ##################################################
16819: #          password associated functions         #
16820: ##################################################
16821: sub des_keys {
16822:     # Make a new key for DES encryption.
16823:     # Each key has two parts which are returned separately.
16824:     # Please note:  Each key must be passed through the &hex function
16825:     # before it is output to the web browser.  The hex versions cannot
16826:     # be used to decrypt.
16827:     my @hexstr=('0','1','2','3','4','5','6','7',
16828:                 '8','9','a','b','c','d','e','f');
16829:     my $lkey='';
16830:     for (0..7) {
16831:         $lkey.=$hexstr[rand(15)];
16832:     }
16833:     my $ukey='';
16834:     for (0..7) {
16835:         $ukey.=$hexstr[rand(15)];
16836:     }
16837:     return ($lkey,$ukey);
16838: }
16839: 
16840: sub des_decrypt {
16841:     my ($key,$cyphertext) = @_;
16842:     my $keybin=pack("H16",$key);
16843:     my $cypher;
16844:     if ($Crypt::DES::VERSION>=2.03) {
16845:         $cypher=new Crypt::DES $keybin;
16846:     } else {
16847:         $cypher=new DES $keybin;
16848:     }
16849:     my $plaintext='';
16850:     my $cypherlength = length($cyphertext);
16851:     my $numchunks = int($cypherlength/32);
16852:     for (my $j=0; $j<$numchunks; $j++) {
16853:         my $start = $j*32;
16854:         my $cypherblock = substr($cyphertext,$start,32);
16855:         my $chunk =
16856:             $cypher->decrypt(unpack("a8",pack("H16",substr($cypherblock,0,16))));
16857:         $chunk .=
16858:             $cypher->decrypt(unpack("a8",pack("H16",substr($cypherblock,16,16))));
16859:         $chunk=substr($chunk,1,ord(substr($chunk,0,1)) );
16860:         $plaintext .= $chunk;
16861:     }
16862:     return $plaintext;
16863: }
16864: 
16865: 1;
16866: __END__;
16867: 

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