File:  [LON-CAPA] / loncom / interface / loncommon.pm
Revision 1.1075.2.130: download - view: text, annotated - select for diffs
Sun Sep 9 21:30:40 2018 UTC (5 years, 8 months ago) by raeburn
Branches: version_2_11_X
- For 2.11
  Backport 1.1301, 1.1302

    1: # The LearningOnline Network with CAPA
    2: # a pile of common routines
    3: #
    4: # $Id: loncommon.pm,v 1.1075.2.130 2018/09/09 21:30:40 raeburn Exp $
    5: #
    6: # Copyright Michigan State University Board of Trustees
    7: #
    8: # This file is part of the LearningOnline Network with CAPA (LON-CAPA).
    9: #
   10: # LON-CAPA is free software; you can redistribute it and/or modify
   11: # it under the terms of the GNU General Public License as published by
   12: # the Free Software Foundation; either version 2 of the License, or
   13: # (at your option) any later version.
   14: #
   15: # LON-CAPA is distributed in the hope that it will be useful,
   16: # but WITHOUT ANY WARRANTY; without even the implied warranty of
   17: # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   18: # GNU General Public License for more details.
   19: #
   20: # You should have received a copy of the GNU General Public License
   21: # along with LON-CAPA; if not, write to the Free Software
   22: # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
   23: #
   24: # /home/httpd/html/adm/gpl.txt
   25: #
   26: # http://www.lon-capa.org/
   27: #
   28: 
   29: # Makes a table out of the previous attempts
   30: # Inputs result_from_symbread, user, domain, course_id
   31: # Reads in non-network-related .tab files
   32: 
   33: # POD header:
   34: 
   35: =pod
   36: 
   37: =head1 NAME
   38: 
   39: Apache::loncommon - pile of common routines
   40: 
   41: =head1 SYNOPSIS
   42: 
   43: Common routines for manipulating connections, student answers,
   44:     domains, common Javascript fragments, etc.
   45: 
   46: =head1 OVERVIEW
   47: 
   48: A collection of commonly used subroutines that don't have a natural
   49: home anywhere else. This collection helps remove
   50: redundancy from other modules and increase efficiency of memory usage.
   51: 
   52: =cut 
   53: 
   54: # End of POD header
   55: package Apache::loncommon;
   56: 
   57: use strict;
   58: use Apache::lonnet;
   59: use GDBM_File;
   60: use POSIX qw(strftime mktime);
   61: use Apache::lonmenu();
   62: use Apache::lonenc();
   63: use Apache::lonlocal;
   64: use Apache::lonnet();
   65: use HTML::Entities;
   66: use Apache::lonhtmlcommon();
   67: use Apache::loncoursedata();
   68: use Apache::lontexconvert();
   69: use Apache::lonclonecourse();
   70: use Apache::lonuserutils();
   71: use Apache::lonuserstate();
   72: use Apache::courseclassifier();
   73: use LONCAPA qw(:DEFAULT :match);
   74: use DateTime::TimeZone;
   75: use DateTime::Locale;
   76: use Encode();
   77: use Authen::Captcha;
   78: use Captcha::reCAPTCHA;
   79: use JSON::DWIW;
   80: use LWP::UserAgent;
   81: use Crypt::DES;
   82: use DynaLoader; # for Crypt::DES version
   83: use File::Copy();
   84: use File::Path();
   85: 
   86: # ---------------------------------------------- Designs
   87: use vars qw(%defaultdesign);
   88: 
   89: my $readit;
   90: 
   91: 
   92: ##
   93: ## Global Variables
   94: ##
   95: 
   96: 
   97: # ----------------------------------------------- SSI with retries:
   98: #
   99: 
  100: =pod
  101: 
  102: =head1 Server Side include with retries:
  103: 
  104: =over 4
  105: 
  106: =item * &ssi_with_retries(resource,retries form)
  107: 
  108: Performs an ssi with some number of retries.  Retries continue either
  109: until the result is ok or until the retry count supplied by the
  110: caller is exhausted.  
  111: 
  112: Inputs:
  113: 
  114: =over 4
  115: 
  116: resource   - Identifies the resource to insert.
  117: 
  118: retries    - Count of the number of retries allowed.
  119: 
  120: form       - Hash that identifies the rendering options.
  121: 
  122: =back
  123: 
  124: Returns:
  125: 
  126: =over 4
  127: 
  128: content    - The content of the response.  If retries were exhausted this is empty.
  129: 
  130: response   - The response from the last attempt (which may or may not have been successful.
  131: 
  132: =back
  133: 
  134: =back
  135: 
  136: =cut
  137: 
  138: sub ssi_with_retries {
  139:     my ($resource, $retries, %form) = @_;
  140: 
  141: 
  142:     my $ok = 0;			# True if we got a good response.
  143:     my $content;
  144:     my $response;
  145: 
  146:     # Try to get the ssi done. within the retries count:
  147: 
  148:     do {
  149: 	($content, $response) = &Apache::lonnet::ssi($resource, %form);
  150: 	$ok      = $response->is_success;
  151:         if (!$ok) {
  152:             &Apache::lonnet::logthis("Failed ssi_with_retries on $resource: ".$response->is_success.', '.$response->code.', '.$response->message);
  153:         }
  154: 	$retries--;
  155:     } while (!$ok && ($retries > 0));
  156: 
  157:     if (!$ok) {
  158: 	$content = '';		# On error return an empty content.
  159:     }
  160:     return ($content, $response);
  161: 
  162: }
  163: 
  164: 
  165: 
  166: # ----------------------------------------------- Filetypes/Languages/Copyright
  167: my %language;
  168: my %supported_language;
  169: my %latex_language;		# For choosing hyphenation in <transl..>
  170: my %latex_language_bykey;	# for choosing hyphenation from metadata
  171: my %cprtag;
  172: my %scprtag;
  173: my %fe; my %fd; my %fm;
  174: my %category_extensions;
  175: 
  176: # ---------------------------------------------- Thesaurus variables
  177: #
  178: # %Keywords:
  179: #      A hash used by &keyword to determine if a word is considered a keyword.
  180: # $thesaurus_db_file 
  181: #      Scalar containing the full path to the thesaurus database.
  182: 
  183: my %Keywords;
  184: my $thesaurus_db_file;
  185: 
  186: #
  187: # Initialize values from language.tab, copyright.tab, filetypes.tab,
  188: # thesaurus.tab, and filecategories.tab.
  189: #
  190: BEGIN {
  191:     # Variable initialization
  192:     $thesaurus_db_file = $Apache::lonnet::perlvar{'lonTabDir'}."/thesaurus.db";
  193:     #
  194:     unless ($readit) {
  195: # ------------------------------------------------------------------- languages
  196:     {
  197:         my $langtabfile = $Apache::lonnet::perlvar{'lonTabDir'}.
  198:                                    '/language.tab';
  199:         if ( open(my $fh,'<',$langtabfile) ) {
  200:             while (my $line = <$fh>) {
  201:                 next if ($line=~/^\#/);
  202:                 chomp($line);
  203:                 my ($key,$two,$country,$three,$enc,$val,$sup,$latex)=(split(/\t/,$line));
  204:                 $language{$key}=$val.' - '.$enc;
  205:                 if ($sup) {
  206:                     $supported_language{$key}=$sup;
  207:                 }
  208: 		if ($latex) {
  209: 		    $latex_language_bykey{$key} = $latex;
  210: 		    $latex_language{$two} = $latex;
  211: 		}
  212:             }
  213:             close($fh);
  214:         }
  215:     }
  216: # ------------------------------------------------------------------ copyrights
  217:     {
  218:         my $copyrightfile = $Apache::lonnet::perlvar{'lonIncludes'}.
  219:                                   '/copyright.tab';
  220:         if ( open (my $fh,'<',$copyrightfile) ) {
  221:             while (my $line = <$fh>) {
  222:                 next if ($line=~/^\#/);
  223:                 chomp($line);
  224:                 my ($key,$val)=(split(/\s+/,$line,2));
  225:                 $cprtag{$key}=$val;
  226:             }
  227:             close($fh);
  228:         }
  229:     }
  230: # ----------------------------------------------------------- source copyrights
  231:     {
  232:         my $sourcecopyrightfile = $Apache::lonnet::perlvar{'lonIncludes'}.
  233:                                   '/source_copyright.tab';
  234:         if ( open (my $fh,'<',$sourcecopyrightfile) ) {
  235:             while (my $line = <$fh>) {
  236:                 next if ($line =~ /^\#/);
  237:                 chomp($line);
  238:                 my ($key,$val)=(split(/\s+/,$line,2));
  239:                 $scprtag{$key}=$val;
  240:             }
  241:             close($fh);
  242:         }
  243:     }
  244: 
  245: # -------------------------------------------------------------- default domain designs
  246:     my $designdir=$Apache::lonnet::perlvar{'lonTabDir'}.'/lonDomColors';
  247:     my $designfile = $designdir.'/default.tab';
  248:     if ( open (my $fh,'<',$designfile) ) {
  249:         while (my $line = <$fh>) {
  250:             next if ($line =~ /^\#/);
  251:             chomp($line);
  252:             my ($key,$val)=(split(/\=/,$line));
  253:             if ($val) { $defaultdesign{$key}=$val; }
  254:         }
  255:         close($fh);
  256:     }
  257: 
  258: # ------------------------------------------------------------- file categories
  259:     {
  260:         my $categoryfile = $Apache::lonnet::perlvar{'lonTabDir'}.
  261:                                   '/filecategories.tab';
  262:         if ( open (my $fh,'<',$categoryfile) ) {
  263: 	    while (my $line = <$fh>) {
  264: 		next if ($line =~ /^\#/);
  265: 		chomp($line);
  266:                 my ($extension,$category)=(split(/\s+/,$line,2));
  267:                 push(@{$category_extensions{lc($category)}},$extension);
  268:             }
  269:             close($fh);
  270:         }
  271: 
  272:     }
  273: # ------------------------------------------------------------------ file types
  274:     {
  275:         my $typesfile = $Apache::lonnet::perlvar{'lonTabDir'}.
  276:                '/filetypes.tab';
  277:         if ( open (my $fh,'<',$typesfile) ) {
  278:             while (my $line = <$fh>) {
  279: 		next if ($line =~ /^\#/);
  280: 		chomp($line);
  281:                 my ($ending,$emb,$mime,$descr)=split(/\s+/,$line,4);
  282:                 if ($descr ne '') {
  283:                     $fe{$ending}=lc($emb);
  284:                     $fd{$ending}=$descr;
  285:                     if ($mime ne 'unk') { $fm{$ending}=$mime; }
  286:                 }
  287:             }
  288:             close($fh);
  289:         }
  290:     }
  291:     &Apache::lonnet::logthis(
  292:              "<span style='color:yellow;'>INFO: Read file types</span>");
  293:     $readit=1;
  294:     }  # end of unless($readit) 
  295:     
  296: }
  297: 
  298: ###############################################################
  299: ##           HTML and Javascript Helper Functions            ##
  300: ###############################################################
  301: 
  302: =pod 
  303: 
  304: =head1 HTML and Javascript Functions
  305: 
  306: =over 4
  307: 
  308: =item * &browser_and_searcher_javascript()
  309: 
  310: X<browsing, javascript>X<searching, javascript>Returns a string
  311: containing javascript with two functions, C<openbrowser> and
  312: C<opensearcher>. Returned string does not contain E<lt>scriptE<gt>
  313: tags.
  314: 
  315: =item * &openbrowser(formname,elementname,only,omit) [javascript]
  316: 
  317: inputs: formname, elementname, only, omit
  318: 
  319: formname and elementname indicate the name of the html form and name of
  320: the element that the results of the browsing selection are to be placed in. 
  321: 
  322: Specifying 'only' will restrict the browser to displaying only files
  323: with the given extension.  Can be a comma separated list.
  324: 
  325: Specifying 'omit' will restrict the browser to NOT displaying files
  326: with the given extension.  Can be a comma separated list.
  327: 
  328: =item * &opensearcher(formname,elementname) [javascript]
  329: 
  330: Inputs: formname, elementname
  331: 
  332: formname and elementname specify the name of the html form and the name
  333: of the element the selection from the search results will be placed in.
  334: 
  335: =cut
  336: 
  337: sub browser_and_searcher_javascript {
  338:     my ($mode)=@_;
  339:     if (!defined($mode)) { $mode='edit'; }
  340:     my $resurl=&escape_single(&lastresurl());
  341:     return <<END;
  342: // <!-- BEGIN LON-CAPA Internal
  343:     var editbrowser = null;
  344:     function openbrowser(formname,elementname,only,omit,titleelement) {
  345:         var url = '$resurl/?';
  346:         if (editbrowser == null) {
  347:             url += 'launch=1&';
  348:         }
  349:         url += 'catalogmode=interactive&';
  350:         url += 'mode=$mode&';
  351:         url += 'inhibitmenu=yes&';
  352:         url += 'form=' + formname + '&';
  353:         if (only != null) {
  354:             url += 'only=' + only + '&';
  355:         } else {
  356:             url += 'only=&';
  357: 	}
  358:         if (omit != null) {
  359:             url += 'omit=' + omit + '&';
  360:         } else {
  361:             url += 'omit=&';
  362: 	}
  363:         if (titleelement != null) {
  364:             url += 'titleelement=' + titleelement + '&';
  365:         } else {
  366: 	    url += 'titleelement=&';
  367: 	}
  368:         url += 'element=' + elementname + '';
  369:         var title = 'Browser';
  370:         var options = 'scrollbars=1,resizable=1,menubar=0,toolbar=1,location=1';
  371:         options += ',width=700,height=600';
  372:         editbrowser = open(url,title,options,'1');
  373:         editbrowser.focus();
  374:     }
  375:     var editsearcher;
  376:     function opensearcher(formname,elementname,titleelement) {
  377:         var url = '/adm/searchcat?';
  378:         if (editsearcher == null) {
  379:             url += 'launch=1&';
  380:         }
  381:         url += 'catalogmode=interactive&';
  382:         url += 'mode=$mode&';
  383:         url += 'form=' + formname + '&';
  384:         if (titleelement != null) {
  385:             url += 'titleelement=' + titleelement + '&';
  386:         } else {
  387: 	    url += 'titleelement=&';
  388: 	}
  389:         url += 'element=' + elementname + '';
  390:         var title = 'Search';
  391:         var options = 'scrollbars=1,resizable=1,menubar=0,toolbar=1,location=1';
  392:         options += ',width=700,height=600';
  393:         editsearcher = open(url,title,options,'1');
  394:         editsearcher.focus();
  395:     }
  396: // END LON-CAPA Internal -->
  397: END
  398: }
  399: 
  400: sub lastresurl {
  401:     if ($env{'environment.lastresurl'}) {
  402: 	return $env{'environment.lastresurl'}
  403:     } else {
  404: 	return '/res';
  405:     }
  406: }
  407: 
  408: sub storeresurl {
  409:     my $resurl=&Apache::lonnet::clutter(shift);
  410:     unless ($resurl=~/^\/res/) { return 0; }
  411:     $resurl=~s/\/$//;
  412:     &Apache::lonnet::put('environment',{'lastresurl' => $resurl});
  413:     &Apache::lonnet::appenv({'environment.lastresurl' => $resurl});
  414:     return 1;
  415: }
  416: 
  417: sub studentbrowser_javascript {
  418:    unless (
  419:             (($env{'request.course.id'}) && 
  420:              (&Apache::lonnet::allowed('srm',$env{'request.course.id'})
  421: 	      || &Apache::lonnet::allowed('srm',$env{'request.course.id'}.
  422: 					  '/'.$env{'request.course.sec'})
  423: 	      ))
  424:          || ($env{'request.role'}=~/^(au|dc|su)/)
  425:           ) { return ''; }  
  426:    return (<<'ENDSTDBRW');
  427: <script type="text/javascript" language="Javascript">
  428: // <![CDATA[
  429:     var stdeditbrowser;
  430:     function openstdbrowser(formname,uname,udom,clicker,roleflag,ignorefilter,courseadvonly) {
  431:         var url = '/adm/pickstudent?';
  432:         var filter;
  433: 	if (!ignorefilter) {
  434: 	    eval('filter=document.'+formname+'.'+uname+'.value;');
  435: 	}
  436:         if (filter != null) {
  437:            if (filter != '') {
  438:                url += 'filter='+filter+'&';
  439: 	   }
  440:         }
  441:         url += 'form=' + formname + '&unameelement='+uname+
  442:                                     '&udomelement='+udom+
  443:                                     '&clicker='+clicker;
  444: 	if (roleflag) { url+="&roles=1"; }
  445:         if (courseadvonly) { url+="&courseadvonly=1"; }
  446:         var title = 'Student_Browser';
  447:         var options = 'scrollbars=1,resizable=1,menubar=0';
  448:         options += ',width=700,height=600';
  449:         stdeditbrowser = open(url,title,options,'1');
  450:         stdeditbrowser.focus();
  451:     }
  452: // ]]>
  453: </script>
  454: ENDSTDBRW
  455: }
  456: 
  457: sub resourcebrowser_javascript {
  458:    unless ($env{'request.course.id'}) { return ''; }
  459:    return (<<'ENDRESBRW');
  460: <script type="text/javascript" language="Javascript">
  461: // <![CDATA[
  462:     var reseditbrowser;
  463:     function openresbrowser(formname,reslink) {
  464:         var url = '/adm/pickresource?form='+formname+'&reslink='+reslink;
  465:         var title = 'Resource_Browser';
  466:         var options = 'scrollbars=1,resizable=1,menubar=0';
  467:         options += ',width=700,height=500';
  468:         reseditbrowser = open(url,title,options,'1');
  469:         reseditbrowser.focus();
  470:     }
  471: // ]]>
  472: </script>
  473: ENDRESBRW
  474: }
  475: 
  476: sub selectstudent_link {
  477:    my ($form,$unameele,$udomele,$courseadvonly,$clickerid)=@_;
  478:    my $callargs = "'".&Apache::lonhtmlcommon::entity_encode($form)."','".
  479:                       &Apache::lonhtmlcommon::entity_encode($unameele)."','".
  480:                       &Apache::lonhtmlcommon::entity_encode($udomele)."'";
  481:    if ($env{'request.course.id'}) {  
  482:        if (!&Apache::lonnet::allowed('srm',$env{'request.course.id'})
  483: 	   && !&Apache::lonnet::allowed('srm',$env{'request.course.id'}.
  484: 					'/'.$env{'request.course.sec'})) {
  485: 	   return '';
  486:        }
  487:        $callargs.=",'".&Apache::lonhtmlcommon::entity_encode($clickerid)."'";
  488:        if ($courseadvonly)  {
  489:            $callargs .= ",'',1,1";
  490:        }
  491:        return '<span class="LC_nobreak">'.
  492:               '<a href="javascript:openstdbrowser('.$callargs.');">'.
  493:               &mt('Select User').'</a></span>';
  494:    }
  495:    if ($env{'request.role'}=~/^(au|dc|su)/) {
  496:        $callargs .= ",'',1"; 
  497:        return '<span class="LC_nobreak">'.
  498:               '<a href="javascript:openstdbrowser('.$callargs.');">'.
  499:               &mt('Select User').'</a></span>';
  500:    }
  501:    return '';
  502: }
  503: 
  504: sub selectresource_link {
  505:    my ($form,$reslink,$arg)=@_;
  506:    
  507:    my $callargs = "'".&Apache::lonhtmlcommon::entity_encode($form)."','".
  508:                       &Apache::lonhtmlcommon::entity_encode($reslink)."'";
  509:    unless ($env{'request.course.id'}) { return $arg; }
  510:    return '<span class="LC_nobreak">'.
  511:               '<a href="javascript:openresbrowser('.$callargs.');">'.
  512:               $arg.'</a></span>';
  513: }
  514: 
  515: 
  516: 
  517: sub authorbrowser_javascript {
  518:     return <<"ENDAUTHORBRW";
  519: <script type="text/javascript" language="JavaScript">
  520: // <![CDATA[
  521: var stdeditbrowser;
  522: 
  523: function openauthorbrowser(formname,udom) {
  524:     var url = '/adm/pickauthor?';
  525:     url += 'form='+formname+'&roledom='+udom;
  526:     var title = 'Author_Browser';
  527:     var options = 'scrollbars=1,resizable=1,menubar=0';
  528:     options += ',width=700,height=600';
  529:     stdeditbrowser = open(url,title,options,'1');
  530:     stdeditbrowser.focus();
  531: }
  532: 
  533: // ]]>
  534: </script>
  535: ENDAUTHORBRW
  536: }
  537: 
  538: sub coursebrowser_javascript {
  539:     my ($domainfilter,$sec_element,$formname,$role_element,$crstype,
  540:         $credits_element,$instcode) = @_;
  541:     my $wintitle = 'Course_Browser';
  542:     if ($crstype eq 'Community') {
  543:         $wintitle = 'Community_Browser';
  544:     }
  545:     my $id_functions = &javascript_index_functions();
  546:     my $output = '
  547: <script type="text/javascript" language="JavaScript">
  548: // <![CDATA[
  549:     var stdeditbrowser;'."\n";
  550: 
  551:     $output .= <<"ENDSTDBRW";
  552:     function opencrsbrowser(formname,uname,udom,desc,extra_element,multflag,type,type_elem) {
  553:         var url = '/adm/pickcourse?';
  554:         var formid = getFormIdByName(formname);
  555:         var domainfilter = getDomainFromSelectbox(formname,udom);
  556:         if (domainfilter != null) {
  557:            if (domainfilter != '') {
  558:                url += 'domainfilter='+domainfilter+'&';
  559: 	   }
  560:         }
  561:         url += 'form=' + formname + '&cnumelement='+uname+
  562: 	                            '&cdomelement='+udom+
  563:                                     '&cnameelement='+desc;
  564:         if (extra_element !=null && extra_element != '') {
  565:             if (formname == 'rolechoice' || formname == 'studentform') {
  566:                 url += '&roleelement='+extra_element;
  567:                 if (domainfilter == null || domainfilter == '') {
  568:                     url += '&domainfilter='+extra_element;
  569:                 }
  570:             }
  571:             else {
  572:                 if (formname == 'portform') {
  573:                     url += '&setroles='+extra_element;
  574:                 } else {
  575:                     if (formname == 'rules') {
  576:                         url += '&fixeddom='+extra_element; 
  577:                     }
  578:                 }
  579:             }     
  580:         }
  581:         if (type != null && type != '') {
  582:             url += '&type='+type;
  583:         }
  584:         if (type_elem != null && type_elem != '') {
  585:             url += '&typeelement='+type_elem;
  586:         }
  587:         if (formname == 'ccrs') {
  588:             var ownername = document.forms[formid].ccuname.value;
  589:             var ownerdom =  document.forms[formid].ccdomain.options[document.forms[formid].ccdomain.selectedIndex].value;
  590:             url += '&cloner='+ownername+':'+ownerdom;
  591:             if (type == 'Course') {
  592:                 url += '&crscode='+document.forms[formid].crscode.value;
  593:             }
  594:         }
  595:         if (formname == 'requestcrs') {
  596:             url += '&crsdom=$domainfilter&crscode=$instcode';
  597:         }
  598:         if (multflag !=null && multflag != '') {
  599:             url += '&multiple='+multflag;
  600:         }
  601:         var title = '$wintitle';
  602:         var options = 'scrollbars=1,resizable=1,menubar=0';
  603:         options += ',width=700,height=600';
  604:         stdeditbrowser = open(url,title,options,'1');
  605:         stdeditbrowser.focus();
  606:     }
  607: $id_functions
  608: ENDSTDBRW
  609:     if (($sec_element ne '') || ($role_element ne '') || ($credits_element ne '')) {
  610:         $output .= &setsec_javascript($sec_element,$formname,$role_element,
  611:                                       $credits_element);
  612:     }
  613:     $output .= '
  614: // ]]>
  615: </script>';
  616:     return $output;
  617: }
  618: 
  619: sub javascript_index_functions {
  620:     return <<"ENDJS";
  621: 
  622: function getFormIdByName(formname) {
  623:     for (var i=0;i<document.forms.length;i++) {
  624:         if (document.forms[i].name == formname) {
  625:             return i;
  626:         }
  627:     }
  628:     return -1;
  629: }
  630: 
  631: function getIndexByName(formid,item) {
  632:     for (var i=0;i<document.forms[formid].elements.length;i++) {
  633:         if (document.forms[formid].elements[i].name == item) {
  634:             return i;
  635:         }
  636:     }
  637:     return -1;
  638: }
  639: 
  640: function getDomainFromSelectbox(formname,udom) {
  641:     var userdom;
  642:     var formid = getFormIdByName(formname);
  643:     if (formid > -1) {
  644:         var domid = getIndexByName(formid,udom);
  645:         if (domid > -1) {
  646:             if (document.forms[formid].elements[domid].type == 'select-one') {
  647:                 userdom=document.forms[formid].elements[domid].options[document.forms[formid].elements[domid].selectedIndex].value;
  648:             }
  649:             if (document.forms[formid].elements[domid].type == 'hidden') {
  650:                 userdom=document.forms[formid].elements[domid].value;
  651:             }
  652:         }
  653:     }
  654:     return userdom;
  655: }
  656: 
  657: ENDJS
  658: 
  659: }
  660: 
  661: sub javascript_array_indexof {
  662:     return <<ENDJS;
  663: <script type="text/javascript" language="JavaScript">
  664: // <![CDATA[
  665: 
  666: if (!Array.prototype.indexOf) {
  667:     Array.prototype.indexOf = function (searchElement /*, fromIndex */ ) {
  668:         "use strict";
  669:         if (this === void 0 || this === null) {
  670:             throw new TypeError();
  671:         }
  672:         var t = Object(this);
  673:         var len = t.length >>> 0;
  674:         if (len === 0) {
  675:             return -1;
  676:         }
  677:         var n = 0;
  678:         if (arguments.length > 0) {
  679:             n = Number(arguments[1]);
  680:             if (n !== n) { // shortcut for verifying if it's NaN
  681:                 n = 0;
  682:             } else if (n !== 0 && n !== (1 / 0) && n !== -(1 / 0)) {
  683:                 n = (n > 0 || -1) * Math.floor(Math.abs(n));
  684:             }
  685:         }
  686:         if (n >= len) {
  687:             return -1;
  688:         }
  689:         var k = n >= 0 ? n : Math.max(len - Math.abs(n), 0);
  690:         for (; k < len; k++) {
  691:             if (k in t && t[k] === searchElement) {
  692:                 return k;
  693:             }
  694:         }
  695:         return -1;
  696:     }
  697: }
  698: 
  699: // ]]>
  700: </script>
  701: 
  702: ENDJS
  703: 
  704: }
  705: 
  706: sub userbrowser_javascript {
  707:     my $id_functions = &javascript_index_functions();
  708:     return <<"ENDUSERBRW";
  709: 
  710: function openuserbrowser(formname,uname,udom,ulast,ufirst,uemail,hideudom,crsdom,caller) {
  711:     var url = '/adm/pickuser?';
  712:     var userdom = getDomainFromSelectbox(formname,udom);
  713:     if (userdom != null) {
  714:        if (userdom != '') {
  715:            url += 'srchdom='+userdom+'&';
  716:        }
  717:     }
  718:     url += 'form=' + formname + '&unameelement='+uname+
  719:                                 '&udomelement='+udom+
  720:                                 '&ulastelement='+ulast+
  721:                                 '&ufirstelement='+ufirst+
  722:                                 '&uemailelement='+uemail+
  723:                                 '&hideudomelement='+hideudom+
  724:                                 '&coursedom='+crsdom;
  725:     if ((caller != null) && (caller != undefined)) {
  726:         url += '&caller='+caller;
  727:     }
  728:     var title = 'User_Browser';
  729:     var options = 'scrollbars=1,resizable=1,menubar=0';
  730:     options += ',width=700,height=600';
  731:     var stdeditbrowser = open(url,title,options,'1');
  732:     stdeditbrowser.focus();
  733: }
  734: 
  735: function fix_domain (formname,udom,origdom,uname) {
  736:     var formid = getFormIdByName(formname);
  737:     if (formid > -1) {
  738:         var unameid = getIndexByName(formid,uname);
  739:         var domid = getIndexByName(formid,udom);
  740:         var hidedomid = getIndexByName(formid,origdom);
  741:         if (hidedomid > -1) {
  742:             var fixeddom = document.forms[formid].elements[hidedomid].value;
  743:             var unameval = document.forms[formid].elements[unameid].value;
  744:             if ((fixeddom != '') && (fixeddom != undefined) && (fixeddom != null) && (unameval != '') && (unameval != undefined) && (unameval != null)) {
  745:                 if (domid > -1) {
  746:                     var slct = document.forms[formid].elements[domid];
  747:                     if (slct.type == 'select-one') {
  748:                         var i;
  749:                         for (i=0;i<slct.length;i++) {
  750:                             if (slct.options[i].value==fixeddom) { slct.selectedIndex=i; }
  751:                         }
  752:                     }
  753:                     if (slct.type == 'hidden') {
  754:                         slct.value = fixeddom;
  755:                     }
  756:                 }
  757:             }
  758:         }
  759:     }
  760:     return;
  761: }
  762: 
  763: $id_functions
  764: ENDUSERBRW
  765: }
  766: 
  767: sub setsec_javascript {
  768:     my ($sec_element,$formname,$role_element,$credits_element) = @_;
  769:     my (@courserolenames,@communityrolenames,$rolestr,$courserolestr,
  770:         $communityrolestr);
  771:     if ($role_element ne '') {
  772:         my @allroles = ('st','ta','ep','in','ad');
  773:         foreach my $crstype ('Course','Community') {
  774:             if ($crstype eq 'Community') {
  775:                 foreach my $role (@allroles) {
  776:                     push(@communityrolenames,&Apache::lonnet::plaintext($role,$crstype));
  777:                 }
  778:                 push(@communityrolenames,&Apache::lonnet::plaintext('co'));
  779:             } else {
  780:                 foreach my $role (@allroles) {
  781:                     push(@courserolenames,&Apache::lonnet::plaintext($role,$crstype));
  782:                 }
  783:                 push(@courserolenames,&Apache::lonnet::plaintext('cc'));
  784:             }
  785:         }
  786:         $rolestr = '"'.join('","',@allroles).'"';
  787:         $courserolestr = '"'.join('","',@courserolenames).'"';
  788:         $communityrolestr = '"'.join('","',@communityrolenames).'"';
  789:     }
  790:     my $setsections = qq|
  791: function setSect(sectionlist) {
  792:     var sectionsArray = new Array();
  793:     if ((sectionlist != '') && (typeof sectionlist != "undefined")) {
  794:         sectionsArray = sectionlist.split(",");
  795:     }
  796:     var numSections = sectionsArray.length;
  797:     document.$formname.$sec_element.length = 0;
  798:     if (numSections == 0) {
  799:         document.$formname.$sec_element.multiple=false;
  800:         document.$formname.$sec_element.size=1;
  801:         document.$formname.$sec_element.options[0] = new Option('No existing sections','',false,false)
  802:     } else {
  803:         if (numSections == 1) {
  804:             document.$formname.$sec_element.multiple=false;
  805:             document.$formname.$sec_element.size=1;
  806:             document.$formname.$sec_element.options[0] = new Option('Select','',true,true);
  807:             document.$formname.$sec_element.options[1] = new Option('No section','',false,false)
  808:             document.$formname.$sec_element.options[2] = new Option(sectionsArray[0],sectionsArray[0],false,false);
  809:         } else {
  810:             for (var i=0; i<numSections; i++) {
  811:                 document.$formname.$sec_element.options[i] = new Option(sectionsArray[i],sectionsArray[i],false,false)
  812:             }
  813:             document.$formname.$sec_element.multiple=true
  814:             if (numSections < 3) {
  815:                 document.$formname.$sec_element.size=numSections;
  816:             } else {
  817:                 document.$formname.$sec_element.size=3;
  818:             }
  819:             document.$formname.$sec_element.options[0].selected = false
  820:         }
  821:     }
  822: }
  823: 
  824: function setRole(crstype) {
  825: |;
  826:     if ($role_element eq '') {
  827:         $setsections .= '    return;
  828: }
  829: ';
  830:     } else {
  831:         $setsections .= qq|
  832:     var elementLength = document.$formname.$role_element.length;
  833:     var allroles = Array($rolestr);
  834:     var courserolenames = Array($courserolestr);
  835:     var communityrolenames = Array($communityrolestr);
  836:     if (elementLength != undefined) {
  837:         if (document.$formname.$role_element.options[5].value == 'cc') {
  838:             if (crstype == 'Course') {
  839:                 return;
  840:             } else {
  841:                 allroles[5] = 'co';
  842:                 for (var i=0; i<6; i++) {
  843:                     document.$formname.$role_element.options[i].value = allroles[i];
  844:                     document.$formname.$role_element.options[i].text = communityrolenames[i];
  845:                 }
  846:             }
  847:         } else {
  848:             if (crstype == 'Community') {
  849:                 return;
  850:             } else {
  851:                 allroles[5] = 'cc';
  852:                 for (var i=0; i<6; i++) {
  853:                     document.$formname.$role_element.options[i].value = allroles[i];
  854:                     document.$formname.$role_element.options[i].text = courserolenames[i];
  855:                 }
  856:             }
  857:         }
  858:     }
  859:     return;
  860: }
  861: |;
  862:     }
  863:     if ($credits_element) {
  864:         $setsections .= qq|
  865: function setCredits(defaultcredits) {
  866:     document.$formname.$credits_element.value = defaultcredits;
  867:     return;
  868: }
  869: |;
  870:     }
  871:     return $setsections;
  872: }
  873: 
  874: sub selectcourse_link {
  875:    my ($form,$unameele,$udomele,$desc,$extra_element,$multflag,$selecttype,
  876:        $typeelement) = @_;
  877:    my $type = $selecttype;
  878:    my $linktext = &mt('Select Course');
  879:    if ($selecttype eq 'Community') {
  880:        $linktext = &mt('Select Community');
  881:    } elsif ($selecttype eq 'Course/Community') {
  882:        $linktext = &mt('Select Course/Community');
  883:        $type = '';
  884:    } elsif ($selecttype eq 'Select') {
  885:        $linktext = &mt('Select');
  886:        $type = '';
  887:    }
  888:    return '<span class="LC_nobreak">'
  889:          ."<a href='"
  890:          .'javascript:opencrsbrowser("'.$form.'","'.$unameele
  891:          .'","'.$udomele.'","'.$desc.'","'.$extra_element
  892:          .'","'.$multflag.'","'.$type.'","'.$typeelement.'");'
  893:          ."'>".$linktext.'</a>'
  894:          .'</span>';
  895: }
  896: 
  897: sub selectauthor_link {
  898:    my ($form,$udom)=@_;
  899:    return '<a href="javascript:openauthorbrowser('."'$form','$udom'".');">'.
  900:           &mt('Select Author').'</a>';
  901: }
  902: 
  903: sub selectuser_link {
  904:     my ($form,$unameelem,$domelem,$lastelem,$firstelem,$emailelem,$hdomelem,
  905:         $coursedom,$linktext,$caller) = @_;
  906:     return '<a href="javascript:openuserbrowser('."'$form','$unameelem','$domelem',".
  907:            "'$lastelem','$firstelem','$emailelem','$hdomelem','$coursedom','$caller'".
  908:            ');">'.$linktext.'</a>';
  909: }
  910: 
  911: sub check_uncheck_jscript {
  912:     my $jscript = <<"ENDSCRT";
  913: function checkAll(field) {
  914:     if (field.length > 0) {
  915:         for (i = 0; i < field.length; i++) {
  916:             if (!field[i].disabled) {
  917:                 field[i].checked = true;
  918:             }
  919:         }
  920:     } else {
  921:         if (!field.disabled) {
  922:             field.checked = true;
  923:         }
  924:     }
  925: }
  926:  
  927: function uncheckAll(field) {
  928:     if (field.length > 0) {
  929:         for (i = 0; i < field.length; i++) {
  930:             field[i].checked = false ;
  931:         }
  932:     } else {
  933:         field.checked = false ;
  934:     }
  935: }
  936: ENDSCRT
  937:     return $jscript;
  938: }
  939: 
  940: sub select_timezone {
  941:    my ($name,$selected,$onchange,$includeempty,$disabled)=@_;
  942:    my $output='<select name="'.$name.'" '.$onchange.$disabled.'>'."\n";
  943:    if ($includeempty) {
  944:        $output .= '<option value=""';
  945:        if (($selected eq '') || ($selected eq 'local')) {
  946:            $output .= ' selected="selected" ';
  947:        }
  948:        $output .= '> </option>';
  949:    }
  950:    my @timezones = DateTime::TimeZone->all_names;
  951:    foreach my $tzone (@timezones) {
  952:        $output.= '<option value="'.$tzone.'"';
  953:        if ($tzone eq $selected) {
  954:            $output.=' selected="selected"';
  955:        }
  956:        $output.=">$tzone</option>\n";
  957:    }
  958:    $output.="</select>";
  959:    return $output;
  960: }
  961: 
  962: sub select_datelocale {
  963:     my ($name,$selected,$onchange,$includeempty,$disabled)=@_;
  964:     my $output='<select name="'.$name.'" '.$onchange.$disabled.'>'."\n";
  965:     if ($includeempty) {
  966:         $output .= '<option value=""';
  967:         if ($selected eq '') {
  968:             $output .= ' selected="selected" ';
  969:         }
  970:         $output .= '> </option>';
  971:     }
  972:     my @languages = &Apache::lonlocal::preferred_languages();
  973:     my (@possibles,%locale_names);
  974:     my @locales = DateTime::Locale->ids();
  975:     foreach my $id (@locales) {
  976:         if ($id ne '') {
  977:             my ($en_terr,$native_terr);
  978:             my $loc = DateTime::Locale->load($id);
  979:             if (ref($loc)) {
  980:                 $en_terr = $loc->name();
  981:                 $native_terr = $loc->native_name();
  982:                 if (grep(/^en$/,@languages) || !@languages) {
  983:                     if ($en_terr ne '') {
  984:                         $locale_names{$id} = '('.$en_terr.')';
  985:                     } elsif ($native_terr ne '') {
  986:                         $locale_names{$id} = $native_terr;
  987:                     }
  988:                 } else {
  989:                     if ($native_terr ne '') {
  990:                         $locale_names{$id} = $native_terr.' ';
  991:                     } elsif ($en_terr ne '') {
  992:                         $locale_names{$id} = '('.$en_terr.')';
  993:                     }
  994:                 }
  995:                 $locale_names{$id} = Encode::encode('UTF-8',$locale_names{$id});
  996:                 push(@possibles,$id);
  997:             }
  998:         }
  999:     }
 1000:     foreach my $item (sort(@possibles)) {
 1001:         $output.= '<option value="'.$item.'"';
 1002:         if ($item eq $selected) {
 1003:             $output.=' selected="selected"';
 1004:         }
 1005:         $output.=">$item";
 1006:         if ($locale_names{$item} ne '') {
 1007:             $output.='  '.$locale_names{$item};
 1008:         }
 1009:         $output.="</option>\n";
 1010:     }
 1011:     $output.="</select>";
 1012:     return $output;
 1013: }
 1014: 
 1015: sub select_language {
 1016:     my ($name,$selected,$includeempty,$noedit) = @_;
 1017:     my %langchoices;
 1018:     if ($includeempty) {
 1019:         %langchoices = ('' => 'No language preference');
 1020:     }
 1021:     foreach my $id (&languageids()) {
 1022:         my $code = &supportedlanguagecode($id);
 1023:         if ($code) {
 1024:             $langchoices{$code} = &plainlanguagedescription($id);
 1025:         }
 1026:     }
 1027:     %langchoices = &Apache::lonlocal::texthash(%langchoices);
 1028:     return &select_form($selected,$name,\%langchoices,undef,$noedit);
 1029: }
 1030: 
 1031: =pod
 1032: 
 1033: =item * &linked_select_forms(...)
 1034: 
 1035: linked_select_forms returns a string containing a <script></script> block
 1036: and html for two <select> menus.  The select menus will be linked in that
 1037: changing the value of the first menu will result in new values being placed
 1038: in the second menu.  The values in the select menu will appear in alphabetical
 1039: order unless a defined order is provided.
 1040: 
 1041: linked_select_forms takes the following ordered inputs:
 1042: 
 1043: =over 4
 1044: 
 1045: =item * $formname, the name of the <form> tag
 1046: 
 1047: =item * $middletext, the text which appears between the <select> tags
 1048: 
 1049: =item * $firstdefault, the default value for the first menu
 1050: 
 1051: =item * $firstselectname, the name of the first <select> tag
 1052: 
 1053: =item * $secondselectname, the name of the second <select> tag
 1054: 
 1055: =item * $hashref, a reference to a hash containing the data for the menus.
 1056: 
 1057: =item * $menuorder, the order of values in the first menu
 1058: 
 1059: =item * $onchangefirst, additional javascript call to execute for an onchange
 1060:         event for the first <select> tag
 1061: 
 1062: =item * $onchangesecond, additional javascript call to execute for an onchange
 1063:         event for the second <select> tag
 1064: 
 1065: =back 
 1066: 
 1067: Below is an example of such a hash.  Only the 'text', 'default', and 
 1068: 'select2' keys must appear as stated.  keys(%menu) are the possible 
 1069: values for the first select menu.  The text that coincides with the 
 1070: first menu value is given in $menu{$choice1}->{'text'}.  The values 
 1071: and text for the second menu are given in the hash pointed to by 
 1072: $menu{$choice1}->{'select2'}.  
 1073: 
 1074:  my %menu = ( A1 => { text =>"Choice A1" ,
 1075:                        default => "B3",
 1076:                        select2 => { 
 1077:                            B1 => "Choice B1",
 1078:                            B2 => "Choice B2",
 1079:                            B3 => "Choice B3",
 1080:                            B4 => "Choice B4"
 1081:                            },
 1082:                        order => ['B4','B3','B1','B2'],
 1083:                    },
 1084:                A2 => { text =>"Choice A2" ,
 1085:                        default => "C2",
 1086:                        select2 => { 
 1087:                            C1 => "Choice C1",
 1088:                            C2 => "Choice C2",
 1089:                            C3 => "Choice C3"
 1090:                            },
 1091:                        order => ['C2','C1','C3'],
 1092:                    },
 1093:                A3 => { text =>"Choice A3" ,
 1094:                        default => "D6",
 1095:                        select2 => { 
 1096:                            D1 => "Choice D1",
 1097:                            D2 => "Choice D2",
 1098:                            D3 => "Choice D3",
 1099:                            D4 => "Choice D4",
 1100:                            D5 => "Choice D5",
 1101:                            D6 => "Choice D6",
 1102:                            D7 => "Choice D7"
 1103:                            },
 1104:                        order => ['D4','D3','D2','D1','D7','D6','D5'],
 1105:                    }
 1106:                );
 1107: 
 1108: =cut
 1109: 
 1110: sub linked_select_forms {
 1111:     my ($formname,
 1112:         $middletext,
 1113:         $firstdefault,
 1114:         $firstselectname,
 1115:         $secondselectname, 
 1116:         $hashref,
 1117:         $menuorder,
 1118:         $onchangefirst,
 1119:         $onchangesecond
 1120:         ) = @_;
 1121:     my $second = "document.$formname.$secondselectname";
 1122:     my $first = "document.$formname.$firstselectname";
 1123:     # output the javascript to do the changing
 1124:     my $result = '';
 1125:     $result.='<script type="text/javascript" language="JavaScript">'."\n";
 1126:     $result.="// <![CDATA[\n";
 1127:     $result.="var select2data = new Object();\n";
 1128:     $" = '","';
 1129:     my $debug = '';
 1130:     foreach my $s1 (sort(keys(%$hashref))) {
 1131:         $result.="select2data.d_$s1 = new Object();\n";        
 1132:         $result.="select2data.d_$s1.def = new String('".
 1133:             $hashref->{$s1}->{'default'}."');\n";
 1134:         $result.="select2data.d_$s1.values = new Array(";
 1135:         my @s2values = sort(keys( %{ $hashref->{$s1}->{'select2'} } ));
 1136:         if (ref($hashref->{$s1}->{'order'}) eq 'ARRAY') {
 1137:             @s2values = @{$hashref->{$s1}->{'order'}};
 1138:         }
 1139:         $result.="\"@s2values\");\n";
 1140:         $result.="select2data.d_$s1.texts = new Array(";        
 1141:         my @s2texts;
 1142:         foreach my $value (@s2values) {
 1143:             push(@s2texts, $hashref->{$s1}->{'select2'}->{$value});
 1144:         }
 1145:         $result.="\"@s2texts\");\n";
 1146:     }
 1147:     $"=' ';
 1148:     $result.= <<"END";
 1149: 
 1150: function select1_changed() {
 1151:     // Determine new choice
 1152:     var newvalue = "d_" + $first.value;
 1153:     // update select2
 1154:     var values     = select2data[newvalue].values;
 1155:     var texts      = select2data[newvalue].texts;
 1156:     var select2def = select2data[newvalue].def;
 1157:     var i;
 1158:     // out with the old
 1159:     for (i = 0; i < $second.options.length; i++) {
 1160:         $second.options[i] = null;
 1161:     }
 1162:     // in with the nuclear
 1163:     for (i=0;i<values.length; i++) {
 1164:         $second.options[i] = new Option(values[i]);
 1165:         $second.options[i].value = values[i];
 1166:         $second.options[i].text = texts[i];
 1167:         if (values[i] == select2def) {
 1168:             $second.options[i].selected = true;
 1169:         }
 1170:     }
 1171: }
 1172: // ]]>
 1173: </script>
 1174: END
 1175:     # output the initial values for the selection lists
 1176:     $result .= "<select size=\"1\" name=\"$firstselectname\" onchange=\"select1_changed();$onchangefirst\">\n";
 1177:     my @order = sort(keys(%{$hashref}));
 1178:     if (ref($menuorder) eq 'ARRAY') {
 1179:         @order = @{$menuorder};
 1180:     }
 1181:     foreach my $value (@order) {
 1182:         $result.="    <option value=\"$value\" ";
 1183:         $result.=" selected=\"selected\" " if ($value eq $firstdefault);
 1184:         $result.=">".&mt($hashref->{$value}->{'text'})."</option>\n";
 1185:     }
 1186:     $result .= "</select>\n";
 1187:     my %select2 = %{$hashref->{$firstdefault}->{'select2'}};
 1188:     $result .= $middletext;
 1189:     $result .= "<select size=\"1\" name=\"$secondselectname\"";
 1190:     if ($onchangesecond) {
 1191:         $result .= ' onchange="'.$onchangesecond.'"';
 1192:     }
 1193:     $result .= ">\n";
 1194:     my $seconddefault = $hashref->{$firstdefault}->{'default'};
 1195:     
 1196:     my @secondorder = sort(keys(%select2));
 1197:     if (ref($hashref->{$firstdefault}->{'order'}) eq 'ARRAY') {
 1198:         @secondorder = @{$hashref->{$firstdefault}->{'order'}};
 1199:     }
 1200:     foreach my $value (@secondorder) {
 1201:         $result.="    <option value=\"$value\" ";        
 1202:         $result.=" selected=\"selected\" " if ($value eq $seconddefault);
 1203:         $result.=">".&mt($select2{$value})."</option>\n";
 1204:     }
 1205:     $result .= "</select>\n";
 1206:     #    return $debug;
 1207:     return $result;
 1208: }   #  end of sub linked_select_forms {
 1209: 
 1210: =pod
 1211: 
 1212: =item * &help_open_topic($topic,$text,$stayOnPage,$width,$height,$imgid)
 1213: 
 1214: Returns a string corresponding to an HTML link to the given help
 1215: $topic, where $topic corresponds to the name of a .tex file in
 1216: /home/httpd/html/adm/help/tex, with underscores replaced by
 1217: spaces. 
 1218: 
 1219: $text will optionally be linked to the same topic, allowing you to
 1220: link text in addition to the graphic. If you do not want to link
 1221: text, but wish to specify one of the later parameters, pass an
 1222: empty string. 
 1223: 
 1224: $stayOnPage is a value that will be interpreted as a boolean. If true,
 1225: the link will not open a new window. If false, the link will open
 1226: a new window using Javascript. (Default is false.) 
 1227: 
 1228: $width and $height are optional numerical parameters that will
 1229: override the width and height of the popped up window, which may
 1230: be useful for certain help topics with big pictures included.
 1231: 
 1232: $imgid is the id of the img tag used for the help icon. This may be
 1233: used in a javascript call to switch the image src.  See 
 1234: lonhtmlcommon::htmlareaselectactive() for an example.
 1235: 
 1236: =cut
 1237: 
 1238: sub help_open_topic {
 1239:     my ($topic, $text, $stayOnPage, $width, $height, $imgid) = @_;
 1240:     $text = "" if (not defined $text);
 1241:     $stayOnPage = 0 if (not defined $stayOnPage);
 1242:     $width = 500 if (not defined $width);
 1243:     $height = 400 if (not defined $height);
 1244:     my $filename = $topic;
 1245:     $filename =~ s/ /_/g;
 1246: 
 1247:     my $template = "";
 1248:     my $link;
 1249:     
 1250:     $topic=~s/\W/\_/g;
 1251: 
 1252:     if (!$stayOnPage) {
 1253:         if ($env{'browser.mobile'}) {
 1254: 	    $link = "javascript:openMyModal('/adm/help/${filename}.hlp',$width,$height,'yes');";
 1255:         } else {
 1256:             $link = "javascript:void(open('/adm/help/${filename}.hlp', 'Help_for_$topic', 'menubar=0,toolbar=1,scrollbars=1,width=$width,height=$height,resizable=yes'))";
 1257:         }
 1258:     } elsif ($stayOnPage eq 'popup') {
 1259:         $link = "javascript:void(open('/adm/help/${filename}.hlp', 'Help_for_$topic', 'menubar=0,toolbar=1,scrollbars=1,width=$width,height=$height,resizable=yes'))";
 1260:     } else {
 1261: 	$link = "/adm/help/${filename}.hlp";
 1262:     }
 1263: 
 1264:     # Add the text
 1265:     if ($text ne "") {	
 1266: 	$template.='<span class="LC_help_open_topic">'
 1267:                   .'<a target="_top" href="'.$link.'">'
 1268:                   .$text.'</a>';
 1269:     }
 1270: 
 1271:     # (Always) Add the graphic
 1272:     my $title = &mt('Online Help');
 1273:     my $helpicon=&lonhttpdurl("/adm/help/help.png");
 1274:     if ($imgid ne '') {
 1275:         $imgid = ' id="'.$imgid.'"';
 1276:     }
 1277:     $template.=' <a target="_top" href="'.$link.'" title="'.$title.'">'
 1278:               .'<img src="'.$helpicon.'" border="0"'
 1279:               .' alt="'.&mt('Help: [_1]',$topic).'"'
 1280:               .' title="'.$title.'" style="vertical-align:middle;"'.$imgid 
 1281:               .' /></a>';
 1282:     if ($text ne "") {	
 1283:         $template.='</span>';
 1284:     }
 1285:     return $template;
 1286: 
 1287: }
 1288: 
 1289: # This is a quicky function for Latex cheatsheet editing, since it 
 1290: # appears in at least four places
 1291: sub helpLatexCheatsheet {
 1292:     my ($topic,$text,$not_author,$stayOnPage) = @_;
 1293:     my $out;
 1294:     my $addOther = '';
 1295:     if ($topic) {
 1296: 	$addOther = '<span>'.&help_open_topic($topic,&mt($text),$stayOnPage, undef, 600).'</span> ';
 1297:     }
 1298:     $out = '<span>' # Start cheatsheet
 1299: 	  .$addOther
 1300:           .'<span>'
 1301: 	  .&help_open_topic('Greek_Symbols',&mt('Greek Symbols'),$stayOnPage,undef,600)
 1302: 	  .'</span> <span>'
 1303: 	  .&help_open_topic('Other_Symbols',&mt('Other Symbols'),$stayOnPage,undef,600)
 1304: 	  .'</span>';
 1305:     unless ($not_author) {
 1306:         $out .= ' <span>'
 1307: 	       .&help_open_topic('Authoring_Output_Tags',&mt('Output Tags'),$stayOnPage,undef,600)
 1308: 	       .'</span> <span>'
 1309:                .&help_open_topic('Authoring_Multilingual_Problems',&mt('Languages'),$stayOnPage,undef,600)
 1310:                .'</span>';
 1311:     }
 1312:     $out .= '</span>'; # End cheatsheet
 1313:     return $out;
 1314: }
 1315: 
 1316: sub general_help {
 1317:     my $helptopic='Student_Intro';
 1318:     if ($env{'request.role'}=~/^(ca|au)/) {
 1319: 	$helptopic='Authoring_Intro';
 1320:     } elsif ($env{'request.role'}=~/^(cc|co)/) {
 1321: 	$helptopic='Course_Coordination_Intro';
 1322:     } elsif ($env{'request.role'}=~/^dc/) {
 1323:         $helptopic='Domain_Coordination_Intro';
 1324:     }
 1325:     return $helptopic;
 1326: }
 1327: 
 1328: sub update_help_link {
 1329:     my ($topic,$component_help,$faq,$bug,$stayOnPage) = @_;
 1330:     my $origurl = $ENV{'REQUEST_URI'};
 1331:     $origurl=~s|^/~|/priv/|;
 1332:     my $timestamp = time;
 1333:     foreach my $datum (\$topic,\$component_help,\$faq,\$bug,\$origurl) {
 1334:         $$datum = &escape($$datum);
 1335:     }
 1336: 
 1337:     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";
 1338:     my $output .= <<"ENDOUTPUT";
 1339: <script type="text/javascript">
 1340: // <![CDATA[
 1341: banner_link = '$banner_link';
 1342: // ]]>
 1343: </script>
 1344: ENDOUTPUT
 1345:     return $output;
 1346: }
 1347: 
 1348: # now just updates the help link and generates a blue icon
 1349: sub help_open_menu {
 1350:     my ($topic,$component_help,$faq,$bug,$stayOnPage,$width,$height,$text) 
 1351: 	= @_;    
 1352:     $stayOnPage = 1;
 1353:     my $output;
 1354:     if ($component_help) {
 1355: 	if (!$text) {
 1356: 	    $output=&help_open_topic($component_help,undef,$stayOnPage,
 1357: 				       $width,$height);
 1358: 	} else {
 1359: 	    my $help_text;
 1360: 	    $help_text=&unescape($topic);
 1361: 	    $output='<table><tr><td>'.
 1362: 		&help_open_topic($component_help,$help_text,$stayOnPage,
 1363: 				 $width,$height).'</td></tr></table>';
 1364: 	}
 1365:     }
 1366:     my $banner_link = &update_help_link($topic,$component_help,$faq,$bug,$stayOnPage);
 1367:     return $output.$banner_link;
 1368: }
 1369: 
 1370: sub top_nav_help {
 1371:     my ($text) = @_;
 1372:     $text = &mt($text);
 1373:     my $stay_on_page;
 1374:     unless ($env{'environment.remote'} eq 'on') {
 1375:         $stay_on_page = 1;
 1376:     }
 1377:     my ($link,$banner_link);
 1378:     unless ($env{'request.noversionuri'} =~ m{^/adm/helpmenu}) {
 1379:         $link = ($stay_on_page) ? "javascript:helpMenu('display')"
 1380: 	                         : "javascript:helpMenu('open')";
 1381:         $banner_link = &update_help_link(undef,undef,undef,undef,$stay_on_page);
 1382:     }
 1383:     my $title = &mt('Get help');
 1384:     if ($link) {
 1385:         return <<"END";
 1386: $banner_link
 1387: <a href="$link" title="$title">$text</a>
 1388: END
 1389:     } else {
 1390:         return '&nbsp;'.$text.'&nbsp;';
 1391:     }
 1392: }
 1393: 
 1394: sub help_menu_js {
 1395:     my ($httphost) = @_;
 1396:     my $stayOnPage = 1;
 1397:     my $width = 620;
 1398:     my $height = 600;
 1399:     my $helptopic=&general_help();
 1400:     my $details_link = $httphost.'/adm/help/'.$helptopic.'.hlp';
 1401:     my $nothing=&Apache::lonhtmlcommon::javascript_nothing();
 1402:     my $start_page =
 1403:         &Apache::loncommon::start_page('Help Menu', undef,
 1404: 				       {'frameset'    => 1,
 1405: 					'js_ready'    => 1,
 1406:                                         'use_absolute' => $httphost, 
 1407: 					'add_entries' => {
 1408: 					    'border' => '0',
 1409: 					    'rows'   => "110,*",},});
 1410:     my $end_page =
 1411:         &Apache::loncommon::end_page({'frameset' => 1,
 1412: 				      'js_ready' => 1,});
 1413: 
 1414:     my $template .= <<"ENDTEMPLATE";
 1415: <script type="text/javascript">
 1416: // <![CDATA[
 1417: // <!-- BEGIN LON-CAPA Internal
 1418: var banner_link = '';
 1419: function helpMenu(target) {
 1420:     var caller = this;
 1421:     if (target == 'open') {
 1422:         var newWindow = null;
 1423:         try {
 1424:             newWindow =  window.open($nothing,"helpmenu","HEIGHT=$height,WIDTH=$width,resizable=yes,scrollbars=yes" )
 1425:         }
 1426:         catch(error) {
 1427:             writeHelp(caller);
 1428:             return;
 1429:         }
 1430:         if (newWindow) {
 1431:             caller = newWindow;
 1432:         }
 1433:     }
 1434:     writeHelp(caller);
 1435:     return;
 1436: }
 1437: function writeHelp(caller) {
 1438:     caller.document.writeln('$start_page\\n<frame name="bannerframe" src="'+banner_link+'" marginwidth="0" marginheight="0" frameborder="0">\\n');
 1439:     caller.document.writeln('<frame name="bodyframe" src="$details_link" marginwidth="0" marginheight="0" frameborder="0">\\n$end_page');
 1440:     caller.document.close();
 1441:     caller.focus();
 1442: }
 1443: // END LON-CAPA Internal -->
 1444: // ]]>
 1445: </script>
 1446: ENDTEMPLATE
 1447:     return $template;
 1448: }
 1449: 
 1450: sub help_open_bug {
 1451:     my ($topic, $text, $stayOnPage, $width, $height) = @_;
 1452:     unless ($env{'user.adv'}) { return ''; }
 1453:     unless ($Apache::lonnet::perlvar{'BugzillaHost'}) { return ''; }
 1454:     $text = "" if (not defined $text);
 1455: 	$stayOnPage=1;
 1456:     $width = 600 if (not defined $width);
 1457:     $height = 600 if (not defined $height);
 1458: 
 1459:     $topic=~s/\W+/\+/g;
 1460:     my $link='';
 1461:     my $template='';
 1462:     my $url=$Apache::lonnet::perlvar{'BugzillaHost'}.'enter_bug.cgi?product=LON-CAPA&amp;bug_file_loc='.
 1463: 	&escape($ENV{'REQUEST_URI'}).'&amp;component='.$topic;
 1464:     if (!$stayOnPage)
 1465:     {
 1466: 	$link = "javascript:void(open('$url', 'Bugzilla', 'menubar=0,toolbar=1,scrollbars=1,width=$width,height=$height,resizable=yes'))";
 1467:     }
 1468:     else
 1469:     {
 1470: 	$link = $url;
 1471:     }
 1472:     # Add the text
 1473:     if ($text ne "")
 1474:     {
 1475: 	$template .= 
 1476:   "<table bgcolor='#AA3333' cellspacing='1' cellpadding='1' border='0'><tr>".
 1477:   "<td bgcolor='#FF5555'><a target=\"_top\" href=\"$link\"><span style=\"color:#FFFFFF;font-size:10pt;\">$text</span></a>";
 1478:     }
 1479: 
 1480:     # Add the graphic
 1481:     my $title = &mt('Report a Bug');
 1482:     my $bugicon=&lonhttpdurl("/adm/lonMisc/smallBug.gif");
 1483:     $template .= <<"ENDTEMPLATE";
 1484:  <a target="_top" href="$link" title="$title"><img src="$bugicon" border="0" alt="(Bug: $topic)" /></a>
 1485: ENDTEMPLATE
 1486:     if ($text ne '') { $template.='</td></tr></table>' };
 1487:     return $template;
 1488: 
 1489: }
 1490: 
 1491: sub help_open_faq {
 1492:     my ($topic, $text, $stayOnPage, $width, $height) = @_;
 1493:     unless ($env{'user.adv'}) { return ''; }
 1494:     unless ($Apache::lonnet::perlvar{'FAQHost'}) { return ''; }
 1495:     $text = "" if (not defined $text);
 1496: 	$stayOnPage=1;
 1497:     $width = 350 if (not defined $width);
 1498:     $height = 400 if (not defined $height);
 1499: 
 1500:     $topic=~s/\W+/\+/g;
 1501:     my $link='';
 1502:     my $template='';
 1503:     my $url=$Apache::lonnet::perlvar{'FAQHost'}.'/fom/cache/'.$topic.'.html';
 1504:     if (!$stayOnPage)
 1505:     {
 1506: 	$link = "javascript:void(open('$url', 'FAQ-O-Matic', 'menubar=0,toolbar=1,scrollbars=1,width=$width,height=$height,resizable=yes'))";
 1507:     }
 1508:     else
 1509:     {
 1510: 	$link = $url;
 1511:     }
 1512: 
 1513:     # Add the text
 1514:     if ($text ne "")
 1515:     {
 1516: 	$template .= 
 1517:   "<table bgcolor='#337733' cellspacing='1' cellpadding='1' border='0'><tr>".
 1518:   "<td bgcolor='#448844'><a target=\"_top\" href=\"$link\"><span style=\"color:#FFFFFF; font-size:10pt;\">$text</span></a>";
 1519:     }
 1520: 
 1521:     # Add the graphic
 1522:     my $title = &mt('View the FAQ');
 1523:     my $faqicon=&lonhttpdurl("/adm/lonMisc/smallFAQ.gif");
 1524:     $template .= <<"ENDTEMPLATE";
 1525:  <a target="_top" href="$link" title="$title"><img src="$faqicon" border="0" alt="(FAQ: $topic)" /></a>
 1526: ENDTEMPLATE
 1527:     if ($text ne '') { $template.='</td></tr></table>' };
 1528:     return $template;
 1529: 
 1530: }
 1531: 
 1532: ###############################################################
 1533: ###############################################################
 1534: 
 1535: =pod
 1536: 
 1537: =item * &change_content_javascript():
 1538: 
 1539: This and the next function allow you to create small sections of an
 1540: otherwise static HTML page that you can update on the fly with
 1541: Javascript, even in Netscape 4.
 1542: 
 1543: The Javascript fragment returned by this function (no E<lt>scriptE<gt> tag)
 1544: must be written to the HTML page once. It will prove the Javascript
 1545: function "change(name, content)". Calling the change function with the
 1546: name of the section 
 1547: you want to update, matching the name passed to C<changable_area>, and
 1548: the new content you want to put in there, will put the content into
 1549: that area.
 1550: 
 1551: B<Note>: Netscape 4 only reserves enough space for the changable area
 1552: to contain room for the original contents. You need to "make space"
 1553: for whatever changes you wish to make, and be B<sure> to check your
 1554: code in Netscape 4. This feature in Netscape 4 is B<not> powerful;
 1555: it's adequate for updating a one-line status display, but little more.
 1556: This script will set the space to 100% width, so you only need to
 1557: worry about height in Netscape 4.
 1558: 
 1559: Modern browsers are much less limiting, and if you can commit to the
 1560: user not using Netscape 4, this feature may be used freely with
 1561: pretty much any HTML.
 1562: 
 1563: =cut
 1564: 
 1565: sub change_content_javascript {
 1566:     # If we're on Netscape 4, we need to use Layer-based code
 1567:     if ($env{'browser.type'} eq 'netscape' &&
 1568: 	$env{'browser.version'} =~ /^4\./) {
 1569: 	return (<<NETSCAPE4);
 1570: 	function change(name, content) {
 1571: 	    doc = document.layers[name+"___escape"].layers[0].document;
 1572: 	    doc.open();
 1573: 	    doc.write(content);
 1574: 	    doc.close();
 1575: 	}
 1576: NETSCAPE4
 1577:     } else {
 1578: 	# Otherwise, we need to use semi-standards-compliant code
 1579: 	# (technically, "innerHTML" isn't standard but the equivalent
 1580: 	# is really scary, and every useful browser supports it
 1581: 	return (<<DOMBASED);
 1582: 	function change(name, content) {
 1583: 	    element = document.getElementById(name);
 1584: 	    element.innerHTML = content;
 1585: 	}
 1586: DOMBASED
 1587:     }
 1588: }
 1589: 
 1590: =pod
 1591: 
 1592: =item * &changable_area($name,$origContent):
 1593: 
 1594: This provides a "changable area" that can be modified on the fly via
 1595: the Javascript code provided in C<change_content_javascript>. $name is
 1596: the name you will use to reference the area later; do not repeat the
 1597: same name on a given HTML page more then once. $origContent is what
 1598: the area will originally contain, which can be left blank.
 1599: 
 1600: =cut
 1601: 
 1602: sub changable_area {
 1603:     my ($name, $origContent) = @_;
 1604: 
 1605:     if ($env{'browser.type'} eq 'netscape' &&
 1606: 	$env{'browser.version'} =~ /^4\./) {
 1607: 	# If this is netscape 4, we need to use the Layer tag
 1608: 	return "<ilayer width='100%' id='${name}___escape' overflow='none'><layer width='100%' id='$name' overflow='none'>$origContent</layer></ilayer>";
 1609:     } else {
 1610: 	return "<span id='$name'>$origContent</span>";
 1611:     }
 1612: }
 1613: 
 1614: =pod
 1615: 
 1616: =item * &viewport_geometry_js 
 1617: 
 1618: Provides javascript object (Geometry) which can provide information about the viewport geometry for the client browser.
 1619: 
 1620: =cut
 1621: 
 1622: 
 1623: sub viewport_geometry_js { 
 1624:     return <<"GEOMETRY";
 1625: var Geometry = {};
 1626: function init_geometry() {
 1627:     if (Geometry.init) { return };
 1628:     Geometry.init=1;
 1629:     if (window.innerHeight) {
 1630:         Geometry.getViewportHeight   = function() { return window.innerHeight; };
 1631:         Geometry.getViewportWidth   = function() { return window.innerWidth; };
 1632:         Geometry.getHorizontalScroll = function() { return window.pageXOffset; };
 1633:         Geometry.getVerticalScroll   = function() { return window.pageYOffset; };
 1634:     }
 1635:     else if (document.documentElement && document.documentElement.clientHeight) {
 1636:         Geometry.getViewportHeight =
 1637:             function() { return document.documentElement.clientHeight; };
 1638:         Geometry.getViewportWidth =
 1639:             function() { return document.documentElement.clientWidth; };
 1640: 
 1641:         Geometry.getHorizontalScroll =
 1642:             function() { return document.documentElement.scrollLeft; };
 1643:         Geometry.getVerticalScroll =
 1644:             function() { return document.documentElement.scrollTop; };
 1645:     }
 1646:     else if (document.body.clientHeight) {
 1647:         Geometry.getViewportHeight =
 1648:             function() { return document.body.clientHeight; };
 1649:         Geometry.getViewportWidth =
 1650:             function() { return document.body.clientWidth; };
 1651:         Geometry.getHorizontalScroll =
 1652:             function() { return document.body.scrollLeft; };
 1653:         Geometry.getVerticalScroll =
 1654:             function() { return document.body.scrollTop; };
 1655:     }
 1656: }
 1657: 
 1658: GEOMETRY
 1659: }
 1660: 
 1661: =pod
 1662: 
 1663: =item * &viewport_size_js()
 1664: 
 1665: 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. 
 1666: 
 1667: =cut
 1668: 
 1669: sub viewport_size_js {
 1670:     my $geometry = &viewport_geometry_js();
 1671:     return <<"DIMS";
 1672: 
 1673: $geometry
 1674: 
 1675: function getViewportDims(width,height) {
 1676:     init_geometry();
 1677:     width.value = Geometry.getViewportWidth();
 1678:     height.value = Geometry.getViewportHeight();
 1679:     return;
 1680: }
 1681: 
 1682: DIMS
 1683: }
 1684: 
 1685: =pod
 1686: 
 1687: =item * &resize_textarea_js()
 1688: 
 1689: emits the needed javascript to resize a textarea to be as big as possible
 1690: 
 1691: creates a function resize_textrea that takes two IDs first should be
 1692: the id of the element to resize, second should be the id of a div that
 1693: surrounds everything that comes after the textarea, this routine needs
 1694: to be attached to the <body> for the onload and onresize events.
 1695: 
 1696: =back
 1697: 
 1698: =cut
 1699: 
 1700: sub resize_textarea_js {
 1701:     my $geometry = &viewport_geometry_js();
 1702:     return <<"RESIZE";
 1703:     <script type="text/javascript">
 1704: // <![CDATA[
 1705: $geometry
 1706: 
 1707: function getX(element) {
 1708:     var x = 0;
 1709:     while (element) {
 1710: 	x += element.offsetLeft;
 1711: 	element = element.offsetParent;
 1712:     }
 1713:     return x;
 1714: }
 1715: function getY(element) {
 1716:     var y = 0;
 1717:     while (element) {
 1718: 	y += element.offsetTop;
 1719: 	element = element.offsetParent;
 1720:     }
 1721:     return y;
 1722: }
 1723: 
 1724: 
 1725: function resize_textarea(textarea_id,bottom_id) {
 1726:     init_geometry();
 1727:     var textarea        = document.getElementById(textarea_id);
 1728:     //alert(textarea);
 1729: 
 1730:     var textarea_top    = getY(textarea);
 1731:     var textarea_height = textarea.offsetHeight;
 1732:     var bottom          = document.getElementById(bottom_id);
 1733:     var bottom_top      = getY(bottom);
 1734:     var bottom_height   = bottom.offsetHeight;
 1735:     var window_height   = Geometry.getViewportHeight();
 1736:     var fudge           = 23;
 1737:     var new_height      = window_height-fudge-textarea_top-bottom_height;
 1738:     if (new_height < 300) {
 1739: 	new_height = 300;
 1740:     }
 1741:     textarea.style.height=new_height+'px';
 1742: }
 1743: // ]]>
 1744: </script>
 1745: RESIZE
 1746: 
 1747: }
 1748: 
 1749: sub colorfuleditor_js {
 1750:     return <<"COLORFULEDIT"
 1751: <script type="text/javascript">
 1752: // <![CDATA[>
 1753:     function fold_box(curDepth, lastresource){
 1754: 
 1755:     // we need a list because there can be several blocks you need to fold in one tag
 1756:         var block = document.getElementsByName('foldblock_'+curDepth);
 1757:     // but there is only one folding button per tag
 1758:         var foldbutton = document.getElementById('folding_btn_'+curDepth);
 1759: 
 1760:         if(block.item(0).style.display == 'none'){
 1761: 
 1762:             foldbutton.value = '@{[&mt("Hide")]}';
 1763:             for (i = 0; i < block.length; i++){
 1764:                 block.item(i).style.display = '';
 1765:             }
 1766:         }else{
 1767: 
 1768:             foldbutton.value = '@{[&mt("Show")]}';
 1769:             for (i = 0; i < block.length; i++){
 1770:                 // block.item(i).style.visibility = 'collapse';
 1771:                 block.item(i).style.display = 'none';
 1772:             }
 1773:         };
 1774:         saveState(lastresource);
 1775:     }
 1776: 
 1777:     function saveState (lastresource) {
 1778: 
 1779:         var tag_list = getTagList();
 1780:         if(tag_list != null){
 1781:             var timestamp = new Date().getTime();
 1782:             var key = lastresource;
 1783: 
 1784:             // the value pattern is: 'time;key1,value1;key2,value2; ... '
 1785:             // starting with timestamp
 1786:             var value = timestamp+';';
 1787: 
 1788:             // building the list of key-value pairs
 1789:             for(var i = 0; i < tag_list.length; i++){
 1790:                 value += tag_list[i]+',';
 1791:                 value += document.getElementsByName(tag_list[i])[0].style.display+';';
 1792:             }
 1793: 
 1794:             // only iterate whole storage if nothing to override
 1795:             if(localStorage.getItem(key) == null){
 1796: 
 1797:                 // prevent storage from growing large
 1798:                 if(localStorage.length > 50){
 1799:                     var regex_getTimestamp = /^(?:\d)+;/;
 1800:                     var oldest_timestamp = regex_getTimestamp.exec(localStorage.key(0));
 1801:                     var oldest_key;
 1802: 
 1803:                     for(var i = 1; i < localStorage.length; i++){
 1804:                         if (regex_getTimestamp.exec(localStorage.key(i)) < oldest_timestamp) {
 1805:                             oldest_key = localStorage.key(i);
 1806:                             oldest_timestamp = regex_getTimestamp.exec(oldest_key);
 1807:                         }
 1808:                     }
 1809:                     localStorage.removeItem(oldest_key);
 1810:                 }
 1811:             }
 1812:             localStorage.setItem(key,value);
 1813:         }
 1814:     }
 1815: 
 1816:     // restore folding status of blocks (on page load)
 1817:     function restoreState (lastresource) {
 1818:         if(localStorage.getItem(lastresource) != null){
 1819:             var key = lastresource;
 1820:             var value = localStorage.getItem(key);
 1821:             var regex_delTimestamp = /^\d+;/;
 1822: 
 1823:             value.replace(regex_delTimestamp, '');
 1824: 
 1825:             var valueArr = value.split(';');
 1826:             var pairs;
 1827:             var elements;
 1828:             for (var i = 0; i < valueArr.length; i++){
 1829:                 pairs = valueArr[i].split(',');
 1830:                 elements = document.getElementsByName(pairs[0]);
 1831: 
 1832:                 for (var j = 0; j < elements.length; j++){
 1833:                     elements[j].style.display = pairs[1];
 1834:                     if (pairs[1] == "none"){
 1835:                         var regex_id = /([_\\d]+)\$/;
 1836:                         regex_id.exec(pairs[0]);
 1837:                         document.getElementById("folding_btn"+RegExp.\$1).value = "Show";
 1838:                     }
 1839:                 }
 1840:             }
 1841:         }
 1842:     }
 1843: 
 1844:     function getTagList () {
 1845: 
 1846:         var stringToSearch = document.lonhomework.innerHTML;
 1847: 
 1848:         var ret = new Array();
 1849:         var regex_findBlock = /(foldblock_.*?)"/g;
 1850:         var tag_list = stringToSearch.match(regex_findBlock);
 1851: 
 1852:         if(tag_list != null){
 1853:             for(var i = 0; i < tag_list.length; i++){
 1854:                 ret.push(tag_list[i].replace(/"/, ''));
 1855:             }
 1856:         }
 1857:         return ret;
 1858:     }
 1859: 
 1860:     function saveScrollPosition (resource) {
 1861:         var tag_list = getTagList();
 1862: 
 1863:         // we dont always want to jump to the first block
 1864:         // 170 is roughly above the "Problem Editing" header. we just want to save if the user scrolled down further than this
 1865:         if(\$(window).scrollTop() > 170){
 1866:             if(tag_list != null){
 1867:                 var result;
 1868:                 for(var i = 0; i < tag_list.length; i++){
 1869:                     if(isElementInViewport(tag_list[i])){
 1870:                         result += tag_list[i]+';';
 1871:                     }
 1872:                 }
 1873:                 sessionStorage.setItem('anchor_'+resource, result);
 1874:             }
 1875:         } else {
 1876:             // we dont need to save zero, just delete the item to leave everything tidy
 1877:             sessionStorage.removeItem('anchor_'+resource);
 1878:         }
 1879:     }
 1880: 
 1881:     function restoreScrollPosition(resource){
 1882: 
 1883:         var elem = sessionStorage.getItem('anchor_'+resource);
 1884:         if(elem != null){
 1885:             var tag_list = elem.split(';');
 1886:             var elem_list;
 1887: 
 1888:             for(var i = 0; i < tag_list.length; i++){
 1889:                 elem_list = document.getElementsByName(tag_list[i]);
 1890: 
 1891:                 if(elem_list.length > 0){
 1892:                     elem = elem_list[0];
 1893:                     break;
 1894:                 }
 1895:             }
 1896:             elem.scrollIntoView();
 1897:         }
 1898:     }
 1899: 
 1900:     function isElementInViewport(el) {
 1901: 
 1902:         // change to last element instead of first
 1903:         var elem = document.getElementsByName(el);
 1904:         var rect = elem[0].getBoundingClientRect();
 1905: 
 1906:         return (
 1907:             rect.top >= 0 &&
 1908:             rect.left >= 0 &&
 1909:             rect.bottom <= (window.innerHeight || document.documentElement.clientHeight) && /*or $(window).height() */
 1910:             rect.right <= (window.innerWidth || document.documentElement.clientWidth) /*or $(window).width() */
 1911:         );
 1912:     }
 1913: 
 1914:     function autosize(depth){
 1915:         var cmInst = window['cm'+depth];
 1916:         var fitsizeButton = document.getElementById('fitsize'+depth);
 1917: 
 1918:         // is fixed size, switching to dynamic
 1919:         if (sessionStorage.getItem("autosized_"+depth) == null) {
 1920:             cmInst.setSize("","auto");
 1921:             fitsizeButton.value = "@{[&mt('Fixed size')]}";
 1922:             sessionStorage.setItem("autosized_"+depth, "yes");
 1923: 
 1924:         // is dynamic size, switching to fixed
 1925:         } else {
 1926:             cmInst.setSize("","300px");
 1927:             fitsizeButton.value = "@{[&mt('Dynamic size')]}";
 1928:             sessionStorage.removeItem("autosized_"+depth);
 1929:         }
 1930:     }
 1931: 
 1932: 
 1933: 
 1934: // ]]>
 1935: </script>
 1936: COLORFULEDIT
 1937: }
 1938: 
 1939: sub xmleditor_js {
 1940:     return <<XMLEDIT
 1941: <script type="text/javascript" src="/adm/jQuery/addons/jquery-scrolltofixed.js"></script>
 1942: <script type="text/javascript">
 1943: // <![CDATA[>
 1944: 
 1945:     function saveScrollPosition (resource) {
 1946: 
 1947:         var scrollPos = \$(window).scrollTop();
 1948:         sessionStorage.setItem(resource,scrollPos);
 1949:     }
 1950: 
 1951:     function restoreScrollPosition(resource){
 1952: 
 1953:         var scrollPos = sessionStorage.getItem(resource);
 1954:         \$(window).scrollTop(scrollPos);
 1955:     }
 1956: 
 1957:     // unless internet explorer
 1958:     if (!(window.navigator.appName == "Microsoft Internet Explorer" && (document.documentMode || document.compatMode))){
 1959: 
 1960:         \$(document).ready(function() {
 1961:              \$(".LC_edit_actionbar").scrollToFixed(\{zIndex: 100\});
 1962:         });
 1963:     }
 1964: 
 1965:     // inserts text at cursor position into codemirror (xml editor only)
 1966:     function insertText(text){
 1967:         cm.focus();
 1968:         var curPos = cm.getCursor();
 1969:         cm.replaceRange(text.replace(/ESCAPEDSCRIPT/g,'script'), {line: curPos.line,ch: curPos.ch});
 1970:     }
 1971: // ]]>
 1972: </script>
 1973: XMLEDIT
 1974: }
 1975: 
 1976: sub insert_folding_button {
 1977:     my $curDepth = $Apache::lonxml::curdepth;
 1978:     my $lastresource = $env{'request.ambiguous'};
 1979: 
 1980:     return "<input type=\"button\" id=\"folding_btn_$curDepth\"
 1981:             value=\"".&mt('Hide')."\" onclick=\"fold_box('$curDepth','$lastresource')\">";
 1982: }
 1983: 
 1984: 
 1985: =pod
 1986: 
 1987: =head1 Excel and CSV file utility routines
 1988: 
 1989: =cut
 1990: 
 1991: ###############################################################
 1992: ###############################################################
 1993: 
 1994: =pod
 1995: 
 1996: =over 4
 1997: 
 1998: =item * &csv_translate($text) 
 1999: 
 2000: Translate $text to allow it to be output as a 'comma separated values' 
 2001: format.
 2002: 
 2003: =cut
 2004: 
 2005: ###############################################################
 2006: ###############################################################
 2007: sub csv_translate {
 2008:     my $text = shift;
 2009:     $text =~ s/\"/\"\"/g;
 2010:     $text =~ s/\n/ /g;
 2011:     return $text;
 2012: }
 2013: 
 2014: ###############################################################
 2015: ###############################################################
 2016: 
 2017: =pod
 2018: 
 2019: =item * &define_excel_formats()
 2020: 
 2021: Define some commonly used Excel cell formats.
 2022: 
 2023: Currently supported formats:
 2024: 
 2025: =over 4
 2026: 
 2027: =item header
 2028: 
 2029: =item bold
 2030: 
 2031: =item h1
 2032: 
 2033: =item h2
 2034: 
 2035: =item h3
 2036: 
 2037: =item h4
 2038: 
 2039: =item i
 2040: 
 2041: =item date
 2042: 
 2043: =back
 2044: 
 2045: Inputs: $workbook
 2046: 
 2047: Returns: $format, a hash reference.
 2048: 
 2049: 
 2050: =cut
 2051: 
 2052: ###############################################################
 2053: ###############################################################
 2054: sub define_excel_formats {
 2055:     my ($workbook) = @_;
 2056:     my $format;
 2057:     $format->{'header'} = $workbook->add_format(bold      => 1, 
 2058:                                                 bottom    => 1,
 2059:                                                 align     => 'center');
 2060:     $format->{'bold'} = $workbook->add_format(bold=>1);
 2061:     $format->{'h1'}   = $workbook->add_format(bold=>1, size=>18);
 2062:     $format->{'h2'}   = $workbook->add_format(bold=>1, size=>16);
 2063:     $format->{'h3'}   = $workbook->add_format(bold=>1, size=>14);
 2064:     $format->{'h4'}   = $workbook->add_format(bold=>1, size=>12);
 2065:     $format->{'i'}    = $workbook->add_format(italic=>1);
 2066:     $format->{'date'} = $workbook->add_format(num_format=>
 2067:                                             'mm/dd/yyyy hh:mm:ss');
 2068:     return $format;
 2069: }
 2070: 
 2071: ###############################################################
 2072: ###############################################################
 2073: 
 2074: =pod
 2075: 
 2076: =item * &create_workbook()
 2077: 
 2078: Create an Excel worksheet.  If it fails, output message on the
 2079: request object and return undefs.
 2080: 
 2081: Inputs: Apache request object
 2082: 
 2083: Returns (undef) on failure, 
 2084:     Excel worksheet object, scalar with filename, and formats 
 2085:     from &Apache::loncommon::define_excel_formats on success
 2086: 
 2087: =cut
 2088: 
 2089: ###############################################################
 2090: ###############################################################
 2091: sub create_workbook {
 2092:     my ($r) = @_;
 2093:         #
 2094:     # Create the excel spreadsheet
 2095:     my $filename = '/prtspool/'.
 2096:         $env{'user.name'}.'_'.$env{'user.domain'}.'_'.
 2097:         time.'_'.rand(1000000000).'.xls';
 2098:     my $workbook  = Spreadsheet::WriteExcel->new('/home/httpd'.$filename);
 2099:     if (! defined($workbook)) {
 2100:         $r->log_error("Error creating excel spreadsheet $filename: $!");
 2101:         $r->print(
 2102:             '<p class="LC_error">'
 2103:            .&mt('Problems occurred in creating the new Excel file.')
 2104:            .' '.&mt('This error has been logged.')
 2105:            .' '.&mt('Please alert your LON-CAPA administrator.')
 2106:            .'</p>'
 2107:         );
 2108:         return (undef);
 2109:     }
 2110:     #
 2111:     $workbook->set_tempdir(LONCAPA::tempdir());
 2112:     #
 2113:     my $format = &Apache::loncommon::define_excel_formats($workbook);
 2114:     return ($workbook,$filename,$format);
 2115: }
 2116: 
 2117: ###############################################################
 2118: ###############################################################
 2119: 
 2120: =pod
 2121: 
 2122: =item * &create_text_file()
 2123: 
 2124: Create a file to write to and eventually make available to the user.
 2125: If file creation fails, outputs an error message on the request object and 
 2126: return undefs.
 2127: 
 2128: Inputs: Apache request object, and file suffix
 2129: 
 2130: Returns (undef) on failure, 
 2131:     Filehandle and filename on success.
 2132: 
 2133: =cut
 2134: 
 2135: ###############################################################
 2136: ###############################################################
 2137: sub create_text_file {
 2138:     my ($r,$suffix) = @_;
 2139:     if (! defined($suffix)) { $suffix = 'txt'; };
 2140:     my $fh;
 2141:     my $filename = '/prtspool/'.
 2142:         $env{'user.name'}.'_'.$env{'user.domain'}.'_'.
 2143:         time.'_'.rand(1000000000).'.'.$suffix;
 2144:     $fh = Apache::File->new('>/home/httpd'.$filename);
 2145:     if (! defined($fh)) {
 2146:         $r->log_error("Couldn't open $filename for output $!");
 2147:         $r->print(
 2148:             '<p class="LC_error">'
 2149:            .&mt('Problems occurred in creating the output file.')
 2150:            .' '.&mt('This error has been logged.')
 2151:            .' '.&mt('Please alert your LON-CAPA administrator.')
 2152:            .'</p>'
 2153:         );
 2154:     }
 2155:     return ($fh,$filename)
 2156: }
 2157: 
 2158: 
 2159: =pod 
 2160: 
 2161: =back
 2162: 
 2163: =cut
 2164: 
 2165: ###############################################################
 2166: ##        Home server <option> list generating code          ##
 2167: ###############################################################
 2168: 
 2169: # ------------------------------------------
 2170: 
 2171: sub domain_select {
 2172:     my ($name,$value,$multiple)=@_;
 2173:     my %domains=map { 
 2174: 	$_ => $_.' '. &Apache::lonnet::domain($_,'description') 
 2175:     } &Apache::lonnet::all_domains();
 2176:     if ($multiple) {
 2177: 	$domains{''}=&mt('Any domain');
 2178: 	$domains{'select_form_order'} = [sort {lc($a) cmp lc($b) } (keys(%domains))];
 2179: 	return &multiple_select_form($name,$value,4,\%domains);
 2180:     } else {
 2181: 	$domains{'select_form_order'} = [sort {lc($a) cmp lc($b) } (keys(%domains))];
 2182: 	return &select_form($name,$value,\%domains);
 2183:     }
 2184: }
 2185: 
 2186: #-------------------------------------------
 2187: 
 2188: =pod
 2189: 
 2190: =head1 Routines for form select boxes
 2191: 
 2192: =over 4
 2193: 
 2194: =item * &multiple_select_form($name,$value,$size,$hash,$order)
 2195: 
 2196: Returns a string containing a <select> element int multiple mode
 2197: 
 2198: 
 2199: Args:
 2200:   $name - name of the <select> element
 2201:   $value - scalar or array ref of values that should already be selected
 2202:   $size - number of rows long the select element is
 2203:   $hash - the elements should be 'option' => 'shown text'
 2204:           (shown text should already have been &mt())
 2205:   $order - (optional) array ref of the order to show the elements in
 2206: 
 2207: =cut
 2208: 
 2209: #-------------------------------------------
 2210: sub multiple_select_form {
 2211:     my ($name,$value,$size,$hash,$order)=@_;
 2212:     my %selected = map { $_ => 1 } ref($value)?@{$value}:($value);
 2213:     my $output='';
 2214:     if (! defined($size)) {
 2215:         $size = 4;
 2216:         if (scalar(keys(%$hash))<4) {
 2217:             $size = scalar(keys(%$hash));
 2218:         }
 2219:     }
 2220:     $output.="\n".'<select name="'.$name.'" size="'.$size.'" multiple="multiple">';
 2221:     my @order;
 2222:     if (ref($order) eq 'ARRAY')  {
 2223:         @order = @{$order};
 2224:     } else {
 2225:         @order = sort(keys(%$hash));
 2226:     }
 2227:     if (exists($$hash{'select_form_order'})) {
 2228:         @order = @{$$hash{'select_form_order'}};
 2229:     }
 2230:         
 2231:     foreach my $key (@order) {
 2232:         $output.='<option value="'.&HTML::Entities::encode($key,'"<>&').'" ';
 2233:         $output.='selected="selected" ' if ($selected{$key});
 2234:         $output.='>'.$hash->{$key}."</option>\n";
 2235:     }
 2236:     $output.="</select>\n";
 2237:     return $output;
 2238: }
 2239: 
 2240: #-------------------------------------------
 2241: 
 2242: =pod
 2243: 
 2244: =item * &select_form($defdom,$name,$hashref,$onchange,$readonly)
 2245: 
 2246: Returns a string containing a <select name='$name' size='1'> form to 
 2247: allow a user to select options from a ref to a hash containing:
 2248: option_name => displayed text. An optional $onchange can include
 2249: a javascript onchange item, e.g., onchange="this.form.submit();".
 2250: An optional arg -- $readonly -- if true will cause the select form
 2251: to be disabled, e.g., for the case where an instructor has a section-
 2252: specific role, and is viewing/modifying parameters.  
 2253: 
 2254: See lonrights.pm for an example invocation and use.
 2255: 
 2256: =cut
 2257: 
 2258: #-------------------------------------------
 2259: sub select_form {
 2260:     my ($def,$name,$hashref,$onchange,$readonly) = @_;
 2261:     return unless (ref($hashref) eq 'HASH');
 2262:     if ($onchange) {
 2263:         $onchange = ' onchange="'.$onchange.'"';
 2264:     }
 2265:     my $disabled;
 2266:     if ($readonly) {
 2267:         $disabled = ' disabled="disabled"';
 2268:     }
 2269:     my $selectform = "<select name=\"$name\" size=\"1\"$onchange$disabled>\n";
 2270:     my @keys;
 2271:     if (exists($hashref->{'select_form_order'})) {
 2272: 	@keys=@{$hashref->{'select_form_order'}};
 2273:     } else {
 2274: 	@keys=sort(keys(%{$hashref}));
 2275:     }
 2276:     foreach my $key (@keys) {
 2277:         $selectform.=
 2278: 	    '<option value="'.&HTML::Entities::encode($key,'"<>&').'" '.
 2279:             ($key eq $def ? 'selected="selected" ' : '').
 2280:                 ">".$hashref->{$key}."</option>\n";
 2281:     }
 2282:     $selectform.="</select>";
 2283:     return $selectform;
 2284: }
 2285: 
 2286: # For display filters
 2287: 
 2288: sub display_filter {
 2289:     my ($context) = @_;
 2290:     if (!$env{'form.show'}) { $env{'form.show'}=10; }
 2291:     if (!$env{'form.displayfilter'}) { $env{'form.displayfilter'}='currentfolder'; }
 2292:     my $phraseinput = 'hidden';
 2293:     my $includeinput = 'hidden';
 2294:     my ($checked,$includetypestext);
 2295:     if ($env{'form.displayfilter'} eq 'containing') {
 2296:         $phraseinput = 'text'; 
 2297:         if ($context eq 'parmslog') {
 2298:             $includeinput = 'checkbox';
 2299:             if ($env{'form.includetypes'}) {
 2300:                 $checked = ' checked="checked"';
 2301:             }
 2302:             $includetypestext = &mt('Include parameter types');
 2303:         }
 2304:     } else {
 2305:         $includetypestext = '&nbsp;';
 2306:     }
 2307:     my ($additional,$secondid,$thirdid);
 2308:     if ($context eq 'parmslog') {
 2309:         $additional = 
 2310:             '<label><input type="'.$includeinput.'" name="includetypes"'. 
 2311:             $checked.' name="includetypes" value="1" id="includetypes" />'.
 2312:             '&nbsp;<span id="includetypestext">'.$includetypestext.'</span>'.
 2313:             '</label>';
 2314:         $secondid = 'includetypes';
 2315:         $thirdid = 'includetypestext';
 2316:     }
 2317:     my $onchange = "javascript:toggleHistoryOptions(this,'containingphrase','$context',
 2318:                                                     '$secondid','$thirdid')";
 2319:     return '<span class="LC_nobreak"><label>'.&mt('Records: [_1]',
 2320: 			       &Apache::lonmeta::selectbox('show',$env{'form.show'},undef,
 2321: 							   (&mt('all'),10,20,50,100,1000,10000))).
 2322: 	   '</label></span> <span class="LC_nobreak">'.
 2323:            &mt('Filter: [_1]',
 2324: 	   &select_form($env{'form.displayfilter'},
 2325: 			'displayfilter',
 2326: 			{'currentfolder' => 'Current folder/page',
 2327: 			 'containing' => 'Containing phrase',
 2328: 			 'none' => 'None'},$onchange)).'&nbsp;'.
 2329: 			 '<input type="'.$phraseinput.'" name="containingphrase" id="containingphrase" size="30" value="'.
 2330:                          &HTML::Entities::encode($env{'form.containingphrase'}).
 2331:                          '" />'.$additional;
 2332: }
 2333: 
 2334: sub display_filter_js {
 2335:     my $includetext = &mt('Include parameter types');
 2336:     return <<"ENDJS";
 2337:   
 2338: function toggleHistoryOptions(setter,firstid,context,secondid,thirdid) {
 2339:     var firstType = 'hidden';
 2340:     if (setter.options[setter.selectedIndex].value == 'containing') {
 2341:         firstType = 'text';
 2342:     }
 2343:     firstObject = document.getElementById(firstid);
 2344:     if (typeof(firstObject) == 'object') {
 2345:         if (firstObject.type != firstType) {
 2346:             changeInputType(firstObject,firstType);
 2347:         }
 2348:     }
 2349:     if (context == 'parmslog') {
 2350:         var secondType = 'hidden';
 2351:         if (firstType == 'text') {
 2352:             secondType = 'checkbox';
 2353:         }
 2354:         secondObject = document.getElementById(secondid);  
 2355:         if (typeof(secondObject) == 'object') {
 2356:             if (secondObject.type != secondType) {
 2357:                 changeInputType(secondObject,secondType);
 2358:             }
 2359:         }
 2360:         var textItem = document.getElementById(thirdid);
 2361:         var currtext = textItem.innerHTML;
 2362:         var newtext;
 2363:         if (firstType == 'text') {
 2364:             newtext = '$includetext';
 2365:         } else {
 2366:             newtext = '&nbsp;';
 2367:         }
 2368:         if (currtext != newtext) {
 2369:             textItem.innerHTML = newtext;
 2370:         }
 2371:     }
 2372:     return;
 2373: }
 2374: 
 2375: function changeInputType(oldObject,newType) {
 2376:     var newObject = document.createElement('input');
 2377:     newObject.type = newType;
 2378:     if (oldObject.size) {
 2379:         newObject.size = oldObject.size;
 2380:     }
 2381:     if (oldObject.value) {
 2382:         newObject.value = oldObject.value;
 2383:     }
 2384:     if (oldObject.name) {
 2385:         newObject.name = oldObject.name;
 2386:     }
 2387:     if (oldObject.id) {
 2388:         newObject.id = oldObject.id;
 2389:     }
 2390:     oldObject.parentNode.replaceChild(newObject,oldObject);
 2391:     return;
 2392: }
 2393: 
 2394: ENDJS
 2395: }
 2396: 
 2397: sub gradeleveldescription {
 2398:     my $gradelevel=shift;
 2399:     my %gradelevels=(0 => 'Not specified',
 2400: 		     1 => 'Grade 1',
 2401: 		     2 => 'Grade 2',
 2402: 		     3 => 'Grade 3',
 2403: 		     4 => 'Grade 4',
 2404: 		     5 => 'Grade 5',
 2405: 		     6 => 'Grade 6',
 2406: 		     7 => 'Grade 7',
 2407: 		     8 => 'Grade 8',
 2408: 		     9 => 'Grade 9',
 2409: 		     10 => 'Grade 10',
 2410: 		     11 => 'Grade 11',
 2411: 		     12 => 'Grade 12',
 2412: 		     13 => 'Grade 13',
 2413: 		     14 => '100 Level',
 2414: 		     15 => '200 Level',
 2415: 		     16 => '300 Level',
 2416: 		     17 => '400 Level',
 2417: 		     18 => 'Graduate Level');
 2418:     return &mt($gradelevels{$gradelevel});
 2419: }
 2420: 
 2421: sub select_level_form {
 2422:     my ($deflevel,$name)=@_;
 2423:     unless ($deflevel) { $deflevel=0; }
 2424:     my $selectform = "<select name=\"$name\" size=\"1\">\n";
 2425:     for (my $i=0; $i<=18; $i++) {
 2426:         $selectform.="<option value=\"$i\" ".
 2427:             ($i==$deflevel ? 'selected="selected" ' : '').
 2428:                 ">".&gradeleveldescription($i)."</option>\n";
 2429:     }
 2430:     $selectform.="</select>";
 2431:     return $selectform;
 2432: }
 2433: 
 2434: #-------------------------------------------
 2435: 
 2436: =pod
 2437: 
 2438: =item * &select_dom_form($defdom,$name,$includeempty,$showdomdesc,$onchange,$incdoms,$excdoms,$disabled)
 2439: 
 2440: Returns a string containing a <select name='$name' size='1'> form to 
 2441: allow a user to select the domain to preform an operation in.  
 2442: See loncreateuser.pm for an example invocation and use.
 2443: 
 2444: If the $includeempty flag is set, it also includes an empty choice ("no domain
 2445: selected");
 2446: 
 2447: If the $showdomdesc flag is set, the domain name is followed by the domain description.
 2448: 
 2449: 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.
 2450: 
 2451: The optional $incdoms is a reference to an array of domains which will be the only available options.
 2452: 
 2453: The optional $excdoms is a reference to an array of domains which will be excluded from the available options.
 2454: 
 2455: The optional $disabled argument, if true, adds the disabled attribute to the select tag. 
 2456: 
 2457: =cut
 2458: 
 2459: #-------------------------------------------
 2460: sub select_dom_form {
 2461:     my ($defdom,$name,$includeempty,$showdomdesc,$onchange,$incdoms,$excdoms,$disabled) = @_;
 2462:     if ($onchange) {
 2463:         $onchange = ' onchange="'.$onchange.'"';
 2464:     }
 2465:     if ($disabled) {
 2466:         $disabled = ' disabled="disabled"';
 2467:     }
 2468:     my (@domains,%exclude);
 2469:     if (ref($incdoms) eq 'ARRAY') {
 2470:         @domains = sort {lc($a) cmp lc($b)} (@{$incdoms});
 2471:     } else {
 2472:         @domains = sort {lc($a) cmp lc($b)} (&Apache::lonnet::all_domains());
 2473:     }
 2474:     if ($includeempty) { @domains=('',@domains); }
 2475:     if (ref($excdoms) eq 'ARRAY') {
 2476:         map { $exclude{$_} = 1; } @{$excdoms};
 2477:     }
 2478:     my $selectdomain = "<select name=\"$name\" size=\"1\"$onchange$disabled>\n";
 2479:     foreach my $dom (@domains) {
 2480:         next if ($exclude{$dom});
 2481:         $selectdomain.="<option value=\"$dom\" ".
 2482:             ($dom eq $defdom ? 'selected="selected" ' : '').'>'.$dom;
 2483:         if ($showdomdesc) {
 2484:             if ($dom ne '') {
 2485:                 my $domdesc = &Apache::lonnet::domain($dom,'description');
 2486:                 if ($domdesc ne '') {
 2487:                     $selectdomain .= ' ('.$domdesc.')';
 2488:                 }
 2489:             } 
 2490:         }
 2491:         $selectdomain .= "</option>\n";
 2492:     }
 2493:     $selectdomain.="</select>";
 2494:     return $selectdomain;
 2495: }
 2496: 
 2497: #-------------------------------------------
 2498: 
 2499: =pod
 2500: 
 2501: =item * &home_server_form_item($domain,$name,$defaultflag)
 2502: 
 2503: input: 4 arguments (two required, two optional) - 
 2504:     $domain - domain of new user
 2505:     $name - name of form element
 2506:     $default - Value of 'default' causes a default item to be first 
 2507:                             option, and selected by default. 
 2508:     $hide - Value of 'hide' causes hiding of the name of the server, 
 2509:                             if 1 server found, or default, if 0 found.
 2510: output: returns 2 items: 
 2511: (a) form element which contains either:
 2512:    (i) <select name="$name">
 2513:         <option value="$hostid1">$hostid $servers{$hostid}</option>
 2514:         <option value="$hostid2">$hostid $servers{$hostid}</option>       
 2515:        </select>
 2516:        form item if there are multiple library servers in $domain, or
 2517:    (ii) an <input type="hidden" name="$name" value="$hostid" /> form item 
 2518:        if there is only one library server in $domain.
 2519: 
 2520: (b) number of library servers found.
 2521: 
 2522: See loncreateuser.pm for example of use.
 2523: 
 2524: =cut
 2525: 
 2526: #-------------------------------------------
 2527: sub home_server_form_item {
 2528:     my ($domain,$name,$default,$hide) = @_;
 2529:     my %servers = &Apache::lonnet::get_servers($domain,'library');
 2530:     my $result;
 2531:     my $numlib = keys(%servers);
 2532:     if ($numlib > 1) {
 2533:         $result .= '<select name="'.$name.'" />'."\n";
 2534:         if ($default) {
 2535:             $result .= '<option value="default" selected="selected">'.&mt('default').
 2536:                        '</option>'."\n";
 2537:         }
 2538:         foreach my $hostid (sort(keys(%servers))) {
 2539:             $result.= '<option value="'.$hostid.'">'.
 2540: 	              $hostid.' '.$servers{$hostid}."</option>\n";
 2541:         }
 2542:         $result .= '</select>'."\n";
 2543:     } elsif ($numlib == 1) {
 2544:         my $hostid;
 2545:         foreach my $item (keys(%servers)) {
 2546:             $hostid = $item;
 2547:         }
 2548:         $result .= '<input type="hidden" name="'.$name.'" value="'.
 2549:                    $hostid.'" />';
 2550:                    if (!$hide) {
 2551:                        $result .= $hostid.' '.$servers{$hostid};
 2552:                    }
 2553:                    $result .= "\n";
 2554:     } elsif ($default) {
 2555:         $result .= '<input type="hidden" name="'.$name.
 2556:                    '" value="default" />';
 2557:                    if (!$hide) {
 2558:                        $result .= &mt('default');
 2559:                    }
 2560:                    $result .= "\n";
 2561:     }
 2562:     return ($result,$numlib);
 2563: }
 2564: 
 2565: =pod
 2566: 
 2567: =back 
 2568: 
 2569: =cut
 2570: 
 2571: ###############################################################
 2572: ##                  Decoding User Agent                      ##
 2573: ###############################################################
 2574: 
 2575: =pod
 2576: 
 2577: =head1 Decoding the User Agent
 2578: 
 2579: =over 4
 2580: 
 2581: =item * &decode_user_agent()
 2582: 
 2583: Inputs: $r
 2584: 
 2585: Outputs:
 2586: 
 2587: =over 4
 2588: 
 2589: =item * $httpbrowser
 2590: 
 2591: =item * $clientbrowser
 2592: 
 2593: =item * $clientversion
 2594: 
 2595: =item * $clientmathml
 2596: 
 2597: =item * $clientunicode
 2598: 
 2599: =item * $clientos
 2600: 
 2601: =item * $clientmobile
 2602: 
 2603: =item * $clientinfo
 2604: 
 2605: =item * $clientosversion
 2606: 
 2607: =back
 2608: 
 2609: =back 
 2610: 
 2611: =cut
 2612: 
 2613: ###############################################################
 2614: ###############################################################
 2615: sub decode_user_agent {
 2616:     my ($r)=@_;
 2617:     my @browsertype=split(/\&/,$Apache::lonnet::perlvar{"lonBrowsDet"});
 2618:     my %mathcap=split(/\&/,$$Apache::lonnet::perlvar{"lonMathML"});
 2619:     my $httpbrowser=$ENV{"HTTP_USER_AGENT"};
 2620:     if (!$httpbrowser && $r) { $httpbrowser=$r->header_in('User-Agent'); }
 2621:     my $clientbrowser='unknown';
 2622:     my $clientversion='0';
 2623:     my $clientmathml='';
 2624:     my $clientunicode='0';
 2625:     my $clientmobile=0;
 2626:     my $clientosversion='';
 2627:     for (my $i=0;$i<=$#browsertype;$i++) {
 2628:         my ($bname,$match,$notmatch,$vreg,$minv,$univ)=split(/\%/,$browsertype[$i]);
 2629: 	if (($httpbrowser=~/$match/i)  && ($httpbrowser!~/$notmatch/i)) {
 2630: 	    $clientbrowser=$bname;
 2631:             $httpbrowser=~/$vreg/i;
 2632: 	    $clientversion=$1;
 2633:             $clientmathml=($clientversion>=$minv);
 2634:             $clientunicode=($clientversion>=$univ);
 2635: 	}
 2636:     }
 2637:     my $clientos='unknown';
 2638:     my $clientinfo;
 2639:     if (($httpbrowser=~/linux/i) ||
 2640:         ($httpbrowser=~/unix/i) ||
 2641:         ($httpbrowser=~/ux/i) ||
 2642:         ($httpbrowser=~/solaris/i)) { $clientos='unix'; }
 2643:     if (($httpbrowser=~/vax/i) ||
 2644:         ($httpbrowser=~/vms/i)) { $clientos='vms'; }
 2645:     if ($httpbrowser=~/next/i) { $clientos='next'; }
 2646:     if (($httpbrowser=~/mac/i) ||
 2647:         ($httpbrowser=~/powerpc/i)) { $clientos='mac'; }
 2648:     if ($httpbrowser=~/win/i) {
 2649:         $clientos='win';
 2650:         if ($httpbrowser =~/Windows\s+NT\s+(\d+\.\d+)/i) {
 2651:             $clientosversion = $1;
 2652:         }
 2653:     }
 2654:     if ($httpbrowser=~/embed/i) { $clientos='pda'; }
 2655:     if ($httpbrowser=~/(Android|iPod|iPad|iPhone|webOS|Blackberry|Windows Phone|Opera m(?:ob|in)|Fennec)/i) {
 2656:         $clientmobile=lc($1);
 2657:     }
 2658:     if ($httpbrowser=~ m{Firefox/(\d+\.\d+)}) {
 2659:         $clientinfo = 'firefox-'.$1;
 2660:     } elsif ($httpbrowser=~ m{chromeframe/(\d+\.\d+)\.}) {
 2661:         $clientinfo = 'chromeframe-'.$1;
 2662:     }
 2663:     return ($httpbrowser,$clientbrowser,$clientversion,$clientmathml,
 2664:             $clientunicode,$clientos,$clientmobile,$clientinfo,
 2665:             $clientosversion);
 2666: }
 2667: 
 2668: ###############################################################
 2669: ##    Authentication changing form generation subroutines    ##
 2670: ###############################################################
 2671: ##
 2672: ## All of the authform_xxxxxxx subroutines take their inputs in a
 2673: ## hash, and have reasonable default values.
 2674: ##
 2675: ##    formname = the name given in the <form> tag.
 2676: #-------------------------------------------
 2677: 
 2678: =pod
 2679: 
 2680: =head1 Authentication Routines
 2681: 
 2682: =over 4
 2683: 
 2684: =item * &authform_xxxxxx()
 2685: 
 2686: The authform_xxxxxx subroutines provide javascript and html forms which 
 2687: handle some of the conveniences required for authentication forms.  
 2688: This is not an optimal method, but it works.  
 2689: 
 2690: =over 4
 2691: 
 2692: =item * authform_header
 2693: 
 2694: =item * authform_authorwarning
 2695: 
 2696: =item * authform_nochange
 2697: 
 2698: =item * authform_kerberos
 2699: 
 2700: =item * authform_internal
 2701: 
 2702: =item * authform_filesystem
 2703: 
 2704: =back
 2705: 
 2706: See loncreateuser.pm for invocation and use examples.
 2707: 
 2708: =cut
 2709: 
 2710: #-------------------------------------------
 2711: sub authform_header{  
 2712:     my %in = (
 2713:         formname => 'cu',
 2714:         kerb_def_dom => '',
 2715:         @_,
 2716:     );
 2717:     $in{'formname'} = 'document.' . $in{'formname'};
 2718:     my $result='';
 2719: 
 2720: #---------------------------------------------- Code for upper case translation
 2721:     my $Javascript_toUpperCase;
 2722:     unless ($in{kerb_def_dom}) {
 2723:         $Javascript_toUpperCase =<<"END";
 2724:         switch (choice) {
 2725:            case 'krb': currentform.elements[choicearg].value =
 2726:                currentform.elements[choicearg].value.toUpperCase();
 2727:                break;
 2728:            default:
 2729:         }
 2730: END
 2731:     } else {
 2732:         $Javascript_toUpperCase = "";
 2733:     }
 2734: 
 2735:     my $radioval = "'nochange'";
 2736:     if (defined($in{'curr_authtype'})) {
 2737:         if ($in{'curr_authtype'} ne '') {
 2738:             $radioval = "'".$in{'curr_authtype'}."arg'";
 2739:         }
 2740:     }
 2741:     my $argfield = 'null';
 2742:     if (defined($in{'mode'})) {
 2743:         if ($in{'mode'} eq 'modifycourse')  {
 2744:             if (defined($in{'curr_autharg'})) {
 2745:                 if ($in{'curr_autharg'} ne '') {
 2746:                     $argfield = "'$in{'curr_autharg'}'";
 2747:                 }
 2748:             }
 2749:         }
 2750:     }
 2751: 
 2752:     $result.=<<"END";
 2753: var current = new Object();
 2754: current.radiovalue = $radioval;
 2755: current.argfield = $argfield;
 2756: 
 2757: function changed_radio(choice,currentform) {
 2758:     var choicearg = choice + 'arg';
 2759:     // If a radio button in changed, we need to change the argfield
 2760:     if (current.radiovalue != choice) {
 2761:         current.radiovalue = choice;
 2762:         if (current.argfield != null) {
 2763:             currentform.elements[current.argfield].value = '';
 2764:         }
 2765:         if (choice == 'nochange') {
 2766:             current.argfield = null;
 2767:         } else {
 2768:             current.argfield = choicearg;
 2769:             switch(choice) {
 2770:                 case 'krb': 
 2771:                     currentform.elements[current.argfield].value = 
 2772:                         "$in{'kerb_def_dom'}";
 2773:                 break;
 2774:               default:
 2775:                 break;
 2776:             }
 2777:         }
 2778:     }
 2779:     return;
 2780: }
 2781: 
 2782: function changed_text(choice,currentform) {
 2783:     var choicearg = choice + 'arg';
 2784:     if (currentform.elements[choicearg].value !='') {
 2785:         $Javascript_toUpperCase
 2786:         // clear old field
 2787:         if ((current.argfield != choicearg) && (current.argfield != null)) {
 2788:             currentform.elements[current.argfield].value = '';
 2789:         }
 2790:         current.argfield = choicearg;
 2791:     }
 2792:     set_auth_radio_buttons(choice,currentform);
 2793:     return;
 2794: }
 2795: 
 2796: function set_auth_radio_buttons(newvalue,currentform) {
 2797:     var numauthchoices = currentform.login.length;
 2798:     if (typeof numauthchoices  == "undefined") {
 2799:         return;
 2800:     } 
 2801:     var i=0;
 2802:     while (i < numauthchoices) {
 2803:         if (currentform.login[i].value == newvalue) { break; }
 2804:         i++;
 2805:     }
 2806:     if (i == numauthchoices) {
 2807:         return;
 2808:     }
 2809:     current.radiovalue = newvalue;
 2810:     currentform.login[i].checked = true;
 2811:     return;
 2812: }
 2813: END
 2814:     return $result;
 2815: }
 2816: 
 2817: sub authform_authorwarning {
 2818:     my $result='';
 2819:     $result='<i>'.
 2820:         &mt('As a general rule, only authors or co-authors should be '.
 2821:             'filesystem authenticated '.
 2822:             '(which allows access to the server filesystem).')."</i>\n";
 2823:     return $result;
 2824: }
 2825: 
 2826: sub authform_nochange {
 2827:     my %in = (
 2828:               formname => 'document.cu',
 2829:               kerb_def_dom => 'MSU.EDU',
 2830:               @_,
 2831:           );
 2832:     my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'}); 
 2833:     my $result;
 2834:     if (!$authnum) {
 2835:         $result = &mt('Under your current role you are not permitted to change login settings for this user');
 2836:     } else {
 2837:         $result = '<label>'.&mt('[_1] Do not change login data',
 2838:                   '<input type="radio" name="login" value="nochange" '.
 2839:                   'checked="checked" onclick="'.
 2840:             "javascript:changed_radio('nochange',$in{'formname'});".'" />').
 2841: 	    '</label>';
 2842:     }
 2843:     return $result;
 2844: }
 2845: 
 2846: sub authform_kerberos {
 2847:     my %in = (
 2848:               formname => 'document.cu',
 2849:               kerb_def_dom => 'MSU.EDU',
 2850:               kerb_def_auth => 'krb4',
 2851:               @_,
 2852:               );
 2853:     my ($check4,$check5,$krbcheck,$krbarg,$krbver,$result,$authtype,
 2854:         $autharg,$jscall,$disabled);
 2855:     my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
 2856:     if ($in{'kerb_def_auth'} eq 'krb5') {
 2857:        $check5 = ' checked="checked"';
 2858:     } else {
 2859:        $check4 = ' checked="checked"';
 2860:     }
 2861:     if ($in{'readonly'}) {
 2862:         $disabled = ' disabled="disabled"';
 2863:     }
 2864:     $krbarg = $in{'kerb_def_dom'};
 2865:     if (defined($in{'curr_authtype'})) {
 2866:         if ($in{'curr_authtype'} eq 'krb') {
 2867:             $krbcheck = ' checked="checked"';
 2868:             if (defined($in{'mode'})) {
 2869:                 if ($in{'mode'} eq 'modifyuser') {
 2870:                     $krbcheck = '';
 2871:                 }
 2872:             }
 2873:             if (defined($in{'curr_kerb_ver'})) {
 2874:                 if ($in{'curr_krb_ver'} eq '5') {
 2875:                     $check5 = ' checked="checked"';
 2876:                     $check4 = '';
 2877:                 } else {
 2878:                     $check4 = ' checked="checked"';
 2879:                     $check5 = '';
 2880:                 }
 2881:             }
 2882:             if (defined($in{'curr_autharg'})) {
 2883:                 $krbarg = $in{'curr_autharg'};
 2884:             }
 2885:             if (!$can_assign{'krb4'} && !$can_assign{'krb5'}) {
 2886:                 if (defined($in{'curr_autharg'})) {
 2887:                     $result = 
 2888:     &mt('Currently Kerberos authenticated with domain [_1] Version [_2].',
 2889:         $in{'curr_autharg'},$krbver);
 2890:                 } else {
 2891:                     $result =
 2892:     &mt('Currently Kerberos authenticated, Version [_1].',$krbver);
 2893:                 }
 2894:                 return $result; 
 2895:             }
 2896:         }
 2897:     } else {
 2898:         if ($authnum == 1) {
 2899:             $authtype = '<input type="hidden" name="login" value="krb" />';
 2900:         }
 2901:     }
 2902:     if (!$can_assign{'krb4'} && !$can_assign{'krb5'}) {
 2903:         return;
 2904:     } elsif ($authtype eq '') {
 2905:         if (defined($in{'mode'})) {
 2906:             if ($in{'mode'} eq 'modifycourse') {
 2907:                 if ($authnum == 1) {
 2908:                     $authtype = '<input type="radio" name="login" value="krb"'.$disabled.' />';
 2909:                 }
 2910:             }
 2911:         }
 2912:     }
 2913:     $jscall = "javascript:changed_radio('krb',$in{'formname'});";
 2914:     if ($authtype eq '') {
 2915:         $authtype = '<input type="radio" name="login" value="krb" '.
 2916:                     'onclick="'.$jscall.'" onchange="'.$jscall.'"'.
 2917:                     $krbcheck.$disabled.' />';
 2918:     }
 2919:     if (($can_assign{'krb4'} && $can_assign{'krb5'}) ||
 2920:         ($can_assign{'krb4'} && !$can_assign{'krb5'} &&
 2921:          $in{'curr_authtype'} eq 'krb5') ||
 2922:         (!$can_assign{'krb4'} && $can_assign{'krb5'} &&
 2923:          $in{'curr_authtype'} eq 'krb4')) {
 2924:         $result .= &mt
 2925:         ('[_1] Kerberos authenticated with domain [_2] '.
 2926:          '[_3] Version 4 [_4] Version 5 [_5]',
 2927:          '<label>'.$authtype,
 2928:          '</label><input type="text" size="10" name="krbarg" '.
 2929:              'value="'.$krbarg.'" '.
 2930:              'onchange="'.$jscall.'"'.$disabled.' />',
 2931:          '<label><input type="radio" name="krbver" value="4" '.$check4.$disabled.' />',
 2932:          '</label><label><input type="radio" name="krbver" value="5" '.$check5.$disabled.' />',
 2933: 	 '</label>');
 2934:     } elsif ($can_assign{'krb4'}) {
 2935:         $result .= &mt
 2936:         ('[_1] Kerberos authenticated with domain [_2] '.
 2937:          '[_3] Version 4 [_4]',
 2938:          '<label>'.$authtype,
 2939:          '</label><input type="text" size="10" name="krbarg" '.
 2940:              'value="'.$krbarg.'" '.
 2941:              'onchange="'.$jscall.'"'.$disabled.' />',
 2942:          '<label><input type="hidden" name="krbver" value="4" />',
 2943:          '</label>');
 2944:     } elsif ($can_assign{'krb5'}) {
 2945:         $result .= &mt
 2946:         ('[_1] Kerberos authenticated with domain [_2] '.
 2947:          '[_3] Version 5 [_4]',
 2948:          '<label>'.$authtype,
 2949:          '</label><input type="text" size="10" name="krbarg" '.
 2950:              'value="'.$krbarg.'" '.
 2951:              'onchange="'.$jscall.'"'.$disabled.' />',
 2952:          '<label><input type="hidden" name="krbver" value="5" />',
 2953:          '</label>');
 2954:     }
 2955:     return $result;
 2956: }
 2957: 
 2958: sub authform_internal {
 2959:     my %in = (
 2960:                 formname => 'document.cu',
 2961:                 kerb_def_dom => 'MSU.EDU',
 2962:                 @_,
 2963:                 );
 2964:     my ($intcheck,$intarg,$result,$authtype,$autharg,$jscall,$disabled);
 2965:     my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
 2966:     if ($in{'readonly'}) {
 2967:         $disabled = ' disabled="disabled"';
 2968:     }
 2969:     if (defined($in{'curr_authtype'})) {
 2970:         if ($in{'curr_authtype'} eq 'int') {
 2971:             if ($can_assign{'int'}) {
 2972:                 $intcheck = 'checked="checked" ';
 2973:                 if (defined($in{'mode'})) {
 2974:                     if ($in{'mode'} eq 'modifyuser') {
 2975:                         $intcheck = '';
 2976:                     }
 2977:                 }
 2978:                 if (defined($in{'curr_autharg'})) {
 2979:                     $intarg = $in{'curr_autharg'};
 2980:                 }
 2981:             } else {
 2982:                 $result = &mt('Currently internally authenticated.');
 2983:                 return $result;
 2984:             }
 2985:         }
 2986:     } else {
 2987:         if ($authnum == 1) {
 2988:             $authtype = '<input type="hidden" name="login" value="int" />';
 2989:         }
 2990:     }
 2991:     if (!$can_assign{'int'}) {
 2992:         return;
 2993:     } elsif ($authtype eq '') {
 2994:         if (defined($in{'mode'})) {
 2995:             if ($in{'mode'} eq 'modifycourse') {
 2996:                 if ($authnum == 1) {
 2997:                     $authtype = '<input type="radio" name="login" value="int"'.$disabled.' />';
 2998:                 }
 2999:             }
 3000:         }
 3001:     }
 3002:     $jscall = "javascript:changed_radio('int',$in{'formname'});";
 3003:     if ($authtype eq '') {
 3004:         $authtype = '<input type="radio" name="login" value="int" '.$intcheck.
 3005:                     ' onchange="'.$jscall.'" onclick="'.$jscall.'"'.$disabled.' />';
 3006:     }
 3007:     $autharg = '<input type="password" size="10" name="intarg" value="'.
 3008:                $intarg.'" onchange="'.$jscall.'"'.$disabled.' />';
 3009:     $result = &mt
 3010:         ('[_1] Internally authenticated (with initial password [_2])',
 3011:          '<label>'.$authtype,'</label>'.$autharg);
 3012:     $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>';
 3013:     return $result;
 3014: }
 3015: 
 3016: sub authform_local {
 3017:     my %in = (
 3018:               formname => 'document.cu',
 3019:               kerb_def_dom => 'MSU.EDU',
 3020:               @_,
 3021:               );
 3022:     my ($loccheck,$locarg,$result,$authtype,$autharg,$jscall,$disabled);
 3023:     my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
 3024:     if ($in{'readonly'}) {
 3025:         $disabled = ' disabled="disabled"';
 3026:     }
 3027:     if (defined($in{'curr_authtype'})) {
 3028:         if ($in{'curr_authtype'} eq 'loc') {
 3029:             if ($can_assign{'loc'}) {
 3030:                 $loccheck = 'checked="checked" ';
 3031:                 if (defined($in{'mode'})) {
 3032:                     if ($in{'mode'} eq 'modifyuser') {
 3033:                         $loccheck = '';
 3034:                     }
 3035:                 }
 3036:                 if (defined($in{'curr_autharg'})) {
 3037:                     $locarg = $in{'curr_autharg'};
 3038:                 }
 3039:             } else {
 3040:                 $result = &mt('Currently using local (institutional) authentication.');
 3041:                 return $result;
 3042:             }
 3043:         }
 3044:     } else {
 3045:         if ($authnum == 1) {
 3046:             $authtype = '<input type="hidden" name="login" value="loc" />';
 3047:         }
 3048:     }
 3049:     if (!$can_assign{'loc'}) {
 3050:         return;
 3051:     } elsif ($authtype eq '') {
 3052:         if (defined($in{'mode'})) {
 3053:             if ($in{'mode'} eq 'modifycourse') {
 3054:                 if ($authnum == 1) {
 3055:                     $authtype = '<input type="radio" name="login" value="loc"'.$disabled.' />';
 3056:                 }
 3057:             }
 3058:         }
 3059:     }
 3060:     $jscall = "javascript:changed_radio('loc',$in{'formname'});";
 3061:     if ($authtype eq '') {
 3062:         $authtype = '<input type="radio" name="login" value="loc" '.
 3063:                     $loccheck.' onchange="'.$jscall.'" onclick="'.
 3064:                     $jscall.'"'.$disabled.' />';
 3065:     }
 3066:     $autharg = '<input type="text" size="10" name="locarg" value="'.
 3067:                $locarg.'" onchange="'.$jscall.'"'.$disabled.' />';
 3068:     $result = &mt('[_1] Local Authentication with argument [_2]',
 3069:                   '<label>'.$authtype,'</label>'.$autharg);
 3070:     return $result;
 3071: }
 3072: 
 3073: sub authform_filesystem {
 3074:     my %in = (
 3075:               formname => 'document.cu',
 3076:               kerb_def_dom => 'MSU.EDU',
 3077:               @_,
 3078:               );
 3079:     my ($fsyscheck,$result,$authtype,$autharg,$jscall,$disabled);
 3080:     my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
 3081:     if ($in{'readonly'}) {
 3082:         $disabled = ' disabled="disabled"';
 3083:     }
 3084:     if (defined($in{'curr_authtype'})) {
 3085:         if ($in{'curr_authtype'} eq 'fsys') {
 3086:             if ($can_assign{'fsys'}) {
 3087:                 $fsyscheck = 'checked="checked" ';
 3088:                 if (defined($in{'mode'})) {
 3089:                     if ($in{'mode'} eq 'modifyuser') {
 3090:                         $fsyscheck = '';
 3091:                     }
 3092:                 }
 3093:             } else {
 3094:                 $result = &mt('Currently Filesystem Authenticated.');
 3095:                 return $result;
 3096:             }           
 3097:         }
 3098:     } else {
 3099:         if ($authnum == 1) {
 3100:             $authtype = '<input type="hidden" name="login" value="fsys" />';
 3101:         }
 3102:     }
 3103:     if (!$can_assign{'fsys'}) {
 3104:         return;
 3105:     } elsif ($authtype eq '') {
 3106:         if (defined($in{'mode'})) {
 3107:             if ($in{'mode'} eq 'modifycourse') {
 3108:                 if ($authnum == 1) {
 3109:                     $authtype = '<input type="radio" name="login" value="fsys"'.$disabled.' />';
 3110:                 }
 3111:             }
 3112:         }
 3113:     }
 3114:     $jscall = "javascript:changed_radio('fsys',$in{'formname'});";
 3115:     if ($authtype eq '') {
 3116:         $authtype = '<input type="radio" name="login" value="fsys" '.
 3117:                     $fsyscheck.' onchange="'.$jscall.'" onclick="'.
 3118:                     $jscall.'"'.$disabled.' />';
 3119:     }
 3120:     $autharg = '<input type="text" size="10" name="fsysarg" value=""'.
 3121:                ' onchange="'.$jscall.'"'.$disabled.' />';
 3122:     $result = &mt
 3123:         ('[_1] Filesystem Authenticated (with initial password [_2])',
 3124:          '<label><input type="radio" name="login" value="fsys" '.
 3125:          $fsyscheck.'onchange="'.$jscall.'" onclick="'.$jscall.'"'.$disabled.' />',
 3126:          '</label><input type="password" size="10" name="fsysarg" value="" '.
 3127:                   'onchange="'.$jscall.'"'.$disabled.' />');
 3128:     return $result;
 3129: }
 3130: 
 3131: sub get_assignable_auth {
 3132:     my ($dom) = @_;
 3133:     if ($dom eq '') {
 3134:         $dom = $env{'request.role.domain'};
 3135:     }
 3136:     my %can_assign = (
 3137:                           krb4 => 1,
 3138:                           krb5 => 1,
 3139:                           int  => 1,
 3140:                           loc  => 1,
 3141:                      );
 3142:     my %domconfig = &Apache::lonnet::get_dom('configuration',['usercreation'],$dom);
 3143:     if (ref($domconfig{'usercreation'}) eq 'HASH') {
 3144:         if (ref($domconfig{'usercreation'}{'authtypes'}) eq 'HASH') {
 3145:             my $authhash = $domconfig{'usercreation'}{'authtypes'};
 3146:             my $context;
 3147:             if ($env{'request.role'} =~ /^au/) {
 3148:                 $context = 'author';
 3149:             } elsif ($env{'request.role'} =~ /^(dc|dh)/) {
 3150:                 $context = 'domain';
 3151:             } elsif ($env{'request.course.id'}) {
 3152:                 $context = 'course';
 3153:             }
 3154:             if ($context) {
 3155:                 if (ref($authhash->{$context}) eq 'HASH') {
 3156:                    %can_assign = %{$authhash->{$context}}; 
 3157:                 }
 3158:             }
 3159:         }
 3160:     }
 3161:     my $authnum = 0;
 3162:     foreach my $key (keys(%can_assign)) {
 3163:         if ($can_assign{$key}) {
 3164:             $authnum ++;
 3165:         }
 3166:     }
 3167:     if ($can_assign{'krb4'} && $can_assign{'krb5'}) {
 3168:         $authnum --;
 3169:     }
 3170:     return ($authnum,%can_assign);
 3171: }
 3172: 
 3173: ###############################################################
 3174: ##    Get Kerberos Defaults for Domain                 ##
 3175: ###############################################################
 3176: ##
 3177: ## Returns default kerberos version and an associated argument
 3178: ## as listed in file domain.tab. If not listed, provides
 3179: ## appropriate default domain and kerberos version.
 3180: ##
 3181: #-------------------------------------------
 3182: 
 3183: =pod
 3184: 
 3185: =item * &get_kerberos_defaults()
 3186: 
 3187: get_kerberos_defaults($target_domain) returns the default kerberos
 3188: version and domain. If not found, it defaults to version 4 and the 
 3189: domain of the server.
 3190: 
 3191: =over 4
 3192: 
 3193: ($def_version, $def_krb_domain) = &get_kerberos_defaults($target_domain);
 3194: 
 3195: =back
 3196: 
 3197: =back
 3198: 
 3199: =cut
 3200: 
 3201: #-------------------------------------------
 3202: sub get_kerberos_defaults {
 3203:     my $domain=shift;
 3204:     my ($krbdef,$krbdefdom);
 3205:     my %domdefaults = &Apache::lonnet::get_domain_defaults($domain);
 3206:     if (($domdefaults{'auth_def'} =~/^krb(4|5)$/) && ($domdefaults{'auth_arg_def'} ne '')) {
 3207:         $krbdef = $domdefaults{'auth_def'};
 3208:         $krbdefdom = $domdefaults{'auth_arg_def'};
 3209:     } else {
 3210:         $ENV{'SERVER_NAME'}=~/(\w+\.\w+)$/;
 3211:         my $krbdefdom=$1;
 3212:         $krbdefdom=~tr/a-z/A-Z/;
 3213:         $krbdef = "krb4";
 3214:     }
 3215:     return ($krbdef,$krbdefdom);
 3216: }
 3217: 
 3218: 
 3219: ###############################################################
 3220: ##                Thesaurus Functions                        ##
 3221: ###############################################################
 3222: 
 3223: =pod
 3224: 
 3225: =head1 Thesaurus Functions
 3226: 
 3227: =over 4
 3228: 
 3229: =item * &initialize_keywords()
 3230: 
 3231: Initializes the package variable %Keywords if it is empty.  Uses the
 3232: package variable $thesaurus_db_file.
 3233: 
 3234: =cut
 3235: 
 3236: ###################################################
 3237: 
 3238: sub initialize_keywords {
 3239:     return 1 if (scalar keys(%Keywords));
 3240:     # If we are here, %Keywords is empty, so fill it up
 3241:     #   Make sure the file we need exists...
 3242:     if (! -e $thesaurus_db_file) {
 3243:         &Apache::lonnet::logthis("Attempt to access $thesaurus_db_file".
 3244:                                  " failed because it does not exist");
 3245:         return 0;
 3246:     }
 3247:     #   Set up the hash as a database
 3248:     my %thesaurus_db;
 3249:     if (! tie(%thesaurus_db,'GDBM_File',
 3250:               $thesaurus_db_file,&GDBM_READER(),0640)){
 3251:         &Apache::lonnet::logthis("Could not tie \%thesaurus_db to ".
 3252:                                  $thesaurus_db_file);
 3253:         return 0;
 3254:     } 
 3255:     #  Get the average number of appearances of a word.
 3256:     my $avecount = $thesaurus_db{'average.count'};
 3257:     #  Put keywords (those that appear > average) into %Keywords
 3258:     while (my ($word,$data)=each (%thesaurus_db)) {
 3259:         my ($count,undef) = split /:/,$data;
 3260:         $Keywords{$word}++ if ($count > $avecount);
 3261:     }
 3262:     untie %thesaurus_db;
 3263:     # Remove special values from %Keywords.
 3264:     foreach my $value ('total.count','average.count') {
 3265:         delete($Keywords{$value}) if (exists($Keywords{$value}));
 3266:   }
 3267:     return 1;
 3268: }
 3269: 
 3270: ###################################################
 3271: 
 3272: =pod
 3273: 
 3274: =item * &keyword($word)
 3275: 
 3276: Returns true if $word is a keyword.  A keyword is a word that appears more 
 3277: than the average number of times in the thesaurus database.  Calls 
 3278: &initialize_keywords
 3279: 
 3280: =cut
 3281: 
 3282: ###################################################
 3283: 
 3284: sub keyword {
 3285:     return if (!&initialize_keywords());
 3286:     my $word=lc(shift());
 3287:     $word=~s/\W//g;
 3288:     return exists($Keywords{$word});
 3289: }
 3290: 
 3291: ###############################################################
 3292: 
 3293: =pod 
 3294: 
 3295: =item * &get_related_words()
 3296: 
 3297: Look up a word in the thesaurus.  Takes a scalar argument and returns
 3298: an array of words.  If the keyword is not in the thesaurus, an empty array
 3299: will be returned.  The order of the words returned is determined by the
 3300: database which holds them.
 3301: 
 3302: Uses global $thesaurus_db_file.
 3303: 
 3304: 
 3305: =cut
 3306: 
 3307: ###############################################################
 3308: sub get_related_words {
 3309:     my $keyword = shift;
 3310:     my %thesaurus_db;
 3311:     if (! -e $thesaurus_db_file) {
 3312:         &Apache::lonnet::logthis("Attempt to access $thesaurus_db_file ".
 3313:                                  "failed because the file does not exist");
 3314:         return ();
 3315:     }
 3316:     if (! tie(%thesaurus_db,'GDBM_File',
 3317:               $thesaurus_db_file,&GDBM_READER(),0640)){
 3318:         return ();
 3319:     } 
 3320:     my @Words=();
 3321:     my $count=0;
 3322:     if (exists($thesaurus_db{$keyword})) {
 3323: 	# The first element is the number of times
 3324: 	# the word appears.  We do not need it now.
 3325: 	my (undef,@RelatedWords) = (split(/:/,$thesaurus_db{$keyword}));
 3326: 	my (undef,$mostfrequentcount)=split(/\,/,$RelatedWords[0]);
 3327: 	my $threshold=$mostfrequentcount/10;
 3328:         foreach my $possibleword (@RelatedWords) {
 3329:             my ($word,$wordcount)=split(/\,/,$possibleword);
 3330:             if ($wordcount>$threshold) {
 3331: 		push(@Words,$word);
 3332:                 $count++;
 3333:                 if ($count>10) { last; }
 3334: 	    }
 3335:         }
 3336:     }
 3337:     untie %thesaurus_db;
 3338:     return @Words;
 3339: }
 3340: 
 3341: =pod
 3342: 
 3343: =back
 3344: 
 3345: =cut
 3346: 
 3347: # -------------------------------------------------------------- Plaintext name
 3348: =pod
 3349: 
 3350: =head1 User Name Functions
 3351: 
 3352: =over 4
 3353: 
 3354: =item * &plainname($uname,$udom,$first)
 3355: 
 3356: Takes a users logon name and returns it as a string in
 3357: "first middle last generation" form 
 3358: if $first is set to 'lastname' then it returns it as
 3359: 'lastname generation, firstname middlename' if their is a lastname
 3360: 
 3361: =cut
 3362: 
 3363: 
 3364: ###############################################################
 3365: sub plainname {
 3366:     my ($uname,$udom,$first)=@_;
 3367:     return if (!defined($uname) || !defined($udom));
 3368:     my %names=&getnames($uname,$udom);
 3369:     my $name=&Apache::lonnet::format_name($names{'firstname'},
 3370: 					  $names{'middlename'},
 3371: 					  $names{'lastname'},
 3372: 					  $names{'generation'},$first);
 3373:     $name=~s/^\s+//;
 3374:     $name=~s/\s+$//;
 3375:     $name=~s/\s+/ /g;
 3376:     if ($name !~ /\S/) { $name=$uname.':'.$udom; }
 3377:     return $name;
 3378: }
 3379: 
 3380: # -------------------------------------------------------------------- Nickname
 3381: =pod
 3382: 
 3383: =item * &nickname($uname,$udom)
 3384: 
 3385: Gets a users name and returns it as a string as
 3386: 
 3387: "&quot;nickname&quot;"
 3388: 
 3389: if the user has a nickname or
 3390: 
 3391: "first middle last generation"
 3392: 
 3393: if the user does not
 3394: 
 3395: =cut
 3396: 
 3397: sub nickname {
 3398:     my ($uname,$udom)=@_;
 3399:     return if (!defined($uname) || !defined($udom));
 3400:     my %names=&getnames($uname,$udom);
 3401:     my $name=$names{'nickname'};
 3402:     if ($name) {
 3403:        $name='&quot;'.$name.'&quot;'; 
 3404:     } else {
 3405:        $name=$names{'firstname'}.' '.$names{'middlename'}.' '.
 3406: 	     $names{'lastname'}.' '.$names{'generation'};
 3407:        $name=~s/\s+$//;
 3408:        $name=~s/\s+/ /g;
 3409:     }
 3410:     return $name;
 3411: }
 3412: 
 3413: sub getnames {
 3414:     my ($uname,$udom)=@_;
 3415:     return if (!defined($uname) || !defined($udom));
 3416:     if ($udom eq 'public' && $uname eq 'public') {
 3417: 	return ('lastname' => &mt('Public'));
 3418:     }
 3419:     my $id=$uname.':'.$udom;
 3420:     my ($names,$cached)=&Apache::lonnet::is_cached_new('namescache',$id);
 3421:     if ($cached) {
 3422: 	return %{$names};
 3423:     } else {
 3424: 	my %loadnames=&Apache::lonnet::get('environment',
 3425:                     ['firstname','middlename','lastname','generation','nickname'],
 3426: 					 $udom,$uname);
 3427: 	&Apache::lonnet::do_cache_new('namescache',$id,\%loadnames);
 3428: 	return %loadnames;
 3429:     }
 3430: }
 3431: 
 3432: # -------------------------------------------------------------------- getemails
 3433: 
 3434: =pod
 3435: 
 3436: =item * &getemails($uname,$udom)
 3437: 
 3438: Gets a user's email information and returns it as a hash with keys:
 3439: notification, critnotification, permanentemail
 3440: 
 3441: For notification and critnotification, values are comma-separated lists 
 3442: of e-mail addresses; for permanentemail, value is a single e-mail address.
 3443:  
 3444: 
 3445: =cut
 3446: 
 3447: 
 3448: sub getemails {
 3449:     my ($uname,$udom)=@_;
 3450:     if ($udom eq 'public' && $uname eq 'public') {
 3451: 	return;
 3452:     }
 3453:     if (!$udom) { $udom=$env{'user.domain'}; }
 3454:     if (!$uname) { $uname=$env{'user.name'}; }
 3455:     my $id=$uname.':'.$udom;
 3456:     my ($names,$cached)=&Apache::lonnet::is_cached_new('emailscache',$id);
 3457:     if ($cached) {
 3458: 	return %{$names};
 3459:     } else {
 3460: 	my %loadnames=&Apache::lonnet::get('environment',
 3461:                     			   ['notification','critnotification',
 3462: 					    'permanentemail'],
 3463: 					   $udom,$uname);
 3464: 	&Apache::lonnet::do_cache_new('emailscache',$id,\%loadnames);
 3465: 	return %loadnames;
 3466:     }
 3467: }
 3468: 
 3469: sub flush_email_cache {
 3470:     my ($uname,$udom)=@_;
 3471:     if (!$udom)  { $udom =$env{'user.domain'}; }
 3472:     if (!$uname) { $uname=$env{'user.name'};   }
 3473:     return if ($udom eq 'public' && $uname eq 'public');
 3474:     my $id=$uname.':'.$udom;
 3475:     &Apache::lonnet::devalidate_cache_new('emailscache',$id);
 3476: }
 3477: 
 3478: # -------------------------------------------------------------------- getlangs
 3479: 
 3480: =pod
 3481: 
 3482: =item * &getlangs($uname,$udom)
 3483: 
 3484: Gets a user's language preference and returns it as a hash with key:
 3485: language.
 3486: 
 3487: =cut
 3488: 
 3489: 
 3490: sub getlangs {
 3491:     my ($uname,$udom) = @_;
 3492:     if (!$udom)  { $udom =$env{'user.domain'}; }
 3493:     if (!$uname) { $uname=$env{'user.name'};   }
 3494:     my $id=$uname.':'.$udom;
 3495:     my ($langs,$cached)=&Apache::lonnet::is_cached_new('userlangs',$id);
 3496:     if ($cached) {
 3497:         return %{$langs};
 3498:     } else {
 3499:         my %loadlangs=&Apache::lonnet::get('environment',['languages'],
 3500:                                            $udom,$uname);
 3501:         &Apache::lonnet::do_cache_new('userlangs',$id,\%loadlangs);
 3502:         return %loadlangs;
 3503:     }
 3504: }
 3505: 
 3506: sub flush_langs_cache {
 3507:     my ($uname,$udom)=@_;
 3508:     if (!$udom)  { $udom =$env{'user.domain'}; }
 3509:     if (!$uname) { $uname=$env{'user.name'};   }
 3510:     return if ($udom eq 'public' && $uname eq 'public');
 3511:     my $id=$uname.':'.$udom;
 3512:     &Apache::lonnet::devalidate_cache_new('userlangs',$id);
 3513: }
 3514: 
 3515: # ------------------------------------------------------------------ Screenname
 3516: 
 3517: =pod
 3518: 
 3519: =item * &screenname($uname,$udom)
 3520: 
 3521: Gets a users screenname and returns it as a string
 3522: 
 3523: =cut
 3524: 
 3525: sub screenname {
 3526:     my ($uname,$udom)=@_;
 3527:     if ($uname eq $env{'user.name'} &&
 3528: 	$udom eq $env{'user.domain'}) {return $env{'environment.screenname'};}
 3529:     my %names=&Apache::lonnet::get('environment',['screenname'],$udom,$uname);
 3530:     return $names{'screenname'};
 3531: }
 3532: 
 3533: 
 3534: # ------------------------------------------------------------- Confirm Wrapper
 3535: =pod
 3536: 
 3537: =item * &confirmwrapper($message)
 3538: 
 3539: Wrap messages about completion of operation in box
 3540: 
 3541: =cut
 3542: 
 3543: sub confirmwrapper {
 3544:     my ($message)=@_;
 3545:     if ($message) {
 3546:         return "\n".'<div class="LC_confirm_box">'."\n"
 3547:                .$message."\n"
 3548:                .'</div>'."\n";
 3549:     } else {
 3550:         return $message;
 3551:     }
 3552: }
 3553: 
 3554: # ------------------------------------------------------------- Message Wrapper
 3555: 
 3556: sub messagewrapper {
 3557:     my ($link,$username,$domain,$subject,$text)=@_;
 3558:     return 
 3559:         '<a href="/adm/email?compose=individual&amp;'.
 3560:         'recname='.$username.'&amp;recdom='.$domain.
 3561: 	'&amp;subject='.&escape($subject).'&amp;text='.&escape($text).'" '.
 3562:         'title="'.&mt('Send message').'">'.$link.'</a>';
 3563: }
 3564: 
 3565: # --------------------------------------------------------------- Notes Wrapper
 3566: 
 3567: sub noteswrapper {
 3568:     my ($link,$un,$do)=@_;
 3569:     return 
 3570: "<a href='/adm/email?recordftf=retrieve&amp;recname=$un&amp;recdom=$do'>$link</a>";
 3571: }
 3572: 
 3573: # ------------------------------------------------------------- Aboutme Wrapper
 3574: 
 3575: sub aboutmewrapper {
 3576:     my ($link,$username,$domain,$target,$class)=@_;
 3577:     if (!defined($username)  && !defined($domain)) {
 3578:         return;
 3579:     }
 3580:     return '<a href="/adm/'.$domain.'/'.$username.'/aboutme"'.
 3581: 	($target?' target="'.$target.'"':'').($class?' class="'.$class.'"':'').' title="'.&mt("View this user's personal information page").'">'.$link.'</a>';
 3582: }
 3583: 
 3584: # ------------------------------------------------------------ Syllabus Wrapper
 3585: 
 3586: sub syllabuswrapper {
 3587:     my ($linktext,$coursedir,$domain)=@_;
 3588:     return qq{<a href="/public/$domain/$coursedir/syllabus">$linktext</a>};
 3589: }
 3590: 
 3591: # -----------------------------------------------------------------------------
 3592: 
 3593: sub track_student_link {
 3594:     my ($linktext,$sname,$sdom,$target,$start,$only_body) = @_;
 3595:     my $link ="/adm/trackstudent?";
 3596:     my $title = 'View recent activity';
 3597:     if (defined($sname) && $sname !~ /^\s*$/ &&
 3598:         defined($sdom)  && $sdom  !~ /^\s*$/) {
 3599:         $link .= "selected_student=$sname:$sdom";
 3600:         $title .= ' of this student';
 3601:     } 
 3602:     if (defined($target) && $target !~ /^\s*$/) {
 3603:         $target = qq{target="$target"};
 3604:     } else {
 3605:         $target = '';
 3606:     }
 3607:     if ($start) { $link.='&amp;start='.$start; }
 3608:     if ($only_body) { $link .= '&amp;only_body=1'; }
 3609:     $title = &mt($title);
 3610:     $linktext = &mt($linktext);
 3611:     return qq{<a href="$link" title="$title" $target>$linktext</a>}.
 3612: 	&help_open_topic('View_recent_activity');
 3613: }
 3614: 
 3615: sub slot_reservations_link {
 3616:     my ($linktext,$sname,$sdom,$target) = @_;
 3617:     my $link ="/adm/slotrequest?command=showresv&amp;origin=aboutme";
 3618:     my $title = 'View slot reservation history';
 3619:     if (defined($sname) && $sname !~ /^\s*$/ &&
 3620:         defined($sdom)  && $sdom  !~ /^\s*$/) {
 3621:         $link .= "&amp;uname=$sname&amp;udom=$sdom";
 3622:         $title .= ' of this student';
 3623:     }
 3624:     if (defined($target) && $target !~ /^\s*$/) {
 3625:         $target = qq{target="$target"};
 3626:     } else {
 3627:         $target = '';
 3628:     }
 3629:     $title = &mt($title);
 3630:     $linktext = &mt($linktext);
 3631:     return qq{<a href="$link" title="$title" $target>$linktext</a>};
 3632: # FIXME uncomment when help item created: &help_open_topic('Slot_Reservation_History');
 3633: 
 3634: }
 3635: 
 3636: # ===================================================== Display a student photo
 3637: 
 3638: 
 3639: sub student_image_tag {
 3640:     my ($domain,$user)=@_;
 3641:     my $imgsrc=&Apache::lonnet::studentphoto($domain,$user,'jpg');
 3642:     if (($imgsrc) && ($imgsrc ne '/adm/lonKaputt/lonlogo_broken.gif')) {
 3643: 	return '<img src="'.$imgsrc.'" align="right" />';
 3644:     } else {
 3645: 	return '';
 3646:     }
 3647: }
 3648: 
 3649: =pod
 3650: 
 3651: =back
 3652: 
 3653: =head1 Access .tab File Data
 3654: 
 3655: =over 4
 3656: 
 3657: =item * &languageids() 
 3658: 
 3659: returns list of all language ids
 3660: 
 3661: =cut
 3662: 
 3663: sub languageids {
 3664:     return sort(keys(%language));
 3665: }
 3666: 
 3667: =pod
 3668: 
 3669: =item * &languagedescription() 
 3670: 
 3671: returns description of a specified language id
 3672: 
 3673: =cut
 3674: 
 3675: sub languagedescription {
 3676:     my $code=shift;
 3677:     return  ($supported_language{$code}?'* ':'').
 3678:             $language{$code}.
 3679: 	    ($supported_language{$code}?' ('.&mt('interface available').')':'');
 3680: }
 3681: 
 3682: =pod
 3683: 
 3684: =item * &plainlanguagedescription
 3685: 
 3686: Returns both the plain language description (e.g. 'Creoles and Pidgins, English-based (Other)')
 3687: and the language character encoding (e.g. ISO) separated by a ' - ' string.
 3688: 
 3689: =cut
 3690: 
 3691: sub plainlanguagedescription {
 3692:     my $code=shift;
 3693:     return $language{$code};
 3694: }
 3695: 
 3696: =pod
 3697: 
 3698: =item * &supportedlanguagecode
 3699: 
 3700: Returns the supported language code (e.g. sptutf maps to pt) given a language
 3701: code.
 3702: 
 3703: =cut
 3704: 
 3705: sub supportedlanguagecode {
 3706:     my $code=shift;
 3707:     return $supported_language{$code};
 3708: }
 3709: 
 3710: =pod
 3711: 
 3712: =item * &latexlanguage()
 3713: 
 3714: Given a language key code returns the correspondnig language to use
 3715: to select the correct hyphenation on LaTeX printouts.  This is undef if there
 3716: is no supported hyphenation for the language code.
 3717: 
 3718: =cut
 3719: 
 3720: sub latexlanguage {
 3721:     my $code = shift;
 3722:     return $latex_language{$code};
 3723: }
 3724: 
 3725: =pod
 3726: 
 3727: =item * &latexhyphenation()
 3728: 
 3729: Same as above but what's supplied is the language as it might be stored
 3730: in the metadata.
 3731: 
 3732: =cut
 3733: 
 3734: sub latexhyphenation {
 3735:     my $key = shift;
 3736:     return $latex_language_bykey{$key};
 3737: }
 3738: 
 3739: =pod
 3740: 
 3741: =item * &copyrightids() 
 3742: 
 3743: returns list of all copyrights
 3744: 
 3745: =cut
 3746: 
 3747: sub copyrightids {
 3748:     return sort(keys(%cprtag));
 3749: }
 3750: 
 3751: =pod
 3752: 
 3753: =item * &copyrightdescription() 
 3754: 
 3755: returns description of a specified copyright id
 3756: 
 3757: =cut
 3758: 
 3759: sub copyrightdescription {
 3760:     return &mt($cprtag{shift(@_)});
 3761: }
 3762: 
 3763: =pod
 3764: 
 3765: =item * &source_copyrightids() 
 3766: 
 3767: returns list of all source copyrights
 3768: 
 3769: =cut
 3770: 
 3771: sub source_copyrightids {
 3772:     return sort(keys(%scprtag));
 3773: }
 3774: 
 3775: =pod
 3776: 
 3777: =item * &source_copyrightdescription() 
 3778: 
 3779: returns description of a specified source copyright id
 3780: 
 3781: =cut
 3782: 
 3783: sub source_copyrightdescription {
 3784:     return &mt($scprtag{shift(@_)});
 3785: }
 3786: 
 3787: =pod
 3788: 
 3789: =item * &filecategories() 
 3790: 
 3791: returns list of all file categories
 3792: 
 3793: =cut
 3794: 
 3795: sub filecategories {
 3796:     return sort(keys(%category_extensions));
 3797: }
 3798: 
 3799: =pod
 3800: 
 3801: =item * &filecategorytypes() 
 3802: 
 3803: returns list of file types belonging to a given file
 3804: category
 3805: 
 3806: =cut
 3807: 
 3808: sub filecategorytypes {
 3809:     my ($cat) = @_;
 3810:     return @{$category_extensions{lc($cat)}};
 3811: }
 3812: 
 3813: =pod
 3814: 
 3815: =item * &fileembstyle() 
 3816: 
 3817: returns embedding style for a specified file type
 3818: 
 3819: =cut
 3820: 
 3821: sub fileembstyle {
 3822:     return $fe{lc(shift(@_))};
 3823: }
 3824: 
 3825: sub filemimetype {
 3826:     return $fm{lc(shift(@_))};
 3827: }
 3828: 
 3829: 
 3830: sub filecategoryselect {
 3831:     my ($name,$value)=@_;
 3832:     return &select_form($value,$name,
 3833:                         {'' => &mt('Any category'), map { $_,$_ } sort(keys(%category_extensions))});
 3834: }
 3835: 
 3836: =pod
 3837: 
 3838: =item * &filedescription() 
 3839: 
 3840: returns description for a specified file type
 3841: 
 3842: =cut
 3843: 
 3844: sub filedescription {
 3845:     my $file_description = $fd{lc(shift())};
 3846:     $file_description =~ s:([\[\]]):~$1:g;
 3847:     return &mt($file_description);
 3848: }
 3849: 
 3850: =pod
 3851: 
 3852: =item * &filedescriptionex() 
 3853: 
 3854: returns description for a specified file type with
 3855: extra formatting
 3856: 
 3857: =cut
 3858: 
 3859: sub filedescriptionex {
 3860:     my $ex=shift;
 3861:     my $file_description = $fd{lc($ex)};
 3862:     $file_description =~ s:([\[\]]):~$1:g;
 3863:     return '.'.$ex.' '.&mt($file_description);
 3864: }
 3865: 
 3866: # End of .tab access
 3867: =pod
 3868: 
 3869: =back
 3870: 
 3871: =cut
 3872: 
 3873: # ------------------------------------------------------------------ File Types
 3874: sub fileextensions {
 3875:     return sort(keys(%fe));
 3876: }
 3877: 
 3878: # ----------------------------------------------------------- Display Languages
 3879: # returns a hash with all desired display languages
 3880: #
 3881: 
 3882: sub display_languages {
 3883:     my %languages=();
 3884:     foreach my $lang (&Apache::lonlocal::preferred_languages()) {
 3885: 	$languages{$lang}=1;
 3886:     }
 3887:     &get_unprocessed_cgi($ENV{'QUERY_STRING'},['displaylanguage']);
 3888:     if ($env{'form.displaylanguage'}) {
 3889: 	foreach my $lang (split(/\s*(\,|\;|\:)\s*/,$env{'form.displaylanguage'})) {
 3890: 	    $languages{$lang}=1;
 3891:         }
 3892:     }
 3893:     return %languages;
 3894: }
 3895: 
 3896: sub languages {
 3897:     my ($possible_langs) = @_;
 3898:     my @preferred_langs = &Apache::lonlocal::preferred_languages();
 3899:     if (!ref($possible_langs)) {
 3900: 	if( wantarray ) {
 3901: 	    return @preferred_langs;
 3902: 	} else {
 3903: 	    return $preferred_langs[0];
 3904: 	}
 3905:     }
 3906:     my %possibilities = map { $_ => 1 } (@$possible_langs);
 3907:     my @preferred_possibilities;
 3908:     foreach my $preferred_lang (@preferred_langs) {
 3909: 	if (exists($possibilities{$preferred_lang})) {
 3910: 	    push(@preferred_possibilities, $preferred_lang);
 3911: 	}
 3912:     }
 3913:     if( wantarray ) {
 3914: 	return @preferred_possibilities;
 3915:     }
 3916:     return $preferred_possibilities[0];
 3917: }
 3918: 
 3919: sub user_lang {
 3920:     my ($touname,$toudom,$fromcid) = @_;
 3921:     my @userlangs;
 3922:     if (($fromcid ne '') && ($env{'course.'.$fromcid.'.languages'} ne '')) {
 3923:         @userlangs=(@userlangs,split(/\s*(\,|\;|\:)\s*/,
 3924:                     $env{'course.'.$fromcid.'.languages'}));
 3925:     } else {
 3926:         my %langhash = &getlangs($touname,$toudom);
 3927:         if ($langhash{'languages'} ne '') {
 3928:             @userlangs = split(/\s*(\,|\;|\:)\s*/,$langhash{'languages'});
 3929:         } else {
 3930:             my %domdefs = &Apache::lonnet::get_domain_defaults($toudom);
 3931:             if ($domdefs{'lang_def'} ne '') {
 3932:                 @userlangs = ($domdefs{'lang_def'});
 3933:             }
 3934:         }
 3935:     }
 3936:     my @languages=&Apache::lonlocal::get_genlanguages(@userlangs);
 3937:     my $user_lh = Apache::localize->get_handle(@languages);
 3938:     return $user_lh;
 3939: }
 3940: 
 3941: 
 3942: ###############################################################
 3943: ##               Student Answer Attempts                     ##
 3944: ###############################################################
 3945: 
 3946: =pod
 3947: 
 3948: =head1 Alternate Problem Views
 3949: 
 3950: =over 4
 3951: 
 3952: =item * &get_previous_attempt($symb, $username, $domain, $course,
 3953:     $getattempt, $regexp, $gradesub, $usec, $identifier)
 3954: 
 3955: Return string with previous attempt on problem. Arguments:
 3956: 
 3957: =over 4
 3958: 
 3959: =item * $symb: Problem, including path
 3960: 
 3961: =item * $username: username of the desired student
 3962: 
 3963: =item * $domain: domain of the desired student
 3964: 
 3965: =item * $course: Course ID
 3966: 
 3967: =item * $getattempt: Leave blank for all attempts, otherwise put
 3968:     something
 3969: 
 3970: =item * $regexp: if string matches this regexp, the string will be
 3971:     sent to $gradesub
 3972: 
 3973: =item * $gradesub: routine that processes the string if it matches $regexp
 3974: 
 3975: =item * $usec: section of the desired student
 3976: 
 3977: =item * $identifier: counter for student (multiple students one problem) or
 3978:     problem (one student; whole sequence).
 3979: 
 3980: =back
 3981: 
 3982: The output string is a table containing all desired attempts, if any.
 3983: 
 3984: =cut
 3985: 
 3986: sub get_previous_attempt {
 3987:   my ($symb,$username,$domain,$course,$getattempt,$regexp,$gradesub,$usec,$identifier)=@_;
 3988:   my $prevattempts='';
 3989:   no strict 'refs';
 3990:   if ($symb) {
 3991:     my (%returnhash)=
 3992:       &Apache::lonnet::restore($symb,$course,$domain,$username);
 3993:     if ($returnhash{'version'}) {
 3994:       my %lasthash=();
 3995:       my $version;
 3996:       for ($version=1;$version<=$returnhash{'version'};$version++) {
 3997:         foreach my $key (reverse(sort(split(/\:/,$returnhash{$version.':keys'})))) {
 3998:             if ($key =~ /\.rawrndseed$/) {
 3999:                 my ($id) = ($key =~ /^(.+)\.rawrndseed$/);
 4000:                 $lasthash{$id.'.rndseed'} = $returnhash{$version.':'.$key};
 4001:             } else {
 4002:                 $lasthash{$key}=$returnhash{$version.':'.$key};
 4003:             }
 4004:         }
 4005:       }
 4006:       $prevattempts=&start_data_table().&start_data_table_header_row();
 4007:       $prevattempts.='<th>'.&mt('History').'</th>';
 4008:       my (%typeparts,%lasthidden,%regraded,%hidestatus);
 4009:       my $showsurv=&Apache::lonnet::allowed('vas',$env{'request.course.id'});
 4010:       foreach my $key (sort(keys(%lasthash))) {
 4011: 	my ($ign,@parts) = split(/\./,$key);
 4012: 	if ($#parts > 0) {
 4013: 	  my $data=$parts[-1];
 4014:           next if ($data eq 'foilorder');
 4015: 	  pop(@parts);
 4016:           $prevattempts.='<th>'.&mt('Part ').join('.',@parts).'<br />'.$data.'&nbsp;</th>';
 4017:           if ($data eq 'type') {
 4018:               unless ($showsurv) {
 4019:                   my $id = join(',',@parts);
 4020:                   $typeparts{$ign.'.'.$id} = $lasthash{$key};
 4021:                   if (($lasthash{$key} eq 'anonsurvey') || ($lasthash{$key} eq 'anonsurveycred')) {
 4022:                       $lasthidden{$ign.'.'.$id} = 1;
 4023:                   }
 4024:               }
 4025:               if ($identifier ne '') {
 4026:                   my $id = join(',',@parts);
 4027:                   if (&Apache::lonnet::EXT("resource.$id.problemstatus",$symb,
 4028:                                                $domain,$username,$usec,undef,$course) =~ /^no/) {
 4029:                       $hidestatus{$ign.'.'.$id} = 1;
 4030:                   }
 4031:               }
 4032:           } elsif ($data eq 'regrader') {
 4033:               if (($identifier ne '') && (@parts)) {
 4034:                   my $id = join(',',@parts);
 4035:                   $regraded{$ign.'.'.$id} = 1;
 4036:               }
 4037:           } 
 4038: 	} else {
 4039: 	  if ($#parts == 0) {
 4040: 	    $prevattempts.='<th>'.$parts[0].'</th>';
 4041: 	  } else {
 4042: 	    $prevattempts.='<th>'.$ign.'</th>';
 4043: 	  }
 4044: 	}
 4045:       }
 4046:       $prevattempts.=&end_data_table_header_row();
 4047:       if ($getattempt eq '') {
 4048:         my (%solved,%resets,%probstatus);
 4049:         if (($identifier ne '') && (keys(%regraded) > 0)) {
 4050:             for ($version=1;$version<=$returnhash{'version'};$version++) {
 4051:                 foreach my $id (keys(%regraded)) {
 4052:                     if (($returnhash{$version.':'.$id.'.regrader'}) &&
 4053:                         ($returnhash{$version.':'.$id.'.tries'} eq '') &&
 4054:                         ($returnhash{$version.':'.$id.'.award'} eq '')) {
 4055:                         push(@{$resets{$id}},$version);
 4056:                     }
 4057:                 }
 4058:             }
 4059:         }
 4060: 	for ($version=1;$version<=$returnhash{'version'};$version++) {
 4061:             my (@hidden,@unsolved);
 4062:             if (%typeparts) {
 4063:                 foreach my $id (keys(%typeparts)) {
 4064:                     if (($returnhash{$version.':'.$id.'.type'} eq 'anonsurvey') ||
 4065:                         ($returnhash{$version.':'.$id.'.type'} eq 'anonsurveycred')) {
 4066:                         push(@hidden,$id);
 4067:                     } elsif ($identifier ne '') {
 4068:                         unless (($returnhash{$version.':'.$id.'.type'} eq 'survey') ||
 4069:                                 ($returnhash{$version.':'.$id.'.type'} eq 'surveycred') ||
 4070:                                 ($hidestatus{$id})) {
 4071:                             next if ((ref($resets{$id}) eq 'ARRAY') && grep(/^\Q$version\E$/,@{$resets{$id}}));
 4072:                             if ($returnhash{$version.':'.$id.'.solved'} eq 'correct_by_student') {
 4073:                                 push(@{$solved{$id}},$version);
 4074:                             } elsif (($returnhash{$version.':'.$id.'.solved'} ne '') &&
 4075:                                      (ref($solved{$id}) eq 'ARRAY')) {
 4076:                                 my $skip;
 4077:                                 if (ref($resets{$id}) eq 'ARRAY') {
 4078:                                     foreach my $reset (@{$resets{$id}}) {
 4079:                                         if ($reset > $solved{$id}[-1]) {
 4080:                                             $skip=1;
 4081:                                             last;
 4082:                                         }
 4083:                                     }
 4084:                                 }
 4085:                                 unless ($skip) {
 4086:                                     my ($ign,$partslist) = split(/\./,$id,2);
 4087:                                     push(@unsolved,$partslist);
 4088:                                 }
 4089:                             }
 4090:                         }
 4091:                     }
 4092:                 }
 4093:             }
 4094:             $prevattempts.=&start_data_table_row().
 4095:                            '<td>'.&mt('Transaction [_1]',$version);
 4096:             if (@unsolved) {
 4097:                 $prevattempts .= '<span class="LC_nobreak"><label>'.
 4098:                                  '<input type="checkbox" name="HIDE'.$identifier.'" value="'.$version.':'.join('_',@unsolved).'" />'.
 4099:                                  &mt('Hide').'</label></span>';
 4100:             }
 4101:             $prevattempts .= '</td>';
 4102:             if (@hidden) {
 4103:                 foreach my $key (sort(keys(%lasthash))) {
 4104:                     next if ($key =~ /\.foilorder$/);
 4105:                     my $hide;
 4106:                     foreach my $id (@hidden) {
 4107:                         if ($key =~ /^\Q$id\E/) {
 4108:                             $hide = 1;
 4109:                             last;
 4110:                         }
 4111:                     }
 4112:                     if ($hide) {
 4113:                         my ($id,$data) = ($key =~ /^(.+)\.([^.]+)$/);
 4114:                         if (($data eq 'award') || ($data eq 'awarddetail')) {
 4115:                             my $value = &format_previous_attempt_value($key,
 4116:                                              $returnhash{$version.':'.$key});
 4117:                             $prevattempts.='<td>'.$value.'&nbsp;</td>';
 4118:                         } else {
 4119:                             $prevattempts.='<td>&nbsp;</td>';
 4120:                         }
 4121:                     } else {
 4122:                         if ($key =~ /\./) {
 4123:                             my $value = $returnhash{$version.':'.$key};
 4124:                             if ($key =~ /\.rndseed$/) {
 4125:                                 my ($id) = ($key =~ /^(.+)\.rndseed$/);
 4126:                                 if (exists($returnhash{$version.':'.$id.'.rawrndseed'})) {
 4127:                                     $value = $returnhash{$version.':'.$id.'.rawrndseed'};
 4128:                                 }
 4129:                             }
 4130:                             $prevattempts.='<td>'.&format_previous_attempt_value($key,$value).
 4131:                                            '&nbsp;</td>';
 4132:                         } else {
 4133:                             $prevattempts.='<td>&nbsp;</td>';
 4134:                         }
 4135:                     }
 4136:                 }
 4137:             } else {
 4138: 	        foreach my $key (sort(keys(%lasthash))) {
 4139:                     next if ($key =~ /\.foilorder$/);
 4140:                     my $value = $returnhash{$version.':'.$key};
 4141:                     if ($key =~ /\.rndseed$/) {
 4142:                         my ($id) = ($key =~ /^(.+)\.rndseed$/);
 4143:                         if (exists($returnhash{$version.':'.$id.'.rawrndseed'})) {
 4144:                             $value = $returnhash{$version.':'.$id.'.rawrndseed'};
 4145:                         }
 4146:                     }
 4147:                     $prevattempts.='<td>'.&format_previous_attempt_value($key,$value).
 4148:                                    '&nbsp;</td>';
 4149: 	        }
 4150:             }
 4151: 	    $prevattempts.=&end_data_table_row();
 4152: 	 }
 4153:       }
 4154:       my @currhidden = keys(%lasthidden);
 4155:       $prevattempts.=&start_data_table_row().'<td>'.&mt('Current').'</td>';
 4156:       foreach my $key (sort(keys(%lasthash))) {
 4157:           next if ($key =~ /\.foilorder$/);
 4158:           if (%typeparts) {
 4159:               my $hidden;
 4160:               foreach my $id (@currhidden) {
 4161:                   if ($key =~ /^\Q$id\E/) {
 4162:                       $hidden = 1;
 4163:                       last;
 4164:                   }
 4165:               }
 4166:               if ($hidden) {
 4167:                   my ($id,$data) = ($key =~ /^(.+)\.([^.]+)$/);
 4168:                   if (($data eq 'award') || ($data eq 'awarddetail')) {
 4169:                       my $value = &format_previous_attempt_value($key,$lasthash{$key});
 4170:                       if ($key =~/$regexp$/ && (defined &$gradesub)) {
 4171:                           $value = &$gradesub($value);
 4172:                       }
 4173:                       $prevattempts.='<td>'.$value.'&nbsp;</td>';
 4174:                   } else {
 4175:                       $prevattempts.='<td>&nbsp;</td>';
 4176:                   }
 4177:               } else {
 4178:                   my $value = &format_previous_attempt_value($key,$lasthash{$key});
 4179:                   if ($key =~/$regexp$/ && (defined &$gradesub)) {
 4180:                       $value = &$gradesub($value);
 4181:                   }
 4182:                   $prevattempts.='<td>'.$value.'&nbsp;</td>';
 4183:               }
 4184:           } else {
 4185: 	      my $value = &format_previous_attempt_value($key,$lasthash{$key});
 4186: 	      if ($key =~/$regexp$/ && (defined &$gradesub)) {
 4187:                   $value = &$gradesub($value);
 4188:               }
 4189: 	      $prevattempts.='<td>'.$value.'&nbsp;</td>';
 4190:           }
 4191:       }
 4192:       $prevattempts.= &end_data_table_row().&end_data_table();
 4193:     } else {
 4194:       $prevattempts=
 4195: 	  &start_data_table().&start_data_table_row().
 4196: 	  '<td>'.&mt('Nothing submitted - no attempts.').'</td>'.
 4197: 	  &end_data_table_row().&end_data_table();
 4198:     }
 4199:   } else {
 4200:     $prevattempts=
 4201: 	  &start_data_table().&start_data_table_row().
 4202: 	  '<td>'.&mt('No data.').'</td>'.
 4203: 	  &end_data_table_row().&end_data_table();
 4204:   }
 4205: }
 4206: 
 4207: sub format_previous_attempt_value {
 4208:     my ($key,$value) = @_;
 4209:     if (($key =~ /timestamp/) || ($key=~/duedate/)) {
 4210: 	$value = &Apache::lonlocal::locallocaltime($value);
 4211:     } elsif (ref($value) eq 'ARRAY') {
 4212: 	$value = '('.join(', ', @{ $value }).')';
 4213:     } elsif ($key =~ /answerstring$/) {
 4214:         my %answers = &Apache::lonnet::str2hash($value);
 4215:         my @anskeys = sort(keys(%answers));
 4216:         if (@anskeys == 1) {
 4217:             my $answer = $answers{$anskeys[0]};
 4218:             if ($answer =~ m{\0}) {
 4219:                 $answer =~ s{\0}{,}g;
 4220:             }
 4221:             my $tag_internal_answer_name = 'INTERNAL';
 4222:             if ($anskeys[0] eq $tag_internal_answer_name) {
 4223:                 $value = $answer; 
 4224:             } else {
 4225:                 $value = $anskeys[0].'='.$answer;
 4226:             }
 4227:         } else {
 4228:             foreach my $ans (@anskeys) {
 4229:                 my $answer = $answers{$ans};
 4230:                 if ($answer =~ m{\0}) {
 4231:                     $answer =~ s{\0}{,}g;
 4232:                 }
 4233:                 $value .=  $ans.'='.$answer.'<br />';;
 4234:             } 
 4235:         }
 4236:     } else {
 4237: 	$value = &unescape($value);
 4238:     }
 4239:     return $value;
 4240: }
 4241: 
 4242: 
 4243: sub relative_to_absolute {
 4244:     my ($url,$output)=@_;
 4245:     my $parser=HTML::TokeParser->new(\$output);
 4246:     my $token;
 4247:     my $thisdir=$url;
 4248:     my @rlinks=();
 4249:     while ($token=$parser->get_token) {
 4250: 	if ($token->[0] eq 'S') {
 4251: 	    if ($token->[1] eq 'a') {
 4252: 		if ($token->[2]->{'href'}) {
 4253: 		    $rlinks[$#rlinks+1]=$token->[2]->{'href'};
 4254: 		}
 4255: 	    } elsif ($token->[1] eq 'img' || $token->[1] eq 'embed' ) {
 4256: 		$rlinks[$#rlinks+1]=$token->[2]->{'src'};
 4257: 	    } elsif ($token->[1] eq 'base') {
 4258: 		$thisdir=$token->[2]->{'href'};
 4259: 	    }
 4260: 	}
 4261:     }
 4262:     $thisdir=~s-/[^/]*$--;
 4263:     foreach my $link (@rlinks) {
 4264: 	unless (($link=~/^https?\:\/\//i) ||
 4265: 		($link=~/^\//) ||
 4266: 		($link=~/^javascript:/i) ||
 4267: 		($link=~/^mailto:/i) ||
 4268: 		($link=~/^\#/)) {
 4269: 	    my $newlocation=&Apache::lonnet::hreflocation($thisdir,$link);
 4270: 	    $output=~s/(\"|\'|\=\s*)\Q$link\E(\"|\'|\s|\>)/$1$newlocation$2/;
 4271: 	}
 4272:     }
 4273: # -------------------------------------------------- Deal with Applet codebases
 4274:     $output=~s/(\<applet[^\>]+)(codebase\=[^\S\>]+)*([^\>]*)\>/$1.($2?$2:' codebase="'.$thisdir.'"').$3.'>'/gei;
 4275:     return $output;
 4276: }
 4277: 
 4278: =pod
 4279: 
 4280: =item * &get_student_view()
 4281: 
 4282: show a snapshot of what student was looking at
 4283: 
 4284: =cut
 4285: 
 4286: sub get_student_view {
 4287:   my ($symb,$username,$domain,$courseid,$target,$moreenv) = @_;
 4288:   my ($map,$id,$feedurl) = &Apache::lonnet::decode_symb($symb);
 4289:   my (%form);
 4290:   my @elements=('symb','courseid','domain','username');
 4291:   foreach my $element (@elements) {
 4292:       $form{'grade_'.$element}=eval '$'.$element #'
 4293:   }
 4294:   if (defined($moreenv)) {
 4295:       %form=(%form,%{$moreenv});
 4296:   }
 4297:   if (defined($target)) { $form{'grade_target'} = $target; }
 4298:   $feedurl=&Apache::lonnet::clutter($feedurl);
 4299:   my ($userview,$response)=&Apache::lonnet::ssi_body($feedurl,%form);
 4300:   $userview=~s/\<body[^\>]*\>//gi;
 4301:   $userview=~s/\<\/body\>//gi;
 4302:   $userview=~s/\<html\>//gi;
 4303:   $userview=~s/\<\/html\>//gi;
 4304:   $userview=~s/\<head\>//gi;
 4305:   $userview=~s/\<\/head\>//gi;
 4306:   $userview=~s/action\s*\=/would_be_action\=/gi;
 4307:   $userview=&relative_to_absolute($feedurl,$userview);
 4308:   if (wantarray) {
 4309:      return ($userview,$response);
 4310:   } else {
 4311:      return $userview;
 4312:   }
 4313: }
 4314: 
 4315: sub get_student_view_with_retries {
 4316:   my ($symb,$retries,$username,$domain,$courseid,$target,$moreenv) = @_;
 4317: 
 4318:     my $ok = 0;                 # True if we got a good response.
 4319:     my $content;
 4320:     my $response;
 4321: 
 4322:     # Try to get the student_view done. within the retries count:
 4323:     
 4324:     do {
 4325:          ($content, $response) = &get_student_view($symb,$username,$domain,$courseid,$target,$moreenv);
 4326:          $ok      = $response->is_success;
 4327:          if (!$ok) {
 4328:             &Apache::lonnet::logthis("Failed get_student_view_with_retries on $symb: ".$response->is_success.', '.$response->code.', '.$response->message);
 4329:          }
 4330:          $retries--;
 4331:     } while (!$ok && ($retries > 0));
 4332:     
 4333:     if (!$ok) {
 4334:        $content = '';          # On error return an empty content.
 4335:     }
 4336:     if (wantarray) {
 4337:        return ($content, $response);
 4338:     } else {
 4339:        return $content;
 4340:     }
 4341: }
 4342: 
 4343: =pod
 4344: 
 4345: =item * &get_student_answers() 
 4346: 
 4347: show a snapshot of how student was answering problem
 4348: 
 4349: =cut
 4350: 
 4351: sub get_student_answers {
 4352:   my ($symb,$username,$domain,$courseid,%form) = @_;
 4353:   my ($map,$id,$feedurl) = &Apache::lonnet::decode_symb($symb);
 4354:   my (%moreenv);
 4355:   my @elements=('symb','courseid','domain','username');
 4356:   foreach my $element (@elements) {
 4357:     $moreenv{'grade_'.$element}=eval '$'.$element #'
 4358:   }
 4359:   $moreenv{'grade_target'}='answer';
 4360:   %moreenv=(%form,%moreenv);
 4361:   $feedurl = &Apache::lonnet::clutter($feedurl);
 4362:   my $userview=&Apache::lonnet::ssi($feedurl,%moreenv);
 4363:   return $userview;
 4364: }
 4365: 
 4366: =pod
 4367: 
 4368: =item * &submlink()
 4369: 
 4370: Inputs: $text $uname $udom $symb $target
 4371: 
 4372: Returns: A link to grades.pm such as to see the SUBM view of a student
 4373: 
 4374: =cut
 4375: 
 4376: ###############################################
 4377: sub submlink {
 4378:     my ($text,$uname,$udom,$symb,$target)=@_;
 4379:     if (!($uname && $udom)) {
 4380: 	(my $cursymb, my $courseid,$udom,$uname)=
 4381: 	    &Apache::lonnet::whichuser($symb);
 4382: 	if (!$symb) { $symb=$cursymb; }
 4383:     }
 4384:     if (!$symb) { $symb=&Apache::lonnet::symbread(); }
 4385:     $symb=&escape($symb);
 4386:     if ($target) { $target=" target=\"$target\""; }
 4387:     return
 4388:         '<a href="/adm/grades?command=submission'.
 4389:         '&amp;symb='.$symb.
 4390:         '&amp;student='.$uname.
 4391:         '&amp;userdom='.$udom.'"'.
 4392:         $target.'>'.$text.'</a>';
 4393: }
 4394: ##############################################
 4395: 
 4396: =pod
 4397: 
 4398: =item * &pgrdlink()
 4399: 
 4400: Inputs: $text $uname $udom $symb $target
 4401: 
 4402: Returns: A link to grades.pm such as to see the PGRD view of a student
 4403: 
 4404: =cut
 4405: 
 4406: ###############################################
 4407: sub pgrdlink {
 4408:     my $link=&submlink(@_);
 4409:     $link=~s/(&command=submission)/$1&showgrading=yes/;
 4410:     return $link;
 4411: }
 4412: ##############################################
 4413: 
 4414: =pod
 4415: 
 4416: =item * &pprmlink()
 4417: 
 4418: Inputs: $text $uname $udom $symb $target
 4419: 
 4420: Returns: A link to parmset.pm such as to see the PPRM view of a
 4421: student and a specific resource
 4422: 
 4423: =cut
 4424: 
 4425: ###############################################
 4426: sub pprmlink {
 4427:     my ($text,$uname,$udom,$symb,$target)=@_;
 4428:     if (!($uname && $udom)) {
 4429: 	(my $cursymb, my $courseid,$udom,$uname)=
 4430: 	    &Apache::lonnet::whichuser($symb);
 4431: 	if (!$symb) { $symb=$cursymb; }
 4432:     }
 4433:     if (!$symb) { $symb=&Apache::lonnet::symbread(); }
 4434:     $symb=&escape($symb);
 4435:     if ($target) { $target="target=\"$target\""; }
 4436:     return '<a href="/adm/parmset?command=set&amp;'.
 4437: 	'symb='.$symb.'&amp;uname='.$uname.
 4438: 	'&amp;udom='.$udom.'" '.$target.'>'.$text.'</a>';
 4439: }
 4440: ##############################################
 4441: 
 4442: =pod
 4443: 
 4444: =back
 4445: 
 4446: =cut
 4447: 
 4448: ###############################################
 4449: 
 4450: 
 4451: sub timehash {
 4452:     my ($thistime) = @_;
 4453:     my $timezone = &Apache::lonlocal::gettimezone();
 4454:     my $dt = DateTime->from_epoch(epoch => $thistime)
 4455:                      ->set_time_zone($timezone);
 4456:     my $wday = $dt->day_of_week();
 4457:     if ($wday == 7) { $wday = 0; }
 4458:     return ( 'second' => $dt->second(),
 4459:              'minute' => $dt->minute(),
 4460:              'hour'   => $dt->hour(),
 4461:              'day'     => $dt->day_of_month(),
 4462:              'month'   => $dt->month(),
 4463:              'year'    => $dt->year(),
 4464:              'weekday' => $wday,
 4465:              'dayyear' => $dt->day_of_year(),
 4466:              'dlsav'   => $dt->is_dst() );
 4467: }
 4468: 
 4469: sub utc_string {
 4470:     my ($date)=@_;
 4471:     return strftime("%Y%m%dT%H%M%SZ",gmtime($date));
 4472: }
 4473: 
 4474: sub maketime {
 4475:     my %th=@_;
 4476:     my ($epoch_time,$timezone,$dt);
 4477:     $timezone = &Apache::lonlocal::gettimezone();
 4478:     eval {
 4479:         $dt = DateTime->new( year   => $th{'year'},
 4480:                              month  => $th{'month'},
 4481:                              day    => $th{'day'},
 4482:                              hour   => $th{'hour'},
 4483:                              minute => $th{'minute'},
 4484:                              second => $th{'second'},
 4485:                              time_zone => $timezone,
 4486:                          );
 4487:     };
 4488:     if (!$@) {
 4489:         $epoch_time = $dt->epoch;
 4490:         if ($epoch_time) {
 4491:             return $epoch_time;
 4492:         }
 4493:     }
 4494:     return POSIX::mktime(
 4495:         ($th{'seconds'},$th{'minutes'},$th{'hours'},
 4496:          $th{'day'},$th{'month'}-1,$th{'year'}-1900,0,0,-1));
 4497: }
 4498: 
 4499: #########################################
 4500: 
 4501: sub findallcourses {
 4502:     my ($roles,$uname,$udom) = @_;
 4503:     my %roles;
 4504:     if (ref($roles)) { %roles = map { $_ => 1 } @{$roles}; }
 4505:     my %courses;
 4506:     my $now=time;
 4507:     if (!defined($uname)) {
 4508:         $uname = $env{'user.name'};
 4509:     }
 4510:     if (!defined($udom)) {
 4511:         $udom = $env{'user.domain'};
 4512:     }
 4513:     if (($uname ne $env{'user.name'}) || ($udom ne $env{'user.domain'})) {
 4514:         my %roleshash = &Apache::lonnet::dump('roles',$udom,$uname);
 4515:         if (!%roles) {
 4516:             %roles = (
 4517:                        cc => 1,
 4518:                        co => 1,
 4519:                        in => 1,
 4520:                        ep => 1,
 4521:                        ta => 1,
 4522:                        cr => 1,
 4523:                        st => 1,
 4524:              );
 4525:         }
 4526:         foreach my $entry (keys(%roleshash)) {
 4527:             my ($trole,$tend,$tstart) = split(/_/,$roleshash{$entry});
 4528:             if ($trole =~ /^cr/) { 
 4529:                 next if (!exists($roles{$trole}) && !exists($roles{'cr'}));
 4530:             } else {
 4531:                 next if (!exists($roles{$trole}));
 4532:             }
 4533:             if ($tend) {
 4534:                 next if ($tend < $now);
 4535:             }
 4536:             if ($tstart) {
 4537:                 next if ($tstart > $now);
 4538:             }
 4539:             my ($cdom,$cnum,$sec,$cnumpart,$secpart,$role);
 4540:             (undef,$cdom,$cnumpart,$secpart) = split(/\//,$entry);
 4541:             my $value = $trole.'/'.$cdom.'/';
 4542:             if ($secpart eq '') {
 4543:                 ($cnum,$role) = split(/_/,$cnumpart); 
 4544:                 $sec = 'none';
 4545:                 $value .= $cnum.'/';
 4546:             } else {
 4547:                 $cnum = $cnumpart;
 4548:                 ($sec,$role) = split(/_/,$secpart);
 4549:                 $value .= $cnum.'/'.$sec;
 4550:             }
 4551:             if (ref($courses{$cdom.'_'.$cnum}{$sec}) eq 'ARRAY') {
 4552:                 unless (grep(/^\Q$value\E$/,@{$courses{$cdom.'_'.$cnum}{$sec}})) {
 4553:                     push(@{$courses{$cdom.'_'.$cnum}{$sec}},$value);
 4554:                 }
 4555:             } else {
 4556:                 @{$courses{$cdom.'_'.$cnum}{$sec}} = ($value);
 4557:             }
 4558:         }
 4559:     } else {
 4560:         foreach my $key (keys(%env)) {
 4561: 	    if ( $key=~m{^user\.role\.(\w+)\./($match_domain)/($match_courseid)/?(\w*)$} ||
 4562:                  $key=~m{^user\.role\.(cr/$match_domain/$match_username/\w+)\./($match_domain)/($match_courseid)/?(\w*)$}) {
 4563: 	        my ($role,$cdom,$cnum,$sec) = ($1,$2,$3,$4);
 4564: 	        next if ($role eq 'ca' || $role eq 'aa');
 4565: 	        next if (%roles && !exists($roles{$role}));
 4566: 	        my ($starttime,$endtime)=split(/\./,$env{$key});
 4567:                 my $active=1;
 4568:                 if ($starttime) {
 4569: 		    if ($now<$starttime) { $active=0; }
 4570:                 }
 4571:                 if ($endtime) {
 4572:                     if ($now>$endtime) { $active=0; }
 4573:                 }
 4574:                 if ($active) {
 4575:                     my $value = $role.'/'.$cdom.'/'.$cnum.'/';
 4576:                     if ($sec eq '') {
 4577:                         $sec = 'none';
 4578:                     } else {
 4579:                         $value .= $sec;
 4580:                     }
 4581:                     if (ref($courses{$cdom.'_'.$cnum}{$sec}) eq 'ARRAY') {
 4582:                         unless (grep(/^\Q$value\E$/,@{$courses{$cdom.'_'.$cnum}{$sec}})) {
 4583:                             push(@{$courses{$cdom.'_'.$cnum}{$sec}},$value);
 4584:                         }
 4585:                     } else {
 4586:                         @{$courses{$cdom.'_'.$cnum}{$sec}} = ($value);
 4587:                     }
 4588:                 }
 4589:             }
 4590:         }
 4591:     }
 4592:     return %courses;
 4593: }
 4594: 
 4595: ###############################################
 4596: 
 4597: sub blockcheck {
 4598:     my ($setters,$activity,$uname,$udom,$url,$is_course) = @_;
 4599: 
 4600:     if (defined($udom) && defined($uname)) {
 4601:         # If uname and udom are for a course, check for blocks in the course.
 4602:         if (($is_course) || (&Apache::lonnet::is_course($udom,$uname))) {
 4603:             my ($startblock,$endblock,$triggerblock) =
 4604:                 &get_blocks($setters,$activity,$udom,$uname,$url);
 4605:             return ($startblock,$endblock,$triggerblock);
 4606:         }
 4607:     } else {
 4608:         $udom = $env{'user.domain'};
 4609:         $uname = $env{'user.name'};
 4610:     }
 4611: 
 4612:     my $startblock = 0;
 4613:     my $endblock = 0;
 4614:     my $triggerblock = '';
 4615:     my %live_courses = &findallcourses(undef,$uname,$udom);
 4616: 
 4617:     # If uname is for a user, and activity is course-specific, i.e.,
 4618:     # boards, chat or groups, check for blocking in current course only.
 4619: 
 4620:     if (($activity eq 'boards' || $activity eq 'chat' ||
 4621:          $activity eq 'groups' || $activity eq 'printout') &&
 4622:         ($env{'request.course.id'})) {
 4623:         foreach my $key (keys(%live_courses)) {
 4624:             if ($key ne $env{'request.course.id'}) {
 4625:                 delete($live_courses{$key});
 4626:             }
 4627:         }
 4628:     }
 4629: 
 4630:     my $otheruser = 0;
 4631:     my %own_courses;
 4632:     if ((($uname ne $env{'user.name'})) || ($udom ne $env{'user.domain'})) {
 4633:         # Resource belongs to user other than current user.
 4634:         $otheruser = 1;
 4635:         # Gather courses for current user
 4636:         %own_courses = 
 4637:             &findallcourses(undef,$env{'user.name'},$env{'user.domain'});
 4638:     }
 4639: 
 4640:     # Gather active course roles - course coordinator, instructor, 
 4641:     # exam proctor, ta, student, or custom role.
 4642: 
 4643:     foreach my $course (keys(%live_courses)) {
 4644:         my ($cdom,$cnum);
 4645:         if ((defined($env{'course.'.$course.'.domain'})) && (defined($env{'course.'.$course.'.num'}))) {
 4646:             $cdom = $env{'course.'.$course.'.domain'};
 4647:             $cnum = $env{'course.'.$course.'.num'};
 4648:         } else {
 4649:             ($cdom,$cnum) = split(/_/,$course); 
 4650:         }
 4651:         my $no_ownblock = 0;
 4652:         my $no_userblock = 0;
 4653:         if ($otheruser && $activity ne 'com') {
 4654:             # Check if current user has 'evb' priv for this
 4655:             if (defined($own_courses{$course})) {
 4656:                 foreach my $sec (keys(%{$own_courses{$course}})) {
 4657:                     my $checkrole = 'cm./'.$cdom.'/'.$cnum;
 4658:                     if ($sec ne 'none') {
 4659:                         $checkrole .= '/'.$sec;
 4660:                     }
 4661:                     if (&Apache::lonnet::allowed('evb',undef,undef,$checkrole)) {
 4662:                         $no_ownblock = 1;
 4663:                         last;
 4664:                     }
 4665:                 }
 4666:             }
 4667:             # if they have 'evb' priv and are currently not playing student
 4668:             next if (($no_ownblock) &&
 4669:                  ($env{'request.role'} !~ m{^st\./$cdom/$cnum}));
 4670:         }
 4671:         foreach my $sec (keys(%{$live_courses{$course}})) {
 4672:             my $checkrole = 'cm./'.$cdom.'/'.$cnum;
 4673:             if ($sec ne 'none') {
 4674:                 $checkrole .= '/'.$sec;
 4675:             }
 4676:             if ($otheruser) {
 4677:                 # Resource belongs to user other than current user.
 4678:                 # Assemble privs for that user, and check for 'evb' priv.
 4679:                 my (%allroles,%userroles);
 4680:                 if (ref($live_courses{$course}{$sec}) eq 'ARRAY') {
 4681:                     foreach my $entry (@{$live_courses{$course}{$sec}}) { 
 4682:                         my ($trole,$tdom,$tnum,$tsec);
 4683:                         if ($entry =~ /^cr/) {
 4684:                             ($trole,$tdom,$tnum,$tsec) = 
 4685:                                 ($entry =~ m|^(cr/$match_domain/$match_username/\w+)\./($match_domain)/($match_username)/?(\w*)$|);
 4686:                         } else {
 4687:                            ($trole,$tdom,$tnum,$tsec) = split(/\//,$entry);
 4688:                         }
 4689:                         my ($spec,$area,$trest);
 4690:                         $area = '/'.$tdom.'/'.$tnum;
 4691:                         $trest = $tnum;
 4692:                         if ($tsec ne '') {
 4693:                             $area .= '/'.$tsec;
 4694:                             $trest .= '/'.$tsec;
 4695:                         }
 4696:                         $spec = $trole.'.'.$area;
 4697:                         if ($trole =~ /^cr/) {
 4698:                             &Apache::lonnet::custom_roleprivs(\%allroles,$trole,
 4699:                                                               $tdom,$spec,$trest,$area);
 4700:                         } else {
 4701:                             &Apache::lonnet::standard_roleprivs(\%allroles,$trole,
 4702:                                                                 $tdom,$spec,$trest,$area);
 4703:                         }
 4704:                     }
 4705:                     my ($author,$adv,$rar) = &Apache::lonnet::set_userprivs(\%userroles,\%allroles);
 4706:                     if ($userroles{'user.priv.'.$checkrole} =~ /evb\&([^\:]*)/) {
 4707:                         if ($1) {
 4708:                             $no_userblock = 1;
 4709:                             last;
 4710:                         }
 4711:                     }
 4712:                 }
 4713:             } else {
 4714:                 # Resource belongs to current user
 4715:                 # Check for 'evb' priv via lonnet::allowed().
 4716:                 if (&Apache::lonnet::allowed('evb',undef,undef,$checkrole)) {
 4717:                     $no_ownblock = 1;
 4718:                     last;
 4719:                 }
 4720:             }
 4721:         }
 4722:         # if they have the evb priv and are currently not playing student
 4723:         next if (($no_ownblock) &&
 4724:                  ($env{'request.role'} !~ m{^st\./\Q$cdom\E/\Q$cnum\E}));
 4725:         next if ($no_userblock);
 4726: 
 4727:         # Retrieve blocking times and identity of blocker for course
 4728:         # of specified user, unless user has 'evb' privilege.
 4729:         
 4730:         my ($start,$end,$trigger) = 
 4731:             &get_blocks($setters,$activity,$cdom,$cnum,$url);
 4732:         if (($start != 0) && 
 4733:             (($startblock == 0) || ($startblock > $start))) {
 4734:             $startblock = $start;
 4735:             if ($trigger ne '') {
 4736:                 $triggerblock = $trigger;
 4737:             }
 4738:         }
 4739:         if (($end != 0)  &&
 4740:             (($endblock == 0) || ($endblock < $end))) {
 4741:             $endblock = $end;
 4742:             if ($trigger ne '') {
 4743:                 $triggerblock = $trigger;
 4744:             }
 4745:         }
 4746:     }
 4747:     return ($startblock,$endblock,$triggerblock);
 4748: }
 4749: 
 4750: sub get_blocks {
 4751:     my ($setters,$activity,$cdom,$cnum,$url) = @_;
 4752:     my $startblock = 0;
 4753:     my $endblock = 0;
 4754:     my $triggerblock = '';
 4755:     my $course = $cdom.'_'.$cnum;
 4756:     $setters->{$course} = {};
 4757:     $setters->{$course}{'staff'} = [];
 4758:     $setters->{$course}{'times'} = [];
 4759:     $setters->{$course}{'triggers'} = [];
 4760:     my (@blockers,%triggered);
 4761:     my $now = time;
 4762:     my %commblocks = &Apache::lonnet::get_comm_blocks($cdom,$cnum);
 4763:     if ($activity eq 'docs') {
 4764:         @blockers = &Apache::lonnet::has_comm_blocking('bre',undef,$url,\%commblocks);
 4765:         foreach my $block (@blockers) {
 4766:             if ($block =~ /^firstaccess____(.+)$/) {
 4767:                 my $item = $1;
 4768:                 my $type = 'map';
 4769:                 my $timersymb = $item;
 4770:                 if ($item eq 'course') {
 4771:                     $type = 'course';
 4772:                 } elsif ($item =~ /___\d+___/) {
 4773:                     $type = 'resource';
 4774:                 } else {
 4775:                     $timersymb = &Apache::lonnet::symbread($item);
 4776:                 }
 4777:                 my $start = $env{'course.'.$cdom.'_'.$cnum.'.firstaccess.'.$timersymb};
 4778:                 my $end = $start + $env{'course.'.$cdom.'_'.$cnum.'.timerinterval.'.$timersymb};
 4779:                 $triggered{$block} = {
 4780:                                        start => $start,
 4781:                                        end   => $end,
 4782:                                        type  => $type,
 4783:                                      };
 4784:             }
 4785:         }
 4786:     } else {
 4787:         foreach my $block (keys(%commblocks)) {
 4788:             if ($block =~ m/^(\d+)____(\d+)$/) { 
 4789:                 my ($start,$end) = ($1,$2);
 4790:                 if ($start <= time && $end >= time) {
 4791:                     if (ref($commblocks{$block}) eq 'HASH') {
 4792:                         if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
 4793:                             if ($commblocks{$block}{'blocks'}{$activity} eq 'on') {
 4794:                                 unless(grep(/^\Q$block\E$/,@blockers)) {
 4795:                                     push(@blockers,$block);
 4796:                                 }
 4797:                             }
 4798:                         }
 4799:                     }
 4800:                 }
 4801:             } elsif ($block =~ /^firstaccess____(.+)$/) {
 4802:                 my $item = $1;
 4803:                 my $timersymb = $item; 
 4804:                 my $type = 'map';
 4805:                 if ($item eq 'course') {
 4806:                     $type = 'course';
 4807:                 } elsif ($item =~ /___\d+___/) {
 4808:                     $type = 'resource';
 4809:                 } else {
 4810:                     $timersymb = &Apache::lonnet::symbread($item);
 4811:                 }
 4812:                 my $start = $env{'course.'.$cdom.'_'.$cnum.'.firstaccess.'.$timersymb};
 4813:                 my $end = $start + $env{'course.'.$cdom.'_'.$cnum.'.timerinterval.'.$timersymb}; 
 4814:                 if ($start && $end) {
 4815:                     if (($start <= time) && ($end >= time)) {
 4816:                         unless (grep(/^\Q$block\E$/,@blockers)) {
 4817:                             push(@blockers,$block);
 4818:                             $triggered{$block} = {
 4819:                                                    start => $start,
 4820:                                                    end   => $end,
 4821:                                                    type  => $type,
 4822:                                                  };
 4823:                         }
 4824:                     }
 4825:                 }
 4826:             }
 4827:         }
 4828:     }
 4829:     foreach my $blocker (@blockers) {
 4830:         my ($staff_name,$staff_dom,$title,$blocks) =
 4831:             &parse_block_record($commblocks{$blocker});
 4832:         push(@{$$setters{$course}{'staff'}},[$staff_name,$staff_dom]);
 4833:         my ($start,$end,$triggertype);
 4834:         if ($blocker =~ m/^(\d+)____(\d+)$/) {
 4835:             ($start,$end) = ($1,$2);
 4836:         } elsif (ref($triggered{$blocker}) eq 'HASH') {
 4837:             $start = $triggered{$blocker}{'start'};
 4838:             $end = $triggered{$blocker}{'end'};
 4839:             $triggertype = $triggered{$blocker}{'type'};
 4840:         }
 4841:         if ($start) {
 4842:             push(@{$$setters{$course}{'times'}}, [$start,$end]);
 4843:             if ($triggertype) {
 4844:                 push(@{$$setters{$course}{'triggers'}},$triggertype);
 4845:             } else {
 4846:                 push(@{$$setters{$course}{'triggers'}},0);
 4847:             }
 4848:             if ( ($startblock == 0) || ($startblock > $start) ) {
 4849:                 $startblock = $start;
 4850:                 if ($triggertype) {
 4851:                     $triggerblock = $blocker;
 4852:                 }
 4853:             }
 4854:             if ( ($endblock == 0) || ($endblock < $end) ) {
 4855:                $endblock = $end;
 4856:                if ($triggertype) {
 4857:                    $triggerblock = $blocker;
 4858:                }
 4859:             }
 4860:         }
 4861:     }
 4862:     return ($startblock,$endblock,$triggerblock);
 4863: }
 4864: 
 4865: sub parse_block_record {
 4866:     my ($record) = @_;
 4867:     my ($setuname,$setudom,$title,$blocks);
 4868:     if (ref($record) eq 'HASH') {
 4869:         ($setuname,$setudom) = split(/:/,$record->{'setter'});
 4870:         $title = &unescape($record->{'event'});
 4871:         $blocks = $record->{'blocks'};
 4872:     } else {
 4873:         my @data = split(/:/,$record,3);
 4874:         if (scalar(@data) eq 2) {
 4875:             $title = $data[1];
 4876:             ($setuname,$setudom) = split(/@/,$data[0]);
 4877:         } else {
 4878:             ($setuname,$setudom,$title) = @data;
 4879:         }
 4880:         $blocks = { 'com' => 'on' };
 4881:     }
 4882:     return ($setuname,$setudom,$title,$blocks);
 4883: }
 4884: 
 4885: sub blocking_status {
 4886:     my ($activity,$uname,$udom,$url,$is_course) = @_;
 4887:     my %setters;
 4888: 
 4889: # check for active blocking
 4890:     my ($startblock,$endblock,$triggerblock) = 
 4891:         &blockcheck(\%setters,$activity,$uname,$udom,$url,$is_course);
 4892:     my $blocked = 0;
 4893:     if ($startblock && $endblock) {
 4894:         $blocked = 1;
 4895:     }
 4896: 
 4897: # caller just wants to know whether a block is active
 4898:     if (!wantarray) { return $blocked; }
 4899: 
 4900: # build a link to a popup window containing the details
 4901:     my $querystring  = "?activity=$activity";
 4902: # $uname and $udom decide whose portfolio the user is trying to look at
 4903:     if (($activity eq 'port') || ($activity eq 'passwd')) {
 4904:         $querystring .= "&amp;udom=$udom"      if ($udom =~ /^$match_domain$/);
 4905:         $querystring .= "&amp;uname=$uname"    if ($uname =~ /^$match_username$/);
 4906:     } elsif ($activity eq 'docs') {
 4907:         $querystring .= '&amp;url='.&HTML::Entities::encode($url,'&"');
 4908:     }
 4909: 
 4910:     my $output .= <<'END_MYBLOCK';
 4911: function openWindow(url, wdwName, w, h, toolbar,scrollbar) {
 4912:     var options = "width=" + w + ",height=" + h + ",";
 4913:     options += "resizable=yes,scrollbars="+scrollbar+",status=no,";
 4914:     options += "menubar=no,toolbar="+toolbar+",location=no,directories=no";
 4915:     var newWin = window.open(url, wdwName, options);
 4916:     newWin.focus();
 4917: }
 4918: END_MYBLOCK
 4919: 
 4920:     $output = Apache::lonhtmlcommon::scripttag($output);
 4921:   
 4922:     my $popupUrl = "/adm/blockingstatus/$querystring";
 4923:     my $text = &mt('Communication Blocked');
 4924:     my $class = 'LC_comblock';
 4925:     if ($activity eq 'docs') {
 4926:         $text = &mt('Content Access Blocked');
 4927:         $class = '';
 4928:     } elsif ($activity eq 'printout') {
 4929:         $text = &mt('Printing Blocked');
 4930:     } elsif ($activity eq 'passwd') {
 4931:         $text = &mt('Password Changing Blocked');
 4932:     }
 4933:     $output .= <<"END_BLOCK";
 4934: <div class='$class'>
 4935:   <a onclick='openWindow("$popupUrl","Blocking Table",600,300,"no","no");return false;' href='/adm/blockingstatus/$querystring'
 4936:   title='$text'>
 4937:   <img class='LC_noBorder LC_middle' title='$text' src='/res/adm/pages/comblock.png' alt='$text'/></a>
 4938:   <a onclick='openWindow("$popupUrl","Blocking Table",600,300,"no","no");return false;' href='/adm/blockingstatus/$querystring' 
 4939:   title='$text'>$text</a>
 4940: </div>
 4941: 
 4942: END_BLOCK
 4943: 
 4944:     return ($blocked, $output);
 4945: }
 4946: 
 4947: ###############################################
 4948: 
 4949: sub check_ip_acc {
 4950:     my ($acc,$clientip)=@_;
 4951:     &Apache::lonxml::debug("acc is $acc");
 4952:     if (!defined($acc) || $acc =~ /^\s*$/ || $acc =~/^\s*no\s*$/i) {
 4953:         return 1;
 4954:     }
 4955:     my $allowed=0;
 4956:     my $ip=$ENV{'REMOTE_ADDR'} || $clientip || $env{'request.host'};
 4957: 
 4958:     my $name;
 4959:     foreach my $pattern (split(',',$acc)) {
 4960:         $pattern =~ s/^\s*//;
 4961:         $pattern =~ s/\s*$//;
 4962:         if ($pattern =~ /\*$/) {
 4963:             #35.8.*
 4964:             $pattern=~s/\*//;
 4965:             if ($ip =~ /^\Q$pattern\E/) { $allowed=1; }
 4966:         } elsif ($pattern =~ /(\d+\.\d+\.\d+)\.\[(\d+)-(\d+)\]$/) {
 4967:             #35.8.3.[34-56]
 4968:             my $low=$2;
 4969:             my $high=$3;
 4970:             $pattern=$1;
 4971:             if ($ip =~ /^\Q$pattern\E/) {
 4972:                 my $last=(split(/\./,$ip))[3];
 4973:                 if ($last <=$high && $last >=$low) { $allowed=1; }
 4974:             }
 4975:         } elsif ($pattern =~ /^\*/) {
 4976:             #*.msu.edu
 4977:             $pattern=~s/\*//;
 4978:             if (!defined($name)) {
 4979:                 use Socket;
 4980:                 my $netaddr=inet_aton($ip);
 4981:                 ($name)=gethostbyaddr($netaddr,AF_INET);
 4982:             }
 4983:             if ($name =~ /\Q$pattern\E$/i) { $allowed=1; }
 4984:         } elsif ($pattern =~ /\d+\.\d+\.\d+\.\d+/) {
 4985:             #127.0.0.1
 4986:             if ($ip =~ /^\Q$pattern\E/) { $allowed=1; }
 4987:         } else {
 4988:             #some.name.com
 4989:             if (!defined($name)) {
 4990:                 use Socket;
 4991:                 my $netaddr=inet_aton($ip);
 4992:                 ($name)=gethostbyaddr($netaddr,AF_INET);
 4993:             }
 4994:             if ($name =~ /\Q$pattern\E$/i) { $allowed=1; }
 4995:         }
 4996:         if ($allowed) { last; }
 4997:     }
 4998:     return $allowed;
 4999: }
 5000: 
 5001: ###############################################
 5002: 
 5003: =pod
 5004: 
 5005: =head1 Domain Template Functions
 5006: 
 5007: =over 4
 5008: 
 5009: =item * &determinedomain()
 5010: 
 5011: Inputs: $domain (usually will be undef)
 5012: 
 5013: Returns: Determines which domain should be used for designs
 5014: 
 5015: =cut
 5016: 
 5017: ###############################################
 5018: sub determinedomain {
 5019:     my $domain=shift;
 5020:     if (! $domain) {
 5021:         # Determine domain if we have not been given one
 5022:         $domain = &Apache::lonnet::default_login_domain();
 5023:         if ($env{'user.domain'}) { $domain=$env{'user.domain'}; }
 5024:         if ($env{'request.role.domain'}) { 
 5025:             $domain=$env{'request.role.domain'}; 
 5026:         }
 5027:     }
 5028:     return $domain;
 5029: }
 5030: ###############################################
 5031: 
 5032: sub devalidate_domconfig_cache {
 5033:     my ($udom)=@_;
 5034:     &Apache::lonnet::devalidate_cache_new('domainconfig',$udom);
 5035: }
 5036: 
 5037: # ---------------------- Get domain configuration for a domain
 5038: sub get_domainconf {
 5039:     my ($udom) = @_;
 5040:     my $cachetime=1800;
 5041:     my ($result,$cached)=&Apache::lonnet::is_cached_new('domainconfig',$udom);
 5042:     if (defined($cached)) { return %{$result}; }
 5043: 
 5044:     my %domconfig = &Apache::lonnet::get_dom('configuration',
 5045: 					     ['login','rolecolors','autoenroll'],$udom);
 5046:     my (%designhash,%legacy);
 5047:     if (keys(%domconfig) > 0) {
 5048:         if (ref($domconfig{'login'}) eq 'HASH') {
 5049:             if (keys(%{$domconfig{'login'}})) {
 5050:                 foreach my $key (keys(%{$domconfig{'login'}})) {
 5051:                     if (ref($domconfig{'login'}{$key}) eq 'HASH') {
 5052:                         if (($key eq 'loginvia') || ($key eq 'headtag')) {
 5053:                             if (ref($domconfig{'login'}{$key}) eq 'HASH') {
 5054:                                 foreach my $hostname (keys(%{$domconfig{'login'}{$key}})) {
 5055:                                     if (ref($domconfig{'login'}{$key}{$hostname}) eq 'HASH') {
 5056:                                         if ($key eq 'loginvia') {
 5057:                                             if ($domconfig{'login'}{'loginvia'}{$hostname}{'server'}) {
 5058:                                                 my $server = $domconfig{'login'}{'loginvia'}{$hostname}{'server'};
 5059:                                                 $designhash{$udom.'.login.loginvia'} = $server;
 5060:                                                 if ($domconfig{'login'}{'loginvia'}{$hostname}{'serverpath'} eq 'custom') {
 5061:                                                     $designhash{$udom.'.login.loginvia_'.$hostname} = $server.':'.$domconfig{'login'}{'loginvia'}{$hostname}{'custompath'};
 5062:                                                 } else {
 5063:                                                     $designhash{$udom.'.login.loginvia_'.$hostname} = $server.':'.$domconfig{'login'}{'loginvia'}{$hostname}{'serverpath'};
 5064:                                                 }
 5065:                                             }
 5066:                                         } elsif ($key eq 'headtag') {
 5067:                                             if ($domconfig{'login'}{'headtag'}{$hostname}{'url'}) {
 5068:                                                 $designhash{$udom.'.login.headtag_'.$hostname} = $domconfig{'login'}{'headtag'}{$hostname}{'url'};
 5069:                                             }
 5070:                                         }
 5071:                                         if ($domconfig{'login'}{$key}{$hostname}{'exempt'}) {
 5072:                                             $designhash{$udom.'.login.'.$key.'_exempt_'.$hostname} = $domconfig{'login'}{$key}{$hostname}{'exempt'};
 5073:                                         }
 5074:                                     }
 5075:                                 }
 5076:                             }
 5077:                         } else {
 5078:                             foreach my $img (keys(%{$domconfig{'login'}{$key}})) {
 5079:                                 $designhash{$udom.'.login.'.$key.'_'.$img} = 
 5080:                                     $domconfig{'login'}{$key}{$img};
 5081:                             }
 5082:                         }
 5083:                     } else {
 5084:                         $designhash{$udom.'.login.'.$key}=$domconfig{'login'}{$key};
 5085:                     }
 5086:                 }
 5087:             } else {
 5088:                 $legacy{'login'} = 1;
 5089:             }
 5090:         } else {
 5091:             $legacy{'login'} = 1;
 5092:         }
 5093:         if (ref($domconfig{'rolecolors'}) eq 'HASH') {
 5094:             if (keys(%{$domconfig{'rolecolors'}})) {
 5095:                 foreach my $role (keys(%{$domconfig{'rolecolors'}})) {
 5096:                     if (ref($domconfig{'rolecolors'}{$role}) eq 'HASH') {
 5097:                         foreach my $item (keys(%{$domconfig{'rolecolors'}{$role}})) {
 5098:                             $designhash{$udom.'.'.$role.'.'.$item}=$domconfig{'rolecolors'}{$role}{$item};
 5099:                         }
 5100:                     }
 5101:                 }
 5102:             } else {
 5103:                 $legacy{'rolecolors'} = 1;
 5104:             }
 5105:         } else {
 5106:             $legacy{'rolecolors'} = 1;
 5107:         }
 5108:         if (ref($domconfig{'autoenroll'}) eq 'HASH') {
 5109:             if ($domconfig{'autoenroll'}{'co-owners'}) {
 5110:                 $designhash{$udom.'.autoassign.co-owners'}=$domconfig{'autoenroll'}{'co-owners'};
 5111:             }
 5112:         }
 5113:         if (keys(%legacy) > 0) {
 5114:             my %legacyhash = &get_legacy_domconf($udom);
 5115:             foreach my $item (keys(%legacyhash)) {
 5116:                 if ($item =~ /^\Q$udom\E\.login/) {
 5117:                     if ($legacy{'login'}) { 
 5118:                         $designhash{$item} = $legacyhash{$item};
 5119:                     }
 5120:                 } else {
 5121:                     if ($legacy{'rolecolors'}) {
 5122:                         $designhash{$item} = $legacyhash{$item};
 5123:                     }
 5124:                 }
 5125:             }
 5126:         }
 5127:     } else {
 5128:         %designhash = &get_legacy_domconf($udom); 
 5129:     }
 5130:     &Apache::lonnet::do_cache_new('domainconfig',$udom,\%designhash,
 5131: 				  $cachetime);
 5132:     return %designhash;
 5133: }
 5134: 
 5135: sub get_legacy_domconf {
 5136:     my ($udom) = @_;
 5137:     my %legacyhash;
 5138:     my $designdir=$Apache::lonnet::perlvar{'lonTabDir'}.'/lonDomColors';
 5139:     my $designfile =  $designdir.'/'.$udom.'.tab';
 5140:     if (-e $designfile) {
 5141:         if ( open (my $fh,'<',$designfile) ) {
 5142:             while (my $line = <$fh>) {
 5143:                 next if ($line =~ /^\#/);
 5144:                 chomp($line);
 5145:                 my ($key,$val)=(split(/\=/,$line));
 5146:                 if ($val) { $legacyhash{$udom.'.'.$key}=$val; }
 5147:             }
 5148:             close($fh);
 5149:         }
 5150:     }
 5151:     if (-e $Apache::lonnet::perlvar{'lonDocRoot'}.'/adm/lonDomLogos/'.$udom.'.gif') {
 5152:         $legacyhash{$udom.'.login.domlogo'} = "/adm/lonDomLogos/$udom.gif";
 5153:     }
 5154:     return %legacyhash;
 5155: }
 5156: 
 5157: =pod
 5158: 
 5159: =item * &domainlogo()
 5160: 
 5161: Inputs: $domain (usually will be undef)
 5162: 
 5163: Returns: A link to a domain logo, if the domain logo exists.
 5164: If the domain logo does not exist, a description of the domain.
 5165: 
 5166: =cut
 5167: 
 5168: ###############################################
 5169: sub domainlogo {
 5170:     my $domain = &determinedomain(shift);
 5171:     my %designhash = &get_domainconf($domain);    
 5172:     # See if there is a logo
 5173:     if ($designhash{$domain.'.login.domlogo'} ne '') {
 5174:         my $imgsrc = $designhash{$domain.'.login.domlogo'};
 5175:         if ($imgsrc =~ m{^/(adm|res)/}) {
 5176: 	    if ($imgsrc =~ m{^/res/}) {
 5177: 		my $local_name = &Apache::lonnet::filelocation('',$imgsrc);
 5178: 		&Apache::lonnet::repcopy($local_name);
 5179: 	    }
 5180: 	   $imgsrc = &lonhttpdurl($imgsrc);
 5181:         } 
 5182:         return '<img src="'.$imgsrc.'" alt="'.$domain.'" />';
 5183:     } elsif (defined(&Apache::lonnet::domain($domain,'description'))) {
 5184:         return &Apache::lonnet::domain($domain,'description');
 5185:     } else {
 5186:         return '';
 5187:     }
 5188: }
 5189: ##############################################
 5190: 
 5191: =pod
 5192: 
 5193: =item * &designparm()
 5194: 
 5195: Inputs: $which parameter; $domain (usually will be undef)
 5196: 
 5197: Returns: value of designparamter $which
 5198: 
 5199: =cut
 5200: 
 5201: 
 5202: ##############################################
 5203: sub designparm {
 5204:     my ($which,$domain)=@_;
 5205:     if (exists($env{'environment.color.'.$which})) {
 5206:         return $env{'environment.color.'.$which};
 5207:     }
 5208:     $domain=&determinedomain($domain);
 5209:     my %domdesign;
 5210:     unless ($domain eq 'public') {
 5211:         %domdesign = &get_domainconf($domain);
 5212:     }
 5213:     my $output;
 5214:     if ($domdesign{$domain.'.'.$which} ne '') {
 5215:         $output = $domdesign{$domain.'.'.$which};
 5216:     } else {
 5217:         $output = $defaultdesign{$which};
 5218:     }
 5219:     if (($which =~ /^(student|coordinator|author|admin)\.img$/) ||
 5220:         ($which =~ /login\.(img|logo|domlogo|login)/)) {
 5221:         if ($output =~ m{^/(adm|res)/}) {
 5222:             if ($output =~ m{^/res/}) {
 5223:                 my $local_name = &Apache::lonnet::filelocation('',$output);
 5224:                 &Apache::lonnet::repcopy($local_name);
 5225:             }
 5226:             $output = &lonhttpdurl($output);
 5227:         }
 5228:     }
 5229:     return $output;
 5230: }
 5231: 
 5232: ##############################################
 5233: =pod
 5234: 
 5235: =item * &authorspace()
 5236: 
 5237: Inputs: $url (usually will be undef).
 5238: 
 5239: Returns: Path to Authoring Space containing the resource or 
 5240:          directory being viewed (or for which action is being taken). 
 5241:          If $url is provided, and begins /priv/<domain>/<uname>
 5242:          the path will be that portion of the $context argument.
 5243:          Otherwise the path will be for the author space of the current
 5244:          user when the current role is author, or for that of the 
 5245:          co-author/assistant co-author space when the current role 
 5246:          is co-author or assistant co-author.
 5247: 
 5248: =cut
 5249: 
 5250: sub authorspace {
 5251:     my ($url) = @_;
 5252:     if ($url ne '') {
 5253:         if ($url =~ m{^(/priv/$match_domain/$match_username/)}) {
 5254:            return $1;
 5255:         }
 5256:     }
 5257:     my $caname = '';
 5258:     my $cadom = '';
 5259:     if ($env{'request.role'} =~ /^(?:ca|aa)/) {
 5260:         ($cadom,$caname) =
 5261:             ($env{'request.role'}=~/($match_domain)\/($match_username)$/);
 5262:     } elsif ($env{'request.role'} =~ m{^au\./($match_domain)/}) {
 5263:         $caname = $env{'user.name'};
 5264:         $cadom = $env{'user.domain'};
 5265:     }
 5266:     if (($caname ne '') && ($cadom ne '')) {
 5267:         return "/priv/$cadom/$caname/";
 5268:     }
 5269:     return;
 5270: }
 5271: 
 5272: ##############################################
 5273: =pod
 5274: 
 5275: =item * &head_subbox()
 5276: 
 5277: Inputs: $content (contains HTML code with page functions, etc.)
 5278: 
 5279: Returns: HTML div with $content
 5280:          To be included in page header
 5281: 
 5282: =cut
 5283: 
 5284: sub head_subbox {
 5285:     my ($content)=@_;
 5286:     my $output =
 5287:         '<div class="LC_head_subbox">'
 5288:        .$content
 5289:        .'</div>'
 5290: }
 5291: 
 5292: ##############################################
 5293: =pod
 5294: 
 5295: =item * &CSTR_pageheader()
 5296: 
 5297: Input: (optional) filename from which breadcrumb trail is built.
 5298:        In most cases no input as needed, as $env{'request.filename'}
 5299:        is appropriate for use in building the breadcrumb trail.
 5300: 
 5301: Returns: HTML div with CSTR path and recent box
 5302:          To be included on Authoring Space pages
 5303: 
 5304: =cut
 5305: 
 5306: sub CSTR_pageheader {
 5307:     my ($trailfile) = @_;
 5308:     if ($trailfile eq '') {
 5309:         $trailfile = $env{'request.filename'};
 5310:     }
 5311: 
 5312: # this is for resources; directories have customtitle, and crumbs
 5313: # and select recent are created in lonpubdir.pm
 5314: 
 5315:     my $londocroot = $Apache::lonnet::perlvar{'lonDocRoot'};
 5316:     my ($udom,$uname,$thisdisfn)=
 5317:         ($trailfile =~ m{^\Q$londocroot\E/priv/([^/]+)/([^/]+)(?:|/(.*))$});
 5318:     my $formaction = "/priv/$udom/$uname/$thisdisfn";
 5319:     $formaction =~ s{/+}{/}g;
 5320: 
 5321:     my $parentpath = '';
 5322:     my $lastitem = '';
 5323:     if ($thisdisfn =~ m-(.+/)([^/]*)$-) {
 5324:         $parentpath = $1;
 5325:         $lastitem = $2;
 5326:     } else {
 5327:         $lastitem = $thisdisfn;
 5328:     }
 5329: 
 5330:     my $output =
 5331:          '<div>'
 5332:         .&Apache::loncommon::help_open_menu('','',3,'Authoring') #FIXME: Broken? Where is it?
 5333:         .'<b>'.&mt('Authoring Space:').'</b> '
 5334:         .'<form name="dirs" method="post" action="'.$formaction
 5335:         .'" target="_top">' #FIXME lonpubdir: target="_parent"
 5336:         .&Apache::lonhtmlcommon::crumbs($uname.'/'.$parentpath,'_top','/priv/'.$udom,undef,undef);
 5337: 
 5338:     if ($lastitem) {
 5339:         $output .=
 5340:              '<span class="LC_filename">'
 5341:             .$lastitem
 5342:             .'</span>';
 5343:     }
 5344:     $output .=
 5345:          '<br />'
 5346:         #FIXME lonpubdir: &Apache::lonhtmlcommon::crumbs($uname.$thisdisfn.'/','_top','/priv','','+1',1)."</b></tt><br />"
 5347:         .&Apache::lonhtmlcommon::select_recent('construct','recent','this.form.action=this.form.recent.value;this.form.submit()')
 5348:         .'</form>'
 5349:         .&Apache::lonmenu::constspaceform()
 5350:         .'</div>';
 5351: 
 5352:     return $output;
 5353: }
 5354: 
 5355: ###############################################
 5356: ###############################################
 5357: 
 5358: =pod
 5359: 
 5360: =back
 5361: 
 5362: =head1 HTML Helpers
 5363: 
 5364: =over 4
 5365: 
 5366: =item * &bodytag()
 5367: 
 5368: Returns a uniform header for LON-CAPA web pages.
 5369: 
 5370: Inputs: 
 5371: 
 5372: =over 4
 5373: 
 5374: =item * $title, A title to be displayed on the page.
 5375: 
 5376: =item * $function, the current role (can be undef).
 5377: 
 5378: =item * $addentries, extra parameters for the <body> tag.
 5379: 
 5380: =item * $bodyonly, if defined, only return the <body> tag.
 5381: 
 5382: =item * $domain, if defined, force a given domain.
 5383: 
 5384: =item * $forcereg, if page should register as content page (relevant for 
 5385:             text interface only)
 5386: 
 5387: =item * $no_nav_bar, if true, keep the 'what is this' info but remove the
 5388:                      navigational links
 5389: 
 5390: =item * $bgcolor, used to override the bgcolor on a webpage to a specific value
 5391: 
 5392: =item * $no_inline_link, if true and in remote mode, don't show the
 5393:          'Switch To Inline Menu' link
 5394: 
 5395: =item * $args, optional argument valid values are
 5396:             no_auto_mt_title -> prevents &mt()ing the title arg
 5397: 
 5398: =item * $advtoolsref, optional argument, ref to an array containing
 5399:             inlineremote items to be added in "Functions" menu below
 5400:             breadcrumbs.
 5401: 
 5402: =back
 5403: 
 5404: Returns: A uniform header for LON-CAPA web pages.  
 5405: If $bodyonly is nonzero, a string containing a <body> tag will be returned.
 5406: If $bodyonly is undef or zero, an html string containing a <body> tag and 
 5407: other decorations will be returned.
 5408: 
 5409: =cut
 5410: 
 5411: sub bodytag {
 5412:     my ($title,$function,$addentries,$bodyonly,$domain,$forcereg,
 5413:         $no_nav_bar,$bgcolor,$no_inline_link,$args,$advtoolsref)=@_;
 5414: 
 5415:     my $public;
 5416:     if ((($env{'user.name'} eq 'public') && ($env{'user.domain'} eq 'public'))
 5417:         || ($env{'user.name'} eq '') && ($env{'user.domain'} eq '')) {
 5418:         $public = 1;
 5419:     }
 5420:     if (!$args->{'no_auto_mt_title'}) { $title = &mt($title); }
 5421:     my $httphost = $args->{'use_absolute'};
 5422: 
 5423:     $function = &get_users_function() if (!$function);
 5424:     my $img =    &designparm($function.'.img',$domain);
 5425:     my $font =   &designparm($function.'.font',$domain);
 5426:     my $pgbg   = $bgcolor || &designparm($function.'.pgbg',$domain);
 5427: 
 5428:     my %design = ( 'style'   => 'margin-top: 0',
 5429: 		   'bgcolor' => $pgbg,
 5430: 		   'text'    => $font,
 5431:                    'alink'   => &designparm($function.'.alink',$domain),
 5432: 		   'vlink'   => &designparm($function.'.vlink',$domain),
 5433: 		   'link'    => &designparm($function.'.link',$domain),);
 5434:     @design{keys(%$addentries)} = @$addentries{keys(%$addentries)}; 
 5435: 
 5436:  # role and realm
 5437:     my ($role,$realm) = split(m{\./},$env{'request.role'},2);
 5438:     if ($realm) {
 5439:         $realm = '/'.$realm;
 5440:     }
 5441:     if ($role  eq 'ca') {
 5442:         my ($rdom,$rname) = ($realm =~ m{^/($match_domain)/($match_username)$});
 5443:         $realm = &plainname($rname,$rdom);
 5444:     } 
 5445: # realm
 5446:     if ($env{'request.course.id'}) {
 5447:         if ($env{'request.role'} !~ /^cr/) {
 5448:             $role = &Apache::lonnet::plaintext($role,&course_type());
 5449:         } elsif ($role =~ m{^cr/($match_domain)/\1-domainconfig/(\w+)$}) {
 5450:             if ($env{'request.role.desc'}) {
 5451:                 $role = $env{'request.role.desc'};
 5452:             } else {
 5453:                 $role = &mt('Helpdesk[_1]','&nbsp;'.$2);
 5454:             }
 5455:         } else {
 5456:             $role = (split(/\//,$role,4))[-1];
 5457:         }
 5458:         if ($env{'request.course.sec'}) {
 5459:             $role .= ('&nbsp;'x2).'-&nbsp;'.&mt('section:').'&nbsp;'.$env{'request.course.sec'};
 5460:         }   
 5461: 	$realm = $env{'course.'.$env{'request.course.id'}.'.description'};
 5462:     } else {
 5463:         $role = &Apache::lonnet::plaintext($role);
 5464:     }
 5465: 
 5466:     if (!$realm) { $realm='&nbsp;'; }
 5467: 
 5468:     my $extra_body_attr = &make_attr_string($forcereg,\%design);
 5469: 
 5470: # construct main body tag
 5471:     my $bodytag = "<body $extra_body_attr>".
 5472: 	&Apache::lontexconvert::init_math_support();
 5473: 
 5474:     &get_unprocessed_cgi($ENV{'QUERY_STRING'}, ['inhibitmenu']);
 5475: 
 5476:     if (($bodyonly) || ($no_nav_bar) || ($env{'form.inhibitmenu'} eq 'yes')) {
 5477:         return $bodytag;
 5478:     }
 5479: 
 5480:     if ($public) {
 5481: 	undef($role);
 5482:     }
 5483:     
 5484:     my $titleinfo = '<h1>'.$title.'</h1>';
 5485:     #
 5486:     # Extra info if you are the DC
 5487:     my $dc_info = '';
 5488:     if ($env{'user.adv'} && exists($env{'user.role.dc./'.
 5489:                         $env{'course.'.$env{'request.course.id'}.
 5490:                                  '.domain'}.'/'})) {
 5491:         my $cid = $env{'request.course.id'};
 5492:         $dc_info = $cid.' '.$env{'course.'.$cid.'.internal.coursecode'};
 5493:         $dc_info =~ s/\s+$//;
 5494:     }
 5495: 
 5496:     $role = '<span class="LC_nobreak">('.$role.')</span>' if ($role && !$env{'browser.mobile'});
 5497: 
 5498:     if ($env{'request.state'} eq 'construct') { $forcereg=1; }
 5499: 
 5500: 
 5501: 
 5502:     my $funclist;
 5503:     if (($env{'environment.remote'} eq 'on') && ($env{'request.state'} ne 'construct')) {
 5504:         $bodytag .= Apache::lonhtmlcommon::scripttag(Apache::lonmenu::utilityfunctions($httphost), 'start')."\n".
 5505:                     Apache::lonmenu::serverform();
 5506:         my $forbodytag;
 5507:         &Apache::lonmenu::prepare_functions($env{'request.noversionuri'},
 5508:                                             $forcereg,$args->{'group'},
 5509:                                             $args->{'bread_crumbs'},
 5510:                                             $advtoolsref,'',\$forbodytag);
 5511:         unless (ref($args->{'bread_crumbs'}) eq 'ARRAY') {
 5512:             $funclist = $forbodytag;
 5513:         }
 5514:     } else {
 5515: 
 5516:         #    if ($env{'request.state'} eq 'construct') {
 5517:         #        $titleinfo = &CSTR_pageheader(); #FIXME: Will be removed once all scripts have their own calls
 5518:         #    }
 5519: 
 5520:         $bodytag .= Apache::lonhtmlcommon::scripttag(
 5521:             Apache::lonmenu::utilityfunctions($httphost), 'start');
 5522: 
 5523:         my ($left,$right) = Apache::lonmenu::primary_menu();
 5524: 
 5525:         if ($env{'request.noversionuri'} =~ m{^/res/adm/pages/}) {
 5526:             if ($dc_info) {
 5527:                  $dc_info = qq|<span class="LC_cusr_subheading">$dc_info</span>|;
 5528:             }
 5529:             $bodytag .= qq|<div id="LC_nav_bar">$left $role<br />
 5530:                            <em>$realm</em> $dc_info</div>|;
 5531:             return $bodytag;
 5532:         }
 5533: 
 5534:         unless ($env{'request.symb'} =~ m/\.page___\d+___/) {
 5535:             $bodytag .= qq|<div id="LC_nav_bar">$left $role</div>|;
 5536:         }
 5537: 
 5538:         $bodytag .= $right;
 5539: 
 5540:         if ($dc_info) {
 5541:             $dc_info = &dc_courseid_toggle($dc_info);
 5542:         }
 5543:         $bodytag .= qq|<div id="LC_realm">$realm $dc_info</div>|;
 5544: 
 5545:         #if directed to not display the secondary menu, don't.
 5546:         if ($args->{'no_secondary_menu'}) {
 5547:             return $bodytag;
 5548:         }
 5549:         #don't show menus for public users
 5550:         if (!$public){
 5551:             $bodytag .= Apache::lonmenu::secondary_menu($httphost);
 5552:             $bodytag .= Apache::lonmenu::serverform();
 5553:             $bodytag .= Apache::lonhtmlcommon::scripttag('', 'end');
 5554:             if ($env{'request.state'} eq 'construct') {
 5555:                 $bodytag .= &Apache::lonmenu::innerregister($forcereg,
 5556:                                 $args->{'bread_crumbs'});
 5557:             } elsif ($forcereg) {
 5558:                 $bodytag .= &Apache::lonmenu::innerregister($forcereg,undef,
 5559:                                                             $args->{'group'},
 5560:                                                             $args->{'hide_buttons'});
 5561:             } else {
 5562:                 my $forbodytag;
 5563:                 &Apache::lonmenu::prepare_functions($env{'request.noversionuri'},
 5564:                                                     $forcereg,$args->{'group'},
 5565:                                                     $args->{'bread_crumbs'},
 5566:                                                     $advtoolsref,'',\$forbodytag);
 5567:                 unless (ref($args->{'bread_crumbs'}) eq 'ARRAY') {
 5568:                     $bodytag .= $forbodytag;
 5569:                 }
 5570:             }
 5571:         }else{
 5572:             # this is to seperate menu from content when there's no secondary
 5573:             # menu. Especially needed for public accessible ressources.
 5574:             $bodytag .= '<hr style="clear:both" />';
 5575:             $bodytag .= Apache::lonhtmlcommon::scripttag('', 'end'); 
 5576:         }
 5577: 
 5578:         return $bodytag;
 5579:     }
 5580: 
 5581: #
 5582: # Top frame rendering, Remote is up
 5583: #
 5584: 
 5585:     my $imgsrc = $img;
 5586:     if ($img =~ /^\/adm/) {
 5587:         $imgsrc = &lonhttpdurl($img);
 5588:     }
 5589:     my $upperleft='<img src="'.$imgsrc.'" alt="'.$function.'" />';
 5590: 
 5591:     my $help=($no_inline_link?''
 5592:               :&Apache::loncommon::top_nav_help('Help'));
 5593: 
 5594:     # Explicit link to get inline menu
 5595:     my $menu= ($no_inline_link?''
 5596:                :'<a href="/adm/remote?action=collapse" target="_top">'.&mt('Switch to Inline Menu Mode').'</a>');
 5597: 
 5598:     if ($dc_info) {
 5599:         $dc_info = qq|<span class="LC_cusr_subheading">($dc_info)</span>|;
 5600:     }
 5601: 
 5602:     my $name = &plainname($env{'user.name'},$env{'user.domain'});
 5603:     unless ($public) {
 5604:         $name = &aboutmewrapper($name,$env{'user.name'},$env{'user.domain'},
 5605:                                 undef,'LC_menubuttons_link');
 5606:     }
 5607: 
 5608:     unless ($env{'form.inhibitmenu'}) {
 5609:         $bodytag .= qq|<div id="LC_nav_bar">$name $role</div>
 5610:                        <ol class="LC_primary_menu LC_floatright LC_right">
 5611:                        <li>$help</li>
 5612:                        <li>$menu</li>
 5613:                        </ol><div id="LC_realm"> $realm $dc_info</div>|;
 5614:     }
 5615:     if ($env{'request.state'} eq 'construct') {
 5616:         if (!$public){
 5617:             if ($env{'request.state'} eq 'construct') {
 5618:                 $funclist = &Apache::lonhtmlcommon::scripttag(
 5619:                                 &Apache::lonmenu::utilityfunctions($httphost), 'start').
 5620:                             &Apache::lonhtmlcommon::scripttag('','end').
 5621:                             &Apache::lonmenu::innerregister($forcereg,
 5622:                                                             $args->{'bread_crumbs'});
 5623:             }
 5624:         }
 5625:     }
 5626:     return $bodytag."\n".$funclist;
 5627: }
 5628: 
 5629: sub dc_courseid_toggle {
 5630:     my ($dc_info) = @_;
 5631:     return ' <span id="dccidtext" class="LC_cusr_subheading LC_nobreak">'.
 5632:            '<a href="javascript:showCourseID();" class="LC_menubuttons_link">'.
 5633:            &mt('(More ...)').'</a></span>'.
 5634:            '<div id="dccid" class="LC_dccid">'.$dc_info.'</div>';
 5635: }
 5636: 
 5637: sub make_attr_string {
 5638:     my ($register,$attr_ref) = @_;
 5639: 
 5640:     if ($attr_ref && !ref($attr_ref)) {
 5641: 	die("addentries Must be a hash ref ".
 5642: 	    join(':',caller(1))." ".
 5643: 	    join(':',caller(0))." ");
 5644:     }
 5645: 
 5646:     if ($register) {
 5647: 	my ($on_load,$on_unload);
 5648: 	foreach my $key (keys(%{$attr_ref})) {
 5649: 	    if      (lc($key) eq 'onload') {
 5650: 		$on_load.=$attr_ref->{$key}.';';
 5651: 		delete($attr_ref->{$key});
 5652: 
 5653: 	    } elsif (lc($key) eq 'onunload') {
 5654: 		$on_unload.=$attr_ref->{$key}.';';
 5655: 		delete($attr_ref->{$key});
 5656: 	    }
 5657: 	}
 5658:         if ($env{'environment.remote'} eq 'on') {
 5659:             $attr_ref->{'onload'}  =
 5660:                 &Apache::lonmenu::loadevents().  $on_load;
 5661:             $attr_ref->{'onunload'}=
 5662:                 &Apache::lonmenu::unloadevents().$on_unload;
 5663:         } else {  
 5664: 	    $attr_ref->{'onload'}  = $on_load;
 5665: 	    $attr_ref->{'onunload'}= $on_unload;
 5666:         }
 5667:     }
 5668: 
 5669:     my $attr_string;
 5670:     foreach my $attr (sort(keys(%$attr_ref))) {
 5671: 	$attr_string .= " $attr=\"".$attr_ref->{$attr}.'" ';
 5672:     }
 5673:     return $attr_string;
 5674: }
 5675: 
 5676: 
 5677: ###############################################
 5678: ###############################################
 5679: 
 5680: =pod
 5681: 
 5682: =item * &endbodytag()
 5683: 
 5684: Returns a uniform footer for LON-CAPA web pages.
 5685: 
 5686: Inputs: 1 - optional reference to an args hash
 5687: If in the hash, key for noredirectlink has a value which evaluates to true,
 5688: a 'Continue' link is not displayed if the page contains an
 5689: internal redirect in the <head></head> section,
 5690: i.e., $env{'internal.head.redirect'} exists   
 5691: 
 5692: =cut
 5693: 
 5694: sub endbodytag {
 5695:     my ($args) = @_;
 5696:     my $endbodytag;
 5697:     unless ((ref($args) eq 'HASH') && ($args->{'notbody'})) {
 5698:         $endbodytag='</body>';
 5699:     }
 5700:     if ( exists( $env{'internal.head.redirect'} ) ) {
 5701:         if (!(ref($args) eq 'HASH' && $args->{'noredirectlink'})) {
 5702: 	    $endbodytag=
 5703: 	        "<br /><a href=\"$env{'internal.head.redirect'}\">".
 5704: 	        &mt('Continue').'</a>'.
 5705: 	        $endbodytag;
 5706:         }
 5707:     }
 5708:     return $endbodytag;
 5709: }
 5710: 
 5711: =pod
 5712: 
 5713: =item * &standard_css()
 5714: 
 5715: Returns a style sheet
 5716: 
 5717: Inputs: (all optional)
 5718:             domain         -> force to color decorate a page for a specific
 5719:                                domain
 5720:             function       -> force usage of a specific rolish color scheme
 5721:             bgcolor        -> override the default page bgcolor
 5722: 
 5723: =cut
 5724: 
 5725: sub standard_css {
 5726:     my ($function,$domain,$bgcolor) = @_;
 5727:     $function  = &get_users_function() if (!$function);
 5728:     my $img    = &designparm($function.'.img',   $domain);
 5729:     my $tabbg  = &designparm($function.'.tabbg', $domain);
 5730:     my $font   = &designparm($function.'.font',  $domain);
 5731:     my $fontmenu = &designparm($function.'.fontmenu', $domain);
 5732: #second colour for later usage
 5733:     my $sidebg = &designparm($function.'.sidebg',$domain);
 5734:     my $pgbg_or_bgcolor =
 5735: 	         $bgcolor ||
 5736: 	         &designparm($function.'.pgbg',  $domain);
 5737:     my $pgbg   = &designparm($function.'.pgbg',  $domain);
 5738:     my $alink  = &designparm($function.'.alink', $domain);
 5739:     my $vlink  = &designparm($function.'.vlink', $domain);
 5740:     my $link   = &designparm($function.'.link',  $domain);
 5741: 
 5742:     my $sans                 = 'Verdana,Arial,Helvetica,sans-serif';
 5743:     my $mono                 = 'monospace';
 5744:     my $data_table_head      = $sidebg;
 5745:     my $data_table_light     = '#FAFAFA';
 5746:     my $data_table_dark      = '#E0E0E0';
 5747:     my $data_table_darker    = '#CCCCCC';
 5748:     my $data_table_highlight = '#FFFF00';
 5749:     my $mail_new             = '#FFBB77';
 5750:     my $mail_new_hover       = '#DD9955';
 5751:     my $mail_read            = '#BBBB77';
 5752:     my $mail_read_hover      = '#999944';
 5753:     my $mail_replied         = '#AAAA88';
 5754:     my $mail_replied_hover   = '#888855';
 5755:     my $mail_other           = '#99BBBB';
 5756:     my $mail_other_hover     = '#669999';
 5757:     my $table_header         = '#DDDDDD';
 5758:     my $feedback_link_bg     = '#BBBBBB';
 5759:     my $lg_border_color      = '#C8C8C8';
 5760:     my $button_hover         = '#BF2317';
 5761: 
 5762:     my $border = ($env{'browser.type'} eq 'explorer' ||
 5763:       $env{'browser.type'} eq 'safari'     ) ? '0 2px 0 2px'
 5764:                                              : '0 3px 0 4px';
 5765: 
 5766: 
 5767:     return <<END;
 5768: 
 5769: /* needed for iframe to allow 100% height in FF */
 5770: body, html { 
 5771:     margin: 0;
 5772:     padding: 0 0.5%;
 5773:     height: 99%; /* to avoid scrollbars */
 5774: }
 5775: 
 5776: body {
 5777:   font-family: $sans;
 5778:   line-height:130%;
 5779:   font-size:0.83em;
 5780:   color:$font;
 5781: }
 5782: 
 5783: a:focus,
 5784: a:focus img {
 5785:   color: red;
 5786: }
 5787: 
 5788: form, .inline {
 5789:   display: inline;
 5790: }
 5791: 
 5792: .LC_right {
 5793:   text-align:right;
 5794: }
 5795: 
 5796: .LC_middle {
 5797:   vertical-align:middle;
 5798: }
 5799: 
 5800: .LC_floatleft {
 5801:   float: left;
 5802: }
 5803: 
 5804: .LC_floatright {
 5805:   float: right;
 5806: }
 5807: 
 5808: .LC_400Box {
 5809:   width:400px;
 5810: }
 5811: 
 5812: .LC_iframecontainer {
 5813:     width: 98%;
 5814:     margin: 0;
 5815:     position: fixed;
 5816:     top: 8.5em;
 5817:     bottom: 0;
 5818: }
 5819: 
 5820: .LC_iframecontainer iframe{
 5821:     border: none;
 5822:     width: 100%;
 5823:     height: 100%;
 5824: }
 5825: 
 5826: .LC_filename {
 5827:   font-family: $mono;
 5828:   white-space:pre;
 5829:   font-size: 120%;
 5830: }
 5831: 
 5832: .LC_fileicon {
 5833:   border: none;
 5834:   height: 1.3em;
 5835:   vertical-align: text-bottom;
 5836:   margin-right: 0.3em;
 5837:   text-decoration:none;
 5838: }
 5839: 
 5840: .LC_setting {
 5841:   text-decoration:underline;
 5842: }
 5843: 
 5844: .LC_error {
 5845:   color: red;
 5846: }
 5847: 
 5848: .LC_warning {
 5849:   color: darkorange;
 5850: }
 5851: 
 5852: .LC_diff_removed {
 5853:   color: red;
 5854: }
 5855: 
 5856: .LC_info,
 5857: .LC_success,
 5858: .LC_diff_added {
 5859:   color: green;
 5860: }
 5861: 
 5862: div.LC_confirm_box {
 5863:   background-color: #FAFAFA;
 5864:   border: 1px solid $lg_border_color;
 5865:   margin-right: 0;
 5866:   padding: 5px;
 5867: }
 5868: 
 5869: div.LC_confirm_box .LC_error img,
 5870: div.LC_confirm_box .LC_success img {
 5871:   vertical-align: middle;
 5872: }
 5873: 
 5874: .LC_maxwidth {
 5875:   max-width: 100%;
 5876:   height: auto;
 5877: }
 5878: 
 5879: .LC_textsize_mobile {
 5880:   \@media only screen and (max-device-width: 480px) {
 5881:       -webkit-text-size-adjust:100%; -moz-text-size-adjust:100%; -ms-text-size-adjust:100%;
 5882:   }
 5883: }
 5884: 
 5885: .LC_icon {
 5886:   border: none;
 5887:   vertical-align: middle;
 5888: }
 5889: 
 5890: .LC_docs_spacer {
 5891:   width: 25px;
 5892:   height: 1px;
 5893:   border: none;
 5894: }
 5895: 
 5896: .LC_internal_info {
 5897:   color: #999999;
 5898: }
 5899: 
 5900: .LC_discussion {
 5901:   background: $data_table_dark;
 5902:   border: 1px solid black;
 5903:   margin: 2px;
 5904: }
 5905: 
 5906: .LC_disc_action_left {
 5907:   background: $sidebg;
 5908:   text-align: left;
 5909:   padding: 4px;
 5910:   margin: 2px;
 5911: }
 5912: 
 5913: .LC_disc_action_right {
 5914:   background: $sidebg;
 5915:   text-align: right;
 5916:   padding: 4px;
 5917:   margin: 2px;
 5918: }
 5919: 
 5920: .LC_disc_new_item {
 5921:   background: white;
 5922:   border: 2px solid red;
 5923:   margin: 4px;
 5924:   padding: 4px;
 5925: }
 5926: 
 5927: .LC_disc_old_item {
 5928:   background: white;
 5929:   margin: 4px;
 5930:   padding: 4px;
 5931: }
 5932: 
 5933: table.LC_pastsubmission {
 5934:   border: 1px solid black;
 5935:   margin: 2px;
 5936: }
 5937: 
 5938: table#LC_menubuttons {
 5939:   width: 100%;
 5940:   background: $pgbg;
 5941:   border: 2px;
 5942:   border-collapse: separate;
 5943:   padding: 0;
 5944: }
 5945: 
 5946: table#LC_title_bar a {
 5947:   color: $fontmenu;
 5948: }
 5949: 
 5950: table#LC_title_bar {
 5951:   clear: both;
 5952:   display: none;
 5953: }
 5954: 
 5955: table#LC_title_bar,
 5956: table.LC_breadcrumbs, /* obsolete? */
 5957: table#LC_title_bar.LC_with_remote {
 5958:   width: 100%;
 5959:   border-color: $pgbg;
 5960:   border-style: solid;
 5961:   border-width: $border;
 5962:   background: $pgbg;
 5963:   color: $fontmenu;
 5964:   border-collapse: collapse;
 5965:   padding: 0;
 5966:   margin: 0;
 5967: }
 5968: 
 5969: ul.LC_breadcrumb_tools_outerlist {
 5970:     margin: 0;
 5971:     padding: 0;
 5972:     position: relative;
 5973:     list-style: none;
 5974: }
 5975: ul.LC_breadcrumb_tools_outerlist li {
 5976:     display: inline;
 5977: }
 5978: 
 5979: .LC_breadcrumb_tools_navigation {
 5980:     padding: 0;
 5981:     margin: 0;
 5982:     float: left;
 5983: }
 5984: .LC_breadcrumb_tools_tools {
 5985:     padding: 0;
 5986:     margin: 0;
 5987:     float: right;
 5988: }
 5989: 
 5990: table#LC_title_bar td {
 5991:   background: $tabbg;
 5992: }
 5993: 
 5994: table#LC_menubuttons img {
 5995:   border: none;
 5996: }
 5997: 
 5998: .LC_breadcrumbs_component {
 5999:   float: right;
 6000:   margin: 0 1em;
 6001: }
 6002: .LC_breadcrumbs_component img {
 6003:   vertical-align: middle;
 6004: }
 6005: 
 6006: .LC_breadcrumbs_hoverable {
 6007:   background: $sidebg;
 6008: }
 6009: 
 6010: td.LC_table_cell_checkbox {
 6011:   text-align: center;
 6012: }
 6013: 
 6014: .LC_fontsize_small {
 6015:   font-size: 70%;
 6016: }
 6017: 
 6018: #LC_breadcrumbs {
 6019:   clear:both;
 6020:   background: $sidebg;
 6021:   border-bottom: 1px solid $lg_border_color;
 6022:   line-height: 2.5em;
 6023:   overflow: hidden;
 6024:   margin: 0;
 6025:   padding: 0;
 6026:   text-align: left;
 6027: }
 6028: 
 6029: .LC_head_subbox, .LC_actionbox {
 6030:   clear:both;
 6031:   background: #F8F8F8; /* $sidebg; */
 6032:   border: 1px solid $sidebg;
 6033:   margin: 0 0 10px 0;
 6034:   padding: 3px;
 6035:   text-align: left;
 6036: }
 6037: 
 6038: .LC_fontsize_medium {
 6039:   font-size: 85%;
 6040: }
 6041: 
 6042: .LC_fontsize_large {
 6043:   font-size: 120%;
 6044: }
 6045: 
 6046: .LC_menubuttons_inline_text {
 6047:   color: $font;
 6048:   font-size: 90%;
 6049:   padding-left:3px;
 6050: }
 6051: 
 6052: .LC_menubuttons_inline_text img{
 6053:   vertical-align: middle;
 6054: }
 6055: 
 6056: li.LC_menubuttons_inline_text img {
 6057:   cursor:pointer;
 6058:   text-decoration: none;
 6059: }
 6060: 
 6061: .LC_menubuttons_link {
 6062:   text-decoration: none;
 6063: }
 6064: 
 6065: .LC_menubuttons_category {
 6066:   color: $font;
 6067:   background: $pgbg;
 6068:   font-size: larger;
 6069:   font-weight: bold;
 6070: }
 6071: 
 6072: td.LC_menubuttons_text {
 6073:   color: $font;
 6074: }
 6075: 
 6076: .LC_current_location {
 6077:   background: $tabbg;
 6078: }
 6079: 
 6080: table.LC_data_table {
 6081:   border: 1px solid #000000;
 6082:   border-collapse: separate;
 6083:   border-spacing: 1px;
 6084:   background: $pgbg;
 6085: }
 6086: 
 6087: .LC_data_table_dense {
 6088:   font-size: small;
 6089: }
 6090: 
 6091: table.LC_nested_outer {
 6092:   border: 1px solid #000000;
 6093:   border-collapse: collapse;
 6094:   border-spacing: 0;
 6095:   width: 100%;
 6096: }
 6097: 
 6098: table.LC_innerpickbox,
 6099: table.LC_nested {
 6100:   border: none;
 6101:   border-collapse: collapse;
 6102:   border-spacing: 0;
 6103:   width: 100%;
 6104: }
 6105: 
 6106: table.LC_data_table tr th,
 6107: table.LC_calendar tr th,
 6108: table.LC_prior_tries tr th,
 6109: table.LC_innerpickbox tr th {
 6110:   font-weight: bold;
 6111:   background-color: $data_table_head;
 6112:   color:$fontmenu;
 6113:   font-size:90%;
 6114: }
 6115: 
 6116: table.LC_innerpickbox tr th,
 6117: table.LC_innerpickbox tr td {
 6118:   vertical-align: top;
 6119: }
 6120: 
 6121: table.LC_data_table tr.LC_info_row > td {
 6122:   background-color: #CCCCCC;
 6123:   font-weight: bold;
 6124:   text-align: left;
 6125: }
 6126: 
 6127: table.LC_data_table tr.LC_odd_row > td {
 6128:   background-color: $data_table_light;
 6129:   padding: 2px;
 6130:   vertical-align: top;
 6131: }
 6132: 
 6133: table.LC_pick_box tr > td.LC_odd_row {
 6134:   background-color: $data_table_light;
 6135:   vertical-align: top;
 6136: }
 6137: 
 6138: table.LC_data_table tr.LC_even_row > td {
 6139:   background-color: $data_table_dark;
 6140:   padding: 2px;
 6141:   vertical-align: top;
 6142: }
 6143: 
 6144: table.LC_pick_box tr > td.LC_even_row {
 6145:   background-color: $data_table_dark;
 6146:   vertical-align: top;
 6147: }
 6148: 
 6149: table.LC_data_table tr.LC_data_table_highlight td {
 6150:   background-color: $data_table_darker;
 6151: }
 6152: 
 6153: table.LC_data_table tr td.LC_leftcol_header {
 6154:   background-color: $data_table_head;
 6155:   font-weight: bold;
 6156: }
 6157: 
 6158: table.LC_data_table tr.LC_empty_row td,
 6159: table.LC_nested tr.LC_empty_row td {
 6160:   font-weight: bold;
 6161:   font-style: italic;
 6162:   text-align: center;
 6163:   padding: 8px;
 6164: }
 6165: 
 6166: table.LC_data_table tr.LC_empty_row td,
 6167: table.LC_data_table tr.LC_footer_row td {
 6168:   background-color: $sidebg;
 6169: }
 6170: 
 6171: table.LC_nested tr.LC_empty_row td {
 6172:   background-color: #FFFFFF;
 6173: }
 6174: 
 6175: table.LC_caption {
 6176: }
 6177: 
 6178: table.LC_nested tr.LC_empty_row td {
 6179:   padding: 4ex
 6180: }
 6181: 
 6182: table.LC_nested_outer tr th {
 6183:   font-weight: bold;
 6184:   color:$fontmenu;
 6185:   background-color: $data_table_head;
 6186:   font-size: small;
 6187:   border-bottom: 1px solid #000000;
 6188: }
 6189: 
 6190: table.LC_nested_outer tr td.LC_subheader {
 6191:   background-color: $data_table_head;
 6192:   font-weight: bold;
 6193:   font-size: small;
 6194:   border-bottom: 1px solid #000000;
 6195:   text-align: right;
 6196: }
 6197: 
 6198: table.LC_nested tr.LC_info_row td {
 6199:   background-color: #CCCCCC;
 6200:   font-weight: bold;
 6201:   font-size: small;
 6202:   text-align: center;
 6203: }
 6204: 
 6205: table.LC_nested tr.LC_info_row td.LC_left_item,
 6206: table.LC_nested_outer tr th.LC_left_item {
 6207:   text-align: left;
 6208: }
 6209: 
 6210: table.LC_nested td {
 6211:   background-color: #FFFFFF;
 6212:   font-size: small;
 6213: }
 6214: 
 6215: table.LC_nested_outer tr th.LC_right_item,
 6216: table.LC_nested tr.LC_info_row td.LC_right_item,
 6217: table.LC_nested tr.LC_odd_row td.LC_right_item,
 6218: table.LC_nested tr td.LC_right_item {
 6219:   text-align: right;
 6220: }
 6221: 
 6222: table.LC_nested tr.LC_odd_row td {
 6223:   background-color: #EEEEEE;
 6224: }
 6225: 
 6226: table.LC_createuser {
 6227: }
 6228: 
 6229: table.LC_createuser tr.LC_section_row td {
 6230:   font-size: small;
 6231: }
 6232: 
 6233: table.LC_createuser tr.LC_info_row td  {
 6234:   background-color: #CCCCCC;
 6235:   font-weight: bold;
 6236:   text-align: center;
 6237: }
 6238: 
 6239: table.LC_calendar {
 6240:   border: 1px solid #000000;
 6241:   border-collapse: collapse;
 6242:   width: 98%;
 6243: }
 6244: 
 6245: table.LC_calendar_pickdate {
 6246:   font-size: xx-small;
 6247: }
 6248: 
 6249: table.LC_calendar tr td {
 6250:   border: 1px solid #000000;
 6251:   vertical-align: top;
 6252:   width: 14%;
 6253: }
 6254: 
 6255: table.LC_calendar tr td.LC_calendar_day_empty {
 6256:   background-color: $data_table_dark;
 6257: }
 6258: 
 6259: table.LC_calendar tr td.LC_calendar_day_current {
 6260:   background-color: $data_table_highlight;
 6261: }
 6262: 
 6263: table.LC_data_table tr td.LC_mail_new {
 6264:   background-color: $mail_new;
 6265: }
 6266: 
 6267: table.LC_data_table tr.LC_mail_new:hover {
 6268:   background-color: $mail_new_hover;
 6269: }
 6270: 
 6271: table.LC_data_table tr td.LC_mail_read {
 6272:   background-color: $mail_read;
 6273: }
 6274: 
 6275: /*
 6276: table.LC_data_table tr.LC_mail_read:hover {
 6277:   background-color: $mail_read_hover;
 6278: }
 6279: */
 6280: 
 6281: table.LC_data_table tr td.LC_mail_replied {
 6282:   background-color: $mail_replied;
 6283: }
 6284: 
 6285: /*
 6286: table.LC_data_table tr.LC_mail_replied:hover {
 6287:   background-color: $mail_replied_hover;
 6288: }
 6289: */
 6290: 
 6291: table.LC_data_table tr td.LC_mail_other {
 6292:   background-color: $mail_other;
 6293: }
 6294: 
 6295: /*
 6296: table.LC_data_table tr.LC_mail_other:hover {
 6297:   background-color: $mail_other_hover;
 6298: }
 6299: */
 6300: 
 6301: table.LC_data_table tr > td.LC_browser_file,
 6302: table.LC_data_table tr > td.LC_browser_file_published {
 6303:   background: #AAEE77;
 6304: }
 6305: 
 6306: table.LC_data_table tr > td.LC_browser_file_locked,
 6307: table.LC_data_table tr > td.LC_browser_file_unpublished {
 6308:   background: #FFAA99;
 6309: }
 6310: 
 6311: table.LC_data_table tr > td.LC_browser_file_obsolete {
 6312:   background: #888888;
 6313: }
 6314: 
 6315: table.LC_data_table tr > td.LC_browser_file_modified,
 6316: table.LC_data_table tr > td.LC_browser_file_metamodified {
 6317:   background: #F8F866;
 6318: }
 6319: 
 6320: table.LC_data_table tr.LC_browser_folder > td {
 6321:   background: #E0E8FF;
 6322: }
 6323: 
 6324: table.LC_data_table tr > td.LC_roles_is {
 6325:   /* background: #77FF77; */
 6326: }
 6327: 
 6328: table.LC_data_table tr > td.LC_roles_future {
 6329:   border-right: 8px solid #FFFF77;
 6330: }
 6331: 
 6332: table.LC_data_table tr > td.LC_roles_will {
 6333:   border-right: 8px solid #FFAA77;
 6334: }
 6335: 
 6336: table.LC_data_table tr > td.LC_roles_expired {
 6337:   border-right: 8px solid #FF7777;
 6338: }
 6339: 
 6340: table.LC_data_table tr > td.LC_roles_will_not {
 6341:   border-right: 8px solid #AAFF77;
 6342: }
 6343: 
 6344: table.LC_data_table tr > td.LC_roles_selected {
 6345:   border-right: 8px solid #11CC55;
 6346: }
 6347: 
 6348: span.LC_current_location {
 6349:   font-size:larger;
 6350:   background: $pgbg;
 6351: }
 6352: 
 6353: span.LC_current_nav_location {
 6354:   font-weight:bold;
 6355:   background: $sidebg;
 6356: }
 6357: 
 6358: span.LC_parm_menu_item {
 6359:   font-size: larger;
 6360: }
 6361: 
 6362: span.LC_parm_scope_all {
 6363:   color: red;
 6364: }
 6365: 
 6366: span.LC_parm_scope_folder {
 6367:   color: green;
 6368: }
 6369: 
 6370: span.LC_parm_scope_resource {
 6371:   color: orange;
 6372: }
 6373: 
 6374: span.LC_parm_part {
 6375:   color: blue;
 6376: }
 6377: 
 6378: span.LC_parm_folder,
 6379: span.LC_parm_symb {
 6380:   font-size: x-small;
 6381:   font-family: $mono;
 6382:   color: #AAAAAA;
 6383: }
 6384: 
 6385: ul.LC_parm_parmlist li {
 6386:   display: inline-block;
 6387:   padding: 0.3em 0.8em;
 6388:   vertical-align: top;
 6389:   width: 150px;
 6390:   border-top:1px solid $lg_border_color;
 6391: }
 6392: 
 6393: td.LC_parm_overview_level_menu,
 6394: td.LC_parm_overview_map_menu,
 6395: td.LC_parm_overview_parm_selectors,
 6396: td.LC_parm_overview_restrictions  {
 6397:   border: 1px solid black;
 6398:   border-collapse: collapse;
 6399: }
 6400: 
 6401: table.LC_parm_overview_restrictions td {
 6402:   border-width: 1px 4px 1px 4px;
 6403:   border-style: solid;
 6404:   border-color: $pgbg;
 6405:   text-align: center;
 6406: }
 6407: 
 6408: table.LC_parm_overview_restrictions th {
 6409:   background: $tabbg;
 6410:   border-width: 1px 4px 1px 4px;
 6411:   border-style: solid;
 6412:   border-color: $pgbg;
 6413: }
 6414: 
 6415: table#LC_helpmenu {
 6416:   border: none;
 6417:   height: 55px;
 6418:   border-spacing: 0;
 6419: }
 6420: 
 6421: table#LC_helpmenu fieldset legend {
 6422:   font-size: larger;
 6423: }
 6424: 
 6425: table#LC_helpmenu_links {
 6426:   width: 100%;
 6427:   border: 1px solid black;
 6428:   background: $pgbg;
 6429:   padding: 0;
 6430:   border-spacing: 1px;
 6431: }
 6432: 
 6433: table#LC_helpmenu_links tr td {
 6434:   padding: 1px;
 6435:   background: $tabbg;
 6436:   text-align: center;
 6437:   font-weight: bold;
 6438: }
 6439: 
 6440: table#LC_helpmenu_links a:link,
 6441: table#LC_helpmenu_links a:visited,
 6442: table#LC_helpmenu_links a:active {
 6443:   text-decoration: none;
 6444:   color: $font;
 6445: }
 6446: 
 6447: table#LC_helpmenu_links a:hover {
 6448:   text-decoration: underline;
 6449:   color: $vlink;
 6450: }
 6451: 
 6452: .LC_chrt_popup_exists {
 6453:   border: 1px solid #339933;
 6454:   margin: -1px;
 6455: }
 6456: 
 6457: .LC_chrt_popup_up {
 6458:   border: 1px solid yellow;
 6459:   margin: -1px;
 6460: }
 6461: 
 6462: .LC_chrt_popup {
 6463:   border: 1px solid #8888FF;
 6464:   background: #CCCCFF;
 6465: }
 6466: 
 6467: table.LC_pick_box {
 6468:   border-collapse: separate;
 6469:   background: white;
 6470:   border: 1px solid black;
 6471:   border-spacing: 1px;
 6472: }
 6473: 
 6474: table.LC_pick_box td.LC_pick_box_title {
 6475:   background: $sidebg;
 6476:   font-weight: bold;
 6477:   text-align: left;
 6478:   vertical-align: top;
 6479:   width: 184px;
 6480:   padding: 8px;
 6481: }
 6482: 
 6483: table.LC_pick_box td.LC_pick_box_value {
 6484:   text-align: left;
 6485:   padding: 8px;
 6486: }
 6487: 
 6488: table.LC_pick_box td.LC_pick_box_select {
 6489:   text-align: left;
 6490:   padding: 8px;
 6491: }
 6492: 
 6493: table.LC_pick_box td.LC_pick_box_separator {
 6494:   padding: 0;
 6495:   height: 1px;
 6496:   background: black;
 6497: }
 6498: 
 6499: table.LC_pick_box td.LC_pick_box_submit {
 6500:   text-align: right;
 6501: }
 6502: 
 6503: table.LC_pick_box td.LC_evenrow_value {
 6504:   text-align: left;
 6505:   padding: 8px;
 6506:   background-color: $data_table_light;
 6507: }
 6508: 
 6509: table.LC_pick_box td.LC_oddrow_value {
 6510:   text-align: left;
 6511:   padding: 8px;
 6512:   background-color: $data_table_light;
 6513: }
 6514: 
 6515: span.LC_helpform_receipt_cat {
 6516:   font-weight: bold;
 6517: }
 6518: 
 6519: table.LC_group_priv_box {
 6520:   background: white;
 6521:   border: 1px solid black;
 6522:   border-spacing: 1px;
 6523: }
 6524: 
 6525: table.LC_group_priv_box td.LC_pick_box_title {
 6526:   background: $tabbg;
 6527:   font-weight: bold;
 6528:   text-align: right;
 6529:   width: 184px;
 6530: }
 6531: 
 6532: table.LC_group_priv_box td.LC_groups_fixed {
 6533:   background: $data_table_light;
 6534:   text-align: center;
 6535: }
 6536: 
 6537: table.LC_group_priv_box td.LC_groups_optional {
 6538:   background: $data_table_dark;
 6539:   text-align: center;
 6540: }
 6541: 
 6542: table.LC_group_priv_box td.LC_groups_functionality {
 6543:   background: $data_table_darker;
 6544:   text-align: center;
 6545:   font-weight: bold;
 6546: }
 6547: 
 6548: table.LC_group_priv td {
 6549:   text-align: left;
 6550:   padding: 0;
 6551: }
 6552: 
 6553: .LC_navbuttons {
 6554:   margin: 2ex 0ex 2ex 0ex;
 6555: }
 6556: 
 6557: .LC_topic_bar {
 6558:   font-weight: bold;
 6559:   background: $tabbg;
 6560:   margin: 1em 0em 1em 2em;
 6561:   padding: 3px;
 6562:   font-size: 1.2em;
 6563: }
 6564: 
 6565: .LC_topic_bar span {
 6566:   left: 0.5em;
 6567:   position: absolute;
 6568:   vertical-align: middle;
 6569:   font-size: 1.2em;
 6570: }
 6571: 
 6572: table.LC_course_group_status {
 6573:   margin: 20px;
 6574: }
 6575: 
 6576: table.LC_status_selector td {
 6577:   vertical-align: top;
 6578:   text-align: center;
 6579:   padding: 4px;
 6580: }
 6581: 
 6582: div.LC_feedback_link {
 6583:   clear: both;
 6584:   background: $sidebg;
 6585:   width: 100%;
 6586:   padding-bottom: 10px;
 6587:   border: 1px $tabbg solid;
 6588:   height: 22px;
 6589:   line-height: 22px;
 6590:   padding-top: 5px;
 6591: }
 6592: 
 6593: div.LC_feedback_link img {
 6594:   height: 22px;
 6595:   vertical-align:middle;
 6596: }
 6597: 
 6598: div.LC_feedback_link a {
 6599:   text-decoration: none;
 6600: }
 6601: 
 6602: div.LC_comblock {
 6603:   display:inline;
 6604:   color:$font;
 6605:   font-size:90%;
 6606: }
 6607: 
 6608: div.LC_feedback_link div.LC_comblock {
 6609:   padding-left:5px;
 6610: }
 6611: 
 6612: div.LC_feedback_link div.LC_comblock a {
 6613:   color:$font;
 6614: }
 6615: 
 6616: span.LC_feedback_link {
 6617:   /* background: $feedback_link_bg; */
 6618:   font-size: larger;
 6619: }
 6620: 
 6621: span.LC_message_link {
 6622:   /* background: $feedback_link_bg; */
 6623:   font-size: larger;
 6624:   position: absolute;
 6625:   right: 1em;
 6626: }
 6627: 
 6628: table.LC_prior_tries {
 6629:   border: 1px solid #000000;
 6630:   border-collapse: separate;
 6631:   border-spacing: 1px;
 6632: }
 6633: 
 6634: table.LC_prior_tries td {
 6635:   padding: 2px;
 6636: }
 6637: 
 6638: .LC_answer_correct {
 6639:   background: lightgreen;
 6640:   color: darkgreen;
 6641:   padding: 6px;
 6642: }
 6643: 
 6644: .LC_answer_charged_try {
 6645:   background: #FFAAAA;
 6646:   color: darkred;
 6647:   padding: 6px;
 6648: }
 6649: 
 6650: .LC_answer_not_charged_try,
 6651: .LC_answer_no_grade,
 6652: .LC_answer_late {
 6653:   background: lightyellow;
 6654:   color: black;
 6655:   padding: 6px;
 6656: }
 6657: 
 6658: .LC_answer_previous {
 6659:   background: lightblue;
 6660:   color: darkblue;
 6661:   padding: 6px;
 6662: }
 6663: 
 6664: .LC_answer_no_message {
 6665:   background: #FFFFFF;
 6666:   color: black;
 6667:   padding: 6px;
 6668: }
 6669: 
 6670: .LC_answer_unknown {
 6671:   background: orange;
 6672:   color: black;
 6673:   padding: 6px;
 6674: }
 6675: 
 6676: span.LC_prior_numerical,
 6677: span.LC_prior_string,
 6678: span.LC_prior_custom,
 6679: span.LC_prior_reaction,
 6680: span.LC_prior_math {
 6681:   font-family: $mono;
 6682:   white-space: pre;
 6683: }
 6684: 
 6685: span.LC_prior_string {
 6686:   font-family: $mono;
 6687:   white-space: pre;
 6688: }
 6689: 
 6690: table.LC_prior_option {
 6691:   width: 100%;
 6692:   border-collapse: collapse;
 6693: }
 6694: 
 6695: table.LC_prior_rank,
 6696: table.LC_prior_match {
 6697:   border-collapse: collapse;
 6698: }
 6699: 
 6700: table.LC_prior_option tr td,
 6701: table.LC_prior_rank tr td,
 6702: table.LC_prior_match tr td {
 6703:   border: 1px solid #000000;
 6704: }
 6705: 
 6706: .LC_nobreak {
 6707:   white-space: nowrap;
 6708: }
 6709: 
 6710: span.LC_cusr_emph {
 6711:   font-style: italic;
 6712: }
 6713: 
 6714: span.LC_cusr_subheading {
 6715:   font-weight: normal;
 6716:   font-size: 85%;
 6717: }
 6718: 
 6719: div.LC_docs_entry_move {
 6720:   border: 1px solid #BBBBBB;
 6721:   background: #DDDDDD;
 6722:   width: 22px;
 6723:   padding: 1px;
 6724:   margin: 0;
 6725: }
 6726: 
 6727: table.LC_data_table tr > td.LC_docs_entry_commands,
 6728: table.LC_data_table tr > td.LC_docs_entry_parameter {
 6729:   font-size: x-small;
 6730: }
 6731: 
 6732: .LC_docs_entry_parameter {
 6733:   white-space: nowrap;
 6734: }
 6735: 
 6736: .LC_docs_copy {
 6737:   color: #000099;
 6738: }
 6739: 
 6740: .LC_docs_cut {
 6741:   color: #550044;
 6742: }
 6743: 
 6744: .LC_docs_rename {
 6745:   color: #009900;
 6746: }
 6747: 
 6748: .LC_docs_remove {
 6749:   color: #990000;
 6750: }
 6751: 
 6752: .LC_docs_reinit_warn,
 6753: .LC_docs_ext_edit {
 6754:   font-size: x-small;
 6755: }
 6756: 
 6757: table.LC_docs_adddocs td,
 6758: table.LC_docs_adddocs th {
 6759:   border: 1px solid #BBBBBB;
 6760:   padding: 4px;
 6761:   background: #DDDDDD;
 6762: }
 6763: 
 6764: table.LC_sty_begin {
 6765:   background: #BBFFBB;
 6766: }
 6767: 
 6768: table.LC_sty_end {
 6769:   background: #FFBBBB;
 6770: }
 6771: 
 6772: table.LC_double_column {
 6773:   border-width: 0;
 6774:   border-collapse: collapse;
 6775:   width: 100%;
 6776:   padding: 2px;
 6777: }
 6778: 
 6779: table.LC_double_column tr td.LC_left_col {
 6780:   top: 2px;
 6781:   left: 2px;
 6782:   width: 47%;
 6783:   vertical-align: top;
 6784: }
 6785: 
 6786: table.LC_double_column tr td.LC_right_col {
 6787:   top: 2px;
 6788:   right: 2px;
 6789:   width: 47%;
 6790:   vertical-align: top;
 6791: }
 6792: 
 6793: div.LC_left_float {
 6794:   float: left;
 6795:   padding-right: 5%;
 6796:   padding-bottom: 4px;
 6797: }
 6798: 
 6799: div.LC_clear_float_header {
 6800:   padding-bottom: 2px;
 6801: }
 6802: 
 6803: div.LC_clear_float_footer {
 6804:   padding-top: 10px;
 6805:   clear: both;
 6806: }
 6807: 
 6808: div.LC_grade_show_user {
 6809: /*  border-left: 5px solid $sidebg; */
 6810:   border-top: 5px solid #000000;
 6811:   margin: 50px 0 0 0;
 6812:   padding: 15px 0 5px 10px;
 6813: }
 6814: 
 6815: div.LC_grade_show_user_odd_row {
 6816: /*  border-left: 5px solid #000000; */
 6817: }
 6818: 
 6819: div.LC_grade_show_user div.LC_Box {
 6820:   margin-right: 50px;
 6821: }
 6822: 
 6823: div.LC_grade_submissions,
 6824: div.LC_grade_message_center,
 6825: div.LC_grade_info_links {
 6826:   margin: 5px;
 6827:   width: 99%;
 6828:   background: #FFFFFF;
 6829: }
 6830: 
 6831: div.LC_grade_submissions_header,
 6832: div.LC_grade_message_center_header {
 6833:   font-weight: bold;
 6834:   font-size: large;
 6835: }
 6836: 
 6837: div.LC_grade_submissions_body,
 6838: div.LC_grade_message_center_body {
 6839:   border: 1px solid black;
 6840:   width: 99%;
 6841:   background: #FFFFFF;
 6842: }
 6843: 
 6844: table.LC_scantron_action {
 6845:   width: 100%;
 6846: }
 6847: 
 6848: table.LC_scantron_action tr th {
 6849:   font-weight:bold;
 6850:   font-style:normal;
 6851: }
 6852: 
 6853: .LC_edit_problem_header,
 6854: div.LC_edit_problem_footer {
 6855:   font-weight: normal;
 6856:   font-size:  medium;
 6857:   margin: 2px;
 6858:   background-color: $sidebg;
 6859: }
 6860: 
 6861: div.LC_edit_problem_header,
 6862: div.LC_edit_problem_header div,
 6863: div.LC_edit_problem_footer,
 6864: div.LC_edit_problem_footer div,
 6865: div.LC_edit_problem_editxml_header,
 6866: div.LC_edit_problem_editxml_header div {
 6867:   z-index: 100;
 6868: }
 6869: 
 6870: div.LC_edit_problem_header_title {
 6871:   font-weight: bold;
 6872:   font-size: larger;
 6873:   background: $tabbg;
 6874:   padding: 3px;
 6875:   margin: 0 0 5px 0;
 6876: }
 6877: 
 6878: table.LC_edit_problem_header_title {
 6879:   width: 100%;
 6880:   background: $tabbg;
 6881: }
 6882: 
 6883: div.LC_edit_actionbar {
 6884:     background-color: $sidebg;
 6885:     margin: 0;
 6886:     padding: 0;
 6887:     line-height: 200%;
 6888: }
 6889: 
 6890: div.LC_edit_actionbar div{
 6891:     padding: 0;
 6892:     margin: 0;
 6893:     display: inline-block;
 6894: }
 6895: 
 6896: .LC_edit_opt {
 6897:   padding-left: 1em;
 6898:   white-space: nowrap;
 6899: }
 6900: 
 6901: .LC_edit_problem_latexhelper{
 6902:     text-align: right;
 6903: }
 6904: 
 6905: #LC_edit_problem_colorful div{
 6906:     margin-left: 40px;
 6907: }
 6908: 
 6909: #LC_edit_problem_codemirror div{
 6910:     margin-left: 0px;
 6911: }
 6912: 
 6913: img.stift {
 6914:   border-width: 0;
 6915:   vertical-align: middle;
 6916: }
 6917: 
 6918: table td.LC_mainmenu_col_fieldset {
 6919:   vertical-align: top;
 6920: }
 6921: 
 6922: div.LC_createcourse {
 6923:   margin: 10px 10px 10px 10px;
 6924: }
 6925: 
 6926: .LC_dccid {
 6927:   float: right;
 6928:   margin: 0.2em 0 0 0;
 6929:   padding: 0;
 6930:   font-size: 90%;
 6931:   display:none;
 6932: }
 6933: 
 6934: ol.LC_primary_menu a:hover,
 6935: ol#LC_MenuBreadcrumbs a:hover,
 6936: ol#LC_PathBreadcrumbs a:hover,
 6937: ul#LC_secondary_menu a:hover,
 6938: .LC_FormSectionClearButton input:hover
 6939: ul.LC_TabContent   li:hover a {
 6940:   color:$button_hover;
 6941:   text-decoration:none;
 6942: }
 6943: 
 6944: h1 {
 6945:   padding: 0;
 6946:   line-height:130%;
 6947: }
 6948: 
 6949: h2,
 6950: h3,
 6951: h4,
 6952: h5,
 6953: h6 {
 6954:   margin: 5px 0 5px 0;
 6955:   padding: 0;
 6956:   line-height:130%;
 6957: }
 6958: 
 6959: .LC_hcell {
 6960:   padding:3px 15px 3px 15px;
 6961:   margin: 0;
 6962:   background-color:$tabbg;
 6963:   color:$fontmenu;
 6964:   border-bottom:solid 1px $lg_border_color;
 6965: }
 6966: 
 6967: .LC_Box > .LC_hcell {
 6968:   margin: 0 -10px 10px -10px;
 6969: }
 6970: 
 6971: .LC_noBorder {
 6972:   border: 0;
 6973: }
 6974: 
 6975: .LC_FormSectionClearButton input {
 6976:   background-color:transparent;
 6977:   border: none;
 6978:   cursor:pointer;
 6979:   text-decoration:underline;
 6980: }
 6981: 
 6982: .LC_help_open_topic {
 6983:   color: #FFFFFF;
 6984:   background-color: #EEEEFF;
 6985:   margin: 1px;
 6986:   padding: 4px;
 6987:   border: 1px solid #000033;
 6988:   white-space: nowrap;
 6989:   /* vertical-align: middle; */
 6990: }
 6991: 
 6992: dl,
 6993: ul,
 6994: div,
 6995: fieldset {
 6996:   margin: 10px 10px 10px 0;
 6997:   /* overflow: hidden; */
 6998: }
 6999: 
 7000: article.geogebraweb div {
 7001:     margin: 0;
 7002: }
 7003: 
 7004: fieldset > legend {
 7005:   font-weight: bold;
 7006:   padding: 0 5px 0 5px;
 7007: }
 7008: 
 7009: #LC_nav_bar {
 7010:   float: left;
 7011:   background-color: $pgbg_or_bgcolor;
 7012:   margin: 0 0 2px 0;
 7013: }
 7014: 
 7015: #LC_realm {
 7016:   margin: 0.2em 0 0 0;
 7017:   padding: 0;
 7018:   font-weight: bold;
 7019:   text-align: center;
 7020:   background-color: $pgbg_or_bgcolor;
 7021: }
 7022: 
 7023: #LC_nav_bar em {
 7024:   font-weight: bold;
 7025:   font-style: normal;
 7026: }
 7027: 
 7028: ol.LC_primary_menu {
 7029:   margin: 0;
 7030:   padding: 0;
 7031: }
 7032: 
 7033: ol#LC_PathBreadcrumbs {
 7034:   margin: 0;
 7035: }
 7036: 
 7037: ol.LC_primary_menu li {
 7038:   color: RGB(80, 80, 80);
 7039:   vertical-align: middle;
 7040:   text-align: left;
 7041:   list-style: none;
 7042:   position: relative;
 7043:   float: left;
 7044:   z-index: 100; /* will be displayed above codemirror and underneath the help-layer */
 7045:   line-height: 1.5em;
 7046: }
 7047: 
 7048: ol.LC_primary_menu li a, 
 7049: ol.LC_primary_menu li p {
 7050:   display: block;
 7051:   margin: 0;
 7052:   padding: 0 5px 0 10px;
 7053:   text-decoration: none;
 7054: }
 7055: 
 7056: ol.LC_primary_menu li p span.LC_primary_menu_innertitle {
 7057:   display: inline-block;
 7058:   width: 95%;
 7059:   text-align: left;
 7060: }
 7061: 
 7062: ol.LC_primary_menu li p span.LC_primary_menu_innerarrow {
 7063:   display: inline-block;
 7064:   width: 5%;
 7065:   float: right;
 7066:   text-align: right;
 7067:   font-size: 70%;
 7068: }
 7069: 
 7070: ol.LC_primary_menu ul {
 7071:   display: none;
 7072:   width: 15em;
 7073:   background-color: $data_table_light;
 7074:   position: absolute;
 7075:   top: 100%;
 7076: }
 7077: 
 7078: ol.LC_primary_menu ul ul {
 7079:   left: 100%;
 7080:   top: 0;
 7081: }
 7082: 
 7083: ol.LC_primary_menu li:hover > ul, ol.LC_primary_menu li.hover > ul {
 7084:   display: block;
 7085:   position: absolute;
 7086:   margin: 0;
 7087:   padding: 0;
 7088:   z-index: 2;
 7089: }
 7090: 
 7091: ol.LC_primary_menu li:hover li, ol.LC_primary_menu li.hover li {
 7092: /* First Submenu -> size should be smaller than the menu title of the whole menu */
 7093:   font-size: 90%;
 7094:   vertical-align: top;
 7095:   float: none;
 7096:   border-left: 1px solid black;
 7097:   border-right: 1px solid black;
 7098: /* A dark bottom border to visualize different menu options;
 7099: overwritten in the create_submenu routine for the last border-bottom of the menu */
 7100:   border-bottom: 1px solid $data_table_dark;
 7101: }
 7102: 
 7103: ol.LC_primary_menu li li p:hover {
 7104:   color:$button_hover;
 7105:   text-decoration:none;
 7106:   background-color:$data_table_dark;
 7107: }
 7108: 
 7109: ol.LC_primary_menu li li a:hover {
 7110:    color:$button_hover;
 7111:    background-color:$data_table_dark;
 7112: }
 7113: 
 7114: /* Font-size equal to the size of the predecessors*/
 7115: ol.LC_primary_menu li:hover li li {
 7116:   font-size: 100%;
 7117: }
 7118: 
 7119: ol.LC_primary_menu li img {
 7120:   vertical-align: bottom;
 7121:   height: 1.1em;
 7122:   margin: 0.2em 0 0 0;
 7123: }
 7124: 
 7125: ol.LC_primary_menu a {
 7126:   color: RGB(80, 80, 80);
 7127:   text-decoration: none;
 7128: }
 7129: 
 7130: ol.LC_primary_menu a.LC_new_message {
 7131:   font-weight:bold;
 7132:   color: darkred;
 7133: }
 7134: 
 7135: ol.LC_docs_parameters {
 7136:   margin-left: 0;
 7137:   padding: 0;
 7138:   list-style: none;
 7139: }
 7140: 
 7141: ol.LC_docs_parameters li {
 7142:   margin: 0;
 7143:   padding-right: 20px;
 7144:   display: inline;
 7145: }
 7146: 
 7147: ol.LC_docs_parameters li:before {
 7148:   content: "\\002022 \\0020";
 7149: }
 7150: 
 7151: li.LC_docs_parameters_title {
 7152:   font-weight: bold;
 7153: }
 7154: 
 7155: ol.LC_docs_parameters li.LC_docs_parameters_title:before {
 7156:   content: "";
 7157: }
 7158: 
 7159: ul#LC_secondary_menu {
 7160:   clear: right;
 7161:   color: $fontmenu;
 7162:   background: $tabbg;
 7163:   list-style: none;
 7164:   padding: 0;
 7165:   margin: 0;
 7166:   width: 100%;
 7167:   text-align: left;
 7168:   float: left;
 7169: }
 7170: 
 7171: ul#LC_secondary_menu li {
 7172:   font-weight: bold;
 7173:   line-height: 1.8em;
 7174:   border-right: 1px solid black;
 7175:   float: left;
 7176: }
 7177: 
 7178: ul#LC_secondary_menu li.LC_hoverable:hover, ul#LC_secondary_menu li.hover {
 7179:   background-color: $data_table_light;
 7180: }
 7181: 
 7182: ul#LC_secondary_menu li a {
 7183:   padding: 0 0.8em;
 7184: }
 7185: 
 7186: ul#LC_secondary_menu li ul {
 7187:   display: none;
 7188: }
 7189: 
 7190: ul#LC_secondary_menu li:hover ul, ul#LC_secondary_menu li.hover ul {
 7191:   display: block;
 7192:   position: absolute;
 7193:   margin: 0;
 7194:   padding: 0;
 7195:   list-style:none;
 7196:   float: none;
 7197:   background-color: $data_table_light;
 7198:   z-index: 2;
 7199:   margin-left: -1px;
 7200: }
 7201: 
 7202: ul#LC_secondary_menu li ul li {
 7203:   font-size: 90%;
 7204:   vertical-align: top;
 7205:   border-left: 1px solid black;
 7206:   border-right: 1px solid black;
 7207:   background-color: $data_table_light;
 7208:   list-style:none;
 7209:   float: none;
 7210: }
 7211: 
 7212: ul#LC_secondary_menu li ul li:hover, ul#LC_secondary_menu li ul li.hover {
 7213:   background-color: $data_table_dark;
 7214: }
 7215: 
 7216: ul.LC_TabContent {
 7217:   display:block;
 7218:   background: $sidebg;
 7219:   border-bottom: solid 1px $lg_border_color;
 7220:   list-style:none;
 7221:   margin: -1px -10px 0 -10px;
 7222:   padding: 0;
 7223: }
 7224: 
 7225: ul.LC_TabContent li,
 7226: ul.LC_TabContentBigger li {
 7227:   float:left;
 7228: }
 7229: 
 7230: ul#LC_secondary_menu li a {
 7231:   color: $fontmenu;
 7232:   text-decoration: none;
 7233: }
 7234: 
 7235: ul.LC_TabContent {
 7236:   min-height:20px;
 7237: }
 7238: 
 7239: ul.LC_TabContent li {
 7240:   vertical-align:middle;
 7241:   padding: 0 16px 0 10px;
 7242:   background-color:$tabbg;
 7243:   border-bottom:solid 1px $lg_border_color;
 7244:   border-left: solid 1px $font;
 7245: }
 7246: 
 7247: ul.LC_TabContent .right {
 7248:   float:right;
 7249: }
 7250: 
 7251: ul.LC_TabContent li a,
 7252: ul.LC_TabContent li {
 7253:   color:rgb(47,47,47);
 7254:   text-decoration:none;
 7255:   font-size:95%;
 7256:   font-weight:bold;
 7257:   min-height:20px;
 7258: }
 7259: 
 7260: ul.LC_TabContent li a:hover,
 7261: ul.LC_TabContent li a:focus {
 7262:   color: $button_hover;
 7263:   background:none;
 7264:   outline:none;
 7265: }
 7266: 
 7267: ul.LC_TabContent li:hover {
 7268:   color: $button_hover;
 7269:   cursor:pointer;
 7270: }
 7271: 
 7272: ul.LC_TabContent li.active {
 7273:   color: $font;
 7274:   background:#FFFFFF url(/adm/lonIcons/open.gif) no-repeat scroll right center;
 7275:   border-bottom:solid 1px #FFFFFF;
 7276:   cursor: default;
 7277: }
 7278: 
 7279: ul.LC_TabContent li.active a {
 7280:   color:$font;
 7281:   background:#FFFFFF;
 7282:   outline: none;
 7283: }
 7284: 
 7285: ul.LC_TabContent li.goback {
 7286:   float: left;
 7287:   border-left: none;
 7288: }
 7289: 
 7290: #maincoursedoc {
 7291:   clear:both;
 7292: }
 7293: 
 7294: ul.LC_TabContentBigger {
 7295:   display:block;
 7296:   list-style:none;
 7297:   padding: 0;
 7298: }
 7299: 
 7300: ul.LC_TabContentBigger li {
 7301:   vertical-align:bottom;
 7302:   height: 30px;
 7303:   font-size:110%;
 7304:   font-weight:bold;
 7305:   color: #737373;
 7306: }
 7307: 
 7308: ul.LC_TabContentBigger li.active {
 7309:   position: relative;
 7310:   top: 1px;
 7311: }
 7312: 
 7313: ul.LC_TabContentBigger li a {
 7314:   background:url('/adm/lonIcons/tabbgleft.gif') left bottom no-repeat;
 7315:   height: 30px;
 7316:   line-height: 30px;
 7317:   text-align: center;
 7318:   display: block;
 7319:   text-decoration: none;
 7320:   outline: none;  
 7321: }
 7322: 
 7323: ul.LC_TabContentBigger li.active a {
 7324:   background:url('/adm/lonIcons/tabbgleft.gif') left top no-repeat;
 7325:   color:$font;
 7326: }
 7327: 
 7328: ul.LC_TabContentBigger li b {
 7329:   background: url('/adm/lonIcons/tabbgright.gif') no-repeat right bottom;
 7330:   display: block;
 7331:   float: left;
 7332:   padding: 0 30px;
 7333:   border-bottom: 1px solid $lg_border_color;
 7334: }
 7335: 
 7336: ul.LC_TabContentBigger li:hover b {
 7337:   color:$button_hover;
 7338: }
 7339: 
 7340: ul.LC_TabContentBigger li.active b {
 7341:   background:url('/adm/lonIcons/tabbgright.gif') right top no-repeat;
 7342:   color:$font;
 7343:   border: 0;
 7344: }
 7345: 
 7346: 
 7347: ul.LC_CourseBreadcrumbs {
 7348:   background: $sidebg;
 7349:   height: 2em;
 7350:   padding-left: 10px;
 7351:   margin: 0;
 7352:   list-style-position: inside;
 7353: }
 7354: 
 7355: ol#LC_MenuBreadcrumbs,
 7356: ol#LC_PathBreadcrumbs {
 7357:   padding-left: 10px;
 7358:   margin: 0;
 7359:   height: 2.5em;  /* equal to #LC_breadcrumbs line-height */
 7360: }
 7361: 
 7362: ol#LC_MenuBreadcrumbs li,
 7363: ol#LC_PathBreadcrumbs li,
 7364: ul.LC_CourseBreadcrumbs li {
 7365:   display: inline;
 7366:   white-space: normal;  
 7367: }
 7368: 
 7369: ol#LC_MenuBreadcrumbs li a,
 7370: ul.LC_CourseBreadcrumbs li a {
 7371:   text-decoration: none;
 7372:   font-size:90%;
 7373: }
 7374: 
 7375: ol#LC_MenuBreadcrumbs h1 {
 7376:   display: inline;
 7377:   font-size: 90%;
 7378:   line-height: 2.5em;
 7379:   margin: 0;
 7380:   padding: 0;
 7381: }
 7382: 
 7383: ol#LC_PathBreadcrumbs li a {
 7384:   text-decoration:none;
 7385:   font-size:100%;
 7386:   font-weight:bold;
 7387: }
 7388: 
 7389: .LC_Box {
 7390:   border: solid 1px $lg_border_color;
 7391:   padding: 0 10px 10px 10px;
 7392: }
 7393: 
 7394: .LC_DocsBox {
 7395:   border: solid 1px $lg_border_color;
 7396:   padding: 0 0 10px 10px;
 7397: }
 7398: 
 7399: .LC_AboutMe_Image {
 7400:   float:left;
 7401:   margin-right:10px;
 7402: }
 7403: 
 7404: .LC_Clear_AboutMe_Image {
 7405:   clear:left;
 7406: }
 7407: 
 7408: dl.LC_ListStyleClean dt {
 7409:   padding-right: 5px;
 7410:   display: table-header-group;
 7411: }
 7412: 
 7413: dl.LC_ListStyleClean dd {
 7414:   display: table-row;
 7415: }
 7416: 
 7417: .LC_ListStyleClean,
 7418: .LC_ListStyleSimple,
 7419: .LC_ListStyleNormal,
 7420: .LC_ListStyleSpecial {
 7421:   /* display:block; */
 7422:   list-style-position: inside;
 7423:   list-style-type: none;
 7424:   overflow: hidden;
 7425:   padding: 0;
 7426: }
 7427: 
 7428: .LC_ListStyleSimple li,
 7429: .LC_ListStyleSimple dd,
 7430: .LC_ListStyleNormal li,
 7431: .LC_ListStyleNormal dd,
 7432: .LC_ListStyleSpecial li,
 7433: .LC_ListStyleSpecial dd {
 7434:   margin: 0;
 7435:   padding: 5px 5px 5px 10px;
 7436:   clear: both;
 7437: }
 7438: 
 7439: .LC_ListStyleClean li,
 7440: .LC_ListStyleClean dd {
 7441:   padding-top: 0;
 7442:   padding-bottom: 0;
 7443: }
 7444: 
 7445: .LC_ListStyleSimple dd,
 7446: .LC_ListStyleSimple li {
 7447:   border-bottom: solid 1px $lg_border_color;
 7448: }
 7449: 
 7450: .LC_ListStyleSpecial li,
 7451: .LC_ListStyleSpecial dd {
 7452:   list-style-type: none;
 7453:   background-color: RGB(220, 220, 220);
 7454:   margin-bottom: 4px;
 7455: }
 7456: 
 7457: table.LC_SimpleTable {
 7458:   margin:5px;
 7459:   border:solid 1px $lg_border_color;
 7460: }
 7461: 
 7462: table.LC_SimpleTable tr {
 7463:   padding: 0;
 7464:   border:solid 1px $lg_border_color;
 7465: }
 7466: 
 7467: table.LC_SimpleTable thead {
 7468:   background:rgb(220,220,220);
 7469: }
 7470: 
 7471: div.LC_columnSection {
 7472:   display: block;
 7473:   clear: both;
 7474:   overflow: hidden;
 7475:   margin: 0;
 7476: }
 7477: 
 7478: div.LC_columnSection>* {
 7479:   float: left;
 7480:   margin: 10px 20px 10px 0;
 7481:   overflow:hidden;
 7482: }
 7483: 
 7484: table em {
 7485:   font-weight: bold;
 7486:   font-style: normal;
 7487: }
 7488: 
 7489: table.LC_tableBrowseRes,
 7490: table.LC_tableOfContent {
 7491:   border:none;
 7492:   border-spacing: 1px;
 7493:   padding: 3px;
 7494:   background-color: #FFFFFF;
 7495:   font-size: 90%;
 7496: }
 7497: 
 7498: table.LC_tableOfContent {
 7499:   border-collapse: collapse;
 7500: }
 7501: 
 7502: table.LC_tableBrowseRes a,
 7503: table.LC_tableOfContent a {
 7504:   background-color: transparent;
 7505:   text-decoration: none;
 7506: }
 7507: 
 7508: table.LC_tableOfContent img {
 7509:   border: none;
 7510:   height: 1.3em;
 7511:   vertical-align: text-bottom;
 7512:   margin-right: 0.3em;
 7513: }
 7514: 
 7515: a#LC_content_toolbar_firsthomework {
 7516:   background-image:url(/res/adm/pages/open-first-problem.gif);
 7517: }
 7518: 
 7519: a#LC_content_toolbar_everything {
 7520:   background-image:url(/res/adm/pages/show-all.gif);
 7521: }
 7522: 
 7523: a#LC_content_toolbar_uncompleted {
 7524:   background-image:url(/res/adm/pages/show-incomplete-problems.gif);
 7525: }
 7526: 
 7527: #LC_content_toolbar_clearbubbles {
 7528:   background-image:url(/res/adm/pages/mark-discussionentries-read.gif);
 7529: }
 7530: 
 7531: a#LC_content_toolbar_changefolder {
 7532:   background : url(/res/adm/pages/close-all-folders.gif) top center ;
 7533: }
 7534: 
 7535: a#LC_content_toolbar_changefolder_toggled {
 7536:   background-image:url(/res/adm/pages/open-all-folders.gif);
 7537: }
 7538: 
 7539: a#LC_content_toolbar_edittoplevel {
 7540:   background-image:url(/res/adm/pages/edittoplevel.gif);
 7541: }
 7542: 
 7543: ul#LC_toolbar li a:hover {
 7544:   background-position: bottom center;
 7545: }
 7546: 
 7547: ul#LC_toolbar {
 7548:   padding: 0;
 7549:   margin: 2px;
 7550:   list-style:none;
 7551:   position:relative;
 7552:   background-color:white;
 7553:   overflow: auto;
 7554: }
 7555: 
 7556: ul#LC_toolbar li {
 7557:   border:1px solid white;
 7558:   padding: 0;
 7559:   margin: 0;
 7560:   float: left;
 7561:   display:inline;
 7562:   vertical-align:middle;
 7563:   white-space: nowrap;
 7564: }
 7565: 
 7566: 
 7567: a.LC_toolbarItem {
 7568:   display:block;
 7569:   padding: 0;
 7570:   margin: 0;
 7571:   height: 32px;
 7572:   width: 32px;
 7573:   color:white;
 7574:   border: none;
 7575:   background-repeat:no-repeat;
 7576:   background-color:transparent;
 7577: }
 7578: 
 7579: ul.LC_funclist {
 7580:     margin: 0;
 7581:     padding: 0.5em 1em 0.5em 0;
 7582: }
 7583: 
 7584: ul.LC_funclist > li:first-child {
 7585:     font-weight:bold; 
 7586:     margin-left:0.8em;
 7587: }
 7588: 
 7589: ul.LC_funclist + ul.LC_funclist {
 7590:     /* 
 7591:        left border as a seperator if we have more than
 7592:        one list 
 7593:     */
 7594:     border-left: 1px solid $sidebg;
 7595:     /* 
 7596:        this hides the left border behind the border of the 
 7597:        outer box if element is wrapped to the next 'line' 
 7598:     */
 7599:     margin-left: -1px;
 7600: }
 7601: 
 7602: ul.LC_funclist li {
 7603:   display: inline;
 7604:   white-space: nowrap;
 7605:   margin: 0 0 0 25px;
 7606:   line-height: 150%;
 7607: }
 7608: 
 7609: .LC_hidden {
 7610:   display: none;
 7611: }
 7612: 
 7613: .LCmodal-overlay {
 7614: 		position:fixed;
 7615: 		top:0;
 7616: 		right:0;
 7617: 		bottom:0;
 7618: 		left:0;
 7619: 		height:100%;
 7620: 		width:100%;
 7621: 		margin:0;
 7622: 		padding:0;
 7623: 		background:#999;
 7624: 		opacity:.75;
 7625: 		filter: alpha(opacity=75);
 7626: 		-moz-opacity: 0.75;
 7627: 		z-index:101;
 7628: }
 7629: 
 7630: * html .LCmodal-overlay {   
 7631: 		position: absolute;
 7632: 		height: expression(document.body.scrollHeight > document.body.offsetHeight ? document.body.scrollHeight : document.body.offsetHeight + 'px');
 7633: }
 7634: 
 7635: .LCmodal-window {
 7636: 		position:fixed;
 7637: 		top:50%;
 7638: 		left:50%;
 7639: 		margin:0;
 7640: 		padding:0;
 7641: 		z-index:102;
 7642: 	}
 7643: 
 7644: * html .LCmodal-window {
 7645: 		position:absolute;
 7646: }
 7647: 
 7648: .LCclose-window {
 7649: 		position:absolute;
 7650: 		width:32px;
 7651: 		height:32px;
 7652: 		right:8px;
 7653: 		top:8px;
 7654: 		background:transparent url('/res/adm/pages/process-stop.png') no-repeat scroll right top;
 7655: 		text-indent:-99999px;
 7656: 		overflow:hidden;
 7657: 		cursor:pointer;
 7658: }
 7659: 
 7660: /*
 7661:   styles used by TTH when "Default set of options to pass to tth/m
 7662:   when converting TeX" in course settings has been set
 7663: 
 7664:   option passed: -t
 7665: 
 7666: */
 7667: 
 7668: td div.comp { margin-top: -0.6ex; margin-bottom: -1ex;}
 7669: td div.comb { margin-top: -0.6ex; margin-bottom: -.6ex;}
 7670: td div.hrcomp { line-height: 0.9; margin-top: -0.8ex; margin-bottom: -1ex;}
 7671: td div.norm {line-height:normal;}
 7672: 
 7673: /*
 7674:   option passed -y3
 7675: */
 7676: 
 7677: span.roman {font-family: serif; font-style: normal; font-weight: normal;}
 7678: span.overacc2 {position: relative;  left: .8em; top: -1.2ex;}
 7679: span.overacc1 {position: relative;  left: .6em; top: -1.2ex;}
 7680: 
 7681: #LC_minitab_header {
 7682:   float:left;
 7683:   width:100%;
 7684:   background:#DAE0D2 url("/res/adm/pages/minitabmenu_bg.gif") repeat-x bottom;
 7685:   font-size:93%;
 7686:   line-height:normal;
 7687:   margin: 0.5em 0 0.5em 0;
 7688: }
 7689: #LC_minitab_header ul {
 7690:   margin:0;
 7691:   padding:10px 10px 0;
 7692:   list-style:none;
 7693: }
 7694: #LC_minitab_header li {
 7695:   float:left;
 7696:   background:url("/res/adm/pages/minitabmenu_left.gif") no-repeat left top;
 7697:   margin:0;
 7698:   padding:0 0 0 9px;
 7699: }
 7700: #LC_minitab_header a {
 7701:   display:block;
 7702:   background:url("/res/adm/pages/minitabmenu_right.gif") no-repeat right top;
 7703:   padding:5px 15px 4px 6px;
 7704: }
 7705: #LC_minitab_header #LC_current_minitab {
 7706:   background-image:url("/res/adm/pages/minitabmenu_left_on.gif");
 7707: }
 7708: #LC_minitab_header #LC_current_minitab a {
 7709:   background-image:url("/res/adm/pages/minitabmenu_right_on.gif");
 7710:   padding-bottom:5px;
 7711: }
 7712: 
 7713: 
 7714: END
 7715: }
 7716: 
 7717: =pod
 7718: 
 7719: =item * &headtag()
 7720: 
 7721: Returns a uniform footer for LON-CAPA web pages.
 7722: 
 7723: Inputs: $title - optional title for the head
 7724:         $head_extra - optional extra HTML to put inside the <head>
 7725:         $args - optional arguments
 7726:             force_register - if is true call registerurl so the remote is 
 7727:                              informed
 7728:             redirect       -> array ref of
 7729:                                    1- seconds before redirect occurs
 7730:                                    2- url to redirect to
 7731:                                    3- whether the side effect should occur
 7732:                            (side effect of setting 
 7733:                                $env{'internal.head.redirect'} to the url 
 7734:                                redirected too)
 7735:             domain         -> force to color decorate a page for a specific
 7736:                                domain
 7737:             function       -> force usage of a specific rolish color scheme
 7738:             bgcolor        -> override the default page bgcolor
 7739:             no_auto_mt_title
 7740:                            -> prevent &mt()ing the title arg
 7741: 
 7742: =cut
 7743: 
 7744: sub headtag {
 7745:     my ($title,$head_extra,$args) = @_;
 7746:     
 7747:     my $function = $args->{'function'} || &get_users_function();
 7748:     my $domain   = $args->{'domain'}   || &determinedomain();
 7749:     my $bgcolor  = $args->{'bgcolor'}  || &designparm($function.'.pgbg',$domain);
 7750:     my $httphost = $args->{'use_absolute'};
 7751:     my $url = join(':',$env{'user.name'},$env{'user.domain'},
 7752: 		   $Apache::lonnet::perlvar{'lonVersion'},
 7753: 		   #time(),
 7754: 		   $env{'environment.color.timestamp'},
 7755: 		   $function,$domain,$bgcolor);
 7756: 
 7757:     $url = '/adm/css/'.&escape($url).'.css';
 7758: 
 7759:     my $result =
 7760: 	'<head>'.
 7761: 	&font_settings($args);
 7762: 
 7763:     my $inhibitprint;
 7764:     if ($args->{'print_suppress'}) {
 7765:         $inhibitprint = &print_suppression();
 7766:     }
 7767: 
 7768:     if (!$args->{'frameset'}) {
 7769: 	$result .= &Apache::lonhtmlcommon::htmlareaheaders();
 7770:     }
 7771:     if ($args->{'force_register'}) {
 7772:         $result .= &Apache::lonmenu::registerurl(1);
 7773:     }
 7774:     if (!$args->{'no_nav_bar'} 
 7775: 	&& !$args->{'only_body'}
 7776: 	&& !$args->{'frameset'}) {
 7777: 	$result .= &help_menu_js($httphost);
 7778:         $result.=&modal_window();
 7779:         $result.=&togglebox_script();
 7780:         $result.=&wishlist_window();
 7781:         $result.=&LCprogressbarUpdate_script();
 7782:     } else {
 7783:         if ($args->{'add_modal'}) {
 7784:            $result.=&modal_window();
 7785:         }
 7786:         if ($args->{'add_wishlist'}) {
 7787:            $result.=&wishlist_window();
 7788:         }
 7789:         if ($args->{'add_togglebox'}) {
 7790:            $result.=&togglebox_script();
 7791:         }
 7792:         if ($args->{'add_progressbar'}) {
 7793:            $result.=&LCprogressbarUpdate_script();
 7794:         }
 7795:     }
 7796:     if (ref($args->{'redirect'})) {
 7797: 	my ($time,$url,$inhibit_continue) = @{$args->{'redirect'}};
 7798: 	$url = &Apache::lonenc::check_encrypt($url);
 7799: 	if (!$inhibit_continue) {
 7800: 	    $env{'internal.head.redirect'} = $url;
 7801: 	}
 7802: 	$result.=<<ADDMETA
 7803: <meta http-equiv="pragma" content="no-cache" />
 7804: <meta http-equiv="Refresh" content="$time; url=$url" />
 7805: ADDMETA
 7806:     } else {
 7807:         unless (($args->{'frameset'}) || ($args->{'js_ready'}) || ($args->{'only_body'}) || ($args->{'no_nav_bar'})) {
 7808:             my $requrl = $env{'request.uri'};
 7809:             if ($requrl eq '') {
 7810:                 $requrl = $ENV{'REQUEST_URI'};
 7811:                 $requrl =~ s/\?.+$//;
 7812:             }
 7813:             unless (($requrl =~ m{^/adm/(?:switchserver|login|authenticate|logout|groupsort|cleanup|helper|slotrequest|grades)(\?|$)}) ||
 7814:                     (($requrl =~ m{^/res/}) && (($env{'form.submitted'} eq 'scantron') ||
 7815:                      ($env{'form.grade_symb'}) || ($Apache::lonhomework::scantronmode)))) {
 7816:                 my $dom_in_use = $Apache::lonnet::perlvar{'lonDefDomain'};
 7817:                 unless (&Apache::lonnet::allowed('mau',$dom_in_use)) {
 7818:                     my %domdefs = &Apache::lonnet::get_domain_defaults($dom_in_use);
 7819:                     if (ref($domdefs{'offloadnow'}) eq 'HASH') {
 7820:                         my $lonhost = $Apache::lonnet::perlvar{'lonHostID'};
 7821:                         if ($domdefs{'offloadnow'}{$lonhost}) {
 7822:                             my $newserver = &Apache::lonnet::spareserver(30000,undef,1,$dom_in_use);
 7823:                             if (($newserver) && ($newserver ne $lonhost)) {
 7824:                                 my $numsec = 5;
 7825:                                 my $timeout = $numsec * 1000;
 7826:                                 my ($newurl,$locknum,%locks,$msg);
 7827:                                 if ($env{'request.role.adv'}) {
 7828:                                     ($locknum,%locks) = &Apache::lonnet::get_locks();
 7829:                                 }
 7830:                                 my $disable_submit = 0;
 7831:                                 if ($requrl =~ /$LONCAPA::assess_re/) {
 7832:                                     $disable_submit = 1;
 7833:                                 }
 7834:                                 if ($locknum) {
 7835:                                     my @lockinfo = sort(values(%locks));
 7836:                                     $msg = &mt('Once the following tasks are complete: ')."\\n".
 7837:                                            join(", ",sort(values(%locks)))."\\n".
 7838:                                            &mt('your session will be transferred to a different server, after you click "Roles".');
 7839:                                 } else {
 7840:                                     if (($requrl =~ m{^/res/}) && ($env{'form.submitted'} =~ /^part_/)) {
 7841:                                         $msg = &mt('Your LON-CAPA submission has been recorded')."\\n";
 7842:                                     }
 7843:                                     $msg .= &mt('Your current LON-CAPA session will be transferred to a different server in [quant,_1,second].',$numsec);
 7844:                                     $newurl = '/adm/switchserver?otherserver='.$newserver;
 7845:                                     if (($env{'request.role'}) && ($env{'request.role'} ne 'cm')) {
 7846:                                         $newurl .= '&role='.$env{'request.role'};
 7847:                                     }
 7848:                                     if ($env{'request.symb'}) {
 7849:                                         $newurl .= '&symb='.$env{'request.symb'};
 7850:                                     } else {
 7851:                                         $newurl .= '&origurl='.$requrl;
 7852:                                     }
 7853:                                 }
 7854:                                 &js_escape(\$msg);
 7855:                                 $result.=<<OFFLOAD
 7856: <meta http-equiv="pragma" content="no-cache" />
 7857: <script type="text/javascript">
 7858: // <![CDATA[
 7859: function LC_Offload_Now() {
 7860:     var dest = "$newurl";
 7861:     if (dest != '') {
 7862:         window.location.href="$newurl";
 7863:     }
 7864: }
 7865: \$(document).ready(function () {
 7866:     window.alert('$msg');
 7867:     if ($disable_submit) {
 7868:         \$(".LC_hwk_submit").prop("disabled", true);
 7869:         \$( ".LC_textline" ).prop( "readonly", "readonly");
 7870:     }
 7871:     setTimeout('LC_Offload_Now()', $timeout);
 7872: });
 7873: // ]]>
 7874: </script>
 7875: OFFLOAD
 7876:                             }
 7877:                         }
 7878:                     }
 7879:                 }
 7880:             }
 7881:         }
 7882:     }
 7883:     if (!defined($title)) {
 7884: 	$title = 'The LearningOnline Network with CAPA';
 7885:     }
 7886:     if (!$args->{'no_auto_mt_title'}) { $title = &mt($title); }
 7887:     $result .= '<title> LON-CAPA '.$title.'</title>'
 7888: 	.'<link rel="stylesheet" type="text/css" href="'.$url.'"';
 7889:     if (!$args->{'frameset'}) {
 7890:         $result .= ' /';
 7891:     }
 7892:     $result .= '>'
 7893:         .$inhibitprint
 7894: 	.$head_extra;
 7895:     my $clientmobile;
 7896:     if (($env{'user.name'} eq '') && ($env{'user.domain'} eq '')) {
 7897:         (undef,undef,undef,undef,undef,undef,$clientmobile) = &decode_user_agent();
 7898:     } else {
 7899:         $clientmobile = $env{'browser.mobile'};
 7900:     }
 7901:     if ($clientmobile) {
 7902:         $result .= '
 7903: <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=0, minimum-scale=1.0, maximum-scale=1.0">
 7904: <meta name="apple-mobile-web-app-capable" content="yes" />';
 7905:     }
 7906:     $result .= '<meta name="google" content="notranslate" />'."\n";
 7907:     return $result.'</head>';
 7908: }
 7909: 
 7910: =pod
 7911: 
 7912: =item * &font_settings()
 7913: 
 7914: Returns neccessary <meta> to set the proper encoding
 7915: 
 7916: Inputs: optional reference to HASH -- $args passed to &headtag()
 7917: 
 7918: =cut
 7919: 
 7920: sub font_settings {
 7921:     my ($args) = @_;
 7922:     my $headerstring='';
 7923:     if ((!$env{'browser.mathml'} && $env{'browser.unicode'}) ||
 7924:         ((ref($args) eq 'HASH') && ($args->{'browser.unicode'}))) {
 7925: 	$headerstring.=
 7926: 	    '<meta http-equiv="Content-Type" content="text/html; charset=utf-8"';
 7927:         if (!$args->{'frameset'}) {
 7928:             $headerstring.= ' /';
 7929:         }
 7930:         $headerstring .= '>'."\n";
 7931:     }
 7932:     return $headerstring;
 7933: }
 7934: 
 7935: =pod
 7936: 
 7937: =item * &print_suppression()
 7938: 
 7939: In course context returns css which causes the body to be blank when media="print",
 7940: if printout generation is unavailable for the current resource.
 7941: 
 7942: This could be because:
 7943: 
 7944: (a) printstartdate is in the future
 7945: 
 7946: (b) printenddate is in the past
 7947: 
 7948: (c) there is an active exam block with "printout"
 7949: functionality blocked
 7950: 
 7951: Users with pav, pfo or evb privileges are exempt.
 7952: 
 7953: Inputs: none
 7954: 
 7955: =cut
 7956: 
 7957: 
 7958: sub print_suppression {
 7959:     my $noprint;
 7960:     if ($env{'request.course.id'}) {
 7961:         my $scope = $env{'request.course.id'};
 7962:         if ((&Apache::lonnet::allowed('pav',$scope)) ||
 7963:             (&Apache::lonnet::allowed('pfo',$scope))) {
 7964:             return;
 7965:         }
 7966:         if ($env{'request.course.sec'} ne '') {
 7967:             $scope .= "/$env{'request.course.sec'}";
 7968:             if ((&Apache::lonnet::allowed('pav',$scope)) ||
 7969:                 (&Apache::lonnet::allowed('pfo',$scope))) {
 7970:                 return;
 7971:             }
 7972:         }
 7973:         my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 7974:         my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 7975:         my $blocked = &blocking_status('printout',$cnum,$cdom,undef,1);
 7976:         if ($blocked) {
 7977:             my $checkrole = "cm./$cdom/$cnum";
 7978:             if ($env{'request.course.sec'} ne '') {
 7979:                 $checkrole .= "/$env{'request.course.sec'}";
 7980:             }
 7981:             unless ((&Apache::lonnet::allowed('evb',undef,undef,$checkrole)) &&
 7982:                     ($env{'request.role'} !~ m{^st\./$cdom/$cnum})) {
 7983:                 $noprint = 1;
 7984:             }
 7985:         }
 7986:         unless ($noprint) {
 7987:             my $symb = &Apache::lonnet::symbread();
 7988:             if ($symb ne '') {
 7989:                 my $navmap = Apache::lonnavmaps::navmap->new();
 7990:                 if (ref($navmap)) {
 7991:                     my $res = $navmap->getBySymb($symb);
 7992:                     if (ref($res)) {
 7993:                         if (!$res->resprintable()) {
 7994:                             $noprint = 1;
 7995:                         }
 7996:                     }
 7997:                 }
 7998:             }
 7999:         }
 8000:         if ($noprint) {
 8001:             return <<"ENDSTYLE";
 8002: <style type="text/css" media="print">
 8003:     body { display:none }
 8004: </style>
 8005: ENDSTYLE
 8006:         }
 8007:     }
 8008:     return;
 8009: }
 8010: 
 8011: =pod
 8012: 
 8013: =item * &xml_begin()
 8014: 
 8015: Returns the needed doctype and <html>
 8016: 
 8017: Inputs: none
 8018: 
 8019: =cut
 8020: 
 8021: sub xml_begin {
 8022:     my ($is_frameset) = @_;
 8023:     my $output='';
 8024: 
 8025:     if ($env{'browser.mathml'}) {
 8026: 	$output='<?xml version="1.0"?>'
 8027:             #.'<?xml-stylesheet type="text/css" href="/adm/MathML/mathml.css"?>'."\n"
 8028: #            .'<!DOCTYPE html SYSTEM "/adm/MathML/mathml.dtd" '
 8029:             
 8030: #	    .'<!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">] >'
 8031: 	    .'<!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">'
 8032:             .'<html xmlns:math="http://www.w3.org/1998/Math/MathML" ' 
 8033: 	    .'xmlns="http://www.w3.org/1999/xhtml">';
 8034:     } elsif ($is_frameset) {
 8035:         $output='<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Frameset//EN" "http://www.w3.org/TR/html4/frameset.dtd">'."\n".
 8036:                 '<html>'."\n";
 8037:     } else {
 8038: 	$output='<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">'."\n".
 8039:                 '<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">'."\n";
 8040:     }
 8041:     return $output;
 8042: }
 8043: 
 8044: =pod
 8045: 
 8046: =item * &start_page()
 8047: 
 8048: Returns a complete <html> .. <body> section for LON-CAPA web pages.
 8049: 
 8050: Inputs:
 8051: 
 8052: =over 4
 8053: 
 8054: $title - optional title for the page
 8055: 
 8056: $head_extra - optional extra HTML to incude inside the <head>
 8057: 
 8058: $args - additional optional args supported are:
 8059: 
 8060: =over 8
 8061: 
 8062:              only_body      -> is true will set &bodytag() onlybodytag
 8063:                                     arg on
 8064:              no_nav_bar     -> is true will set &bodytag() no_nav_bar arg on
 8065:              add_entries    -> additional attributes to add to the  <body>
 8066:              domain         -> force to color decorate a page for a 
 8067:                                     specific domain
 8068:              function       -> force usage of a specific rolish color
 8069:                                     scheme
 8070:              redirect       -> see &headtag()
 8071:              bgcolor        -> override the default page bg color
 8072:              js_ready       -> return a string ready for being used in 
 8073:                                     a javascript writeln
 8074:              html_encode    -> return a string ready for being used in 
 8075:                                     a html attribute
 8076:              force_register -> if is true will turn on the &bodytag()
 8077:                                     $forcereg arg
 8078:              frameset       -> if true will start with a <frameset>
 8079:                                     rather than <body>
 8080:              skip_phases    -> hash ref of 
 8081:                                     head -> skip the <html><head> generation
 8082:                                     body -> skip all <body> generation
 8083:              no_inline_link -> if true and in remote mode, don't show the
 8084:                                     'Switch To Inline Menu' link
 8085:              no_auto_mt_title -> prevent &mt()ing the title arg
 8086:              bread_crumbs ->             Array containing breadcrumbs
 8087:              bread_crumbs_component ->  if exists show it as headline else show only the breadcrumbs
 8088:              bread_crumbs_nomenu -> if true will pass false as the value of $menulink
 8089:                                     to lonhtmlcommon::breadcrumbs
 8090:              group          -> includes the current group, if page is for a
 8091:                                specific group
 8092: 
 8093: =back
 8094: 
 8095: =back
 8096: 
 8097: =cut
 8098: 
 8099: sub start_page {
 8100:     my ($title,$head_extra,$args) = @_;
 8101:     #&Apache::lonnet::logthis("start_page ".join(':',caller(0)));
 8102: 
 8103:     $env{'internal.start_page'}++;
 8104:     my ($result,@advtools);
 8105: 
 8106:     if (! exists($args->{'skip_phases'}{'head'}) ) {
 8107:         $result .= &xml_begin($args->{'frameset'}) . &headtag($title, $head_extra, $args);
 8108:     }
 8109:     
 8110:     if (! exists($args->{'skip_phases'}{'body'}) ) {
 8111: 	if ($args->{'frameset'}) {
 8112: 	    my $attr_string = &make_attr_string($args->{'force_register'},
 8113: 						$args->{'add_entries'});
 8114: 	    $result .= "\n<frameset $attr_string>\n";
 8115:         } else {
 8116:             $result .=
 8117:                 &bodytag($title, 
 8118:                          $args->{'function'},       $args->{'add_entries'},
 8119:                          $args->{'only_body'},      $args->{'domain'},
 8120:                          $args->{'force_register'}, $args->{'no_nav_bar'},
 8121:                          $args->{'bgcolor'},        $args->{'no_inline_link'},
 8122:                          $args,                     \@advtools);
 8123:         }
 8124:     }
 8125: 
 8126:     if ($args->{'js_ready'}) {
 8127: 		$result = &js_ready($result);
 8128:     }
 8129:     if ($args->{'html_encode'}) {
 8130: 		$result = &html_encode($result);
 8131:     }
 8132: 
 8133:     # Preparation for new and consistent functionlist at top of screen
 8134:     # if ($args->{'functionlist'}) {
 8135:     #            $result .= &build_functionlist();
 8136:     #}
 8137: 
 8138:     # Don't add anything more if only_body wanted or in const space
 8139:     return $result if    $args->{'only_body'} 
 8140:                       || $env{'request.state'} eq 'construct';
 8141: 
 8142:     #Breadcrumbs
 8143:     if (exists($args->{'bread_crumbs'}) or exists($args->{'bread_crumbs_component'})) {
 8144: 		&Apache::lonhtmlcommon::clear_breadcrumbs();
 8145: 		#if any br links exists, add them to the breadcrumbs
 8146: 		if (exists($args->{'bread_crumbs'}) and ref($args->{'bread_crumbs'}) eq 'ARRAY') {         
 8147: 			foreach my $crumb (@{$args->{'bread_crumbs'}}){
 8148: 				&Apache::lonhtmlcommon::add_breadcrumb($crumb);
 8149: 			}
 8150: 		}
 8151:                 # if @advtools array contains items add then to the breadcrumbs
 8152:                 if (@advtools > 0) {
 8153:                     &Apache::lonmenu::advtools_crumbs(@advtools);
 8154:                 }
 8155:                 my $menulink;
 8156:                 # if arg: bread_crumbs_nomenu is true pass 0 as $menulink item.
 8157:                 if (exists($args->{'bread_crumbs_nomenu'})) {
 8158:                     $menulink = 0;
 8159:                 } else {
 8160:                     undef($menulink);
 8161:                 }
 8162: 		#if bread_crumbs_component exists show it as headline else show only the breadcrumbs
 8163: 		if(exists($args->{'bread_crumbs_component'})){
 8164: 			$result .= &Apache::lonhtmlcommon::breadcrumbs($args->{'bread_crumbs_component'},'',$menulink);
 8165: 		}else{
 8166: 			$result .= &Apache::lonhtmlcommon::breadcrumbs('','',$menulink);
 8167: 		}
 8168:     } elsif (($env{'environment.remote'} eq 'on') &&
 8169:              ($env{'form.inhibitmenu'} ne 'yes') &&
 8170:              ($env{'request.noversionuri'} =~ m{^/res/}) &&
 8171:              ($env{'request.noversionuri'} !~ m{^/res/adm/pages/})) {
 8172:         $result .= '<div style="padding:0;margin:0;clear:both"><hr /></div>';
 8173:     }
 8174:     return $result;
 8175: }
 8176: 
 8177: sub end_page {
 8178:     my ($args) = @_;
 8179:     $env{'internal.end_page'}++;
 8180:     my $result;
 8181:     if ($args->{'discussion'}) {
 8182: 	my ($target,$parser);
 8183: 	if (ref($args->{'discussion'})) {
 8184: 	    ($target,$parser) =($args->{'discussion'}{'target'},
 8185: 				$args->{'discussion'}{'parser'});
 8186: 	}
 8187: 	$result .= &Apache::lonxml::xmlend($target,$parser);
 8188:     }
 8189:     if ($args->{'frameset'}) {
 8190: 	$result .= '</frameset>';
 8191:     } else {
 8192: 	$result .= &endbodytag($args);
 8193:     }
 8194:     unless ($args->{'notbody'}) {
 8195:         $result .= "\n</html>";
 8196:     }
 8197: 
 8198:     if ($args->{'js_ready'}) {
 8199: 	$result = &js_ready($result);
 8200:     }
 8201: 
 8202:     if ($args->{'html_encode'}) {
 8203: 	$result = &html_encode($result);
 8204:     }
 8205: 
 8206:     return $result;
 8207: }
 8208: 
 8209: sub wishlist_window {
 8210:     return(<<'ENDWISHLIST');
 8211: <script type="text/javascript">
 8212: // <![CDATA[
 8213: // <!-- BEGIN LON-CAPA Internal
 8214: function set_wishlistlink(title, path) {
 8215:     if (!title) {
 8216:         title = document.title;
 8217:         title = title.replace(/^LON-CAPA /,'');
 8218:     }
 8219:     title = encodeURIComponent(title);
 8220:     title = title.replace("'","\\\'");
 8221:     if (!path) {
 8222:         path = location.pathname;
 8223:     }
 8224:     path = encodeURIComponent(path);
 8225:     path = path.replace("'","\\\'");
 8226:     Win = window.open('/adm/wishlist?mode=newLink&setTitle='+title+'&setPath='+path,
 8227:                       'wishlistNewLink','width=560,height=350,scrollbars=0');
 8228: }
 8229: // END LON-CAPA Internal -->
 8230: // ]]>
 8231: </script>
 8232: ENDWISHLIST
 8233: }
 8234: 
 8235: sub modal_window {
 8236:     return(<<'ENDMODAL');
 8237: <script type="text/javascript">
 8238: // <![CDATA[
 8239: // <!-- BEGIN LON-CAPA Internal
 8240: var modalWindow = {
 8241: 	parent:"body",
 8242: 	windowId:null,
 8243: 	content:null,
 8244: 	width:null,
 8245: 	height:null,
 8246: 	close:function()
 8247: 	{
 8248: 	        $(".LCmodal-window").remove();
 8249: 	        $(".LCmodal-overlay").remove();
 8250: 	},
 8251: 	open:function()
 8252: 	{
 8253: 		var modal = "";
 8254: 		modal += "<div class=\"LCmodal-overlay\"></div>";
 8255: 		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;\">";
 8256: 		modal += this.content;
 8257: 		modal += "</div>";	
 8258: 
 8259: 		$(this.parent).append(modal);
 8260: 
 8261: 		$(".LCmodal-window").append("<a class=\"LCclose-window\"></a>");
 8262: 		$(".LCclose-window").click(function(){modalWindow.close();});
 8263: 		$(".LCmodal-overlay").click(function(){modalWindow.close();});
 8264: 	}
 8265: };
 8266: 	var openMyModal = function(source,width,height,scrolling,transparency,style)
 8267: 	{
 8268:                 source = source.replace(/'/g,"&#39;");
 8269: 		modalWindow.windowId = "myModal";
 8270: 		modalWindow.width = width;
 8271: 		modalWindow.height = height;
 8272: 		modalWindow.content = "<iframe width='"+width+"' height='"+height+"' frameborder='0' scrolling='"+scrolling+"' allowtransparency='"+transparency+"' src='" + source + "' style='"+style+"'></iframe>";
 8273: 		modalWindow.open();
 8274: 	};
 8275: // END LON-CAPA Internal -->
 8276: // ]]>
 8277: </script>
 8278: ENDMODAL
 8279: }
 8280: 
 8281: sub modal_link {
 8282:     my ($link,$linktext,$width,$height,$target,$scrolling,$title,$transparency,$style)=@_;
 8283:     unless ($width) { $width=480; }
 8284:     unless ($height) { $height=400; }
 8285:     unless ($scrolling) { $scrolling='yes'; }
 8286:     unless ($transparency) { $transparency='true'; }
 8287: 
 8288:     my $target_attr;
 8289:     if (defined($target)) {
 8290:         $target_attr = 'target="'.$target.'"';
 8291:     }
 8292:     return <<"ENDLINK";
 8293: <a href="$link" $target_attr title="$title" onclick="javascript:openMyModal('$link',$width,$height,'$scrolling','$transparency','$style'); return false;">
 8294:            $linktext</a>
 8295: ENDLINK
 8296: }
 8297: 
 8298: sub modal_adhoc_script {
 8299:     my ($funcname,$width,$height,$content)=@_;
 8300:     return (<<ENDADHOC);
 8301: <script type="text/javascript">
 8302: // <![CDATA[
 8303:         var $funcname = function()
 8304:         {
 8305:                 modalWindow.windowId = "myModal";
 8306:                 modalWindow.width = $width;
 8307:                 modalWindow.height = $height;
 8308:                 modalWindow.content = '$content';
 8309:                 modalWindow.open();
 8310:         };  
 8311: // ]]>
 8312: </script>
 8313: ENDADHOC
 8314: }
 8315: 
 8316: sub modal_adhoc_inner {
 8317:     my ($funcname,$width,$height,$content)=@_;
 8318:     my $innerwidth=$width-20;
 8319:     $content=&js_ready(
 8320:                &start_page('Dialog',undef,{'only_body'=>1,'bgcolor'=>'#FFFFFF'}).
 8321:                  &start_scrollbox($width.'px',$innerwidth.'px',$height.'px','myModal','#FFFFFF',undef,1).
 8322:                  $content.
 8323:                  &end_scrollbox().
 8324:                  &end_page()
 8325:              );
 8326:     return &modal_adhoc_script($funcname,$width,$height,$content);
 8327: }
 8328: 
 8329: sub modal_adhoc_window {
 8330:     my ($funcname,$width,$height,$content,$linktext)=@_;
 8331:     return &modal_adhoc_inner($funcname,$width,$height,$content).
 8332:            "<a href=\"javascript:$funcname();void(0);\">".$linktext."</a>";
 8333: }
 8334: 
 8335: sub modal_adhoc_launch {
 8336:     my ($funcname,$width,$height,$content)=@_;
 8337:     return &modal_adhoc_inner($funcname,$width,$height,$content).(<<ENDLAUNCH);
 8338: <script type="text/javascript">
 8339: // <![CDATA[
 8340: $funcname();
 8341: // ]]>
 8342: </script>
 8343: ENDLAUNCH
 8344: }
 8345: 
 8346: sub modal_adhoc_close {
 8347:     return (<<ENDCLOSE);
 8348: <script type="text/javascript">
 8349: // <![CDATA[
 8350: modalWindow.close();
 8351: // ]]>
 8352: </script>
 8353: ENDCLOSE
 8354: }
 8355: 
 8356: sub togglebox_script {
 8357:    return(<<ENDTOGGLE);
 8358: <script type="text/javascript"> 
 8359: // <![CDATA[
 8360: function LCtoggleDisplay(id,hidetext,showtext) {
 8361:    link = document.getElementById(id + "link").childNodes[0];
 8362:    with (document.getElementById(id).style) {
 8363:       if (display == "none" ) {
 8364:           display = "inline";
 8365:           link.nodeValue = hidetext;
 8366:         } else {
 8367:           display = "none";
 8368:           link.nodeValue = showtext;
 8369:        }
 8370:    }
 8371: }
 8372: // ]]>
 8373: </script>
 8374: ENDTOGGLE
 8375: }
 8376: 
 8377: sub start_togglebox {
 8378:     my ($id,$heading,$headerbg,$hidetext,$showtext)=@_;
 8379:     unless ($heading) { $heading=''; } else { $heading.=' '; }
 8380:     unless ($showtext) { $showtext=&mt('show'); }
 8381:     unless ($hidetext) { $hidetext=&mt('hide'); }
 8382:     unless ($headerbg) { $headerbg='#FFFFFF'; }
 8383:     return &start_data_table().
 8384:            &start_data_table_header_row().
 8385:            '<td bgcolor="'.$headerbg.'">'.$heading.
 8386:            '[<a id="'.$id.'link" href="javascript:LCtoggleDisplay(\''.$id.'\',\''.$hidetext.'\',\''.
 8387:            $showtext.'\')">'.$showtext.'</a>]</td>'.
 8388:            &end_data_table_header_row().
 8389:            '<tr id="'.$id.'" style="display:none""><td>';
 8390: }
 8391: 
 8392: sub end_togglebox {
 8393:     return '</td></tr>'.&end_data_table();
 8394: }
 8395: 
 8396: sub LCprogressbar_script {
 8397:    my ($id,$number_to_do)=@_;
 8398:    if ($number_to_do) {
 8399:        return(<<ENDPROGRESS);
 8400: <script type="text/javascript">
 8401: // <![CDATA[
 8402: \$('#progressbar$id').progressbar({
 8403:   value: 0,
 8404:   change: function(event, ui) {
 8405:     var newVal = \$(this).progressbar('option', 'value');
 8406:     \$('.pblabel', this).text(LCprogressTxt);
 8407:   }
 8408: });
 8409: // ]]>
 8410: </script>
 8411: ENDPROGRESS
 8412:    } else {
 8413:        return(<<ENDPROGRESS);
 8414: <script type="text/javascript">
 8415: // <![CDATA[
 8416: \$('#progressbar$id').progressbar({
 8417:   value: false,
 8418:   create: function(event, ui) {
 8419:     \$('.ui-widget-header', this).css({'background':'#F0F0F0'});
 8420:     \$('.ui-progressbar-overlay', this).css({'margin':'0'});
 8421:   }
 8422: });
 8423: // ]]>
 8424: </script>
 8425: ENDPROGRESS
 8426:    }
 8427: }
 8428: 
 8429: sub LCprogressbarUpdate_script {
 8430:    return(<<ENDPROGRESSUPDATE);
 8431: <style type="text/css">
 8432: .ui-progressbar { position:relative; }
 8433: .progress-label {position: absolute; width: 100%; text-align: center; top: 1px; font-weight: bold; text-shadow: 1px 1px 0 #fff;margin: 0; line-height: 200%; }
 8434: .pblabel { position: absolute; width: 100%; text-align: center; line-height: 1.9em; }
 8435: </style>
 8436: <script type="text/javascript">
 8437: // <![CDATA[
 8438: var LCprogressTxt='---';
 8439: 
 8440: function LCupdateProgress(percent,progresstext,id,maxnum) {
 8441:    LCprogressTxt=progresstext;
 8442:    if ((maxnum == '') || (maxnum == undefined) || (maxnum == null)) {
 8443:        \$('#progressbar'+id).find('.progress-label').text(LCprogressTxt);
 8444:    } else if (percent === \$('#progressbar'+id).progressbar( "value" )) {
 8445:        \$('#progressbar'+id).find('.pblabel').text(LCprogressTxt);
 8446:    } else {
 8447:        \$('#progressbar'+id).progressbar('value',percent);
 8448:    }
 8449: }
 8450: // ]]>
 8451: </script>
 8452: ENDPROGRESSUPDATE
 8453: }
 8454: 
 8455: my $LClastpercent;
 8456: my $LCidcnt;
 8457: my $LCcurrentid;
 8458: 
 8459: sub LCprogressbar {
 8460:     my ($r,$number_to_do,$preamble)=@_;
 8461:     $LClastpercent=0;
 8462:     $LCidcnt++;
 8463:     $LCcurrentid=$$.'_'.$LCidcnt;
 8464:     my ($starting,$content);
 8465:     if ($number_to_do) {
 8466:         $starting=&mt('Starting');
 8467:         $content=(<<ENDPROGBAR);
 8468: $preamble
 8469:   <div id="progressbar$LCcurrentid">
 8470:     <span class="pblabel">$starting</span>
 8471:   </div>
 8472: ENDPROGBAR
 8473:     } else {
 8474:         $starting=&mt('Loading...');
 8475:         $LClastpercent='false';
 8476:         $content=(<<ENDPROGBAR);
 8477: $preamble
 8478:   <div id="progressbar$LCcurrentid">
 8479:       <div class="progress-label">$starting</div>
 8480:   </div>
 8481: ENDPROGBAR
 8482:     }
 8483:     &r_print($r,$content.&LCprogressbar_script($LCcurrentid,$number_to_do));
 8484: }
 8485: 
 8486: sub LCprogressbarUpdate {
 8487:     my ($r,$val,$text,$number_to_do)=@_;
 8488:     if ($number_to_do) {
 8489:         unless ($val) { 
 8490:             if ($LClastpercent) {
 8491:                 $val=$LClastpercent;
 8492:             } else {
 8493:                 $val=0;
 8494:             }
 8495:         }
 8496:         if ($val<0) { $val=0; }
 8497:         if ($val>100) { $val=0; }
 8498:         $LClastpercent=$val;
 8499:         unless ($text) { $text=$val.'%'; }
 8500:     } else {
 8501:         $val = 'false';
 8502:     }
 8503:     $text=&js_ready($text);
 8504:     &r_print($r,<<ENDUPDATE);
 8505: <script type="text/javascript">
 8506: // <![CDATA[
 8507: LCupdateProgress($val,'$text','$LCcurrentid','$number_to_do');
 8508: // ]]>
 8509: </script>
 8510: ENDUPDATE
 8511: }
 8512: 
 8513: sub LCprogressbarClose {
 8514:     my ($r)=@_;
 8515:     $LClastpercent=0;
 8516:     &r_print($r,<<ENDCLOSE);
 8517: <script type="text/javascript">
 8518: // <![CDATA[
 8519: \$("#progressbar$LCcurrentid").hide('slow'); 
 8520: // ]]>
 8521: </script>
 8522: ENDCLOSE
 8523: }
 8524: 
 8525: sub r_print {
 8526:     my ($r,$to_print)=@_;
 8527:     if ($r) {
 8528:       $r->print($to_print);
 8529:       $r->rflush();
 8530:     } else {
 8531:       print($to_print);
 8532:     }
 8533: }
 8534: 
 8535: sub html_encode {
 8536:     my ($result) = @_;
 8537: 
 8538:     $result = &HTML::Entities::encode($result,'<>&"');
 8539:     
 8540:     return $result;
 8541: }
 8542: 
 8543: sub js_ready {
 8544:     my ($result) = @_;
 8545: 
 8546:     $result =~ s/[\n\r]/ /xmsg;
 8547:     $result =~ s/\\/\\\\/xmsg;
 8548:     $result =~ s/'/\\'/xmsg;
 8549:     $result =~ s{</}{<\\/}xmsg;
 8550:     
 8551:     return $result;
 8552: }
 8553: 
 8554: sub validate_page {
 8555:     if (  exists($env{'internal.start_page'})
 8556: 	  &&     $env{'internal.start_page'} > 1) {
 8557: 	&Apache::lonnet::logthis('start_page called multiple times '.
 8558: 				 $env{'internal.start_page'}.' '.
 8559: 				 $ENV{'request.filename'});
 8560:     }
 8561:     if (  exists($env{'internal.end_page'})
 8562: 	  &&     $env{'internal.end_page'} > 1) {
 8563: 	&Apache::lonnet::logthis('end_page called multiple times '.
 8564: 				 $env{'internal.end_page'}.' '.
 8565: 				 $env{'request.filename'});
 8566:     }
 8567:     if (     exists($env{'internal.start_page'})
 8568: 	&& ! exists($env{'internal.end_page'})) {
 8569: 	&Apache::lonnet::logthis('start_page called without end_page '.
 8570: 				 $env{'request.filename'});
 8571:     }
 8572:     if (   ! exists($env{'internal.start_page'})
 8573: 	&&   exists($env{'internal.end_page'})) {
 8574: 	&Apache::lonnet::logthis('end_page called without start_page'.
 8575: 				 $env{'request.filename'});
 8576:     }
 8577: }
 8578: 
 8579: 
 8580: sub start_scrollbox {
 8581:     my ($outerwidth,$width,$height,$id,$bgcolor,$cursor,$needjsready) = @_;
 8582:     unless ($outerwidth) { $outerwidth='520px'; }
 8583:     unless ($width) { $width='500px'; }
 8584:     unless ($height) { $height='200px'; }
 8585:     my ($table_id,$div_id,$tdcol);
 8586:     if ($id ne '') {
 8587:         $table_id = ' id="table_'.$id.'"';
 8588:         $div_id = ' id="div_'.$id.'"';
 8589:     }
 8590:     if ($bgcolor ne '') {
 8591:         $tdcol = "background-color: $bgcolor;";
 8592:     }
 8593:     my $nicescroll_js;
 8594:     if ($env{'browser.mobile'}) {
 8595:         $nicescroll_js = &nicescroll_javascript('div_'.$id,$cursor,$needjsready);
 8596:     }
 8597:     return <<"END";
 8598: $nicescroll_js
 8599: 
 8600: <table style="width: $outerwidth; border: 1px solid none;"$table_id><tr><td style="width: $width;$tdcol">
 8601: <div style="overflow:auto; width:$width; height:$height;"$div_id>
 8602: END
 8603: }
 8604: 
 8605: sub end_scrollbox {
 8606:     return '</div></td></tr></table>';
 8607: }
 8608: 
 8609: sub nicescroll_javascript {
 8610:     my ($id,$cursor,$needjsready,$framecheck,$location) = @_;
 8611:     my %options;
 8612:     if (ref($cursor) eq 'HASH') {
 8613:         %options = %{$cursor};
 8614:     }
 8615:     unless ($options{'railalign'} =~ /^left|right$/) {
 8616:         $options{'railalign'} = 'left';
 8617:     }
 8618:     unless ($options{'cursorcolor'} =~ /^\#\w+$/) {
 8619:         my $function  = &get_users_function();
 8620:         $options{'cursorcolor'} = &designparm($function.'.sidebg',$env{'request.role.domain'});
 8621:         unless ($options{'cursorcolor'} =~ /^\#\w+$/) {
 8622:             $options{'cursorcolor'} = '#00F';
 8623:         }
 8624:     }
 8625:     if ($options{'cursoropacity'} =~ /^[\d.]+$/) {
 8626:         unless ($options{'cursoropacity'} >= 0.0 && $options{'cursoropacity'} <=1.0) {
 8627:             $options{'cursoropacity'}='1.0';
 8628:         }
 8629:     } else {
 8630:         $options{'cursoropacity'}='1.0';
 8631:     }
 8632:     if ($options{'cursorfixedheight'} eq 'none') {
 8633:         delete($options{'cursorfixedheight'});
 8634:     } else {
 8635:         unless ($options{'cursorfixedheight'} =~ /^\d+$/) { $options{'cursorfixedheight'}='50'; }
 8636:     }
 8637:     unless ($options{'railoffset'} =~ /^{[\w\:\d\-,]+}$/) {
 8638:         delete($options{'railoffset'});
 8639:     }
 8640:     my @niceoptions;
 8641:     while (my($key,$value) = each(%options)) {
 8642:         if ($value =~ /^\{.+\}$/) {
 8643:             push(@niceoptions,$key.':'.$value);
 8644:         } else {
 8645:             push(@niceoptions,$key.':"'.$value.'"');
 8646:         }
 8647:     }
 8648:     my $nicescroll_js = '
 8649: $(document).ready(
 8650:       function() {
 8651:           $("#'.$id.'").niceScroll({'.join(',',@niceoptions).'});
 8652:       }
 8653: );
 8654: ';
 8655:     if ($framecheck) {
 8656:         $nicescroll_js .= '
 8657: function expand_div(caller) {
 8658:     if (top === self) {
 8659:         document.getElementById("'.$id.'").style.width = "auto";
 8660:         document.getElementById("'.$id.'").style.height = "auto";
 8661:     } else {
 8662:         try {
 8663:             if (parent.frames) {
 8664:                 if (parent.frames.length > 1) {
 8665:                     var framesrc = parent.frames[1].location.href;
 8666:                     var currsrc = framesrc.replace(/\#.*$/,"");
 8667:                     if ((caller == "search") || (currsrc == "'.$location.'")) {
 8668:                         document.getElementById("'.$id.'").style.width = "auto";
 8669:                         document.getElementById("'.$id.'").style.height = "auto";
 8670:                     }
 8671:                 }
 8672:             }
 8673:         } catch (e) {
 8674:             return;
 8675:         }
 8676:     }
 8677:     return;
 8678: }
 8679: ';
 8680:     }
 8681:     if ($needjsready) {
 8682:         $nicescroll_js = '
 8683: <script type="text/javascript">'."\n".$nicescroll_js."\n</script>\n";
 8684:     } else {
 8685:         $nicescroll_js = &Apache::lonhtmlcommon::scripttag($nicescroll_js);
 8686:     }
 8687:     return $nicescroll_js;
 8688: }
 8689: 
 8690: sub simple_error_page {
 8691:     my ($r,$title,$msg,$args) = @_;
 8692:     if (ref($args) eq 'HASH') {
 8693:         if (!$args->{'no_auto_mt_msg'}) { $msg = &mt($msg); }
 8694:     } else {
 8695:         $msg = &mt($msg);
 8696:     }
 8697: 
 8698:     my $page =
 8699: 	&Apache::loncommon::start_page($title).
 8700: 	'<p class="LC_error">'.$msg.'</p>'.
 8701: 	&Apache::loncommon::end_page();
 8702:     if (ref($r)) {
 8703: 	$r->print($page);
 8704: 	return;
 8705:     }
 8706:     return $page;
 8707: }
 8708: 
 8709: {
 8710:     my @row_count;
 8711: 
 8712:     sub start_data_table_count {
 8713:         unshift(@row_count, 0);
 8714:         return;
 8715:     }
 8716: 
 8717:     sub end_data_table_count {
 8718:         shift(@row_count);
 8719:         return;
 8720:     }
 8721: 
 8722:     sub start_data_table {
 8723: 	my ($add_class,$id) = @_;
 8724: 	my $css_class = (join(' ','LC_data_table',$add_class));
 8725:         my $table_id;
 8726:         if (defined($id)) {
 8727:             $table_id = ' id="'.$id.'"';
 8728:         }
 8729: 	&start_data_table_count();
 8730: 	return '<table class="'.$css_class.'"'.$table_id.'>'."\n";
 8731:     }
 8732: 
 8733:     sub end_data_table {
 8734: 	&end_data_table_count();
 8735: 	return '</table>'."\n";;
 8736:     }
 8737: 
 8738:     sub start_data_table_row {
 8739: 	my ($add_class, $id) = @_;
 8740: 	$row_count[0]++;
 8741: 	my $css_class = ($row_count[0] % 2)?'LC_odd_row':'LC_even_row';
 8742: 	$css_class = (join(' ',$css_class,$add_class)) unless ($add_class eq '');
 8743:         $id = (' id="'.$id.'"') unless ($id eq '');
 8744:         return  '<tr class="'.$css_class.'"'.$id.'>'."\n";
 8745:     }
 8746:     
 8747:     sub continue_data_table_row {
 8748: 	my ($add_class, $id) = @_;
 8749: 	my $css_class = ($row_count[0] % 2)?'LC_odd_row':'LC_even_row';
 8750: 	$css_class = (join(' ',$css_class,$add_class)) unless ($add_class eq '');
 8751:         $id = (' id="'.$id.'"') unless ($id eq '');
 8752:         return  '<tr class="'.$css_class.'"'.$id.'>'."\n";
 8753:     }
 8754: 
 8755:     sub end_data_table_row {
 8756: 	return '</tr>'."\n";;
 8757:     }
 8758: 
 8759:     sub start_data_table_empty_row {
 8760: #	$row_count[0]++;
 8761: 	return  '<tr class="LC_empty_row" >'."\n";;
 8762:     }
 8763: 
 8764:     sub end_data_table_empty_row {
 8765: 	return '</tr>'."\n";;
 8766:     }
 8767: 
 8768:     sub start_data_table_header_row {
 8769: 	return  '<tr class="LC_header_row">'."\n";;
 8770:     }
 8771: 
 8772:     sub end_data_table_header_row {
 8773: 	return '</tr>'."\n";;
 8774:     }
 8775: 
 8776:     sub data_table_caption {
 8777:         my $caption = shift;
 8778:         return "<caption class=\"LC_caption\">$caption</caption>";
 8779:     }
 8780: }
 8781: 
 8782: =pod
 8783: 
 8784: =item * &inhibit_menu_check($arg)
 8785: 
 8786: Checks for a inhibitmenu state and generates output to preserve it
 8787: 
 8788: Inputs:         $arg - can be any of
 8789:                      - undef - in which case the return value is a string 
 8790:                                to add  into arguments list of a uri
 8791:                      - 'input' - in which case the return value is a HTML
 8792:                                  <form> <input> field of type hidden to
 8793:                                  preserve the value
 8794:                      - a url - in which case the return value is the url with
 8795:                                the neccesary cgi args added to preserve the
 8796:                                inhibitmenu state
 8797:                      - a ref to a url - no return value, but the string is
 8798:                                         updated to include the neccessary cgi
 8799:                                         args to preserve the inhibitmenu state
 8800: 
 8801: =cut
 8802: 
 8803: sub inhibit_menu_check {
 8804:     my ($arg) = @_;
 8805:     &get_unprocessed_cgi($ENV{'QUERY_STRING'}, ['inhibitmenu']);
 8806:     if ($arg eq 'input') {
 8807: 	if ($env{'form.inhibitmenu'}) {
 8808: 	    return '<input type="hidden" name="inhibitmenu" value="'.$env{'form.inhibitmenu'}.'" />';
 8809: 	} else {
 8810: 	    return
 8811: 	}
 8812:     }
 8813:     if ($env{'form.inhibitmenu'}) {
 8814: 	if (ref($arg)) {
 8815: 	    $$arg .= '?inhibitmenu='.$env{'form.inhibitmenu'};
 8816: 	} elsif ($arg eq '') {
 8817: 	    $arg .= 'inhibitmenu='.$env{'form.inhibitmenu'};
 8818: 	} else {
 8819: 	    $arg .= '?inhibitmenu='.$env{'form.inhibitmenu'};
 8820: 	}
 8821:     }
 8822:     if (!ref($arg)) {
 8823: 	return $arg;
 8824:     }
 8825: }
 8826: 
 8827: ###############################################
 8828: 
 8829: =pod
 8830: 
 8831: =back
 8832: 
 8833: =head1 User Information Routines
 8834: 
 8835: =over 4
 8836: 
 8837: =item * &get_users_function()
 8838: 
 8839: Used by &bodytag to determine the current users primary role.
 8840: Returns either 'student','coordinator','admin', or 'author'.
 8841: 
 8842: =cut
 8843: 
 8844: ###############################################
 8845: sub get_users_function {
 8846:     my $function = 'norole';
 8847:     if ($env{'request.role'}=~/^(st)/) {
 8848:         $function='student';
 8849:     }
 8850:     if ($env{'request.role'}=~/^(cc|co|in|ta|ep)/) {
 8851:         $function='coordinator';
 8852:     }
 8853:     if ($env{'request.role'}=~/^(su|dc|ad|li)/) {
 8854:         $function='admin';
 8855:     }
 8856:     if (($env{'request.role'}=~/^(au|ca|aa)/) ||
 8857:         ($ENV{'REQUEST_URI'}=~ m{/^(/priv)})) {
 8858:         $function='author';
 8859:     }
 8860:     return $function;
 8861: }
 8862: 
 8863: ###############################################
 8864: 
 8865: =pod
 8866: 
 8867: =item * &show_course()
 8868: 
 8869: Used by lonmenu.pm and lonroles.pm to determine whether to use the word
 8870: 'Courses' or 'Roles' in inline navigation and on screen displaying user's roles.
 8871: 
 8872: Inputs:
 8873: None
 8874: 
 8875: Outputs:
 8876: Scalar: 1 if 'Course' to be used, 0 otherwise.
 8877: 
 8878: =cut
 8879: 
 8880: ###############################################
 8881: sub show_course {
 8882:     my $course = !$env{'user.adv'};
 8883:     if (!$env{'user.adv'}) {
 8884:         foreach my $env (keys(%env)) {
 8885:             next if ($env !~ m/^user\.priv\./);
 8886:             if ($env !~ m/^user\.priv\.(?:st|cm)/) {
 8887:                 $course = 0;
 8888:                 last;
 8889:             }
 8890:         }
 8891:     }
 8892:     return $course;
 8893: }
 8894: 
 8895: ###############################################
 8896: 
 8897: =pod
 8898: 
 8899: =item * &check_user_status()
 8900: 
 8901: Determines current status of supplied role for a
 8902: specific user. Roles can be active, previous or future.
 8903: 
 8904: Inputs: 
 8905: user's domain, user's username, course's domain,
 8906: course's number, optional section ID.
 8907: 
 8908: Outputs:
 8909: role status: active, previous or future. 
 8910: 
 8911: =cut
 8912: 
 8913: sub check_user_status {
 8914:     my ($udom,$uname,$cdom,$crs,$role,$sec) = @_;
 8915:     my %userinfo = &Apache::lonnet::dump('roles',$udom,$uname);
 8916:     my @uroles = keys(%userinfo);
 8917:     my $srchstr;
 8918:     my $active_chk = 'none';
 8919:     my $now = time;
 8920:     if (@uroles > 0) {
 8921:         if (($role eq 'cc') || ($role eq 'co') || ($sec eq '') || (!defined($sec))) {
 8922:             $srchstr = '/'.$cdom.'/'.$crs.'_'.$role;
 8923:         } else {
 8924:             $srchstr = '/'.$cdom.'/'.$crs.'/'.$sec.'_'.$role;
 8925:         }
 8926:         if (grep/^\Q$srchstr\E$/,@uroles) {
 8927:             my $role_end = 0;
 8928:             my $role_start = 0;
 8929:             $active_chk = 'active';
 8930:             if ($userinfo{$srchstr} =~ m/^\Q$role\E_(\d+)/) {
 8931:                 $role_end = $1;
 8932:                 if ($userinfo{$srchstr} =~ m/^\Q$role\E_\Q$role_end\E_(\d+)$/) {
 8933:                     $role_start = $1;
 8934:                 }
 8935:             }
 8936:             if ($role_start > 0) {
 8937:                 if ($now < $role_start) {
 8938:                     $active_chk = 'future';
 8939:                 }
 8940:             }
 8941:             if ($role_end > 0) {
 8942:                 if ($now > $role_end) {
 8943:                     $active_chk = 'previous';
 8944:                 }
 8945:             }
 8946:         }
 8947:     }
 8948:     return $active_chk;
 8949: }
 8950: 
 8951: ###############################################
 8952: 
 8953: =pod
 8954: 
 8955: =item * &get_sections()
 8956: 
 8957: Determines all the sections for a course including
 8958: sections with students and sections containing other roles.
 8959: Incoming parameters: 
 8960: 
 8961: 1. domain
 8962: 2. course number 
 8963: 3. reference to array containing roles for which sections should 
 8964: be gathered (optional).
 8965: 4. reference to array containing status types for which sections 
 8966: should be gathered (optional).
 8967: 
 8968: If the third argument is undefined, sections are gathered for any role. 
 8969: If the fourth argument is undefined, sections are gathered for any status.
 8970: Permissible values are 'active' or 'future' or 'previous'.
 8971:  
 8972: Returns section hash (keys are section IDs, values are
 8973: number of users in each section), subject to the
 8974: optional roles filter, optional status filter 
 8975: 
 8976: =cut
 8977: 
 8978: ###############################################
 8979: sub get_sections {
 8980:     my ($cdom,$cnum,$possible_roles,$possible_status) = @_;
 8981:     if (!defined($cdom) || !defined($cnum)) {
 8982:         my $cid =  $env{'request.course.id'};
 8983: 
 8984: 	return if (!defined($cid));
 8985: 
 8986:         $cdom = $env{'course.'.$cid.'.domain'};
 8987:         $cnum = $env{'course.'.$cid.'.num'};
 8988:     }
 8989: 
 8990:     my %sectioncount;
 8991:     my $now = time;
 8992: 
 8993:     my $check_students = 1;
 8994:     my $only_students = 0;
 8995:     if (ref($possible_roles) eq 'ARRAY') {
 8996:         if (grep(/^st$/,@{$possible_roles})) {
 8997:             if (@{$possible_roles} == 1) {
 8998:                 $only_students = 1;
 8999:             }
 9000:         } else {
 9001:             $check_students = 0;
 9002:         }
 9003:     }
 9004: 
 9005:     if ($check_students) {
 9006: 	my ($classlist) = &Apache::loncoursedata::get_classlist($cdom,$cnum);
 9007: 	my $sec_index = &Apache::loncoursedata::CL_SECTION();
 9008: 	my $status_index = &Apache::loncoursedata::CL_STATUS();
 9009:         my $start_index = &Apache::loncoursedata::CL_START();
 9010:         my $end_index = &Apache::loncoursedata::CL_END();
 9011:         my $status;
 9012: 	while (my ($student,$data) = each(%$classlist)) {
 9013: 	    my ($section,$stu_status,$start,$end) = ($data->[$sec_index],
 9014: 				                     $data->[$status_index],
 9015:                                                      $data->[$start_index],
 9016:                                                      $data->[$end_index]);
 9017:             if ($stu_status eq 'Active') {
 9018:                 $status = 'active';
 9019:             } elsif ($end < $now) {
 9020:                 $status = 'previous';
 9021:             } elsif ($start > $now) {
 9022:                 $status = 'future';
 9023:             } 
 9024: 	    if ($section ne '-1' && $section !~ /^\s*$/) {
 9025:                 if ((!defined($possible_status)) || (($status ne '') && 
 9026:                     (grep/^\Q$status\E$/,@{$possible_status}))) { 
 9027: 		    $sectioncount{$section}++;
 9028:                 }
 9029: 	    }
 9030: 	}
 9031:     }
 9032:     if ($only_students) {
 9033:         return %sectioncount;
 9034:     }
 9035:     my %courseroles = &Apache::lonnet::dump('nohist_userroles',$cdom,$cnum);
 9036:     foreach my $user (sort(keys(%courseroles))) {
 9037: 	if ($user !~ /^(\w{2})/) { next; }
 9038: 	my ($role) = ($user =~ /^(\w{2})/);
 9039: 	if ($possible_roles && !(grep(/^$role$/,@$possible_roles))) { next; }
 9040: 	my ($section,$status);
 9041: 	if ($role eq 'cr' &&
 9042: 	    $user =~ m-^$role/[^/]*/[^/]*/[^/]*:[^:]*:[^:]*:(\w+)-) {
 9043: 	    $section=$1;
 9044: 	}
 9045: 	if ($user =~ /^$role:[^:]*:[^:]*:(\w+)/) { $section=$1; }
 9046: 	if (!defined($section) || $section eq '-1') { next; }
 9047:         my ($end,$start) = ($courseroles{$user} =~ /^([^:]*):([^:]*)$/);
 9048:         if ($end == -1 && $start == -1) {
 9049:             next; #deleted role
 9050:         }
 9051:         if (!defined($possible_status)) { 
 9052:             $sectioncount{$section}++;
 9053:         } else {
 9054:             if ((!$end || $end >= $now) && (!$start || $start <= $now)) {
 9055:                 $status = 'active';
 9056:             } elsif ($end < $now) {
 9057:                 $status = 'future';
 9058:             } elsif ($start > $now) {
 9059:                 $status = 'previous';
 9060:             }
 9061:             if (($status ne '') && (grep/^\Q$status\E$/,@{$possible_status})) {
 9062:                 $sectioncount{$section}++;
 9063:             }
 9064:         }
 9065:     }
 9066:     return %sectioncount;
 9067: }
 9068: 
 9069: ###############################################
 9070: 
 9071: =pod
 9072: 
 9073: =item * &get_course_users()
 9074: 
 9075: Retrieves usernames:domains for users in the specified course
 9076: with specific role(s), and access status. 
 9077: 
 9078: Incoming parameters:
 9079: 1. course domain
 9080: 2. course number
 9081: 3. access status: users must have - either active, 
 9082: previous, future, or all.
 9083: 4. reference to array of permissible roles
 9084: 5. reference to array of section restrictions (optional)
 9085: 6. reference to results object (hash of hashes).
 9086: 7. reference to optional userdata hash
 9087: 8. reference to optional statushash
 9088: 9. flag if privileged users (except those set to unhide in
 9089:    course settings) should be excluded    
 9090: Keys of top level results hash are roles.
 9091: Keys of inner hashes are username:domain, with 
 9092: values set to access type.
 9093: Optional userdata hash returns an array with arguments in the 
 9094: same order as loncoursedata::get_classlist() for student data.
 9095: 
 9096: Optional statushash returns
 9097: 
 9098: Entries for end, start, section and status are blank because
 9099: of the possibility of multiple values for non-student roles.
 9100: 
 9101: =cut
 9102: 
 9103: ###############################################
 9104: 
 9105: sub get_course_users {
 9106:     my ($cdom,$cnum,$types,$roles,$sections,$users,$userdata,$statushash,$hidepriv) = @_;
 9107:     my %idx = ();
 9108:     my %seclists;
 9109: 
 9110:     $idx{udom} = &Apache::loncoursedata::CL_SDOM();
 9111:     $idx{uname} =  &Apache::loncoursedata::CL_SNAME();
 9112:     $idx{end} = &Apache::loncoursedata::CL_END();
 9113:     $idx{start} = &Apache::loncoursedata::CL_START();
 9114:     $idx{id} = &Apache::loncoursedata::CL_ID();
 9115:     $idx{section} = &Apache::loncoursedata::CL_SECTION();
 9116:     $idx{fullname} = &Apache::loncoursedata::CL_FULLNAME();
 9117:     $idx{status} = &Apache::loncoursedata::CL_STATUS();
 9118: 
 9119:     if (grep(/^st$/,@{$roles})) {
 9120:         my ($classlist,$keylist)=&Apache::loncoursedata::get_classlist($cdom,$cnum);
 9121:         my $now = time;
 9122:         foreach my $student (keys(%{$classlist})) {
 9123:             my $match = 0;
 9124:             my $secmatch = 0;
 9125:             my $section = $$classlist{$student}[$idx{section}];
 9126:             my $status = $$classlist{$student}[$idx{status}];
 9127:             if ($section eq '') {
 9128:                 $section = 'none';
 9129:             }
 9130:             if ((ref($sections) eq 'ARRAY') && (@{$sections} > 0)) {
 9131:                 if (grep(/^all$/,@{$sections})) {
 9132:                     $secmatch = 1;
 9133:                 } elsif ($$classlist{$student}[$idx{section}] eq '') {
 9134:                     if (grep(/^none$/,@{$sections})) {
 9135:                         $secmatch = 1;
 9136:                     }
 9137:                 } else {  
 9138: 		    if (grep(/^\Q$section\E$/,@{$sections})) {
 9139: 		        $secmatch = 1;
 9140:                     }
 9141: 		}
 9142:                 if (!$secmatch) {
 9143:                     next;
 9144:                 }
 9145:             }
 9146:             if (defined($$types{'active'})) {
 9147:                 if ($$classlist{$student}[$idx{status}] eq 'Active') {
 9148:                     push(@{$$users{st}{$student}},'active');
 9149:                     $match = 1;
 9150:                 }
 9151:             }
 9152:             if (defined($$types{'previous'})) {
 9153:                 if ($$classlist{$student}[$idx{status}] eq 'Expired') {
 9154:                     push(@{$$users{st}{$student}},'previous');
 9155:                     $match = 1;
 9156:                 }
 9157:             }
 9158:             if (defined($$types{'future'})) {
 9159:                 if ($$classlist{$student}[$idx{status}] eq 'Future') {
 9160:                     push(@{$$users{st}{$student}},'future');
 9161:                     $match = 1;
 9162:                 }
 9163:             }
 9164:             if ($match) {
 9165:                 push(@{$seclists{$student}},$section);
 9166:                 if (ref($userdata) eq 'HASH') {
 9167:                     $$userdata{$student} = $$classlist{$student};
 9168:                 }
 9169:                 if (ref($statushash) eq 'HASH') {
 9170:                     $statushash->{$student}{'st'}{$section} = $status;
 9171:                 }
 9172:             }
 9173:         }
 9174:     }
 9175:     if ((@{$roles} > 1) || ((@{$roles} == 1) && ($$roles[0] ne "st"))) {
 9176:         my %coursepersonnel = &Apache::lonnet::dump('nohist_userroles',$cdom,$cnum);
 9177:         my $now = time;
 9178:         my %displaystatus = ( previous => 'Expired',
 9179:                               active   => 'Active',
 9180:                               future   => 'Future',
 9181:                             );
 9182:         my (%nothide,@possdoms);
 9183:         if ($hidepriv) {
 9184:             my %coursehash=&Apache::lonnet::coursedescription($cdom.'_'.$cnum);
 9185:             foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
 9186:                 if ($user !~ /:/) {
 9187:                     $nothide{join(':',split(/[\@]/,$user))}=1;
 9188:                 } else {
 9189:                     $nothide{$user} = 1;
 9190:                 }
 9191:             }
 9192:             my @possdoms = ($cdom);
 9193:             if ($coursehash{'checkforpriv'}) {
 9194:                 push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
 9195:             }
 9196:         }
 9197:         foreach my $person (sort(keys(%coursepersonnel))) {
 9198:             my $match = 0;
 9199:             my $secmatch = 0;
 9200:             my $status;
 9201:             my ($role,$user,$usec) = ($person =~ /^([^:]*):([^:]+:[^:]+):([^:]*)/);
 9202:             $user =~ s/:$//;
 9203:             my ($end,$start) = split(/:/,$coursepersonnel{$person});
 9204:             if ($end == -1 || $start == -1) {
 9205:                 next;
 9206:             }
 9207:             if (($role) && ((grep(/^\Q$role\E$/,@{$roles})) ||
 9208:                 (grep(/^cr$/,@{$roles}) && $role =~ /^cr\//))) {
 9209:                 my ($uname,$udom) = split(/:/,$user);
 9210:                 if ((ref($sections) eq 'ARRAY') && (@{$sections} > 0)) {
 9211:                     if (grep(/^all$/,@{$sections})) {
 9212:                         $secmatch = 1;
 9213:                     } elsif ($usec eq '') {
 9214:                         if (grep(/^none$/,@{$sections})) {
 9215:                             $secmatch = 1;
 9216:                         }
 9217:                     } else {
 9218:                         if (grep(/^\Q$usec\E$/,@{$sections})) {
 9219:                             $secmatch = 1;
 9220:                         }
 9221:                     }
 9222:                     if (!$secmatch) {
 9223:                         next;
 9224:                     }
 9225:                 }
 9226:                 if ($usec eq '') {
 9227:                     $usec = 'none';
 9228:                 }
 9229:                 if ($uname ne '' && $udom ne '') {
 9230:                     if ($hidepriv) {
 9231:                         if ((&Apache::lonnet::privileged($uname,$udom,\@possdoms)) &&
 9232:                             (!$nothide{$uname.':'.$udom})) {
 9233:                             next;
 9234:                         }
 9235:                     }
 9236:                     if ($end > 0 && $end < $now) {
 9237:                         $status = 'previous';
 9238:                     } elsif ($start > $now) {
 9239:                         $status = 'future';
 9240:                     } else {
 9241:                         $status = 'active';
 9242:                     }
 9243:                     foreach my $type (keys(%{$types})) { 
 9244:                         if ($status eq $type) {
 9245:                             if (!grep(/^\Q$type\E$/,@{$$users{$role}{$user}})) {
 9246:                                 push(@{$$users{$role}{$user}},$type);
 9247:                             }
 9248:                             $match = 1;
 9249:                         }
 9250:                     }
 9251:                     if (($match) && (ref($userdata) eq 'HASH')) {
 9252:                         if (!exists($$userdata{$uname.':'.$udom})) {
 9253: 			    &get_user_info($udom,$uname,\%idx,$userdata);
 9254:                         }
 9255:                         if (!grep(/^\Q$usec\E$/,@{$seclists{$uname.':'.$udom}})) {
 9256:                             push(@{$seclists{$uname.':'.$udom}},$usec);
 9257:                         }
 9258:                         if (ref($statushash) eq 'HASH') {
 9259:                             $statushash->{$uname.':'.$udom}{$role}{$usec} = $displaystatus{$status};
 9260:                         }
 9261:                     }
 9262:                 }
 9263:             }
 9264:         }
 9265:         if (grep(/^ow$/,@{$roles})) {
 9266:             if ((defined($cdom)) && (defined($cnum))) {
 9267:                 my %csettings = &Apache::lonnet::get('environment',['internal.courseowner'],$cdom,$cnum);
 9268:                 if ( defined($csettings{'internal.courseowner'}) ) {
 9269:                     my $owner = $csettings{'internal.courseowner'};
 9270:                     next if ($owner eq '');
 9271:                     my ($ownername,$ownerdom);
 9272:                     if ($owner =~ /^([^:]+):([^:]+)$/) {
 9273:                         $ownername = $1;
 9274:                         $ownerdom = $2;
 9275:                     } else {
 9276:                         $ownername = $owner;
 9277:                         $ownerdom = $cdom;
 9278:                         $owner = $ownername.':'.$ownerdom;
 9279:                     }
 9280:                     @{$$users{'ow'}{$owner}} = 'any';
 9281:                     if (defined($userdata) && 
 9282: 			!exists($$userdata{$owner})) {
 9283: 			&get_user_info($ownerdom,$ownername,\%idx,$userdata);
 9284:                         if (!grep(/^none$/,@{$seclists{$owner}})) {
 9285:                             push(@{$seclists{$owner}},'none');
 9286:                         }
 9287:                         if (ref($statushash) eq 'HASH') {
 9288:                             $statushash->{$owner}{'ow'}{'none'} = 'Any';
 9289:                         }
 9290: 		    }
 9291:                 }
 9292:             }
 9293:         }
 9294:         foreach my $user (keys(%seclists)) {
 9295:             @{$seclists{$user}} = (sort {$a <=> $b} @{$seclists{$user}});
 9296:             $$userdata{$user}[$idx{section}] = join(',',@{$seclists{$user}});
 9297:         }
 9298:     }
 9299:     return;
 9300: }
 9301: 
 9302: sub get_user_info {
 9303:     my ($udom,$uname,$idx,$userdata) = @_;
 9304:     $$userdata{$uname.':'.$udom}[$$idx{fullname}] = 
 9305: 	&plainname($uname,$udom,'lastname');
 9306:     $$userdata{$uname.':'.$udom}[$$idx{uname}] = $uname;
 9307:     $$userdata{$uname.':'.$udom}[$$idx{udom}] = $udom;
 9308:     my %idhash =  &Apache::lonnet::idrget($udom,($uname));
 9309:     $$userdata{$uname.':'.$udom}[$$idx{id}] = $idhash{$uname}; 
 9310:     return;
 9311: }
 9312: 
 9313: ###############################################
 9314: 
 9315: =pod
 9316: 
 9317: =item * &get_user_quota()
 9318: 
 9319: Retrieves quota assigned for storage of user files.
 9320: Default is to report quota for portfolio files.
 9321: 
 9322: Incoming parameters:
 9323: 1. user's username
 9324: 2. user's domain
 9325: 3. quota name - portfolio, author, or course
 9326:    (if no quota name provided, defaults to portfolio).
 9327: 4. crstype - official, unofficial, textbook or community, if quota name is
 9328:    course
 9329: 
 9330: Returns:
 9331: 1. Disk quota (in MB) assigned to student.
 9332: 2. (Optional) Type of setting: custom or default
 9333:    (individually assigned or default for user's 
 9334:    institutional status).
 9335: 3. (Optional) - User's institutional status (e.g., faculty, staff
 9336:    or student - types as defined in localenroll::inst_usertypes 
 9337:    for user's domain, which determines default quota for user.
 9338: 4. (Optional) - Default quota which would apply to the user.
 9339: 
 9340: If a value has been stored in the user's environment, 
 9341: it will return that, otherwise it returns the maximal default
 9342: defined for the user's institutional status(es) in the domain.
 9343: 
 9344: =cut
 9345: 
 9346: ###############################################
 9347: 
 9348: 
 9349: sub get_user_quota {
 9350:     my ($uname,$udom,$quotaname,$crstype) = @_;
 9351:     my ($quota,$quotatype,$settingstatus,$defquota);
 9352:     if (!defined($udom)) {
 9353:         $udom = $env{'user.domain'};
 9354:     }
 9355:     if (!defined($uname)) {
 9356:         $uname = $env{'user.name'};
 9357:     }
 9358:     if (($udom eq '' || $uname eq '') ||
 9359:         ($udom eq 'public') && ($uname eq 'public')) {
 9360:         $quota = 0;
 9361:         $quotatype = 'default';
 9362:         $defquota = 0; 
 9363:     } else {
 9364:         my $inststatus;
 9365:         if ($quotaname eq 'course') {
 9366:             if (($env{'course.'.$udom.'_'.$uname.'.num'} eq $uname) &&
 9367:                 ($env{'course.'.$udom.'_'.$uname.'.domain'} eq $udom)) {
 9368:                 $quota = $env{'course.'.$udom.'_'.$uname.'.internal.uploadquota'};
 9369:             } else {
 9370:                 my %cenv = &Apache::lonnet::coursedescription("$udom/$uname");
 9371:                 $quota = $cenv{'internal.uploadquota'};
 9372:             }
 9373:         } else {
 9374:             if ($udom eq $env{'user.domain'} && $uname eq $env{'user.name'}) {
 9375:                 if ($quotaname eq 'author') {
 9376:                     $quota = $env{'environment.authorquota'};
 9377:                 } else {
 9378:                     $quota = $env{'environment.portfolioquota'};
 9379:                 }
 9380:                 $inststatus = $env{'environment.inststatus'};
 9381:             } else {
 9382:                 my %userenv = 
 9383:                     &Apache::lonnet::get('environment',['portfolioquota',
 9384:                                          'authorquota','inststatus'],$udom,$uname);
 9385:                 my ($tmp) = keys(%userenv);
 9386:                 if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
 9387:                     if ($quotaname eq 'author') {
 9388:                         $quota = $userenv{'authorquota'};
 9389:                     } else {
 9390:                         $quota = $userenv{'portfolioquota'};
 9391:                     }
 9392:                     $inststatus = $userenv{'inststatus'};
 9393:                 } else {
 9394:                     undef(%userenv);
 9395:                 }
 9396:             }
 9397:         }
 9398:         if ($quota eq '' || wantarray) {
 9399:             if ($quotaname eq 'course') {
 9400:                 my %domdefs = &Apache::lonnet::get_domain_defaults($udom);
 9401:                 if (($crstype eq 'official') || ($crstype eq 'unofficial') ||
 9402:                     ($crstype eq 'community') || ($crstype eq 'textbook')) {
 9403:                     $defquota = $domdefs{$crstype.'quota'};
 9404:                 }
 9405:                 if ($defquota eq '') {
 9406:                     $defquota = 500;
 9407:                 }
 9408:             } else {
 9409:                 ($defquota,$settingstatus) = &default_quota($udom,$inststatus,$quotaname);
 9410:             }
 9411:             if ($quota eq '') {
 9412:                 $quota = $defquota;
 9413:                 $quotatype = 'default';
 9414:             } else {
 9415:                 $quotatype = 'custom';
 9416:             }
 9417:         }
 9418:     }
 9419:     if (wantarray) {
 9420:         return ($quota,$quotatype,$settingstatus,$defquota);
 9421:     } else {
 9422:         return $quota;
 9423:     }
 9424: }
 9425: 
 9426: ###############################################
 9427: 
 9428: =pod
 9429: 
 9430: =item * &default_quota()
 9431: 
 9432: Retrieves default quota assigned for storage of user portfolio files,
 9433: given an (optional) user's institutional status.
 9434: 
 9435: Incoming parameters:
 9436: 
 9437: 1. domain
 9438: 2. (Optional) institutional status(es).  This is a : separated list of 
 9439:    status types (e.g., faculty, staff, student etc.)
 9440:    which apply to the user for whom the default is being retrieved.
 9441:    If the institutional status string in undefined, the domain
 9442:    default quota will be returned.
 9443: 3.  quota name - portfolio, author, or course
 9444:    (if no quota name provided, defaults to portfolio).
 9445: 
 9446: Returns:
 9447: 
 9448: 1. Default disk quota (in MB) for user portfolios in the domain.
 9449: 2. (Optional) institutional type which determined the value of the
 9450:    default quota.
 9451: 
 9452: If a value has been stored in the domain's configuration db,
 9453: it will return that, otherwise it returns 20 (for backwards 
 9454: compatibility with domains which have not set up a configuration
 9455: db file; the original statically defined portfolio quota was 20 MB). 
 9456: 
 9457: If the user's status includes multiple types (e.g., staff and student),
 9458: the largest default quota which applies to the user determines the
 9459: default quota returned.
 9460: 
 9461: =cut
 9462: 
 9463: ###############################################
 9464: 
 9465: 
 9466: sub default_quota {
 9467:     my ($udom,$inststatus,$quotaname) = @_;
 9468:     my ($defquota,$settingstatus);
 9469:     my %quotahash = &Apache::lonnet::get_dom('configuration',
 9470:                                             ['quotas'],$udom);
 9471:     my $key = 'defaultquota';
 9472:     if ($quotaname eq 'author') {
 9473:         $key = 'authorquota';
 9474:     }
 9475:     if (ref($quotahash{'quotas'}) eq 'HASH') {
 9476:         if ($inststatus ne '') {
 9477:             my @statuses = map { &unescape($_); } split(/:/,$inststatus);
 9478:             foreach my $item (@statuses) {
 9479:                 if (ref($quotahash{'quotas'}{$key}) eq 'HASH') {
 9480:                     if ($quotahash{'quotas'}{$key}{$item} ne '') {
 9481:                         if ($defquota eq '') {
 9482:                             $defquota = $quotahash{'quotas'}{$key}{$item};
 9483:                             $settingstatus = $item;
 9484:                         } elsif ($quotahash{'quotas'}{$key}{$item} > $defquota) {
 9485:                             $defquota = $quotahash{'quotas'}{$key}{$item};
 9486:                             $settingstatus = $item;
 9487:                         }
 9488:                     }
 9489:                 } elsif ($key eq 'defaultquota') {
 9490:                     if ($quotahash{'quotas'}{$item} ne '') {
 9491:                         if ($defquota eq '') {
 9492:                             $defquota = $quotahash{'quotas'}{$item};
 9493:                             $settingstatus = $item;
 9494:                         } elsif ($quotahash{'quotas'}{$item} > $defquota) {
 9495:                             $defquota = $quotahash{'quotas'}{$item};
 9496:                             $settingstatus = $item;
 9497:                         }
 9498:                     }
 9499:                 }
 9500:             }
 9501:         }
 9502:         if ($defquota eq '') {
 9503:             if (ref($quotahash{'quotas'}{$key}) eq 'HASH') {
 9504:                 $defquota = $quotahash{'quotas'}{$key}{'default'};
 9505:             } elsif ($key eq 'defaultquota') {
 9506:                 $defquota = $quotahash{'quotas'}{'default'};
 9507:             }
 9508:             $settingstatus = 'default';
 9509:             if ($defquota eq '') {
 9510:                 if ($quotaname eq 'author') {
 9511:                     $defquota = 500;
 9512:                 }
 9513:             }
 9514:         }
 9515:     } else {
 9516:         $settingstatus = 'default';
 9517:         if ($quotaname eq 'author') {
 9518:             $defquota = 500;
 9519:         } else {
 9520:             $defquota = 20;
 9521:         }
 9522:     }
 9523:     if (wantarray) {
 9524:         return ($defquota,$settingstatus);
 9525:     } else {
 9526:         return $defquota;
 9527:     }
 9528: }
 9529: 
 9530: ###############################################
 9531: 
 9532: =pod
 9533: 
 9534: =item * &excess_filesize_warning()
 9535: 
 9536: Returns warning message if upload of file to authoring space, or copying
 9537: of existing file within authoring space will cause quota for the authoring
 9538: space to be exceeded.
 9539: 
 9540: Same, if upload of a file directly to a course/community via Course Editor
 9541: will cause quota for uploaded content for the course to be exceeded.
 9542: 
 9543: Inputs: 7 
 9544: 1. username or coursenum
 9545: 2. domain
 9546: 3. context ('author' or 'course')
 9547: 4. filename of file for which action is being requested
 9548: 5. filesize (kB) of file
 9549: 6. action being taken: copy or upload.
 9550: 7. quotatype (in course context -- official, unofficial, community or textbook).
 9551: 
 9552: Returns: 1 scalar: HTML to display containing warning if quota would be exceeded,
 9553:          otherwise return null.
 9554: 
 9555: =back
 9556: 
 9557: =cut
 9558: 
 9559: sub excess_filesize_warning {
 9560:     my ($uname,$udom,$context,$filename,$filesize,$action,$quotatype) = @_;
 9561:     my $current_disk_usage = 0;
 9562:     my $disk_quota = &get_user_quota($uname,$udom,$context,$quotatype); #expressed in MB
 9563:     if ($context eq 'author') {
 9564:         my $authorspace = $Apache::lonnet::perlvar{'lonDocRoot'}."/priv/$udom/$uname";
 9565:         $current_disk_usage = &Apache::lonnet::diskusage($udom,$uname,$authorspace);
 9566:     } else {
 9567:         foreach my $subdir ('docs','supplemental') {
 9568:             $current_disk_usage += &Apache::lonnet::diskusage($udom,$uname,"userfiles/$subdir",1);
 9569:         }
 9570:     }
 9571:     $disk_quota = int($disk_quota * 1000);
 9572:     if (($current_disk_usage + $filesize) > $disk_quota) {
 9573:         return '<p class="LC_warning">'.
 9574:                 &mt("Unable to $action [_1]. (size = [_2] kilobytes). Disk quota will be exceeded.",
 9575:                     '<span class="LC_filename">'.$filename.'</span>',$filesize).'</p>'.
 9576:                '<p>'.&mt('Disk quota is [_1] kilobytes. Your current disk usage is [_2] kilobytes.',
 9577:                             $disk_quota,$current_disk_usage).
 9578:                '</p>';
 9579:     }
 9580:     return;
 9581: }
 9582: 
 9583: ###############################################
 9584: 
 9585: 
 9586: sub get_secgrprole_info {
 9587:     my ($cdom,$cnum,$needroles,$type)  = @_;
 9588:     my %sections_count = &get_sections($cdom,$cnum);
 9589:     my @sections =  (sort {$a <=> $b} keys(%sections_count));
 9590:     my %curr_groups = &Apache::longroup::coursegroups($cdom,$cnum);
 9591:     my @groups = sort(keys(%curr_groups));
 9592:     my $allroles = [];
 9593:     my $rolehash;
 9594:     my $accesshash = {
 9595:                      active => 'Currently has access',
 9596:                      future => 'Will have future access',
 9597:                      previous => 'Previously had access',
 9598:                   };
 9599:     if ($needroles) {
 9600:         $rolehash = {'all' => 'all'};
 9601:         my %user_roles = &Apache::lonnet::dump('nohist_userroles',$cdom,$cnum);
 9602: 	if (&Apache::lonnet::error(%user_roles)) {
 9603: 	    undef(%user_roles);
 9604: 	}
 9605:         foreach my $item (keys(%user_roles)) {
 9606:             my ($role)=split(/\:/,$item,2);
 9607:             if ($role eq 'cr') { next; }
 9608:             if ($role =~ /^cr/) {
 9609:                 $$rolehash{$role} = (split('/',$role))[3];
 9610:             } else {
 9611:                 $$rolehash{$role} = &Apache::lonnet::plaintext($role,$type);
 9612:             }
 9613:         }
 9614:         foreach my $key (sort(keys(%{$rolehash}))) {
 9615:             push(@{$allroles},$key);
 9616:         }
 9617:         push (@{$allroles},'st');
 9618:         $$rolehash{'st'} = &Apache::lonnet::plaintext('st',$type);
 9619:     }
 9620:     return (\@sections,\@groups,$allroles,$rolehash,$accesshash);
 9621: }
 9622: 
 9623: sub user_picker {
 9624:     my ($dom,$srch,$forcenewuser,$caller,$cancreate,$usertype,$context,$fixeddom,$noinstd) = @_;
 9625:     my $currdom = $dom;
 9626:     my @alldoms = &Apache::lonnet::all_domains();
 9627:     if (@alldoms == 1) {
 9628:         my %domsrch = &Apache::lonnet::get_dom('configuration',
 9629:                                                ['directorysrch'],$alldoms[0]);
 9630:         my $domdesc = &Apache::lonnet::domain($alldoms[0],'description');
 9631:         my $showdom = $domdesc;
 9632:         if ($showdom eq '') {
 9633:             $showdom = $dom;
 9634:         }
 9635:         if (ref($domsrch{'directorysrch'}) eq 'HASH') {
 9636:             if ((!$domsrch{'directorysrch'}{'available'}) &&
 9637:                 ($domsrch{'directorysrch'}{'lcavailable'} eq '0')) {
 9638:                 return (&mt('LON-CAPA directory search is not available in domain: [_1]',$showdom),0);
 9639:             }
 9640:         }
 9641:     }
 9642:     my %curr_selected = (
 9643:                         srchin => 'dom',
 9644:                         srchby => 'lastname',
 9645:                       );
 9646:     my $srchterm;
 9647:     if ((ref($srch) eq 'HASH') && ($env{'form.origform'} ne 'crtusername')) {
 9648:         if ($srch->{'srchby'} ne '') {
 9649:             $curr_selected{'srchby'} = $srch->{'srchby'};
 9650:         }
 9651:         if ($srch->{'srchin'} ne '') {
 9652:             $curr_selected{'srchin'} = $srch->{'srchin'};
 9653:         }
 9654:         if ($srch->{'srchtype'} ne '') {
 9655:             $curr_selected{'srchtype'} = $srch->{'srchtype'};
 9656:         }
 9657:         if ($srch->{'srchdomain'} ne '') {
 9658:             $currdom = $srch->{'srchdomain'};
 9659:         }
 9660:         $srchterm = $srch->{'srchterm'};
 9661:     }
 9662:     my %html_lt=&Apache::lonlocal::texthash(
 9663:                     'usr'       => 'Search criteria',
 9664:                     'doma'      => 'Domain/institution to search',
 9665:                     'uname'     => 'username',
 9666:                     'lastname'  => 'last name',
 9667:                     'lastfirst' => 'last name, first name',
 9668:                     'crs'       => 'in this course',
 9669:                     'dom'       => 'in selected LON-CAPA domain', 
 9670:                     'alc'       => 'all LON-CAPA',
 9671:                     'instd'     => 'in institutional directory for selected domain',
 9672:                     'exact'     => 'is',
 9673:                     'contains'  => 'contains',
 9674:                     'begins'    => 'begins with',
 9675:                                        );
 9676:     my %js_lt=&Apache::lonlocal::texthash(
 9677:                     'youm'      => "You must include some text to search for.",
 9678:                     'thte'      => "The text you are searching for must contain at least two characters when using a 'begins' type search.",
 9679:                     'thet'      => "The text you are searching for must contain at least three characters when using a 'contains' type search.",
 9680:                     'yomc'      => "You must choose a domain when using an institutional directory search.",
 9681:                     'ymcd'      => "You must choose a domain when using a domain search.",
 9682:                     'whus'      => "When using searching by last,first you must include a comma as separator between last name and first name.",
 9683:                     'whse'      => "When searching by last,first you must include at least one character in the first name.",
 9684:                      'thfo'     => "The following need to be corrected before the search can be run:",
 9685:                                        );
 9686:     &html_escape(\%html_lt);
 9687:     &js_escape(\%js_lt);
 9688:     my $domform;
 9689:     my $allow_blank = 1;
 9690:     if ($fixeddom) {
 9691:         $allow_blank = 0;
 9692:         $domform = &select_dom_form($currdom,'srchdomain',$allow_blank,1,undef,[$currdom]);
 9693:     } else {
 9694:         $domform = &select_dom_form($currdom,'srchdomain',$allow_blank,1);
 9695:     }
 9696:     my $srchinsel = ' <select name="srchin">';
 9697: 
 9698:     my @srchins = ('crs','dom','alc','instd');
 9699: 
 9700:     foreach my $option (@srchins) {
 9701:         # FIXME 'alc' option unavailable until 
 9702:         #       loncreateuser::print_user_query_page()
 9703:         #       has been completed.
 9704:         next if ($option eq 'alc');
 9705:         next if (($option eq 'crs') && ($env{'form.form'} eq 'requestcrs'));  
 9706:         next if ($option eq 'crs' && !$env{'request.course.id'});
 9707:         next if (($option eq 'instd') && ($noinstd));
 9708:         if ($curr_selected{'srchin'} eq $option) {
 9709:             $srchinsel .= ' 
 9710:    <option value="'.$option.'" selected="selected">'.$html_lt{$option}.'</option>';
 9711:         } else {
 9712:             $srchinsel .= '
 9713:    <option value="'.$option.'">'.$html_lt{$option}.'</option>';
 9714:         }
 9715:     }
 9716:     $srchinsel .= "\n  </select>\n";
 9717: 
 9718:     my $srchbysel =  ' <select name="srchby">';
 9719:     foreach my $option ('lastname','lastfirst','uname') {
 9720:         if ($curr_selected{'srchby'} eq $option) {
 9721:             $srchbysel .= '
 9722:    <option value="'.$option.'" selected="selected">'.$html_lt{$option}.'</option>';
 9723:         } else {
 9724:             $srchbysel .= '
 9725:    <option value="'.$option.'">'.$html_lt{$option}.'</option>';
 9726:          }
 9727:     }
 9728:     $srchbysel .= "\n  </select>\n";
 9729: 
 9730:     my $srchtypesel = ' <select name="srchtype">';
 9731:     foreach my $option ('begins','contains','exact') {
 9732:         if ($curr_selected{'srchtype'} eq $option) {
 9733:             $srchtypesel .= '
 9734:    <option value="'.$option.'" selected="selected">'.$html_lt{$option}.'</option>';
 9735:         } else {
 9736:             $srchtypesel .= '
 9737:    <option value="'.$option.'">'.$html_lt{$option}.'</option>';
 9738:         }
 9739:     }
 9740:     $srchtypesel .= "\n  </select>\n";
 9741: 
 9742:     my ($newuserscript,$new_user_create);
 9743:     my $context_dom = $env{'request.role.domain'};
 9744:     if ($context eq 'requestcrs') {
 9745:         if ($env{'form.coursedom'} ne '') { 
 9746:             $context_dom = $env{'form.coursedom'};
 9747:         }
 9748:     }
 9749:     if ($forcenewuser) {
 9750:         if (ref($srch) eq 'HASH') {
 9751:             if ($srch->{'srchby'} eq 'uname' && $srch->{'srchtype'} eq 'exact' && $srch->{'srchin'} eq 'dom' && $srch->{'srchdomain'} eq $context_dom) {
 9752:                 if ($cancreate) {
 9753:                     $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>';
 9754:                 } else {
 9755:                     my $helplink = 'javascript:helpMenu('."'display'".')';
 9756:                     my %usertypetext = (
 9757:                         official   => 'institutional',
 9758:                         unofficial => 'non-institutional',
 9759:                     );
 9760:                     $new_user_create = '<p class="LC_warning">'
 9761:                                       .&mt("You are not authorized to create new $usertypetext{$usertype} users in this domain.")
 9762:                                       .' '
 9763:                                       .&mt('Please contact the [_1]helpdesk[_2] for assistance.'
 9764:                                           ,'<a href="'.$helplink.'">','</a>')
 9765:                                       .'</p><br />';
 9766:                 }
 9767:             }
 9768:         }
 9769: 
 9770:         $newuserscript = <<"ENDSCRIPT";
 9771: 
 9772: function setSearch(createnew,callingForm) {
 9773:     if (createnew == 1) {
 9774:         for (var i=0; i<callingForm.srchby.length; i++) {
 9775:             if (callingForm.srchby.options[i].value == 'uname') {
 9776:                 callingForm.srchby.selectedIndex = i;
 9777:             }
 9778:         }
 9779:         for (var i=0; i<callingForm.srchin.length; i++) {
 9780:             if ( callingForm.srchin.options[i].value == 'dom') {
 9781: 		callingForm.srchin.selectedIndex = i;
 9782:             }
 9783:         }
 9784:         for (var i=0; i<callingForm.srchtype.length; i++) {
 9785:             if (callingForm.srchtype.options[i].value == 'exact') {
 9786:                 callingForm.srchtype.selectedIndex = i;
 9787:             }
 9788:         }
 9789:         for (var i=0; i<callingForm.srchdomain.length; i++) {
 9790:             if (callingForm.srchdomain.options[i].value == '$context_dom') {
 9791:                 callingForm.srchdomain.selectedIndex = i;
 9792:             }
 9793:         }
 9794:     }
 9795: }
 9796: ENDSCRIPT
 9797: 
 9798:     }
 9799: 
 9800:     my $output = <<"END_BLOCK";
 9801: <script type="text/javascript">
 9802: // <![CDATA[
 9803: function validateEntry(callingForm) {
 9804: 
 9805:     var checkok = 1;
 9806:     var srchin;
 9807:     for (var i=0; i<callingForm.srchin.length; i++) {
 9808: 	if ( callingForm.srchin[i].checked ) {
 9809: 	    srchin = callingForm.srchin[i].value;
 9810: 	}
 9811:     }
 9812: 
 9813:     var srchtype = callingForm.srchtype.options[callingForm.srchtype.selectedIndex].value;
 9814:     var srchby = callingForm.srchby.options[callingForm.srchby.selectedIndex].value;
 9815:     var srchdomain = callingForm.srchdomain.options[callingForm.srchdomain.selectedIndex].value;
 9816:     var srchterm =  callingForm.srchterm.value;
 9817:     var srchin = callingForm.srchin.options[callingForm.srchin.selectedIndex].value;
 9818:     var msg = "";
 9819: 
 9820:     if (srchterm == "") {
 9821:         checkok = 0;
 9822:         msg += "$js_lt{'youm'}\\n";
 9823:     }
 9824: 
 9825:     if (srchtype== 'begins') {
 9826:         if (srchterm.length < 2) {
 9827:             checkok = 0;
 9828:             msg += "$js_lt{'thte'}\\n";
 9829:         }
 9830:     }
 9831: 
 9832:     if (srchtype== 'contains') {
 9833:         if (srchterm.length < 3) {
 9834:             checkok = 0;
 9835:             msg += "$js_lt{'thet'}\\n";
 9836:         }
 9837:     }
 9838:     if (srchin == 'instd') {
 9839:         if (srchdomain == '') {
 9840:             checkok = 0;
 9841:             msg += "$js_lt{'yomc'}\\n";
 9842:         }
 9843:     }
 9844:     if (srchin == 'dom') {
 9845:         if (srchdomain == '') {
 9846:             checkok = 0;
 9847:             msg += "$js_lt{'ymcd'}\\n";
 9848:         }
 9849:     }
 9850:     if (srchby == 'lastfirst') {
 9851:         if (srchterm.indexOf(",") == -1) {
 9852:             checkok = 0;
 9853:             msg += "$js_lt{'whus'}\\n";
 9854:         }
 9855:         if (srchterm.indexOf(",") == srchterm.length -1) {
 9856:             checkok = 0;
 9857:             msg += "$js_lt{'whse'}\\n";
 9858:         }
 9859:     }
 9860:     if (checkok == 0) {
 9861:         alert("$js_lt{'thfo'}\\n"+msg);
 9862:         return;
 9863:     }
 9864:     if (checkok == 1) {
 9865:         callingForm.submit();
 9866:     }
 9867: }
 9868: 
 9869: $newuserscript
 9870: 
 9871: // ]]>
 9872: </script>
 9873: 
 9874: $new_user_create
 9875: 
 9876: END_BLOCK
 9877: 
 9878:     $output .= &Apache::lonhtmlcommon::start_pick_box().
 9879:                &Apache::lonhtmlcommon::row_title($html_lt{'doma'}).
 9880:                $domform.
 9881:                &Apache::lonhtmlcommon::row_closure().
 9882:                &Apache::lonhtmlcommon::row_title($html_lt{'usr'}).
 9883:                $srchbysel.
 9884:                $srchtypesel. 
 9885:                '<input type="text" size="15" name="srchterm" value="'.$srchterm.'" />'.
 9886:                $srchinsel.
 9887:                &Apache::lonhtmlcommon::row_closure(1). 
 9888:                &Apache::lonhtmlcommon::end_pick_box().
 9889:                '<br />';
 9890:     return ($output,1);
 9891: }
 9892: 
 9893: sub user_rule_check {
 9894:     my ($usershash,$checks,$alerts,$rulematch,$inst_results,$curr_rules,$got_rules) = @_;
 9895:     my ($response,%inst_response);
 9896:     if (ref($usershash) eq 'HASH') {
 9897:         if (keys(%{$usershash}) > 1) {
 9898:             my (%by_username,%by_id,%userdoms);
 9899:             my $checkid;
 9900:             if (ref($checks) eq 'HASH') {
 9901:                 if ((!defined($checks->{'username'})) && (defined($checks->{'id'}))) {
 9902:                     $checkid = 1;
 9903:                 }
 9904:             }
 9905:             foreach my $user (keys(%{$usershash})) {
 9906:                 my ($uname,$udom) = split(/:/,$user);
 9907:                 if ($checkid) {
 9908:                     if (ref($usershash->{$user}) eq 'HASH') {
 9909:                         if ($usershash->{$user}->{'id'} ne '') {
 9910:                             $by_id{$udom}{$usershash->{$user}->{'id'}} = $uname;
 9911:                             $userdoms{$udom} = 1;
 9912:                             if (ref($inst_results) eq 'HASH') {
 9913:                                 $inst_results->{$uname.':'.$udom} = {};
 9914:                             }
 9915:                         }
 9916:                     }
 9917:                 } else {
 9918:                     $by_username{$udom}{$uname} = 1;
 9919:                     $userdoms{$udom} = 1;
 9920:                     if (ref($inst_results) eq 'HASH') {
 9921:                         $inst_results->{$uname.':'.$udom} = {};
 9922:                     }
 9923:                 }
 9924:             }
 9925:             foreach my $udom (keys(%userdoms)) {
 9926:                 if (!$got_rules->{$udom}) {
 9927:                     my %domconfig = &Apache::lonnet::get_dom('configuration',
 9928:                                                              ['usercreation'],$udom);
 9929:                     if (ref($domconfig{'usercreation'}) eq 'HASH') {
 9930:                         foreach my $item ('username','id') {
 9931:                             if (ref($domconfig{'usercreation'}{$item.'_rule'}) eq 'ARRAY') {
 9932:                                 $$curr_rules{$udom}{$item} =
 9933:                                     $domconfig{'usercreation'}{$item.'_rule'};
 9934:                             }
 9935:                         }
 9936:                     }
 9937:                     $got_rules->{$udom} = 1;
 9938:                 }
 9939:             }
 9940:             if ($checkid) {
 9941:                 foreach my $udom (keys(%by_id)) {
 9942:                     my ($outcome,$results) = &Apache::lonnet::get_multiple_instusers($udom,$by_id{$udom},'id');
 9943:                     if ($outcome eq 'ok') {
 9944:                         foreach my $id (keys(%{$by_id{$udom}})) {
 9945:                             my $uname = $by_id{$udom}{$id};
 9946:                             $inst_response{$uname.':'.$udom} = $outcome;
 9947:                         }
 9948:                         if (ref($results) eq 'HASH') {
 9949:                             foreach my $uname (keys(%{$results})) {
 9950:                                 if (exists($inst_response{$uname.':'.$udom})) {
 9951:                                     $inst_response{$uname.':'.$udom} = $outcome;
 9952:                                     $inst_results->{$uname.':'.$udom} = $results->{$uname};
 9953:                                 }
 9954:                             }
 9955:                         }
 9956:                     }
 9957:                 }
 9958:             } else {
 9959:                 foreach my $udom (keys(%by_username)) {
 9960:                     my ($outcome,$results) = &Apache::lonnet::get_multiple_instusers($udom,$by_username{$udom});
 9961:                     if ($outcome eq 'ok') {
 9962:                         foreach my $uname (keys(%{$by_username{$udom}})) {
 9963:                             $inst_response{$uname.':'.$udom} = $outcome;
 9964:                         }
 9965:                         if (ref($results) eq 'HASH') {
 9966:                             foreach my $uname (keys(%{$results})) {
 9967:                                 $inst_results->{$uname.':'.$udom} = $results->{$uname};
 9968:                             }
 9969:                         }
 9970:                     }
 9971:                 }
 9972:             }
 9973:         } elsif (keys(%{$usershash}) == 1) {
 9974:             my $user = (keys(%{$usershash}))[0];
 9975:             my ($uname,$udom) = split(/:/,$user);
 9976:             if (($udom ne '') && ($uname ne '')) {
 9977:                 if (ref($usershash->{$user}) eq 'HASH') {
 9978:                     if (ref($checks) eq 'HASH') {
 9979:                         if (defined($checks->{'username'})) {
 9980:                             ($inst_response{$user},%{$inst_results->{$user}}) =
 9981:                                 &Apache::lonnet::get_instuser($udom,$uname);
 9982:                         } elsif (defined($checks->{'id'})) {
 9983:                             if ($usershash->{$user}->{'id'} ne '') {
 9984:                                 ($inst_response{$user},%{$inst_results->{$user}}) =
 9985:                                     &Apache::lonnet::get_instuser($udom,undef,
 9986:                                                                   $usershash->{$user}->{'id'});
 9987:                             } else {
 9988:                                 ($inst_response{$user},%{$inst_results->{$user}}) =
 9989:                                     &Apache::lonnet::get_instuser($udom,$uname);
 9990:                             }
 9991:                         }
 9992:                     } else {
 9993:                        ($inst_response{$user},%{$inst_results->{$user}}) =
 9994:                             &Apache::lonnet::get_instuser($udom,$uname);
 9995:                        return;
 9996:                     }
 9997:                     if (!$got_rules->{$udom}) {
 9998:                         my %domconfig = &Apache::lonnet::get_dom('configuration',
 9999:                                                                  ['usercreation'],$udom);
10000:                         if (ref($domconfig{'usercreation'}) eq 'HASH') {
10001:                             foreach my $item ('username','id') {
10002:                                 if (ref($domconfig{'usercreation'}{$item.'_rule'}) eq 'ARRAY') {
10003:                                    $$curr_rules{$udom}{$item} =
10004:                                        $domconfig{'usercreation'}{$item.'_rule'};
10005:                                 }
10006:                             }
10007:                         }
10008:                         $got_rules->{$udom} = 1;
10009:                     }
10010:                 }
10011:             } else {
10012:                 return;
10013:             }
10014:         } else {
10015:             return;
10016:         }
10017:         foreach my $user (keys(%{$usershash})) {
10018:             my ($uname,$udom) = split(/:/,$user);
10019:             next if (($udom eq '') || ($uname eq ''));
10020:             my $id;
10021:             if (ref($inst_results) eq 'HASH') {
10022:                 if (ref($inst_results->{$user}) eq 'HASH') {
10023:                     $id = $inst_results->{$user}->{'id'};
10024:                 }
10025:             }
10026:             if ($id eq '') {
10027:                 if (ref($usershash->{$user})) {
10028:                     $id = $usershash->{$user}->{'id'};
10029:                 }
10030:             }
10031:             foreach my $item (keys(%{$checks})) {
10032:                 if (ref($$curr_rules{$udom}) eq 'HASH') {
10033:                     if (ref($$curr_rules{$udom}{$item}) eq 'ARRAY') {
10034:                         if (@{$$curr_rules{$udom}{$item}} > 0) {
10035:                             my %rule_check = &Apache::lonnet::inst_rulecheck($udom,$uname,$id,$item,
10036:                                                                              $$curr_rules{$udom}{$item});
10037:                             foreach my $rule (@{$$curr_rules{$udom}{$item}}) {
10038:                                 if ($rule_check{$rule}) {
10039:                                     $$rulematch{$user}{$item} = $rule;
10040:                                     if ($inst_response{$user} eq 'ok') {
10041:                                         if (ref($inst_results) eq 'HASH') {
10042:                                             if (ref($inst_results->{$user}) eq 'HASH') {
10043:                                                 if (keys(%{$inst_results->{$user}}) == 0) {
10044:                                                     $$alerts{$item}{$udom}{$uname} = 1;
10045:                                                 } elsif ($item eq 'id') {
10046:                                                     if ($inst_results->{$user}->{'id'} eq '') {
10047:                                                         $$alerts{$item}{$udom}{$uname} = 1;
10048:                                                     }
10049:                                                 }
10050:                                             }
10051:                                         }
10052:                                     }
10053:                                     last;
10054:                                 }
10055:                             }
10056:                         }
10057:                     }
10058:                 }
10059:             }
10060:         }
10061:     }
10062:     return;
10063: }
10064: 
10065: sub user_rule_formats {
10066:     my ($domain,$domdesc,$curr_rules,$check) = @_;
10067:     my %text = ( 
10068:                  'username' => 'Usernames',
10069:                  'id'       => 'IDs',
10070:                );
10071:     my $output;
10072:     my ($rules,$ruleorder) = &Apache::lonnet::inst_userrules($domain,$check);
10073:     if ((ref($rules) eq 'HASH') && (ref($ruleorder) eq 'ARRAY')) {
10074:         if (@{$ruleorder} > 0) {
10075:             $output = '<br />'.
10076:                       &mt($text{$check}.' with the following format(s) may [_1]only[_2] be used for verified users at [_3]:',
10077:                           '<span class="LC_cusr_emph">','</span>',$domdesc).
10078:                       ' <ul>';
10079:             foreach my $rule (@{$ruleorder}) {
10080:                 if (ref($curr_rules) eq 'ARRAY') {
10081:                     if (grep(/^\Q$rule\E$/,@{$curr_rules})) {
10082:                         if (ref($rules->{$rule}) eq 'HASH') {
10083:                             $output .= '<li>'.$rules->{$rule}{'name'}.': '.
10084:                                         $rules->{$rule}{'desc'}.'</li>';
10085:                         }
10086:                     }
10087:                 }
10088:             }
10089:             $output .= '</ul>';
10090:         }
10091:     }
10092:     return $output;
10093: }
10094: 
10095: sub instrule_disallow_msg {
10096:     my ($checkitem,$domdesc,$count,$mode) = @_;
10097:     my $response;
10098:     my %text = (
10099:                   item   => 'username',
10100:                   items  => 'usernames',
10101:                   match  => 'matches',
10102:                   do     => 'does',
10103:                   action => 'a username',
10104:                   one    => 'one',
10105:                );
10106:     if ($count > 1) {
10107:         $text{'item'} = 'usernames';
10108:         $text{'match'} ='match';
10109:         $text{'do'} = 'do';
10110:         $text{'action'} = 'usernames',
10111:         $text{'one'} = 'ones';
10112:     }
10113:     if ($checkitem eq 'id') {
10114:         $text{'items'} = 'IDs';
10115:         $text{'item'} = 'ID';
10116:         $text{'action'} = 'an ID';
10117:         if ($count > 1) {
10118:             $text{'item'} = 'IDs';
10119:             $text{'action'} = 'IDs';
10120:         }
10121:     }
10122:     $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 />';
10123:     if ($mode eq 'upload') {
10124:         if ($checkitem eq 'username') {
10125:             $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'}.");
10126:         } elsif ($checkitem eq 'id') {
10127:             $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.");
10128:         }
10129:     } elsif ($mode eq 'selfcreate') {
10130:         if ($checkitem eq 'id') {
10131:             $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.");
10132:         }
10133:     } else {
10134:         if ($checkitem eq 'username') {
10135:             $response .= &mt("You must choose $text{'action'} with a different format --  $text{'one'} that will not conflict with 'official' institutional $text{'items'}.");
10136:         } elsif ($checkitem eq 'id') {
10137:             $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.");
10138:         }
10139:     }
10140:     return $response;
10141: }
10142: 
10143: sub personal_data_fieldtitles {
10144:     my %fieldtitles = &Apache::lonlocal::texthash (
10145:                         id => 'Student/Employee ID',
10146:                         permanentemail => 'E-mail address',
10147:                         lastname => 'Last Name',
10148:                         firstname => 'First Name',
10149:                         middlename => 'Middle Name',
10150:                         generation => 'Generation',
10151:                         gen => 'Generation',
10152:                         inststatus => 'Affiliation',
10153:                    );
10154:     return %fieldtitles;
10155: }
10156: 
10157: sub sorted_inst_types {
10158:     my ($dom) = @_;
10159:     my ($usertypes,$order);
10160:     my %domdefaults = &Apache::lonnet::get_domain_defaults($dom);
10161:     if (ref($domdefaults{'inststatus'}) eq 'HASH') {
10162:         $usertypes = $domdefaults{'inststatus'}{'inststatustypes'};
10163:         $order = $domdefaults{'inststatus'}{'inststatusorder'};
10164:     } else {
10165:         ($usertypes,$order) = &Apache::lonnet::retrieve_inst_usertypes($dom);
10166:     }
10167:     my $othertitle = &mt('All users');
10168:     if ($env{'request.course.id'}) {
10169:         $othertitle  = &mt('Any users');
10170:     }
10171:     my @types;
10172:     if (ref($order) eq 'ARRAY') {
10173:         @types = @{$order};
10174:     }
10175:     if (@types == 0) {
10176:         if (ref($usertypes) eq 'HASH') {
10177:             @types = sort(keys(%{$usertypes}));
10178:         }
10179:     }
10180:     if (keys(%{$usertypes}) > 0) {
10181:         $othertitle = &mt('Other users');
10182:     }
10183:     return ($othertitle,$usertypes,\@types);
10184: }
10185: 
10186: sub get_institutional_codes {
10187:     my ($settings,$allcourses,$LC_code) = @_;
10188: # Get complete list of course sections to update
10189:     my @currsections = ();
10190:     my @currxlists = ();
10191:     my $coursecode = $$settings{'internal.coursecode'};
10192: 
10193:     if ($$settings{'internal.sectionnums'} ne '') {
10194:         @currsections = split(/,/,$$settings{'internal.sectionnums'});
10195:     }
10196: 
10197:     if ($$settings{'internal.crosslistings'} ne '') {
10198:         @currxlists = split(/,/,$$settings{'internal.crosslistings'});
10199:     }
10200: 
10201:     if (@currxlists > 0) {
10202:         foreach (@currxlists) {
10203:             if (m/^([^:]+):(\w*)$/) {
10204:                 unless (grep/^$1$/,@{$allcourses}) {
10205:                     push(@{$allcourses},$1);
10206:                     $$LC_code{$1} = $2;
10207:                 }
10208:             }
10209:         }
10210:     }
10211:  
10212:     if (@currsections > 0) {
10213:         foreach (@currsections) {
10214:             if (m/^(\w+):(\w*)$/) {
10215:                 my $sec = $coursecode.$1;
10216:                 my $lc_sec = $2;
10217:                 unless (grep/^$sec$/,@{$allcourses}) {
10218:                     push(@{$allcourses},$sec);
10219:                     $$LC_code{$sec} = $lc_sec;
10220:                 }
10221:             }
10222:         }
10223:     }
10224:     return;
10225: }
10226: 
10227: sub get_standard_codeitems {
10228:     return ('Year','Semester','Department','Number','Section');
10229: }
10230: 
10231: =pod
10232: 
10233: =head1 Slot Helpers
10234: 
10235: =over 4
10236: 
10237: =item * sorted_slots()
10238: 
10239: Sorts an array of slot names in order of an optional sort key,
10240: default sort is by slot start time (earliest first). 
10241: 
10242: Inputs:
10243: 
10244: =over 4
10245: 
10246: slotsarr  - Reference to array of unsorted slot names.
10247: 
10248: slots     - Reference to hash of hash, where outer hash keys are slot names.
10249: 
10250: sortkey   - Name of key in inner hash to be sorted on (e.g., starttime).
10251: 
10252: =back
10253: 
10254: Returns:
10255: 
10256: =over 4
10257: 
10258: sorted   - An array of slot names sorted by a specified sort key 
10259:            (default sort key is start time of the slot).
10260: 
10261: =back
10262: 
10263: =cut
10264: 
10265: 
10266: sub sorted_slots {
10267:     my ($slotsarr,$slots,$sortkey) = @_;
10268:     if ($sortkey eq '') {
10269:         $sortkey = 'starttime';
10270:     }
10271:     my @sorted;
10272:     if ((ref($slotsarr) eq 'ARRAY') && (ref($slots) eq 'HASH')) {
10273:         @sorted =
10274:             sort {
10275:                      if (ref($slots->{$a}) && ref($slots->{$b})) {
10276:                          return $slots->{$a}{$sortkey} <=> $slots->{$b}{$sortkey}
10277:                      }
10278:                      if (ref($slots->{$a})) { return -1;}
10279:                      if (ref($slots->{$b})) { return 1;}
10280:                      return 0;
10281:                  } @{$slotsarr};
10282:     }
10283:     return @sorted;
10284: }
10285: 
10286: =pod
10287: 
10288: =item * get_future_slots()
10289: 
10290: Inputs:
10291: 
10292: =over 4
10293: 
10294: cnum - course number
10295: 
10296: cdom - course domain
10297: 
10298: now - current UNIX time
10299: 
10300: symb - optional symb
10301: 
10302: =back
10303: 
10304: Returns:
10305: 
10306: =over 4
10307: 
10308: sorted_reservable - ref to array of student_schedulable slots currently 
10309:                     reservable, ordered by end date of reservation period.
10310: 
10311: reservable_now - ref to hash of student_schedulable slots currently
10312:                  reservable.
10313: 
10314:     Keys in inner hash are:
10315:     (a) symb: either blank or symb to which slot use is restricted.
10316:     (b) endreserve: end date of reservation period.
10317:     (c) uniqueperiod: start,end dates when slot is to be uniquely
10318:         selected.
10319: 
10320: sorted_future - ref to array of student_schedulable slots reservable in
10321:                 the future, ordered by start date of reservation period.
10322: 
10323: future_reservable - ref to hash of student_schedulable slots reservable
10324:                     in the future.
10325: 
10326:     Keys in inner hash are:
10327:     (a) symb: either blank or symb to which slot use is restricted.
10328:     (b) startreserve:  start date of reservation period.
10329:     (c) uniqueperiod: start,end dates when slot is to be uniquely
10330:         selected.
10331: 
10332: =back
10333: 
10334: =cut
10335: 
10336: sub get_future_slots {
10337:     my ($cnum,$cdom,$now,$symb) = @_;
10338:     my (%reservable_now,%future_reservable,@sorted_reservable,@sorted_future);
10339:     my %slots = &Apache::lonnet::get_course_slots($cnum,$cdom);
10340:     foreach my $slot (keys(%slots)) {
10341:         next unless($slots{$slot}->{'type'} eq 'schedulable_student');
10342:         if ($symb) {
10343:             next if (($slots{$slot}->{'symb'} ne '') && 
10344:                      ($slots{$slot}->{'symb'} ne $symb));
10345:         }
10346:         if (($slots{$slot}->{'starttime'} > $now) &&
10347:             ($slots{$slot}->{'endtime'} > $now)) {
10348:             if (($slots{$slot}->{'allowedsections'}) || ($slots{$slot}->{'allowedusers'})) {
10349:                 my $userallowed = 0;
10350:                 if ($slots{$slot}->{'allowedsections'}) {
10351:                     my @allowed_sec = split(',',$slots{$slot}->{'allowedsections'});
10352:                     if (!defined($env{'request.role.sec'})
10353:                         && grep(/^No section assigned$/,@allowed_sec)) {
10354:                         $userallowed=1;
10355:                     } else {
10356:                         if (grep(/^\Q$env{'request.role.sec'}\E$/,@allowed_sec)) {
10357:                             $userallowed=1;
10358:                         }
10359:                     }
10360:                     unless ($userallowed) {
10361:                         if (defined($env{'request.course.groups'})) {
10362:                             my @groups = split(/:/,$env{'request.course.groups'});
10363:                             foreach my $group (@groups) {
10364:                                 if (grep(/^\Q$group\E$/,@allowed_sec)) {
10365:                                     $userallowed=1;
10366:                                     last;
10367:                                 }
10368:                             }
10369:                         }
10370:                     }
10371:                 }
10372:                 if ($slots{$slot}->{'allowedusers'}) {
10373:                     my @allowed_users = split(',',$slots{$slot}->{'allowedusers'});
10374:                     my $user = $env{'user.name'}.':'.$env{'user.domain'};
10375:                     if (grep(/^\Q$user\E$/,@allowed_users)) {
10376:                         $userallowed = 1;
10377:                     }
10378:                 }
10379:                 next unless($userallowed);
10380:             }
10381:             my $startreserve = $slots{$slot}->{'startreserve'};
10382:             my $endreserve = $slots{$slot}->{'endreserve'};
10383:             my $symb = $slots{$slot}->{'symb'};
10384:             my $uniqueperiod;
10385:             if (ref($slots{$slot}->{'uniqueperiod'}) eq 'ARRAY') {
10386:                 $uniqueperiod = join(',',@{$slots{$slot}->{'uniqueperiod'}});
10387:             }
10388:             if (($startreserve < $now) &&
10389:                 (!$endreserve || $endreserve > $now)) {
10390:                 my $lastres = $endreserve;
10391:                 if (!$lastres) {
10392:                     $lastres = $slots{$slot}->{'starttime'};
10393:                 }
10394:                 $reservable_now{$slot} = {
10395:                                            symb       => $symb,
10396:                                            endreserve => $lastres,
10397:                                            uniqueperiod => $uniqueperiod,   
10398:                                          };
10399:             } elsif (($startreserve > $now) &&
10400:                      (!$endreserve || $endreserve > $startreserve)) {
10401:                 $future_reservable{$slot} = {
10402:                                               symb         => $symb,
10403:                                               startreserve => $startreserve,
10404:                                               uniqueperiod => $uniqueperiod,
10405:                                             };
10406:             }
10407:         }
10408:     }
10409:     my @unsorted_reservable = keys(%reservable_now);
10410:     if (@unsorted_reservable > 0) {
10411:         @sorted_reservable = 
10412:             &sorted_slots(\@unsorted_reservable,\%reservable_now,'endreserve');
10413:     }
10414:     my @unsorted_future = keys(%future_reservable);
10415:     if (@unsorted_future > 0) {
10416:         @sorted_future =
10417:             &sorted_slots(\@unsorted_future,\%future_reservable,'startreserve');
10418:     }
10419:     return (\@sorted_reservable,\%reservable_now,\@sorted_future,\%future_reservable);
10420: }
10421: 
10422: =pod
10423: 
10424: =back
10425: 
10426: =head1 HTTP Helpers
10427: 
10428: =over 4
10429: 
10430: =item * &get_unprocessed_cgi($query,$possible_names)
10431: 
10432: Modify the %env hash to contain unprocessed CGI form parameters held in
10433: $query.  The parameters listed in $possible_names (an array reference),
10434: will be set in $env{'form.name'} if they do not already exist.
10435: 
10436: Typically called with $ENV{'QUERY_STRING'} as the first parameter.  
10437: $possible_names is an ref to an array of form element names.  As an example:
10438: get_unprocessed_cgi($ENV{'QUERY_STRING'},['uname','udom']);
10439: will result in $env{'form.uname'} and $env{'form.udom'} being set.
10440: 
10441: =cut
10442: 
10443: sub get_unprocessed_cgi {
10444:   my ($query,$possible_names)= @_;
10445:   # $Apache::lonxml::debug=1;
10446:   foreach my $pair (split(/&/,$query)) {
10447:     my ($name, $value) = split(/=/,$pair);
10448:     $name = &unescape($name);
10449:     if (!defined($possible_names) || (grep {$_ eq $name} @$possible_names)) {
10450:       $value =~ tr/+/ /;
10451:       $value =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack("C",hex($1))/eg;
10452:       unless (defined($env{'form.'.$name})) { &add_to_env('form.'.$name,$value) };
10453:     }
10454:   }
10455: }
10456: 
10457: =pod
10458: 
10459: =item * &cacheheader() 
10460: 
10461: returns cache-controlling header code
10462: 
10463: =cut
10464: 
10465: sub cacheheader {
10466:     unless ($env{'request.method'} eq 'GET') { return ''; }
10467:     my $date=strftime("%a, %d %b %Y %H:%M:%S GMT",gmtime);
10468:     my $output .='<meta HTTP-EQUIV="Expires" CONTENT="'.$date.'" />
10469:                 <meta HTTP-EQUIV="Cache-control" CONTENT="no-cache" />
10470:                 <meta HTTP-EQUIV="Pragma" CONTENT="no-cache" />';
10471:     return $output;
10472: }
10473: 
10474: =pod
10475: 
10476: =item * &no_cache($r) 
10477: 
10478: specifies header code to not have cache
10479: 
10480: =cut
10481: 
10482: sub no_cache {
10483:     my ($r) = @_;
10484:     if ($ENV{'REQUEST_METHOD'} ne 'GET' &&
10485: 	$env{'request.method'} ne 'GET') { return ''; }
10486:     my $date=strftime("%a, %d %b %Y %H:%M:%S GMT",gmtime(time));
10487:     $r->no_cache(1);
10488:     $r->header_out("Expires" => $date);
10489:     $r->header_out("Pragma" => "no-cache");
10490: }
10491: 
10492: sub content_type {
10493:     my ($r,$type,$charset) = @_;
10494:     if ($r) {
10495: 	#  Note that printout.pl calls this with undef for $r.
10496: 	&no_cache($r);
10497:     }
10498:     if ($env{'browser.mathml'} && $type eq 'text/html') { $type='text/xml'; }
10499:     unless ($charset) {
10500: 	$charset=&Apache::lonlocal::current_encoding;
10501:     }
10502:     if ($charset) { $type.='; charset='.$charset; }
10503:     if ($r) {
10504: 	$r->content_type($type);
10505:     } else {
10506: 	print("Content-type: $type\n\n");
10507:     }
10508: }
10509: 
10510: =pod
10511: 
10512: =item * &add_to_env($name,$value) 
10513: 
10514: adds $name to the %env hash with value
10515: $value, if $name already exists, the entry is converted to an array
10516: reference and $value is added to the array.
10517: 
10518: =cut
10519: 
10520: sub add_to_env {
10521:   my ($name,$value)=@_;
10522:   if (defined($env{$name})) {
10523:     if (ref($env{$name})) {
10524:       #already have multiple values
10525:       push(@{ $env{$name} },$value);
10526:     } else {
10527:       #first time seeing multiple values, convert hash entry to an arrayref
10528:       my $first=$env{$name};
10529:       undef($env{$name});
10530:       push(@{ $env{$name} },$first,$value);
10531:     }
10532:   } else {
10533:     $env{$name}=$value;
10534:   }
10535: }
10536: 
10537: =pod
10538: 
10539: =item * &get_env_multiple($name) 
10540: 
10541: gets $name from the %env hash, it seemlessly handles the cases where multiple
10542: values may be defined and end up as an array ref.
10543: 
10544: returns an array of values
10545: 
10546: =cut
10547: 
10548: sub get_env_multiple {
10549:     my ($name) = @_;
10550:     my @values;
10551:     if (defined($env{$name})) {
10552:         # exists is it an array
10553:         if (ref($env{$name})) {
10554:             @values=@{ $env{$name} };
10555:         } else {
10556:             $values[0]=$env{$name};
10557:         }
10558:     }
10559:     return(@values);
10560: }
10561: 
10562: sub ask_for_embedded_content {
10563:     my ($actionurl,$state,$allfiles,$codebase,$args)=@_;
10564:     my (%subdependencies,%dependencies,%mapping,%existing,%newfiles,%pathchanges,
10565:         %currsubfile,%unused,$rem);
10566:     my $counter = 0;
10567:     my $numnew = 0;
10568:     my $numremref = 0;
10569:     my $numinvalid = 0;
10570:     my $numpathchg = 0;
10571:     my $numexisting = 0;
10572:     my $numunused = 0;
10573:     my ($output,$upload_output,$toplevel,$url,$udom,$uname,$getpropath,$cdom,$cnum,
10574:         $fileloc,$filename,$delete_output,$modify_output,$title,$symb,$path,$navmap);
10575:     my $heading = &mt('Upload embedded files');
10576:     my $buttontext = &mt('Upload');
10577: 
10578:     if ($env{'request.course.id'}) {
10579:         if ($actionurl eq '/adm/dependencies') {
10580:             $navmap = Apache::lonnavmaps::navmap->new();
10581:         }
10582:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
10583:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
10584:     }
10585:     if (($actionurl eq '/adm/portfolio') ||
10586:         ($actionurl eq '/adm/coursegrp_portfolio')) {
10587:         my $current_path='/';
10588:         if ($env{'form.currentpath'}) {
10589:             $current_path = $env{'form.currentpath'};
10590:         }
10591:         if ($actionurl eq '/adm/coursegrp_portfolio') {
10592:             $udom = $cdom;
10593:             $uname = $cnum;
10594:             $url = '/userfiles/groups/'.$env{'form.group'}.'/portfolio';
10595:         } else {
10596:             $udom = $env{'user.domain'};
10597:             $uname = $env{'user.name'};
10598:             $url = '/userfiles/portfolio';
10599:         }
10600:         $toplevel = $url.'/';
10601:         $url .= $current_path;
10602:         $getpropath = 1;
10603:     } elsif (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank') ||
10604:              ($actionurl eq '/adm/imsimport')) { 
10605:         my ($udom,$uname,$rest) = ($args->{'current_path'} =~ m{/priv/($match_domain)/($match_username)/?(.*)$});
10606:         $url = $Apache::lonnet::perlvar{'lonDocRoot'}."/priv/$udom/$uname/";
10607:         $toplevel = $url;
10608:         if ($rest ne '') {
10609:             $url .= $rest;
10610:         }
10611:     } elsif ($actionurl eq '/adm/coursedocs') {
10612:         if (ref($args) eq 'HASH') {
10613:             $url = $args->{'docs_url'};
10614:             $toplevel = $url;
10615:             if ($args->{'context'} eq 'paste') {
10616:                 ($cdom,$cnum) = ($url =~ m{^\Q/uploaded/\E($match_domain)/($match_courseid)/});
10617:                 ($path) =
10618:                     ($toplevel =~ m{^(\Q/uploaded/$cdom/$cnum/\E(?:docs|supplemental)/(?:default|\d+)/\d+)/});
10619:                 $fileloc = &Apache::lonnet::filelocation('',$toplevel);
10620:                 $fileloc =~ s{^/}{};
10621:             }
10622:         }
10623:     } elsif ($actionurl eq '/adm/dependencies') {
10624:         if ($env{'request.course.id'} ne '') {
10625:             if (ref($args) eq 'HASH') {
10626:                 $url = $args->{'docs_url'};
10627:                 $title = $args->{'docs_title'};
10628:                 $toplevel = $url;
10629:                 unless ($toplevel =~ m{^/}) {
10630:                     $toplevel = "/$url";
10631:                 }
10632:                 ($rem) = ($toplevel =~ m{^(.+/)[^/]+$});
10633:                 if ($toplevel =~ m{^(\Q/uploaded/$cdom/$cnum/portfolio/syllabus\E)}) {
10634:                     $path = $1;
10635:                 } else {
10636:                     ($path) =
10637:                         ($toplevel =~ m{^(\Q/uploaded/$cdom/$cnum/\E(?:docs|supplemental)/(?:default|\d+)/\d+)/});
10638:                 }
10639:                 if ($toplevel=~/^\/*(uploaded|editupload)/) {
10640:                     $fileloc = $toplevel;
10641:                     $fileloc=~ s/^\s*(\S+)\s*$/$1/;
10642:                     my ($udom,$uname,$fname) =
10643:                         ($fileloc=~ m{^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$});
10644:                     $fileloc = propath($udom,$uname).'/userfiles/'.$fname;
10645:                 } else {
10646:                     $fileloc = &Apache::lonnet::filelocation('',$toplevel);
10647:                 }
10648:                 $fileloc =~ s{^/}{};
10649:                 ($filename) = ($fileloc =~ m{.+/([^/]+)$});
10650:                 $heading = &mt('Status of dependencies in [_1]',"$title ($filename)");
10651:             }
10652:         }
10653:     } elsif ($actionurl eq "/public/$cdom/$cnum/syllabus") {
10654:         $udom = $cdom;
10655:         $uname = $cnum;
10656:         $url = "/uploaded/$cdom/$cnum/portfolio/syllabus";
10657:         $toplevel = $url;
10658:         $path = $url;
10659:         $fileloc = &Apache::lonnet::filelocation('',$toplevel).'/';
10660:         $fileloc =~ s{^/}{};
10661:     }
10662:     foreach my $file (keys(%{$allfiles})) {
10663:         my $embed_file;
10664:         if (($path eq "/uploaded/$cdom/$cnum/portfolio/syllabus") && ($file =~ m{^\Q$path/\E(.+)$})) {
10665:             $embed_file = $1;
10666:         } else {
10667:             $embed_file = $file;
10668:         }
10669:         my ($absolutepath,$cleaned_file);
10670:         if ($embed_file =~ m{^\w+://}) {
10671:             $cleaned_file = $embed_file;
10672:             $newfiles{$cleaned_file} = 1;
10673:             $mapping{$cleaned_file} = $embed_file;
10674:         } else {
10675:             $cleaned_file = &clean_path($embed_file);
10676:             if ($embed_file =~ m{^/}) {
10677:                 $absolutepath = $embed_file;
10678:             }
10679:             if ($cleaned_file =~ m{/}) {
10680:                 my ($path,$fname) = ($cleaned_file =~ m{^(.+)/([^/]*)$});
10681:                 $path = &check_for_traversal($path,$url,$toplevel);
10682:                 my $item = $fname;
10683:                 if ($path ne '') {
10684:                     $item = $path.'/'.$fname;
10685:                     $subdependencies{$path}{$fname} = 1;
10686:                 } else {
10687:                     $dependencies{$item} = 1;
10688:                 }
10689:                 if ($absolutepath) {
10690:                     $mapping{$item} = $absolutepath;
10691:                 } else {
10692:                     $mapping{$item} = $embed_file;
10693:                 }
10694:             } else {
10695:                 $dependencies{$embed_file} = 1;
10696:                 if ($absolutepath) {
10697:                     $mapping{$cleaned_file} = $absolutepath;
10698:                 } else {
10699:                     $mapping{$cleaned_file} = $embed_file;
10700:                 }
10701:             }
10702:         }
10703:     }
10704:     my $dirptr = 16384;
10705:     foreach my $path (keys(%subdependencies)) {
10706:         $currsubfile{$path} = {};
10707:         if (($actionurl eq '/adm/portfolio') ||
10708:             ($actionurl eq '/adm/coursegrp_portfolio')) { 
10709:             my ($sublistref,$listerror) =
10710:                 &Apache::lonnet::dirlist($url.$path,$udom,$uname,$getpropath);
10711:             if (ref($sublistref) eq 'ARRAY') {
10712:                 foreach my $line (@{$sublistref}) {
10713:                     my ($file_name,$rest) = split(/\&/,$line,2);
10714:                     $currsubfile{$path}{$file_name} = 1;
10715:                 }
10716:             }
10717:         } elsif (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank')) {
10718:             if (opendir(my $dir,$url.'/'.$path)) {
10719:                 my @subdir_list = grep(!/^\./,readdir($dir));
10720:                 map {$currsubfile{$path}{$_} = 1;} @subdir_list;
10721:             }
10722:         } elsif (($actionurl eq '/adm/dependencies') ||
10723:                  (($actionurl eq '/adm/coursedocs') && (ref($args) eq 'HASH') &&
10724:                   ($args->{'context'} eq 'paste')) ||
10725:                  ($actionurl eq "/public/$cdom/$cnum/syllabus")) {
10726:             if ($env{'request.course.id'} ne '') {
10727:                 my $dir;
10728:                 if ($actionurl eq "/public/$cdom/$cnum/syllabus") {
10729:                     $dir = $fileloc;
10730:                 } else {
10731:                     ($dir) = ($fileloc =~ m{^(.+/)[^/]+$});
10732:                 }
10733:                 if ($dir ne '') {
10734:                     my ($sublistref,$listerror) =
10735:                         &Apache::lonnet::dirlist($dir.$path,$cdom,$cnum,$getpropath,undef,'/');
10736:                     if (ref($sublistref) eq 'ARRAY') {
10737:                         foreach my $line (@{$sublistref}) {
10738:                             my ($file_name,$dom,undef,$testdir,undef,undef,undef,undef,$size,
10739:                                 undef,$mtime)=split(/\&/,$line,12);
10740:                             unless (($testdir&$dirptr) ||
10741:                                     ($file_name =~ /^\.\.?$/)) {
10742:                                 $currsubfile{$path}{$file_name} = [$size,$mtime];
10743:                             }
10744:                         }
10745:                     }
10746:                 }
10747:             }
10748:         }
10749:         foreach my $file (keys(%{$subdependencies{$path}})) {
10750:             if (exists($currsubfile{$path}{$file})) {
10751:                 my $item = $path.'/'.$file;
10752:                 unless ($mapping{$item} eq $item) {
10753:                     $pathchanges{$item} = 1;
10754:                 }
10755:                 $existing{$item} = 1;
10756:                 $numexisting ++;
10757:             } else {
10758:                 $newfiles{$path.'/'.$file} = 1;
10759:             }
10760:         }
10761:         if ($actionurl eq '/adm/dependencies') {
10762:             foreach my $path (keys(%currsubfile)) {
10763:                 if (ref($currsubfile{$path}) eq 'HASH') {
10764:                     foreach my $file (keys(%{$currsubfile{$path}})) {
10765:                          unless ($subdependencies{$path}{$file}) {
10766:                              next if (($rem ne '') &&
10767:                                       (($env{"httpref.$rem"."$path/$file"} ne '') ||
10768:                                        (ref($navmap) &&
10769:                                        (($navmap->getResourceByUrl($rem."$path/$file") ne '') ||
10770:                                         (($file =~ /^(.*\.s?html?)\.bak$/i) &&
10771:                                          ($navmap->getResourceByUrl($rem."$path/$1")))))));
10772:                              $unused{$path.'/'.$file} = 1; 
10773:                          }
10774:                     }
10775:                 }
10776:             }
10777:         }
10778:     }
10779:     my %currfile;
10780:     if (($actionurl eq '/adm/portfolio') ||
10781:         ($actionurl eq '/adm/coursegrp_portfolio')) {
10782:         my ($dirlistref,$listerror) =
10783:             &Apache::lonnet::dirlist($url,$udom,$uname,$getpropath);
10784:         if (ref($dirlistref) eq 'ARRAY') {
10785:             foreach my $line (@{$dirlistref}) {
10786:                 my ($file_name,$rest) = split(/\&/,$line,2);
10787:                 $currfile{$file_name} = 1;
10788:             }
10789:         }
10790:     } elsif (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank')) {
10791:         if (opendir(my $dir,$url)) {
10792:             my @dir_list = grep(!/^\./,readdir($dir));
10793:             map {$currfile{$_} = 1;} @dir_list;
10794:         }
10795:     } elsif (($actionurl eq '/adm/dependencies') ||
10796:              (($actionurl eq '/adm/coursedocs') && (ref($args) eq 'HASH') &&
10797:               ($args->{'context'} eq 'paste')) ||
10798:              ($actionurl eq "/public/$cdom/$cnum/syllabus")) {
10799:         if ($env{'request.course.id'} ne '') {
10800:             my ($dir) = ($fileloc =~ m{^(.+/)[^/]+$});
10801:             if ($dir ne '') {
10802:                 my ($dirlistref,$listerror) =
10803:                     &Apache::lonnet::dirlist($dir,$cdom,$cnum,$getpropath,undef,'/');
10804:                 if (ref($dirlistref) eq 'ARRAY') {
10805:                     foreach my $line (@{$dirlistref}) {
10806:                         my ($file_name,$dom,undef,$testdir,undef,undef,undef,undef,
10807:                             $size,undef,$mtime)=split(/\&/,$line,12);
10808:                         unless (($testdir&$dirptr) ||
10809:                                 ($file_name =~ /^\.\.?$/)) {
10810:                             $currfile{$file_name} = [$size,$mtime];
10811:                         }
10812:                     }
10813:                 }
10814:             }
10815:         }
10816:     }
10817:     foreach my $file (keys(%dependencies)) {
10818:         if (exists($currfile{$file})) {
10819:             unless ($mapping{$file} eq $file) {
10820:                 $pathchanges{$file} = 1;
10821:             }
10822:             $existing{$file} = 1;
10823:             $numexisting ++;
10824:         } else {
10825:             $newfiles{$file} = 1;
10826:         }
10827:     }
10828:     foreach my $file (keys(%currfile)) {
10829:         unless (($file eq $filename) ||
10830:                 ($file eq $filename.'.bak') ||
10831:                 ($dependencies{$file})) {
10832:             if ($actionurl eq '/adm/dependencies') {
10833:                 unless ($toplevel =~ m{^\Q/uploaded/$cdom/$cnum/portfolio/syllabus\E}) {
10834:                     next if (($rem ne '') &&
10835:                              (($env{"httpref.$rem".$file} ne '') ||
10836:                               (ref($navmap) &&
10837:                               (($navmap->getResourceByUrl($rem.$file) ne '') ||
10838:                                (($file =~ /^(.*\.s?html?)\.bak$/i) &&
10839:                                 ($navmap->getResourceByUrl($rem.$1)))))));
10840:                 }
10841:             }
10842:             $unused{$file} = 1;
10843:         }
10844:     }
10845:     if (($actionurl eq '/adm/coursedocs') && (ref($args) eq 'HASH') &&
10846:         ($args->{'context'} eq 'paste')) {
10847:         $counter = scalar(keys(%existing));
10848:         $numpathchg = scalar(keys(%pathchanges));
10849:         return ($output,$counter,$numpathchg,\%existing);
10850:     } elsif (($actionurl eq "/public/$cdom/$cnum/syllabus") &&
10851:              (ref($args) eq 'HASH') && ($args->{'context'} eq 'rewrites')) {
10852:         $counter = scalar(keys(%existing));
10853:         $numpathchg = scalar(keys(%pathchanges));
10854:         return ($output,$counter,$numpathchg,\%existing,\%mapping);
10855:     }
10856:     foreach my $embed_file (sort {lc($a) cmp lc($b)} keys(%newfiles)) {
10857:         if ($actionurl eq '/adm/dependencies') {
10858:             next if ($embed_file =~ m{^\w+://});
10859:         }
10860:         $upload_output .= &start_data_table_row().
10861:                           '<td valign="top"><img src="'.&icon($embed_file).'" />&nbsp;'.
10862:                           '<span class="LC_filename">'.$embed_file.'</span>';
10863:         unless ($mapping{$embed_file} eq $embed_file) {
10864:             $upload_output .= '<br /><span class="LC_info" style="font-size:smaller;">'.
10865:                               &mt('changed from: [_1]',$mapping{$embed_file}).'</span>';
10866:         }
10867:         $upload_output .= '</td>';
10868:         if ($args->{'ignore_remote_references'} && $embed_file =~ m{^\w+://}) { 
10869:             $upload_output.='<td align="right">'.
10870:                             '<span class="LC_info LC_fontsize_medium">'.
10871:                             &mt("URL points to web address").'</span>';
10872:             $numremref++;
10873:         } elsif ($args->{'error_on_invalid_names'}
10874:             && $embed_file ne &Apache::lonnet::clean_filename($embed_file,{'keep_path' => 1,})) {
10875:             $upload_output.='<td align="right"><span class="LC_warning">'.
10876:                             &mt('Invalid characters').'</span>';
10877:             $numinvalid++;
10878:         } else {
10879:             $upload_output .= '<td>'.
10880:                               &embedded_file_element('upload_embedded',$counter,
10881:                                                      $embed_file,\%mapping,
10882:                                                      $allfiles,$codebase,'upload');
10883:             $counter ++;
10884:             $numnew ++;
10885:         }
10886:         $upload_output .= '</td>'.&Apache::loncommon::end_data_table_row()."\n";
10887:     }
10888:     foreach my $embed_file (sort {lc($a) cmp lc($b)} keys(%existing)) {
10889:         if ($actionurl eq '/adm/dependencies') {
10890:             my ($size,$mtime) = &get_dependency_details(\%currfile,\%currsubfile,$embed_file);
10891:             $modify_output .= &start_data_table_row().
10892:                               '<td><a href="'.$path.'/'.$embed_file.'" style="text-decoration:none;">'.
10893:                               '<img src="'.&icon($embed_file).'" border="0" />'.
10894:                               '&nbsp;<span class="LC_filename">'.$embed_file.'</span></a></td>'.
10895:                               '<td>'.$size.'</td>'.
10896:                               '<td>'.$mtime.'</td>'.
10897:                               '<td><label><input type="checkbox" name="mod_upload_dep" '.
10898:                               'onclick="toggleBrowse('."'$counter'".')" id="mod_upload_dep_'.
10899:                               $counter.'" value="'.$counter.'" />'.&mt('Yes').'</label>'.
10900:                               '<div id="moduploaddep_'.$counter.'" style="display:none;">'.
10901:                               &embedded_file_element('upload_embedded',$counter,
10902:                                                      $embed_file,\%mapping,
10903:                                                      $allfiles,$codebase,'modify').
10904:                               '</div></td>'.
10905:                               &end_data_table_row()."\n";
10906:             $counter ++;
10907:         } else {
10908:             $upload_output .= &start_data_table_row().
10909:                               '<td valign="top"><img src="'.&icon($embed_file).'" />&nbsp;'.
10910:                               '<span class="LC_filename">'.$embed_file.'</span></td>'.
10911:                               '<td align="right"><span class="LC_info LC_fontsize_medium">'.&mt('Already exists').'</span></td>'.
10912:                               &Apache::loncommon::end_data_table_row()."\n";
10913:         }
10914:     }
10915:     my $delidx = $counter;
10916:     foreach my $oldfile (sort {lc($a) cmp lc($b)} keys(%unused)) {
10917:         my ($size,$mtime) = &get_dependency_details(\%currfile,\%currsubfile,$oldfile);
10918:         $delete_output .= &start_data_table_row().
10919:                           '<td><img src="'.&icon($oldfile).'" />'.
10920:                           '&nbsp;<span class="LC_filename">'.$oldfile.'</span></td>'.
10921:                           '<td>'.$size.'</td>'.
10922:                           '<td>'.$mtime.'</td>'.
10923:                           '<td><label><input type="checkbox" name="del_upload_dep" '.
10924:                           ' value="'.$delidx.'" />'.&mt('Yes').'</label>'.
10925:                           &embedded_file_element('upload_embedded',$delidx,
10926:                                                  $oldfile,\%mapping,$allfiles,
10927:                                                  $codebase,'delete').'</td>'.
10928:                           &end_data_table_row()."\n"; 
10929:         $numunused ++;
10930:         $delidx ++;
10931:     }
10932:     if ($upload_output) {
10933:         $upload_output = &start_data_table().
10934:                          $upload_output.
10935:                          &end_data_table()."\n";
10936:     }
10937:     if ($modify_output) {
10938:         $modify_output = &start_data_table().
10939:                          &start_data_table_header_row().
10940:                          '<th>'.&mt('File').'</th>'.
10941:                          '<th>'.&mt('Size (KB)').'</th>'.
10942:                          '<th>'.&mt('Modified').'</th>'.
10943:                          '<th>'.&mt('Upload replacement?').'</th>'.
10944:                          &end_data_table_header_row().
10945:                          $modify_output.
10946:                          &end_data_table()."\n";
10947:     }
10948:     if ($delete_output) {
10949:         $delete_output = &start_data_table().
10950:                          &start_data_table_header_row().
10951:                          '<th>'.&mt('File').'</th>'.
10952:                          '<th>'.&mt('Size (KB)').'</th>'.
10953:                          '<th>'.&mt('Modified').'</th>'.
10954:                          '<th>'.&mt('Delete?').'</th>'.
10955:                          &end_data_table_header_row().
10956:                          $delete_output.
10957:                          &end_data_table()."\n";
10958:     }
10959:     my $applies = 0;
10960:     if ($numremref) {
10961:         $applies ++;
10962:     }
10963:     if ($numinvalid) {
10964:         $applies ++;
10965:     }
10966:     if ($numexisting) {
10967:         $applies ++;
10968:     }
10969:     if ($counter || $numunused) {
10970:         $output = '<form name="upload_embedded" action="'.$actionurl.'"'.
10971:                   ' method="post" enctype="multipart/form-data">'."\n".
10972:                   $state.'<h3>'.$heading.'</h3>'; 
10973:         if ($actionurl eq '/adm/dependencies') {
10974:             if ($numnew) {
10975:                 $output .= '<h4>'.&mt('Missing dependencies').'</h4>'.
10976:                            '<p>'.&mt('The following files need to be uploaded.').'</p>'."\n".
10977:                            $upload_output.'<br />'."\n";
10978:             }
10979:             if ($numexisting) {
10980:                 $output .= '<h4>'.&mt('Uploaded dependencies (in use)').'</h4>'.
10981:                            '<p>'.&mt('Upload a new file to replace the one currently in use.').'</p>'."\n".
10982:                            $modify_output.'<br />'."\n";
10983:                            $buttontext = &mt('Save changes');
10984:             }
10985:             if ($numunused) {
10986:                 $output .= '<h4>'.&mt('Unused files').'</h4>'.
10987:                            '<p>'.&mt('The following uploaded files are no longer used.').'</p>'."\n".
10988:                            $delete_output.'<br />'."\n";
10989:                            $buttontext = &mt('Save changes');
10990:             }
10991:         } else {
10992:             $output .= $upload_output.'<br />'."\n";
10993:         }
10994:         $output .= '<input type ="hidden" name="number_embedded_items" value="'.
10995:                    $counter.'" />'."\n";
10996:         if ($actionurl eq '/adm/dependencies') { 
10997:             $output .= '<input type ="hidden" name="number_newemb_items" value="'.
10998:                        $numnew.'" />'."\n";
10999:         } elsif ($actionurl eq '') {
11000:             $output .=  '<input type="hidden" name="phase" value="three" />';
11001:         }
11002:     } elsif ($applies) {
11003:         $output = '<b>'.&mt('Referenced files').'</b>:<br />';
11004:         if ($applies > 1) {
11005:             $output .=  
11006:                 &mt('No dependencies need to be uploaded, as one of the following applies to each reference:').'<ul>';
11007:             if ($numremref) {
11008:                 $output .= '<li>'.&mt('reference is to a URL which points to another server').'</li>'."\n";
11009:             }
11010:             if ($numinvalid) {
11011:                 $output .= '<li>'.&mt('reference is to file with a name containing invalid characters').'</li>'."\n";
11012:             }
11013:             if ($numexisting) {
11014:                 $output .= '<li>'.&mt('reference is to an existing file at the specified location').'</li>'."\n";
11015:             }
11016:             $output .= '</ul><br />';
11017:         } elsif ($numremref) {
11018:             $output .= '<p>'.&mt('None to upload, as all references are to URLs pointing to another server.').'</p>';
11019:         } elsif ($numinvalid) {
11020:             $output .= '<p>'.&mt('None to upload, as all references are to files with names containing invalid characters.').'</p>';
11021:         } elsif ($numexisting) {
11022:             $output .= '<p>'.&mt('None to upload, as all references are to existing files.').'</p>';
11023:         }
11024:         $output .= $upload_output.'<br />';
11025:     }
11026:     my ($pathchange_output,$chgcount);
11027:     $chgcount = $counter;
11028:     if (keys(%pathchanges) > 0) {
11029:         foreach my $embed_file (sort {lc($a) cmp lc($b)} keys(%pathchanges)) {
11030:             if ($counter) {
11031:                 $output .= &embedded_file_element('pathchange',$chgcount,
11032:                                                   $embed_file,\%mapping,
11033:                                                   $allfiles,$codebase,'change');
11034:             } else {
11035:                 $pathchange_output .= 
11036:                     &start_data_table_row().
11037:                     '<td><input type ="checkbox" name="namechange" value="'.
11038:                     $chgcount.'" checked="checked" /></td>'.
11039:                     '<td>'.$mapping{$embed_file}.'</td>'.
11040:                     '<td>'.$embed_file.
11041:                     &embedded_file_element('pathchange',$numpathchg,$embed_file,
11042:                                            \%mapping,$allfiles,$codebase,'change').
11043:                     '</td>'.&end_data_table_row();
11044:             }
11045:             $numpathchg ++;
11046:             $chgcount ++;
11047:         }
11048:     }
11049:     if (($counter) || ($numunused)) {
11050:         if ($numpathchg) {
11051:             $output .= '<input type ="hidden" name="number_pathchange_items" value="'.
11052:                        $numpathchg.'" />'."\n";
11053:         }
11054:         if (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank') || 
11055:             ($actionurl eq '/adm/imsimport')) {
11056:             $output .= '<input type="hidden" name="phase" value="three" />'."\n";
11057:         } elsif ($actionurl eq '/adm/portfolio' || $actionurl eq '/adm/coursegrp_portfolio') {
11058:             $output .= '<input type="hidden" name="action" value="upload_embedded" />';
11059:         } elsif ($actionurl eq '/adm/dependencies') {
11060:             $output .= '<input type="hidden" name="action" value="process_changes" />';
11061:         }
11062:         $output .= '<input type ="submit" value="'.$buttontext.'" />'."\n".'</form>'."\n";
11063:     } elsif ($numpathchg) {
11064:         my %pathchange = ();
11065:         $output .= &modify_html_form('pathchange',$actionurl,$state,\%pathchange,$pathchange_output);
11066:         if (($actionurl eq '/adm/portfolio') || ($actionurl eq '/adm/coursegrp_portfolio')) {
11067:             $output .= '<p>'.&mt('or').'</p>'; 
11068:         }
11069:     }
11070:     return ($output,$counter,$numpathchg);
11071: }
11072: 
11073: =pod
11074: 
11075: =item * clean_path($name)
11076: 
11077: Performs clean-up of directories, subdirectories and filename in an
11078: embedded object, referenced in an HTML file which is being uploaded
11079: to a course or portfolio, where
11080: "Upload embedded images/multimedia files if HTML file" checkbox was
11081: checked.
11082: 
11083: Clean-up is similar to replacements in lonnet::clean_filename()
11084: except each / between sub-directory and next level is preserved.
11085: 
11086: =cut
11087: 
11088: sub clean_path {
11089:     my ($embed_file) = @_;
11090:     $embed_file =~s{^/+}{};
11091:     my @contents;
11092:     if ($embed_file =~ m{/}) {
11093:         @contents = split(/\//,$embed_file);
11094:     } else {
11095:         @contents = ($embed_file);
11096:     }
11097:     my $lastidx = scalar(@contents)-1;
11098:     for (my $i=0; $i<=$lastidx; $i++) {
11099:         $contents[$i]=~s{\\}{/}g;
11100:         $contents[$i]=~s/\s+/\_/g;
11101:         $contents[$i]=~s{[^/\w\.\-]}{}g;
11102:         if ($i == $lastidx) {
11103:             $contents[$i]=~s/\.(\d+)(?=\.)/_$1/g;
11104:         }
11105:     }
11106:     if ($lastidx > 0) {
11107:         return join('/',@contents);
11108:     } else {
11109:         return $contents[0];
11110:     }
11111: }
11112: 
11113: sub embedded_file_element {
11114:     my ($context,$num,$embed_file,$mapping,$allfiles,$codebase,$type) = @_;
11115:     return unless ((ref($mapping) eq 'HASH') && (ref($allfiles) eq 'HASH') &&
11116:                    (ref($codebase) eq 'HASH'));
11117:     my $output;
11118:     if (($context eq 'upload_embedded') && ($type ne 'delete')) {
11119:        $output = '<input name="embedded_item_'.$num.'" type="file" value="" />'."\n";
11120:     }
11121:     $output .= '<input name="embedded_orig_'.$num.'" type="hidden" value="'.
11122:                &escape($embed_file).'" />';
11123:     unless (($context eq 'upload_embedded') && 
11124:             ($mapping->{$embed_file} eq $embed_file)) {
11125:         $output .='
11126:         <input name="embedded_ref_'.$num.'" type="hidden" value="'.&escape($mapping->{$embed_file}).'" />';
11127:     }
11128:     my $attrib;
11129:     if (ref($allfiles->{$mapping->{$embed_file}}) eq 'ARRAY') {
11130:         $attrib = &escape(join(':',@{$allfiles->{$mapping->{$embed_file}}}));
11131:     }
11132:     $output .=
11133:         "\n\t\t".
11134:         '<input name="embedded_attrib_'.$num.'" type="hidden" value="'.
11135:         $attrib.'" />';
11136:     if (exists($codebase->{$mapping->{$embed_file}})) {
11137:         $output .=
11138:             "\n\t\t".
11139:             '<input name="codebase_'.$num.'" type="hidden" value="'.
11140:             &escape($codebase->{$mapping->{$embed_file}}).'" />';
11141:     }
11142:     return $output;
11143: }
11144: 
11145: sub get_dependency_details {
11146:     my ($currfile,$currsubfile,$embed_file) = @_;
11147:     my ($size,$mtime,$showsize,$showmtime);
11148:     if ((ref($currfile) eq 'HASH') && (ref($currsubfile))) {
11149:         if ($embed_file =~ m{/}) {
11150:             my ($path,$fname) = split(/\//,$embed_file);
11151:             if (ref($currsubfile->{$path}{$fname}) eq 'ARRAY') {
11152:                 ($size,$mtime) = @{$currsubfile->{$path}{$fname}};
11153:             }
11154:         } else {
11155:             if (ref($currfile->{$embed_file}) eq 'ARRAY') {
11156:                 ($size,$mtime) = @{$currfile->{$embed_file}};
11157:             }
11158:         }
11159:         $showsize = $size/1024.0;
11160:         $showsize = sprintf("%.1f",$showsize);
11161:         if ($mtime > 0) {
11162:             $showmtime = &Apache::lonlocal::locallocaltime($mtime);
11163:         }
11164:     }
11165:     return ($showsize,$showmtime);
11166: }
11167: 
11168: sub ask_embedded_js {
11169:     return <<"END";
11170: <script type="text/javascript"">
11171: // <![CDATA[
11172: function toggleBrowse(counter) {
11173:     var chkboxid = document.getElementById('mod_upload_dep_'+counter);
11174:     var fileid = document.getElementById('embedded_item_'+counter);
11175:     var uploaddivid = document.getElementById('moduploaddep_'+counter);
11176:     if (chkboxid.checked == true) {
11177:         uploaddivid.style.display='block';
11178:     } else {
11179:         uploaddivid.style.display='none';
11180:         fileid.value = '';
11181:     }
11182: }
11183: // ]]>
11184: </script>
11185: 
11186: END
11187: }
11188: 
11189: sub upload_embedded {
11190:     my ($context,$dirpath,$uname,$udom,$dir_root,$url_root,$group,$disk_quota,
11191:         $current_disk_usage,$hiddenstate,$actionurl) = @_;
11192:     my (%pathchange,$output,$modifyform,$footer,$returnflag);
11193:     for (my $i=0; $i<$env{'form.number_embedded_items'}; $i++) {
11194:         next if (!exists($env{'form.embedded_item_'.$i.'.filename'}));
11195:         my $orig_uploaded_filename =
11196:             $env{'form.embedded_item_'.$i.'.filename'};
11197:         foreach my $type ('orig','ref','attrib','codebase') {
11198:             if ($env{'form.embedded_'.$type.'_'.$i} ne '') {
11199:                 $env{'form.embedded_'.$type.'_'.$i} =
11200:                     &unescape($env{'form.embedded_'.$type.'_'.$i});
11201:             }
11202:         }
11203:         my ($path,$fname) =
11204:             ($env{'form.embedded_orig_'.$i} =~ m{(.*/)([^/]*)});
11205:         # no path, whole string is fname
11206:         if (!$fname) { $fname = $env{'form.embedded_orig_'.$i} };
11207:         $fname = &Apache::lonnet::clean_filename($fname);
11208:         # See if there is anything left
11209:         next if ($fname eq '');
11210: 
11211:         # Check if file already exists as a file or directory.
11212:         my ($state,$msg);
11213:         if ($context eq 'portfolio') {
11214:             my $port_path = $dirpath;
11215:             if ($group ne '') {
11216:                 $port_path = "groups/$group/$port_path";
11217:             }
11218:             ($state,$msg) = &check_for_upload($env{'form.currentpath'}.$path,
11219:                                               $fname,$group,'embedded_item_'.$i,
11220:                                               $dir_root,$port_path,$disk_quota,
11221:                                               $current_disk_usage,$uname,$udom);
11222:             if ($state eq 'will_exceed_quota'
11223:                 || $state eq 'file_locked') {
11224:                 $output .= $msg;
11225:                 next;
11226:             }
11227:         } elsif (($context eq 'author') || ($context eq 'testbank')) {
11228:             ($state,$msg) = &check_for_existing($path,$fname,'embedded_item_'.$i);
11229:             if ($state eq 'exists') {
11230:                 $output .= $msg;
11231:                 next;
11232:             }
11233:         }
11234:         # Check if extension is valid
11235:         if (($fname =~ /\.(\w+)$/) &&
11236:             (&Apache::loncommon::fileembstyle($1) eq 'hdn')) {
11237:             $output .= &mt('Invalid file extension ([_1]) - reserved for internal use.',$1)
11238:                       .' '.&mt('Rename the file with a different extension and re-upload.').'<br />';
11239:             next;
11240:         } elsif (($fname =~ /\.(\w+)$/) &&
11241:                  (!defined(&Apache::loncommon::fileembstyle($1)))) {
11242:             $output .= &mt('Unrecognized file extension ([_1]) - rename the file with a proper extension and re-upload.',$1).'<br />';
11243:             next;
11244:         } elsif ($fname=~/\.(\d+)\.(\w+)$/) {
11245:             $output .= &mt('Filename not allowed - rename the file to remove the number immediately before the file extension([_1]) and re-upload.',$2).'<br />';
11246:             next;
11247:         }
11248:         $env{'form.embedded_item_'.$i.'.filename'}=$fname;
11249:         my $subdir = $path;
11250:         $subdir =~ s{/+$}{};
11251:         if ($context eq 'portfolio') {
11252:             my $result;
11253:             if ($state eq 'existingfile') {
11254:                 $result=
11255:                     &Apache::lonnet::userfileupload('embedded_item_'.$i,'existingfile',
11256:                                                     $dirpath.$env{'form.currentpath'}.$subdir);
11257:             } else {
11258:                 $result=
11259:                     &Apache::lonnet::userfileupload('embedded_item_'.$i,'',
11260:                                                     $dirpath.
11261:                                                     $env{'form.currentpath'}.$subdir);
11262:                 if ($result !~ m|^/uploaded/|) {
11263:                     $output .= '<span class="LC_error">'
11264:                                .&mt('An error occurred ([_1]) while trying to upload [_2] for embedded element [_3].'
11265:                                ,$result,$orig_uploaded_filename,$env{'form.embedded_orig_'.$i})
11266:                                .'</span><br />';
11267:                     next;
11268:                 } else {
11269:                     $output .= &mt('Uploaded [_1]','<span class="LC_filename">'.
11270:                                $path.$fname.'</span>').'<br />';     
11271:                 }
11272:             }
11273:         } elsif (($context eq 'coursedoc') || ($context eq 'syllabus')) {
11274:             my $extendedsubdir = $dirpath.'/'.$subdir;
11275:             $extendedsubdir =~ s{/+$}{};
11276:             my $result =
11277:                 &Apache::lonnet::userfileupload('embedded_item_'.$i,$context,$extendedsubdir);
11278:             if ($result !~ m|^/uploaded/|) {
11279:                 $output .= '<span class="LC_error">'
11280:                            .&mt('An error occurred ([_1]) while trying to upload [_2] for embedded element [_3].'
11281:                            ,$result,$orig_uploaded_filename,$env{'form.embedded_orig_'.$i})
11282:                            .'</span><br />';
11283:                     next;
11284:             } else {
11285:                 $output .= &mt('Uploaded [_1]','<span class="LC_filename">'.
11286:                            $path.$fname.'</span>').'<br />';
11287:                 if ($context eq 'syllabus') {
11288:                     &Apache::lonnet::make_public_indefinitely($result);
11289:                 }
11290:             }
11291:         } else {
11292: # Save the file
11293:             my $target = $env{'form.embedded_item_'.$i};
11294:             my $fullpath = $dir_root.$dirpath.'/'.$path;
11295:             my $dest = $fullpath.$fname;
11296:             my $url = $url_root.$dirpath.'/'.$path.$fname;
11297:             my @parts=split(/\//,"$dirpath/$path");
11298:             my $count;
11299:             my $filepath = $dir_root;
11300:             foreach my $subdir (@parts) {
11301:                 $filepath .= "/$subdir";
11302:                 if (!-e $filepath) {
11303:                     mkdir($filepath,0770);
11304:                 }
11305:             }
11306:             my $fh;
11307:             if (!open($fh,'>'.$dest)) {
11308:                 &Apache::lonnet::logthis('Failed to create '.$dest);
11309:                 $output .= '<span class="LC_error">'.
11310:                            &mt('An error occurred while trying to upload [_1] for embedded element [_2].',
11311:                                $orig_uploaded_filename,$env{'form.embedded_orig_'.$i}).
11312:                            '</span><br />';
11313:             } else {
11314:                 if (!print $fh $env{'form.embedded_item_'.$i}) {
11315:                     &Apache::lonnet::logthis('Failed to write to '.$dest);
11316:                     $output .= '<span class="LC_error">'.
11317:                               &mt('An error occurred while writing the file [_1] for embedded element [_2].',
11318:                                   $orig_uploaded_filename,$env{'form.embedded_orig_'.$i}).
11319:                               '</span><br />';
11320:                 } else {
11321:                     $output .= &mt('Uploaded [_1]','<span class="LC_filename">'.
11322:                                $url.'</span>').'<br />';
11323:                     unless ($context eq 'testbank') {
11324:                         $footer .= &mt('View embedded file: [_1]',
11325:                                        '<a href="'.$url.'">'.$fname.'</a>').'<br />';
11326:                     }
11327:                 }
11328:                 close($fh);
11329:             }
11330:         }
11331:         if ($env{'form.embedded_ref_'.$i}) {
11332:             $pathchange{$i} = 1;
11333:         }
11334:     }
11335:     if ($output) {
11336:         $output = '<p>'.$output.'</p>';
11337:     }
11338:     $output .= &modify_html_form('upload_embedded',$actionurl,$hiddenstate,\%pathchange);
11339:     $returnflag = 'ok';
11340:     my $numpathchgs = scalar(keys(%pathchange));
11341:     if ($numpathchgs > 0) {
11342:         if ($context eq 'portfolio') {
11343:             $output .= '<p>'.&mt('or').'</p>';
11344:         } elsif ($context eq 'testbank') {
11345:             $output .=  '<p>'.&mt('Or [_1]continue[_2] the testbank import without modifying the reference(s).',
11346:                                   '<a href="javascript:document.testbankForm.submit();">','</a>').'</p>';
11347:             $returnflag = 'modify_orightml';
11348:         }
11349:     }
11350:     return ($output.$footer,$returnflag,$numpathchgs);
11351: }
11352: 
11353: sub modify_html_form {
11354:     my ($context,$actionurl,$hiddenstate,$pathchange,$pathchgtable) = @_;
11355:     my $end = 0;
11356:     my $modifyform;
11357:     if ($context eq 'upload_embedded') {
11358:         return unless (ref($pathchange) eq 'HASH');
11359:         if ($env{'form.number_embedded_items'}) {
11360:             $end += $env{'form.number_embedded_items'};
11361:         }
11362:         if ($env{'form.number_pathchange_items'}) {
11363:             $end += $env{'form.number_pathchange_items'};
11364:         }
11365:         if ($end) {
11366:             for (my $i=0; $i<$end; $i++) {
11367:                 if ($i < $env{'form.number_embedded_items'}) {
11368:                     next unless($pathchange->{$i});
11369:                 }
11370:                 $modifyform .=
11371:                     &start_data_table_row().
11372:                     '<td><input type ="checkbox" name="namechange" value="'.$i.'" '.
11373:                     'checked="checked" /></td>'.
11374:                     '<td>'.$env{'form.embedded_ref_'.$i}.
11375:                     '<input type="hidden" name="embedded_ref_'.$i.'" value="'.
11376:                     &escape($env{'form.embedded_ref_'.$i}).'" />'.
11377:                     '<input type="hidden" name="embedded_codebase_'.$i.'" value="'.
11378:                     &escape($env{'form.embedded_codebase_'.$i}).'" />'.
11379:                     '<input type="hidden" name="embedded_attrib_'.$i.'" value="'.
11380:                     &escape($env{'form.embedded_attrib_'.$i}).'" /></td>'.
11381:                     '<td>'.$env{'form.embedded_orig_'.$i}.
11382:                     '<input type="hidden" name="embedded_orig_'.$i.'" value="'.
11383:                     &escape($env{'form.embedded_orig_'.$i}).'" /></td>'.
11384:                     &end_data_table_row();
11385:             }
11386:         }
11387:     } else {
11388:         $modifyform = $pathchgtable;
11389:         if (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank')) {
11390:             $hiddenstate .= '<input type="hidden" name="phase" value="four" />';
11391:         } elsif (($actionurl eq '/adm/portfolio') || ($actionurl eq '/adm/coursegrp_portfolio')) {
11392:             $hiddenstate .= '<input type="hidden" name="action" value="modify_orightml" />';
11393:         }
11394:     }
11395:     if ($modifyform) {
11396:         if ($actionurl eq '/adm/dependencies') {
11397:             $hiddenstate .= '<input type="hidden" name="action" value="modifyhrefs" />';
11398:         }
11399:         return '<h3>'.&mt('Changes in content of HTML file required').'</h3>'."\n".
11400:                '<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".
11401:                '<li>'.&mt('For consistency between the reference(s) and the location of the corresponding stored file within LON-CAPA.').'</li>'."\n".
11402:                '<li>'.&mt('To change absolute paths to relative paths, or replace directory traversal via "../" within the original reference.').'</li>'."\n".
11403:                '</ol></p>'."\n".'<p>'.
11404:                &mt('LON-CAPA can make the required changes to your HTML file.').'</p>'."\n".
11405:                '<form method="post" name="refchanger" action="'.$actionurl.'">'.
11406:                &start_data_table()."\n".
11407:                &start_data_table_header_row().
11408:                '<th>'.&mt('Change?').'</th>'.
11409:                '<th>'.&mt('Current reference').'</th>'.
11410:                '<th>'.&mt('Required reference').'</th>'.
11411:                &end_data_table_header_row()."\n".
11412:                $modifyform.
11413:                &end_data_table().'<br />'."\n".$hiddenstate.
11414:                '<input type="submit" name="pathchanges" value="'.&mt('Modify HTML file').'" />'.
11415:                '</form>'."\n";
11416:     }
11417:     return;
11418: }
11419: 
11420: sub modify_html_refs {
11421:     my ($context,$dirpath,$uname,$udom,$dir_root,$url) = @_;
11422:     my $container;
11423:     if ($context eq 'portfolio') {
11424:         $container = $env{'form.container'};
11425:     } elsif ($context eq 'coursedoc') {
11426:         $container = $env{'form.primaryurl'};
11427:     } elsif ($context eq 'manage_dependencies') {
11428:         (undef,undef,$container) = &Apache::lonnet::decode_symb($env{'form.symb'});
11429:         $container = "/$container";
11430:     } elsif ($context eq 'syllabus') {
11431:         $container = $url;
11432:     } else {
11433:         $container = $Apache::lonnet::perlvar{'lonDocRoot'}.$env{'form.filename'};
11434:     }
11435:     my (%allfiles,%codebase,$output,$content);
11436:     my @changes = &get_env_multiple('form.namechange');
11437:     unless ((@changes > 0)  || ($context eq 'syllabus')) {
11438:         if (wantarray) {
11439:             return ('',0,0); 
11440:         } else {
11441:             return;
11442:         }
11443:     }
11444:     if (($context eq 'portfolio') || ($context eq 'coursedoc') || 
11445:         ($context eq 'manage_dependencies') || ($context eq 'syllabus')) {
11446:         unless ($container =~ m{^/uploaded/\Q$udom\E/\Q$uname\E/}) {
11447:             if (wantarray) {
11448:                 return ('',0,0);
11449:             } else {
11450:                 return;
11451:             }
11452:         } 
11453:         $content = &Apache::lonnet::getfile($container);
11454:         if ($content eq '-1') {
11455:             if (wantarray) {
11456:                 return ('',0,0);
11457:             } else {
11458:                 return;
11459:             }
11460:         }
11461:     } else {
11462:         unless ($container =~ /^\Q$dir_root\E/) {
11463:             if (wantarray) {
11464:                 return ('',0,0);
11465:             } else {
11466:                 return;
11467:             }
11468:         } 
11469:         if (open(my $fh,'<',$container)) {
11470:             $content = join('', <$fh>);
11471:             close($fh);
11472:         } else {
11473:             if (wantarray) {
11474:                 return ('',0,0);
11475:             } else {
11476:                 return;
11477:             }
11478:         }
11479:     }
11480:     my ($count,$codebasecount) = (0,0);
11481:     my $mm = new File::MMagic;
11482:     my $mime_type = $mm->checktype_contents($content);
11483:     if ($mime_type eq 'text/html') {
11484:         my $parse_result = 
11485:             &Apache::lonnet::extract_embedded_items($container,\%allfiles,
11486:                                                     \%codebase,\$content);
11487:         if ($parse_result eq 'ok') {
11488:             foreach my $i (@changes) {
11489:                 my $orig = &unescape($env{'form.embedded_orig_'.$i});
11490:                 my $ref = &unescape($env{'form.embedded_ref_'.$i});
11491:                 if ($allfiles{$ref}) {
11492:                     my $newname =  $orig;
11493:                     my ($attrib_regexp,$codebase);
11494:                     $attrib_regexp = &unescape($env{'form.embedded_attrib_'.$i});
11495:                     if ($attrib_regexp =~ /:/) {
11496:                         $attrib_regexp =~ s/\:/|/g;
11497:                     }
11498:                     if ($content =~ m{($attrib_regexp\s*=\s*['"]?)\Q$ref\E(['"]?)}) {
11499:                         my $numchg = ($content =~ s{($attrib_regexp\s*=\s*['"]?)\Q$ref\E(['"]?)}{$1$newname$2}gi);
11500:                         $count += $numchg;
11501:                         $allfiles{$newname} = $allfiles{$ref};
11502:                         delete($allfiles{$ref});
11503:                     }
11504:                     if ($env{'form.embedded_codebase_'.$i} ne '') {
11505:                         $codebase = &unescape($env{'form.embedded_codebase_'.$i});
11506:                         my $numchg = ($content =~ s/(codebase\s*=\s*["']?)\Q$codebase\E(["']?)/$1.$2/i); #' stupid emacs
11507:                         $codebasecount ++;
11508:                     }
11509:                 }
11510:             }
11511:             my $skiprewrites;
11512:             if ($count || $codebasecount) {
11513:                 my $saveresult;
11514:                 if (($context eq 'portfolio') || ($context eq 'coursedoc') || 
11515:                     ($context eq 'manage_dependencies') || ($context eq 'syllabus')) {
11516:                     my $url = &Apache::lonnet::store_edited_file($container,$content,$udom,$uname,\$saveresult);
11517:                     if ($url eq $container) {
11518:                         my ($fname) = ($container =~ m{/([^/]+)$});
11519:                         $output = '<p>'.&mt('Updated [quant,_1,reference] in [_2].',
11520:                                             $count,'<span class="LC_filename">'.
11521:                                             $fname.'</span>').'</p>';
11522:                     } else {
11523:                          $output = '<p class="LC_error">'.
11524:                                    &mt('Error: update failed for: [_1].',
11525:                                    '<span class="LC_filename">'.
11526:                                    $container.'</span>').'</p>';
11527:                     }
11528:                     if ($context eq 'syllabus') {
11529:                         unless ($saveresult eq 'ok') {
11530:                             $skiprewrites = 1;
11531:                         }
11532:                     }
11533:                 } else {
11534:                     if (open(my $fh,'>',$container)) {
11535:                         print $fh $content;
11536:                         close($fh);
11537:                         $output = '<p>'.&mt('Updated [quant,_1,reference] in [_2].',
11538:                                   $count,'<span class="LC_filename">'.
11539:                                   $container.'</span>').'</p>';
11540:                     } else {
11541:                          $output = '<p class="LC_error">'.
11542:                                    &mt('Error: could not update [_1].',
11543:                                    '<span class="LC_filename">'.
11544:                                    $container.'</span>').'</p>';
11545:                     }
11546:                 }
11547:             }
11548:             if (($context eq 'syllabus') && (!$skiprewrites)) {
11549:                 my ($actionurl,$state);
11550:                 $actionurl = "/public/$udom/$uname/syllabus";
11551:                 my ($ignore,$num,$numpathchanges,$existing,$mapping) =
11552:                     &ask_for_embedded_content($actionurl,$state,\%allfiles,
11553:                                               \%codebase,
11554:                                               {'context' => 'rewrites',
11555:                                                'ignore_remote_references' => 1,});
11556:                 if (ref($mapping) eq 'HASH') {
11557:                     my $rewrites = 0;
11558:                     foreach my $key (keys(%{$mapping})) {
11559:                         next if ($key =~ m{^https?://});
11560:                         my $ref = $mapping->{$key};
11561:                         my $newname = "/uploaded/$udom/$uname/portfolio/syllabus/$key";
11562:                         my $attrib;
11563:                         if (ref($allfiles{$mapping->{$key}}) eq 'ARRAY') {
11564:                             $attrib = join('|',@{$allfiles{$mapping->{$key}}});
11565:                         }
11566:                         if ($content =~ m{($attrib\s*=\s*['"]?)\Q$ref\E(['"]?)}) {
11567:                             my $numchg = ($content =~ s{($attrib\s*=\s*['"]?)\Q$ref\E(['"]?)}{$1$newname$2}gi);
11568:                             $rewrites += $numchg;
11569:                         }
11570:                     }
11571:                     if ($rewrites) {
11572:                         my $saveresult;
11573:                         my $url = &Apache::lonnet::store_edited_file($container,$content,$udom,$uname,\$saveresult);
11574:                         if ($url eq $container) {
11575:                             my ($fname) = ($container =~ m{/([^/]+)$});
11576:                             $output .= '<p>'.&mt('Rewrote [quant,_1,link] as [quant,_1,absolute link] in [_2].',
11577:                                             $count,'<span class="LC_filename">'.
11578:                                             $fname.'</span>').'</p>';
11579:                         } else {
11580:                             $output .= '<p class="LC_error">'.
11581:                                        &mt('Error: could not update links in [_1].',
11582:                                        '<span class="LC_filename">'.
11583:                                        $container.'</span>').'</p>';
11584: 
11585:                         }
11586:                     }
11587:                 }
11588:             }
11589:         } else {
11590:             &logthis('Failed to parse '.$container.
11591:                      ' to modify references: '.$parse_result);
11592:         }
11593:     }
11594:     if (wantarray) {
11595:         return ($output,$count,$codebasecount);
11596:     } else {
11597:         return $output;
11598:     }
11599: }
11600: 
11601: sub check_for_existing {
11602:     my ($path,$fname,$element) = @_;
11603:     my ($state,$msg);
11604:     if (-d $path.'/'.$fname) {
11605:         $state = 'exists';
11606:         $msg = &mt('Unable to upload [_1]. A directory by that name was found in [_2].','<span class="LC_filename">'.$fname.'</span>',$path);
11607:     } elsif (-e $path.'/'.$fname) {
11608:         $state = 'exists';
11609:         $msg = &mt('Unable to upload [_1]. A file by that name was found in [_2].','<span class="LC_filename">'.$fname.'</span>',$path);
11610:     }
11611:     if ($state eq 'exists') {
11612:         $msg = '<span class="LC_error">'.$msg.'</span><br />';
11613:     }
11614:     return ($state,$msg);
11615: }
11616: 
11617: sub check_for_upload {
11618:     my ($path,$fname,$group,$element,$portfolio_root,$port_path,
11619:         $disk_quota,$current_disk_usage,$uname,$udom) = @_;
11620:     my $filesize = length($env{'form.'.$element});
11621:     if (!$filesize) {
11622:         my $msg = '<span class="LC_error">'.
11623:                   &mt('Unable to upload [_1]. (size = [_2] bytes)', 
11624:                       '<span class="LC_filename">'.$fname.'</span>',
11625:                       $filesize).'<br />'.
11626:                   &mt('Either the file you attempted to upload was empty, or your web browser was unable to read its contents.').'<br />'.
11627:                   '</span>';
11628:         return ('zero_bytes',$msg);
11629:     }
11630:     $filesize =  $filesize/1000; #express in k (1024?)
11631:     my $getpropath = 1;
11632:     my ($dirlistref,$listerror) =
11633:          &Apache::lonnet::dirlist($portfolio_root.$path,$udom,$uname,$getpropath);
11634:     my $found_file = 0;
11635:     my $locked_file = 0;
11636:     my @lockers;
11637:     my $navmap;
11638:     if ($env{'request.course.id'}) {
11639:         $navmap = Apache::lonnavmaps::navmap->new();
11640:     }
11641:     if (ref($dirlistref) eq 'ARRAY') {
11642:         foreach my $line (@{$dirlistref}) {
11643:             my ($file_name,$rest)=split(/\&/,$line,2);
11644:             if ($file_name eq $fname){
11645:                 $file_name = $path.$file_name;
11646:                 if ($group ne '') {
11647:                     $file_name = $group.$file_name;
11648:                 }
11649:                 $found_file = 1;
11650:                 if (&Apache::lonnet::is_locked($file_name,$udom,$uname,\@lockers) eq 'true') {
11651:                     foreach my $lock (@lockers) {
11652:                         if (ref($lock) eq 'ARRAY') {
11653:                             my ($symb,$crsid) = @{$lock};
11654:                             if ($crsid eq $env{'request.course.id'}) {
11655:                                 if (ref($navmap)) {
11656:                                     my $res = $navmap->getBySymb($symb);
11657:                                     foreach my $part (@{$res->parts()}) { 
11658:                                         my ($slot_status,$slot_time,$slot_name)=$res->check_for_slot($part);
11659:                                         unless (($slot_status == $res->RESERVED) ||
11660:                                                 ($slot_status == $res->RESERVED_LOCATION)) {
11661:                                             $locked_file = 1;
11662:                                         }
11663:                                     }
11664:                                 } else {
11665:                                     $locked_file = 1;
11666:                                 }
11667:                             } else {
11668:                                 $locked_file = 1;
11669:                             }
11670:                         }
11671:                    }
11672:                 } else {
11673:                     my @info = split(/\&/,$rest);
11674:                     my $currsize = $info[6]/1000;
11675:                     if ($currsize < $filesize) {
11676:                         my $extra = $filesize - $currsize;
11677:                         if (($current_disk_usage + $extra) > $disk_quota) {
11678:                             my $msg = '<p class="LC_warning">'.
11679:                                       &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.',
11680:                                           '<span class="LC_filename">'.$fname.'</span>',$filesize,$currsize).'</p>'.
11681:                                       '<p>'.&mt('Disk quota is [_1] kilobytes. Your current disk usage is [_2] kilobytes.',
11682:                                                    $disk_quota,$current_disk_usage).'</p>';
11683:                             return ('will_exceed_quota',$msg);
11684:                         }
11685:                     }
11686:                 }
11687:             }
11688:         }
11689:     }
11690:     if (($current_disk_usage + $filesize) > $disk_quota){
11691:         my $msg = '<p class="LC_warning">'.
11692:                 &mt('Unable to upload [_1]. (size = [_2] kilobytes). Disk quota will be exceeded.','<span class="LC_filename">'.$fname.'</span>',$filesize).'</p>'.
11693:                   '<p>'.&mt('Disk quota is [_1] kilobytes. Your current disk usage is [_2] kilobytes.',$disk_quota,$current_disk_usage).'</p>';
11694:         return ('will_exceed_quota',$msg);
11695:     } elsif ($found_file) {
11696:         if ($locked_file) {
11697:             my $msg = '<p class="LC_warning">';
11698:             $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>');
11699:             $msg .= '</p>';
11700:             $msg .= &mt('You will be able to rename or delete existing [_1] after a grade has been assigned.','<span class="LC_filename">'.$fname.'</span>');
11701:             return ('file_locked',$msg);
11702:         } else {
11703:             my $msg = '<p class="LC_error">';
11704:             $msg .= &mt(' A file by that name: [_1] was found in [_2].','<span class="LC_filename">'.$fname.'</span>',$port_path.$env{'form.currentpath'});
11705:             $msg .= '</p>';
11706:             return ('existingfile',$msg);
11707:         }
11708:     }
11709: }
11710: 
11711: sub check_for_traversal {
11712:     my ($path,$url,$toplevel) = @_;
11713:     my @parts=split(/\//,$path);
11714:     my $cleanpath;
11715:     my $fullpath = $url;
11716:     for (my $i=0;$i<@parts;$i++) {
11717:         next if ($parts[$i] eq '.');
11718:         if ($parts[$i] eq '..') {
11719:             $fullpath =~ s{([^/]+/)$}{};
11720:         } else {
11721:             $fullpath .= $parts[$i].'/';
11722:         }
11723:     }
11724:     if ($fullpath =~ /^\Q$url\E(.*)$/) {
11725:         $cleanpath = $1;
11726:     } elsif ($fullpath =~ /^\Q$toplevel\E(.*)$/) {
11727:         my $curr_toprel = $1;
11728:         my @parts = split(/\//,$curr_toprel);
11729:         my ($url_toprel) = ($url =~ /^\Q$toplevel\E(.*)$/);
11730:         my @urlparts = split(/\//,$url_toprel);
11731:         my $doubledots;
11732:         my $startdiff = -1;
11733:         for (my $i=0; $i<@urlparts; $i++) {
11734:             if ($startdiff == -1) {
11735:                 unless ($urlparts[$i] eq $parts[$i]) {
11736:                     $startdiff = $i;
11737:                     $doubledots .= '../';
11738:                 }
11739:             } else {
11740:                 $doubledots .= '../';
11741:             }
11742:         }
11743:         if ($startdiff > -1) {
11744:             $cleanpath = $doubledots;
11745:             for (my $i=$startdiff; $i<@parts; $i++) {
11746:                 $cleanpath .= $parts[$i].'/';
11747:             }
11748:         }
11749:     }
11750:     $cleanpath =~ s{(/)$}{};
11751:     return $cleanpath;
11752: }
11753: 
11754: sub is_archive_file {
11755:     my ($mimetype) = @_;
11756:     if (($mimetype eq 'application/octet-stream') ||
11757:         ($mimetype eq 'application/x-stuffit') ||
11758:         ($mimetype =~ m{^application/(x\-)?(compressed|tar|zip|tgz|gz|gtar|gzip|gunzip|bz|bz2|bzip2)})) {
11759:         return 1;
11760:     }
11761:     return;
11762: }
11763: 
11764: sub decompress_form {
11765:     my ($mimetype,$archiveurl,$action,$noextract,$hiddenelements,$dirlist) = @_;
11766:     my %lt = &Apache::lonlocal::texthash (
11767:         this => 'This file is an archive file.',
11768:         camt => 'This file is a Camtasia archive file.',
11769:         itsc => 'Its contents are as follows:',
11770:         youm => 'You may wish to extract its contents.',
11771:         extr => 'Extract contents',
11772:         auto => 'LON-CAPA can process the files automatically, or you can decide how each should be handled.',
11773:         proa => 'Process automatically?',
11774:         yes  => 'Yes',
11775:         no   => 'No',
11776:         fold => 'Title for folder containing movie',
11777:         movi => 'Title for page containing embedded movie', 
11778:     );
11779:     my $fileloc = &Apache::lonnet::filelocation(undef,$archiveurl);
11780:     my ($is_camtasia,$topdir,%toplevel,@paths);
11781:     my $info = &list_archive_contents($fileloc,\@paths);
11782:     if (@paths) {
11783:         foreach my $path (@paths) {
11784:             $path =~ s{^/}{};
11785:             if ($path =~ m{^([^/]+)/$}) {
11786:                 $topdir = $1;
11787:             }
11788:             if ($path =~ m{^([^/]+)/}) {
11789:                 $toplevel{$1} = $path;
11790:             } else {
11791:                 $toplevel{$path} = $path;
11792:             }
11793:         }
11794:     }
11795:     if ($mimetype =~ m{^application/(x\-)?(compressed|zip)}) {
11796:         my @camtasia6 = ("$topdir/","$topdir/index.html",
11797:                         "$topdir/media/",
11798:                         "$topdir/media/$topdir.mp4",
11799:                         "$topdir/media/FirstFrame.png",
11800:                         "$topdir/media/player.swf",
11801:                         "$topdir/media/swfobject.js",
11802:                         "$topdir/media/expressInstall.swf");
11803:         my @camtasia8_1 = ("$topdir/","$topdir/$topdir.html",
11804:                          "$topdir/$topdir.mp4",
11805:                          "$topdir/$topdir\_config.xml",
11806:                          "$topdir/$topdir\_controller.swf",
11807:                          "$topdir/$topdir\_embed.css",
11808:                          "$topdir/$topdir\_First_Frame.png",
11809:                          "$topdir/$topdir\_player.html",
11810:                          "$topdir/$topdir\_Thumbnails.png",
11811:                          "$topdir/playerProductInstall.swf",
11812:                          "$topdir/scripts/",
11813:                          "$topdir/scripts/config_xml.js",
11814:                          "$topdir/scripts/handlebars.js",
11815:                          "$topdir/scripts/jquery-1.7.1.min.js",
11816:                          "$topdir/scripts/jquery-ui-1.8.15.custom.min.js",
11817:                          "$topdir/scripts/modernizr.js",
11818:                          "$topdir/scripts/player-min.js",
11819:                          "$topdir/scripts/swfobject.js",
11820:                          "$topdir/skins/",
11821:                          "$topdir/skins/configuration_express.xml",
11822:                          "$topdir/skins/express_show/",
11823:                          "$topdir/skins/express_show/player-min.css",
11824:                          "$topdir/skins/express_show/spritesheet.png");
11825:         my @camtasia8_4 = ("$topdir/","$topdir/$topdir.html",
11826:                          "$topdir/$topdir.mp4",
11827:                          "$topdir/$topdir\_config.xml",
11828:                          "$topdir/$topdir\_controller.swf",
11829:                          "$topdir/$topdir\_embed.css",
11830:                          "$topdir/$topdir\_First_Frame.png",
11831:                          "$topdir/$topdir\_player.html",
11832:                          "$topdir/$topdir\_Thumbnails.png",
11833:                          "$topdir/playerProductInstall.swf",
11834:                          "$topdir/scripts/",
11835:                          "$topdir/scripts/config_xml.js",
11836:                          "$topdir/scripts/techsmith-smart-player.min.js",
11837:                          "$topdir/skins/",
11838:                          "$topdir/skins/configuration_express.xml",
11839:                          "$topdir/skins/express_show/",
11840:                          "$topdir/skins/express_show/spritesheet.min.css",
11841:                          "$topdir/skins/express_show/spritesheet.png",
11842:                          "$topdir/skins/express_show/techsmith-smart-player.min.css");
11843:         my @diffs = &compare_arrays(\@paths,\@camtasia6);
11844:         if (@diffs == 0) {
11845:             $is_camtasia = 6;
11846:         } else {
11847:             @diffs = &compare_arrays(\@paths,\@camtasia8_1);
11848:             if (@diffs == 0) {
11849:                 $is_camtasia = 8;
11850:             } else {
11851:                 @diffs = &compare_arrays(\@paths,\@camtasia8_4);
11852:                 if (@diffs == 0) {
11853:                     $is_camtasia = 8;
11854:                 }
11855:             }
11856:         }
11857:     }
11858:     my $output;
11859:     if ($is_camtasia) {
11860:         $output = <<"ENDCAM";
11861: <script type="text/javascript" language="Javascript">
11862: // <![CDATA[
11863: 
11864: function camtasiaToggle() {
11865:     for (var i=0; i<document.uploaded_decompress.autoextract_camtasia.length; i++) {
11866:         if (document.uploaded_decompress.autoextract_camtasia[i].checked) {
11867:             if (document.uploaded_decompress.autoextract_camtasia[i].value == $is_camtasia) {
11868:                 document.getElementById('camtasia_titles').style.display='block';
11869:             } else {
11870:                 document.getElementById('camtasia_titles').style.display='none';
11871:             }
11872:         }
11873:     }
11874:     return;
11875: }
11876: 
11877: // ]]>
11878: </script>
11879: <p>$lt{'camt'}</p>
11880: ENDCAM
11881:     } else {
11882:         $output = '<p>'.$lt{'this'};
11883:         if ($info eq '') {
11884:             $output .= ' '.$lt{'youm'}.'</p>'."\n";
11885:         } else {
11886:             $output .= ' '.$lt{'itsc'}.'</p>'."\n".
11887:                        '<div><pre>'.$info.'</pre></div>';
11888:         }
11889:     }
11890:     $output .= '<form name="uploaded_decompress" action="'.$action.'" method="post">'."\n";
11891:     my $duplicates;
11892:     my $num = 0;
11893:     if (ref($dirlist) eq 'ARRAY') {
11894:         foreach my $item (@{$dirlist}) {
11895:             if (ref($item) eq 'ARRAY') {
11896:                 if (exists($toplevel{$item->[0]})) {
11897:                     $duplicates .= 
11898:                         &start_data_table_row().
11899:                         '<td><label><input type="radio" name="archive_overwrite_'.$num.'" '.
11900:                         'value="0" checked="checked" />'.&mt('No').'</label>'.
11901:                         '&nbsp;<label><input type="radio" name="archive_overwrite_'.$num.'" '.
11902:                         'value="1" />'.&mt('Yes').'</label>'.
11903:                         '<input type="hidden" name="archive_overwrite_name_'.$num.'" value="'.$item->[0].'" /></td>'."\n".
11904:                         '<td>'.$item->[0].'</td>';
11905:                     if ($item->[2]) {
11906:                         $duplicates .= '<td>'.&mt('Directory').'</td>';
11907:                     } else {
11908:                         $duplicates .= '<td>'.&mt('File').'</td>';
11909:                     }
11910:                     $duplicates .= '<td>'.$item->[3].'</td>'.
11911:                                    '<td>'.
11912:                                    &Apache::lonlocal::locallocaltime($item->[4]).
11913:                                    '</td>'.
11914:                                    &end_data_table_row();
11915:                     $num ++;
11916:                 }
11917:             }
11918:         }
11919:     }
11920:     my $itemcount;
11921:     if (@paths > 0) {
11922:         $itemcount = scalar(@paths);
11923:     } else {
11924:         $itemcount = 1;
11925:     }
11926:     if ($is_camtasia) {
11927:         $output .= $lt{'auto'}.'<br />'.
11928:                    '<span class="LC_nobreak">'.$lt{'proa'}.'<label>'.
11929:                    '<input type="radio" name="autoextract_camtasia" value="'.$is_camtasia.'" onclick="javascript:camtasiaToggle();" checked="checked" />'.
11930:                    $lt{'yes'}.'</label>&nbsp;<label>'.
11931:                    '<input type="radio" name="autoextract_camtasia" value="0" onclick="javascript:camtasiaToggle();" />'.
11932:                    $lt{'no'}.'</label></span><br />'.
11933:                    '<div id="camtasia_titles" style="display:block">'.
11934:                    &Apache::lonhtmlcommon::start_pick_box().
11935:                    &Apache::lonhtmlcommon::row_title($lt{'fold'}).
11936:                    '<input type="textbox" name="camtasia_foldername" value="'.$env{'form.comment'}.'" />'."\n".
11937:                    &Apache::lonhtmlcommon::row_closure().
11938:                    &Apache::lonhtmlcommon::row_title($lt{'movi'}).
11939:                    '<input type="textbox" name="camtasia_moviename" value="" />'."\n".
11940:                    &Apache::lonhtmlcommon::row_closure(1).
11941:                    &Apache::lonhtmlcommon::end_pick_box().
11942:                    '</div>';
11943:     }
11944:     $output .= 
11945:         '<input type="hidden" name="archive_overwrite_total" value="'.$num.'" />'.
11946:         '<input type="hidden" name="archive_itemcount" value="'.$itemcount.'" />'.
11947:         "\n";
11948:     if ($duplicates ne '') {
11949:         $output .= '<p><span class="LC_warning">'.
11950:                    &mt('Warning: decompression of the archive will overwrite the following items which already exist:').'</span><br />'.  
11951:                    &start_data_table().
11952:                    &start_data_table_header_row().
11953:                    '<th>'.&mt('Overwrite?').'</th>'.
11954:                    '<th>'.&mt('Name').'</th>'.
11955:                    '<th>'.&mt('Type').'</th>'.
11956:                    '<th>'.&mt('Size').'</th>'.
11957:                    '<th>'.&mt('Last modified').'</th>'.
11958:                    &end_data_table_header_row().
11959:                    $duplicates.
11960:                    &end_data_table().
11961:                    '</p>';
11962:     }
11963:     $output .= '<input type="hidden" name="archiveurl" value="'.$archiveurl.'" />'."\n";
11964:     if (ref($hiddenelements) eq 'HASH') {
11965:         foreach my $hidden (sort(keys(%{$hiddenelements}))) {
11966:             $output .= '<input type="hidden" name="'.$hidden.'" value="'.$hiddenelements->{$hidden}.'" />'."\n";
11967:         }
11968:     }
11969:     $output .= <<"END";
11970: <br />
11971: <input type="submit" name="decompress" value="$lt{'extr'}" />
11972: </form>
11973: $noextract
11974: END
11975:     return $output;
11976: }
11977: 
11978: sub decompression_utility {
11979:     my ($program) = @_;
11980:     my @utilities = ('tar','gunzip','bunzip2','unzip'); 
11981:     my $location;
11982:     if (grep(/^\Q$program\E$/,@utilities)) { 
11983:         foreach my $dir ('/bin/','/usr/bin/','/usr/local/bin/','/sbin/',
11984:                          '/usr/sbin/') {
11985:             if (-x $dir.$program) {
11986:                 $location = $dir.$program;
11987:                 last;
11988:             }
11989:         }
11990:     }
11991:     return $location;
11992: }
11993: 
11994: sub list_archive_contents {
11995:     my ($file,$pathsref) = @_;
11996:     my (@cmd,$output);
11997:     my $needsregexp;
11998:     if ($file =~ /\.zip$/) {
11999:         @cmd = (&decompression_utility('unzip'),"-l");
12000:         $needsregexp = 1;
12001:     } elsif (($file =~ m/\.tar\.gz$/) ||
12002:              ($file =~ /\.tgz$/)) {
12003:         @cmd = (&decompression_utility('tar'),"-ztf");
12004:     } elsif ($file =~ /\.tar\.bz2$/) {
12005:         @cmd = (&decompression_utility('tar'),"-jtf");
12006:     } elsif ($file =~ m|\.tar$|) {
12007:         @cmd = (&decompression_utility('tar'),"-tf");
12008:     }
12009:     if (@cmd) {
12010:         undef($!);
12011:         undef($@);
12012:         if (open(my $fh,"-|", @cmd, $file)) {
12013:             while (my $line = <$fh>) {
12014:                 $output .= $line;
12015:                 chomp($line);
12016:                 my $item;
12017:                 if ($needsregexp) {
12018:                     ($item) = ($line =~ /^\s*\d+\s+[\d\-]+\s+[\d:]+\s*(.+)$/); 
12019:                 } else {
12020:                     $item = $line;
12021:                 }
12022:                 if ($item ne '') {
12023:                     unless (grep(/^\Q$item\E$/,@{$pathsref})) {
12024:                         push(@{$pathsref},$item);
12025:                     } 
12026:                 }
12027:             }
12028:             close($fh);
12029:         }
12030:     }
12031:     return $output;
12032: }
12033: 
12034: sub decompress_uploaded_file {
12035:     my ($file,$dir) = @_;
12036:     &Apache::lonnet::appenv({'cgi.file' => $file});
12037:     &Apache::lonnet::appenv({'cgi.dir' => $dir});
12038:     my $result = &Apache::lonnet::ssi_body('/cgi-bin/decompress.pl');
12039:     my ($handle) = ($env{'user.environment'} =~m{/([^/]+)\.id$});
12040:     my $lonidsdir = $Apache::lonnet::perlvar{'lonIDsDir'};
12041:     &Apache::lonnet::transfer_profile_to_env($lonidsdir,$handle,1);
12042:     my $decompressed = $env{'cgi.decompressed'};
12043:     &Apache::lonnet::delenv('cgi.file');
12044:     &Apache::lonnet::delenv('cgi.dir');
12045:     &Apache::lonnet::delenv('cgi.decompressed');
12046:     return ($decompressed,$result);
12047: }
12048: 
12049: sub process_decompression {
12050:     my ($docudom,$docuname,$file,$destination,$dir_root,$hiddenelem) = @_;
12051:     unless (($dir_root eq '/userfiles') && ($destination =~ m{^(docs|supplemental)/(default|\d+)/\d+$})) {
12052:         return '<p class="LC_error">'.&mt('Not extracted.').'<br />'.
12053:                &mt('Unexpected file path.').'</p>'."\n";
12054:     }
12055:     unless (($docudom =~ /^$match_domain$/) && ($docuname =~ /^$match_courseid$/)) {
12056:         return '<p class="LC_error">'.&mt('Not extracted.').'<br />'.
12057:                &mt('Unexpected course context.').'</p>'."\n";
12058:     }
12059:     unless ($file eq &Apache::lonnet::clean_filename($file)) {
12060:         return '<p class="LC_error">'.&mt('Not extracted.').'<br />'.
12061:                &mt('Filename contained unexpected characters.').'</p>'."\n";
12062:     }
12063:     my ($dir,$error,$warning,$output);
12064:     if ($file !~ /\.(zip|tar|bz2|gz|tar.gz|tar.bz2|tgz)$/i) {
12065:         $error = &mt('Filename not a supported archive file type.').
12066:                  '<br />'.&mt('Filename should end with one of: [_1].',
12067:                               '.zip, .tar, .bz2, .gz, .tar.gz, .tar.bz2, .tgz');
12068:     } else {
12069:         my $docuhome = &Apache::lonnet::homeserver($docuname,$docudom);
12070:         if ($docuhome eq 'no_host') {
12071:             $error = &mt('Could not determine home server for course.');
12072:         } else {
12073:             my @ids=&Apache::lonnet::current_machine_ids();
12074:             my $currdir = "$dir_root/$destination";
12075:             if (grep(/^\Q$docuhome\E$/,@ids)) {
12076:                 $dir = &LONCAPA::propath($docudom,$docuname).
12077:                        "$dir_root/$destination";
12078:             } else {
12079:                 $dir = $Apache::lonnet::perlvar{'lonDocRoot'}.
12080:                        "$dir_root/$docudom/$docuname/$destination";
12081:                 unless (&Apache::lonnet::repcopy_userfile("$dir/$file") eq 'ok') {
12082:                     $error = &mt('Archive file not found.');
12083:                 }
12084:             }
12085:             my (@to_overwrite,@to_skip);
12086:             if ($env{'form.archive_overwrite_total'} > 0) {
12087:                 my $total = $env{'form.archive_overwrite_total'};
12088:                 for (my $i=0; $i<$total; $i++) {
12089:                     if ($env{'form.archive_overwrite_'.$i} == 1) {
12090:                         push(@to_overwrite,$env{'form.archive_overwrite_name_'.$i});
12091:                     } elsif ($env{'form.archive_overwrite_'.$i} == 0) {
12092:                         push(@to_skip,$env{'form.archive_overwrite_name_'.$i});
12093:                     }
12094:                 }
12095:             }
12096:             my $numskip = scalar(@to_skip);
12097:             my $numoverwrite = scalar(@to_overwrite);
12098:             if (($numskip) && (!$numoverwrite)) {
12099:                 $warning = &mt('All items in the archive file already exist, and no overwriting of existing files has been requested.');         
12100:             } elsif ($dir eq '') {
12101:                 $error = &mt('Directory containing archive file unavailable.');
12102:             } elsif (!$error) {
12103:                 my ($decompressed,$display);
12104:                 if (($numskip) || ($numoverwrite)) {
12105:                     my $tempdir = time.'_'.$$.int(rand(10000));
12106:                     mkdir("$dir/$tempdir",0755);
12107:                     if (&File::Copy::move("$dir/$file","$dir/$tempdir/$file")) {
12108:                         ($decompressed,$display) =
12109:                             &decompress_uploaded_file($file,"$dir/$tempdir");
12110:                         foreach my $item (@to_skip) {
12111:                             if (($item ne '') && ($item !~ /\.\./)) {
12112:                                 if (-f "$dir/$tempdir/$item") {
12113:                                     unlink("$dir/$tempdir/$item");
12114:                                 } elsif (-d "$dir/$tempdir/$item") {
12115:                                     &File::Path::remove_tree("$dir/$tempdir/$item",{ safe => 1 });
12116:                                 }
12117:                             }
12118:                         }
12119:                         foreach my $item (@to_overwrite) {
12120:                             if ((-e "$dir/$tempdir/$item") && (-e "$dir/$item")) {
12121:                                 if (($item ne '') && ($item !~ /\.\./)) {
12122:                                     if (-f "$dir/$item") {
12123:                                         unlink("$dir/$item");
12124:                                     } elsif (-d "$dir/$item") {
12125:                                         &File::Path::remove_tree("$dir/$item",{ safe => 1 });
12126:                                     }
12127:                                     &File::Copy::move("$dir/$tempdir/$item","$dir/$item");
12128:                                 }
12129:                             }
12130:                         }
12131:                         if (&File::Copy::move("$dir/$tempdir/$file","$dir/$file")) {
12132:                             &File::Path::remove_tree("$dir/$tempdir",{ safe => 1 });
12133:                         }
12134:                     }
12135:                 } else {
12136:                     ($decompressed,$display) = 
12137:                         &decompress_uploaded_file($file,$dir);
12138:                 }
12139:                 if ($decompressed eq 'ok') {
12140:                     $output = '<p class="LC_info">'.
12141:                               &mt('Files extracted successfully from archive.').
12142:                               '</p>'."\n";
12143:                     my ($warning,$result,@contents);
12144:                     my ($newdirlistref,$newlisterror) =
12145:                         &Apache::lonnet::dirlist($currdir,$docudom,
12146:                                                  $docuname,1);
12147:                     my (%is_dir,%changes,@newitems);
12148:                     my $dirptr = 16384;
12149:                     if (ref($newdirlistref) eq 'ARRAY') {
12150:                         foreach my $dir_line (@{$newdirlistref}) {
12151:                             my ($item,undef,undef,$testdir)=split(/\&/,$dir_line,5);
12152:                             unless (($item =~ /^\.+$/) || ($item eq $file)) { 
12153:                                 push(@newitems,$item);
12154:                                 if ($dirptr&$testdir) {
12155:                                     $is_dir{$item} = 1;
12156:                                 }
12157:                                 $changes{$item} = 1;
12158:                             }
12159:                         }
12160:                     }
12161:                     if (keys(%changes) > 0) {
12162:                         foreach my $item (sort(@newitems)) {
12163:                             if ($changes{$item}) {
12164:                                 push(@contents,$item);
12165:                             }
12166:                         }
12167:                     }
12168:                     if (@contents > 0) {
12169:                         my $wantform;
12170:                         unless ($env{'form.autoextract_camtasia'}) {
12171:                             $wantform = 1;
12172:                         }
12173:                         my (%children,%parent,%dirorder,%titles);
12174:                         my ($count,$datatable) = &get_extracted($docudom,$docuname,
12175:                                                                 $currdir,\%is_dir,
12176:                                                                 \%children,\%parent,
12177:                                                                 \@contents,\%dirorder,
12178:                                                                 \%titles,$wantform);
12179:                         if ($datatable ne '') {
12180:                             $output .= &archive_options_form('decompressed',$datatable,
12181:                                                              $count,$hiddenelem);
12182:                             my $startcount = 6;
12183:                             $output .= &archive_javascript($startcount,$count,
12184:                                                            \%titles,\%children);
12185:                         }
12186:                         if ($env{'form.autoextract_camtasia'}) {
12187:                             my $version = $env{'form.autoextract_camtasia'};
12188:                             my %displayed;
12189:                             my $total = 1;
12190:                             $env{'form.archive_directory'} = [];
12191:                             foreach my $i (sort { $a <=> $b } keys(%dirorder)) {
12192:                                 my $path = join('/',map { $titles{$_}; } @{$dirorder{$i}});
12193:                                 $path =~ s{/$}{};
12194:                                 my $item;
12195:                                 if ($path ne '') {
12196:                                     $item = "$path/$titles{$i}";
12197:                                 } else {
12198:                                     $item = $titles{$i};
12199:                                 }
12200:                                 $env{'form.archive_content_'.$i} = "$dir_root/$destination/$item";
12201:                                 if ($item eq $contents[0]) {
12202:                                     push(@{$env{'form.archive_directory'}},$i);
12203:                                     $env{'form.archive_'.$i} = 'display';
12204:                                     $env{'form.archive_title_'.$i} = $env{'form.camtasia_foldername'};
12205:                                     $displayed{'folder'} = $i;
12206:                                 } elsif ((($item eq "$contents[0]/index.html") && ($version == 6)) ||
12207:                                          (($item eq "$contents[0]/$contents[0]".'.html') && ($version == 8))) {
12208:                                     $env{'form.archive_'.$i} = 'display';
12209:                                     $env{'form.archive_title_'.$i} = $env{'form.camtasia_moviename'};
12210:                                     $displayed{'web'} = $i;
12211:                                 } else {
12212:                                     if ((($item eq "$contents[0]/media") && ($version == 6)) ||
12213:                                         ((($item eq "$contents[0]/scripts") || ($item eq "$contents[0]/skins") ||
12214:                                              ($item eq "$contents[0]/skins/express_show")) && ($version == 8))) {
12215:                                         push(@{$env{'form.archive_directory'}},$i);
12216:                                     }
12217:                                     $env{'form.archive_'.$i} = 'dependency';
12218:                                 }
12219:                                 $total ++;
12220:                             }
12221:                             for (my $i=1; $i<$total; $i++) {
12222:                                 next if ($i == $displayed{'web'});
12223:                                 next if ($i == $displayed{'folder'});
12224:                                 $env{'form.archive_dependent_on_'.$i} = $displayed{'web'};
12225:                             }
12226:                             $env{'form.phase'} = 'decompress_cleanup';
12227:                             $env{'form.archivedelete'} = 1;
12228:                             $env{'form.archive_count'} = $total-1;
12229:                             $output .=
12230:                                 &process_extracted_files('coursedocs',$docudom,
12231:                                                          $docuname,$destination,
12232:                                                          $dir_root,$hiddenelem);
12233:                         }
12234:                     } else {
12235:                         $warning = &mt('No new items extracted from archive file.');
12236:                     }
12237:                 } else {
12238:                     $output = $display;
12239:                     $error = &mt('An error occurred during extraction from the archive file.');
12240:                 }
12241:             }
12242:         }
12243:     }
12244:     if ($error) {
12245:         $output .= '<p class="LC_error">'.&mt('Not extracted.').'<br />'.
12246:                    $error.'</p>'."\n";
12247:     }
12248:     if ($warning) {
12249:         $output .= '<p class="LC_warning">'.$warning.'</p>'."\n";
12250:     }
12251:     return $output;
12252: }
12253: 
12254: sub get_extracted {
12255:     my ($docudom,$docuname,$currdir,$is_dir,$children,$parent,$contents,$dirorder,
12256:         $titles,$wantform) = @_;
12257:     my $count = 0;
12258:     my $depth = 0;
12259:     my $datatable;
12260:     my @hierarchy;
12261:     return unless ((ref($is_dir) eq 'HASH') && (ref($children) eq 'HASH') &&
12262:                    (ref($parent) eq 'HASH') && (ref($contents) eq 'ARRAY') &&
12263:                    (ref($dirorder) eq 'HASH') && (ref($titles) eq 'HASH'));
12264:     foreach my $item (@{$contents}) {
12265:         $count ++;
12266:         @{$dirorder->{$count}} = @hierarchy;
12267:         $titles->{$count} = $item;
12268:         &archive_hierarchy($depth,$count,$parent,$children);
12269:         if ($wantform) {
12270:             $datatable .= &archive_row($is_dir->{$item},$item,
12271:                                        $currdir,$depth,$count);
12272:         }
12273:         if ($is_dir->{$item}) {
12274:             $depth ++;
12275:             push(@hierarchy,$count);
12276:             $parent->{$depth} = $count;
12277:             $datatable .=
12278:                 &recurse_extracted_archive("$currdir/$item",$docudom,$docuname,
12279:                                            \$depth,\$count,\@hierarchy,$dirorder,
12280:                                            $children,$parent,$titles,$wantform);
12281:             $depth --;
12282:             pop(@hierarchy);
12283:         }
12284:     }
12285:     return ($count,$datatable);
12286: }
12287: 
12288: sub recurse_extracted_archive {
12289:     my ($currdir,$docudom,$docuname,$depth,$count,$hierarchy,$dirorder,
12290:         $children,$parent,$titles,$wantform) = @_;
12291:     my $result='';
12292:     unless ((ref($depth)) && (ref($count)) && (ref($hierarchy) eq 'ARRAY') &&
12293:             (ref($children) eq 'HASH') && (ref($parent) eq 'HASH') &&
12294:             (ref($dirorder) eq 'HASH')) {
12295:         return $result;
12296:     }
12297:     my $dirptr = 16384;
12298:     my ($newdirlistref,$newlisterror) =
12299:         &Apache::lonnet::dirlist($currdir,$docudom,$docuname,1);
12300:     if (ref($newdirlistref) eq 'ARRAY') {
12301:         foreach my $dir_line (@{$newdirlistref}) {
12302:             my ($item,undef,undef,$testdir)=split(/\&/,$dir_line,5);
12303:             unless ($item =~ /^\.+$/) {
12304:                 $$count ++;
12305:                 @{$dirorder->{$$count}} = @{$hierarchy};
12306:                 $titles->{$$count} = $item;
12307:                 &archive_hierarchy($$depth,$$count,$parent,$children);
12308: 
12309:                 my $is_dir;
12310:                 if ($dirptr&$testdir) {
12311:                     $is_dir = 1;
12312:                 }
12313:                 if ($wantform) {
12314:                     $result .= &archive_row($is_dir,$item,$currdir,$$depth,$$count);
12315:                 }
12316:                 if ($is_dir) {
12317:                     $$depth ++;
12318:                     push(@{$hierarchy},$$count);
12319:                     $parent->{$$depth} = $$count;
12320:                     $result .=
12321:                         &recurse_extracted_archive("$currdir/$item",$docudom,
12322:                                                    $docuname,$depth,$count,
12323:                                                    $hierarchy,$dirorder,$children,
12324:                                                    $parent,$titles,$wantform);
12325:                     $$depth --;
12326:                     pop(@{$hierarchy});
12327:                 }
12328:             }
12329:         }
12330:     }
12331:     return $result;
12332: }
12333: 
12334: sub archive_hierarchy {
12335:     my ($depth,$count,$parent,$children) =@_;
12336:     if ((ref($parent) eq 'HASH') && (ref($children) eq 'HASH')) {
12337:         if (exists($parent->{$depth})) {
12338:              $children->{$parent->{$depth}} .= $count.':';
12339:         }
12340:     }
12341:     return;
12342: }
12343: 
12344: sub archive_row {
12345:     my ($is_dir,$item,$currdir,$depth,$count) = @_;
12346:     my ($name) = ($item =~ m{([^/]+)$});
12347:     my %choices = &Apache::lonlocal::texthash (
12348:                                        'display'    => 'Add as file',
12349:                                        'dependency' => 'Include as dependency',
12350:                                        'discard'    => 'Discard',
12351:                                       );
12352:     if ($is_dir) {
12353:         $choices{'display'} = &mt('Add as folder'); 
12354:     }
12355:     my $output = &start_data_table_row().'<td align="right">'.$count.'</td>'."\n";
12356:     my $offset = 0;
12357:     foreach my $action ('display','dependency','discard') {
12358:         $offset ++;
12359:         if ($action ne 'display') {
12360:             $offset ++;
12361:         }  
12362:         $output .= '<td><span class="LC_nobreak">'.
12363:                    '<label><input type="radio" name="archive_'.$count.
12364:                    '" id="archive_'.$action.'_'.$count.'" value="'.$action.'"';
12365:         my $text = $choices{$action};
12366:         if ($is_dir) {
12367:             $output .= ' onclick="javascript:propagateCheck(this.form,'."'$count'".');"';
12368:             if ($action eq 'display') {
12369:                 $text = &mt('Add as folder');
12370:             }
12371:         } else {
12372:             $output .= ' onclick="javascript:dependencyCheck(this.form,'."$count,$offset".');"';
12373: 
12374:         }
12375:         $output .= ' />&nbsp;'.$choices{$action}.'</label></span>';
12376:         if ($action eq 'dependency') {
12377:             $output .= '<div id="arc_depon_'.$count.'" style="display:none;">'."\n".
12378:                        &mt('Used by:').'&nbsp;<select name="archive_dependent_on_'.$count.'" '.
12379:                        'onchange="propagateSelect(this.form,'."$count,$offset".')">'."\n".
12380:                        '<option value=""></option>'."\n".
12381:                        '</select>'."\n".
12382:                        '</div>';
12383:         } elsif ($action eq 'display') {
12384:             $output .= '<div id="arc_title_'.$count.'" style="display:none;">'."\n".
12385:                        &mt('Title:').'&nbsp;<input type="text" name="archive_title_'.$count.'" id="archive_title_'.$count.'" />'."\n".
12386:                        '</div>';
12387:         }
12388:         $output .= '</td>';
12389:     }
12390:     $output .= '<td><input type="hidden" name="archive_content_'.$count.'" value="'.
12391:                &HTML::Entities::encode("$currdir/$item",'"<>&').'" />'.('&nbsp;' x 2);
12392:     for (my $i=0; $i<$depth; $i++) {
12393:         $output .= ('<img src="/adm/lonIcons/whitespace1.gif" class="LC_docs_spacer" alt="" />' x2)."\n";
12394:     }
12395:     if ($is_dir) {
12396:         $output .= '<img src="/adm/lonIcons/navmap.folder.open.gif" alt="" />&nbsp;'."\n".
12397:                    '<input type="hidden" name="archive_directory" value="'.$count.'" />'."\n";
12398:     } else {
12399:         $output .= '<input type="hidden" name="archive_file" value="'.$count.'" />'."\n";
12400:     }
12401:     $output .= '&nbsp;'.$name.'</td>'."\n".
12402:                &end_data_table_row();
12403:     return $output;
12404: }
12405: 
12406: sub archive_options_form {
12407:     my ($form,$display,$count,$hiddenelem) = @_;
12408:     my %lt = &Apache::lonlocal::texthash(
12409:                perm => 'Permanently remove archive file?',
12410:                hows => 'How should each extracted item be incorporated in the course?',
12411:                cont => 'Content actions for all',
12412:                addf => 'Add as folder/file',
12413:                incd => 'Include as dependency for a displayed file',
12414:                disc => 'Discard',
12415:                no   => 'No',
12416:                yes  => 'Yes',
12417:                save => 'Save',
12418:     );
12419:     my $output = <<"END";
12420: <form name="$form" method="post" action="">
12421: <p><span class="LC_nobreak">$lt{'perm'}&nbsp;
12422: <label>
12423:   <input type="radio" name="archivedelete" value="0" checked="checked" />$lt{'no'}
12424: </label>
12425: &nbsp;
12426: <label>
12427:   <input type="radio" name="archivedelete" value="1" />$lt{'yes'}</label>
12428: </span>
12429: </p>
12430: <input type="hidden" name="phase" value="decompress_cleanup" />
12431: <br />$lt{'hows'}
12432: <div class="LC_columnSection">
12433:   <fieldset>
12434:     <legend>$lt{'cont'}</legend>
12435:     <input type="button" value="$lt{'addf'}" onclick="javascript:checkAll(document.$form,'display');" /> 
12436:     &nbsp;&nbsp;<input type="button" value="$lt{'incd'}" onclick="javascript:checkAll(document.$form,'dependency');" />
12437:     &nbsp;&nbsp;<input type="button" value="$lt{'disc'}" onclick="javascript:checkAll(document.$form,'discard');" />
12438:   </fieldset>
12439: </div>
12440: END
12441:     return $output.
12442:            &start_data_table()."\n".
12443:            $display."\n".
12444:            &end_data_table()."\n".
12445:            '<input type="hidden" name="archive_count" value="'.$count.'" />'.
12446:            $hiddenelem.
12447:            '<br /><input type="submit" name="archive_submit" value="'.$lt{'save'}.'" />'.
12448:            '</form>';
12449: }
12450: 
12451: sub archive_javascript {
12452:     my ($startcount,$numitems,$titles,$children) = @_;
12453:     return unless ((ref($titles) eq 'HASH') && (ref($children) eq 'HASH'));
12454:     my $maintitle = $env{'form.comment'};
12455:     my $scripttag = <<START;
12456: <script type="text/javascript">
12457: // <![CDATA[
12458: 
12459: function checkAll(form,prefix) {
12460:     var idstr =  new RegExp("^archive_"+prefix+"_\\\\d+\$");
12461:     for (var i=0; i < form.elements.length; i++) {
12462:         var id = form.elements[i].id;
12463:         if ((id != '') && (id != undefined)) {
12464:             if (idstr.test(id)) {
12465:                 if (form.elements[i].type == 'radio') {
12466:                     form.elements[i].checked = true;
12467:                     var nostart = i-$startcount;
12468:                     var offset = nostart%7;
12469:                     var count = (nostart-offset)/7;    
12470:                     dependencyCheck(form,count,offset);
12471:                 }
12472:             }
12473:         }
12474:     }
12475: }
12476: 
12477: function propagateCheck(form,count) {
12478:     if (count > 0) {
12479:         var startelement = $startcount + ((count-1) * 7);
12480:         for (var j=1; j<6; j++) {
12481:             if ((j != 2) && (j != 4)) {
12482:                 var item = startelement + j; 
12483:                 if (form.elements[item].type == 'radio') {
12484:                     if (form.elements[item].checked) {
12485:                         containerCheck(form,count,j);
12486:                         break;
12487:                     }
12488:                 }
12489:             }
12490:         }
12491:     }
12492: }
12493: 
12494: numitems = $numitems
12495: var titles = new Array(numitems);
12496: var parents = new Array(numitems);
12497: for (var i=0; i<numitems; i++) {
12498:     parents[i] = new Array;
12499: }
12500: var maintitle = '$maintitle';
12501: 
12502: START
12503: 
12504:     foreach my $container (sort { $a <=> $b } (keys(%{$children}))) {
12505:         my @contents = split(/:/,$children->{$container});
12506:         for (my $i=0; $i<@contents; $i ++) {
12507:             $scripttag .= 'parents['.$container.']['.$i.'] = '.$contents[$i]."\n";
12508:         }
12509:     }
12510: 
12511:     foreach my $key (sort { $a <=> $b } (keys(%{$titles}))) {
12512:         $scripttag .= "titles[$key] = '".$titles->{$key}."';\n";
12513:     }
12514: 
12515:     $scripttag .= <<END;
12516: 
12517: function containerCheck(form,count,offset) {
12518:     if (count > 0) {
12519:         dependencyCheck(form,count,offset);
12520:         var item = (offset+$startcount)+7*(count-1);
12521:         form.elements[item].checked = true;
12522:         if(Object.prototype.toString.call(parents[count]) === '[object Array]') {
12523:             if (parents[count].length > 0) {
12524:                 for (var j=0; j<parents[count].length; j++) {
12525:                     containerCheck(form,parents[count][j],offset);
12526:                 }
12527:             }
12528:         }
12529:     }
12530: }
12531: 
12532: function dependencyCheck(form,count,offset) {
12533:     if (count > 0) {
12534:         var chosen = (offset+$startcount)+7*(count-1);
12535:         var depitem = $startcount + ((count-1) * 7) + 4;
12536:         var currtype = form.elements[depitem].type;
12537:         if (form.elements[chosen].value == 'dependency') {
12538:             document.getElementById('arc_depon_'+count).style.display='block'; 
12539:             form.elements[depitem].options.length = 0;
12540:             form.elements[depitem].options[0] = new Option('Select','',true,true);
12541:             for (var i=1; i<=numitems; i++) {
12542:                 if (i == count) {
12543:                     continue;
12544:                 }
12545:                 var startelement = $startcount + (i-1) * 7;
12546:                 for (var j=1; j<6; j++) {
12547:                     if ((j != 2) && (j!= 4)) {
12548:                         var item = startelement + j;
12549:                         if (form.elements[item].type == 'radio') {
12550:                             if (form.elements[item].checked) {
12551:                                 if (form.elements[item].value == 'display') {
12552:                                     var n = form.elements[depitem].options.length;
12553:                                     form.elements[depitem].options[n] = new Option(titles[i],i,false,false);
12554:                                 }
12555:                             }
12556:                         }
12557:                     }
12558:                 }
12559:             }
12560:         } else {
12561:             document.getElementById('arc_depon_'+count).style.display='none';
12562:             form.elements[depitem].options.length = 0;
12563:             form.elements[depitem].options[0] = new Option('Select','',true,true);
12564:         }
12565:         titleCheck(form,count,offset);
12566:     }
12567: }
12568: 
12569: function propagateSelect(form,count,offset) {
12570:     if (count > 0) {
12571:         var item = (1+offset+$startcount)+7*(count-1);
12572:         var picked = form.elements[item].options[form.elements[item].selectedIndex].value; 
12573:         if (Object.prototype.toString.call(parents[count]) === '[object Array]') {
12574:             if (parents[count].length > 0) {
12575:                 for (var j=0; j<parents[count].length; j++) {
12576:                     containerSelect(form,parents[count][j],offset,picked);
12577:                 }
12578:             }
12579:         }
12580:     }
12581: }
12582: 
12583: function containerSelect(form,count,offset,picked) {
12584:     if (count > 0) {
12585:         var item = (offset+$startcount)+7*(count-1);
12586:         if (form.elements[item].type == 'radio') {
12587:             if (form.elements[item].value == 'dependency') {
12588:                 if (form.elements[item+1].type == 'select-one') {
12589:                     for (var i=0; i<form.elements[item+1].options.length; i++) {
12590:                         if (form.elements[item+1].options[i].value == picked) {
12591:                             form.elements[item+1].selectedIndex = i;
12592:                             break;
12593:                         }
12594:                     }
12595:                 }
12596:                 if (Object.prototype.toString.call(parents[count]) === '[object Array]') {
12597:                     if (parents[count].length > 0) {
12598:                         for (var j=0; j<parents[count].length; j++) {
12599:                             containerSelect(form,parents[count][j],offset,picked);
12600:                         }
12601:                     }
12602:                 }
12603:             }
12604:         }
12605:     }
12606: }
12607: 
12608: function titleCheck(form,count,offset) {
12609:     if (count > 0) {
12610:         var chosen = (offset+$startcount)+7*(count-1);
12611:         var depitem = $startcount + ((count-1) * 7) + 2;
12612:         var currtype = form.elements[depitem].type;
12613:         if (form.elements[chosen].value == 'display') {
12614:             document.getElementById('arc_title_'+count).style.display='block';
12615:             if ((count==1) && ((parents[count].length > 0) || (numitems == 1))) {
12616:                 document.getElementById('archive_title_'+count).value=maintitle;
12617:             }
12618:         } else {
12619:             document.getElementById('arc_title_'+count).style.display='none';
12620:             if (currtype == 'text') { 
12621:                 document.getElementById('archive_title_'+count).value='';
12622:             }
12623:         }
12624:     }
12625:     return;
12626: }
12627: 
12628: // ]]>
12629: </script>
12630: END
12631:     return $scripttag;
12632: }
12633: 
12634: sub process_extracted_files {
12635:     my ($context,$docudom,$docuname,$destination,$dir_root,$hiddenelem) = @_;
12636:     my $numitems = $env{'form.archive_count'};
12637:     return if ((!$numitems) || ($numitems =~ /\D/));
12638:     my @ids=&Apache::lonnet::current_machine_ids();
12639:     my ($prefix,$pathtocheck,$dir,$ishome,$error,$warning,%toplevelitems,%is_dir,
12640:         %folders,%containers,%mapinner,%prompttofetch);
12641:     my $docuhome = &Apache::lonnet::homeserver($docuname,$docudom);
12642:     if (grep(/^\Q$docuhome\E$/,@ids)) {
12643:         $prefix = &LONCAPA::propath($docudom,$docuname);
12644:         $pathtocheck = "$dir_root/$destination";
12645:         $dir = $dir_root;
12646:         $ishome = 1;
12647:     } else {
12648:         $prefix = $Apache::lonnet::perlvar{'lonDocRoot'};
12649:         $pathtocheck = "$dir_root/$docudom/$docuname/$destination";
12650:         $dir = "$dir_root/$docudom/$docuname";
12651:     }
12652:     my $currdir = "$dir_root/$destination";
12653:     (my $docstype,$mapinner{'0'}) = ($destination =~ m{^(docs|supplemental)/(\w+)/});
12654:     if ($env{'form.folderpath'}) {
12655:         my @items = split('&',$env{'form.folderpath'});
12656:         $folders{'0'} = $items[-2];
12657:         if ($env{'form.folderpath'} =~ /\:1$/) {
12658:             $containers{'0'}='page';
12659:         } else {
12660:             $containers{'0'}='sequence';
12661:         }
12662:     }
12663:     my @archdirs = &get_env_multiple('form.archive_directory');
12664:     if ($numitems) {
12665:         for (my $i=1; $i<=$numitems; $i++) {
12666:             my $path = $env{'form.archive_content_'.$i};
12667:             if ($path =~ m{^\Q$pathtocheck\E/([^/]+)$}) {
12668:                 my $item = $1;
12669:                 $toplevelitems{$item} = $i;
12670:                 if (grep(/^\Q$i\E$/,@archdirs)) {
12671:                     $is_dir{$item} = 1;
12672:                 }
12673:             }
12674:         }
12675:     }
12676:     my ($output,%children,%parent,%titles,%dirorder,$result);
12677:     if (keys(%toplevelitems) > 0) {
12678:         my @contents = sort(keys(%toplevelitems));
12679:         (my $count,undef) = &get_extracted($docudom,$docuname,$currdir,\%is_dir,\%children,
12680:                                            \%parent,\@contents,\%dirorder,\%titles);
12681:     }
12682:     my (%referrer,%orphaned,%todelete,%todeletedir,%newdest,%newseqid);
12683:     if ($numitems) {
12684:         for (my $i=1; $i<=$numitems; $i++) {
12685:             next if ($env{'form.archive_'.$i} eq 'dependency');
12686:             my $path = $env{'form.archive_content_'.$i};
12687:             if ($path =~ /^\Q$pathtocheck\E/) {
12688:                 if ($env{'form.archive_'.$i} eq 'discard') {
12689:                     if ($prefix ne '' && $path ne '') {
12690:                         if (-e $prefix.$path) {
12691:                             if ((@archdirs > 0) && 
12692:                                 (grep(/^\Q$i\E$/,@archdirs))) {
12693:                                 $todeletedir{$prefix.$path} = 1;
12694:                             } else {
12695:                                 $todelete{$prefix.$path} = 1;
12696:                             }
12697:                         }
12698:                     }
12699:                 } elsif ($env{'form.archive_'.$i} eq 'display') {
12700:                     my ($docstitle,$title,$url,$outer);
12701:                     ($title) = ($path =~ m{/([^/]+)$});
12702:                     $docstitle = $env{'form.archive_title_'.$i};
12703:                     if ($docstitle eq '') {
12704:                         $docstitle = $title;
12705:                     }
12706:                     $outer = 0;
12707:                     if (ref($dirorder{$i}) eq 'ARRAY') {
12708:                         if (@{$dirorder{$i}} > 0) {
12709:                             foreach my $item (reverse(@{$dirorder{$i}})) {
12710:                                 if ($env{'form.archive_'.$item} eq 'display') {
12711:                                     $outer = $item;
12712:                                     last;
12713:                                 }
12714:                             }
12715:                         }
12716:                     }
12717:                     my ($errtext,$fatal) = 
12718:                         &LONCAPA::map::mapread('/uploaded/'.$docudom.'/'.$docuname.
12719:                                                '/'.$folders{$outer}.'.'.
12720:                                                $containers{$outer});
12721:                     next if ($fatal);
12722:                     if ((@archdirs > 0) && (grep(/^\Q$i\E$/,@archdirs))) {
12723:                         if ($context eq 'coursedocs') {
12724:                             $mapinner{$i} = time;
12725:                             $folders{$i} = 'default_'.$mapinner{$i};
12726:                             $containers{$i} = 'sequence';
12727:                             my $url = '/uploaded/'.$docudom.'/'.$docuname.'/'.
12728:                                       $folders{$i}.'.'.$containers{$i};
12729:                             my $newidx = &LONCAPA::map::getresidx();
12730:                             $LONCAPA::map::resources[$newidx]=
12731:                                 $docstitle.':'.$url.':false:normal:res';
12732:                             push(@LONCAPA::map::order,$newidx);
12733:                             my ($outtext,$errtext) =
12734:                                 &LONCAPA::map::storemap('/uploaded/'.$docudom.'/'.
12735:                                                         $docuname.'/'.$folders{$outer}.
12736:                                                         '.'.$containers{$outer},1,1);
12737:                             $newseqid{$i} = $newidx;
12738:                             unless ($errtext) {
12739:                                 $result .=  '<li>'.&mt('Folder: [_1] added to course',
12740:                                                        &HTML::Entities::encode($docstitle,'<>&"'))..
12741:                                             '</li>'."\n";
12742:                             }
12743:                         }
12744:                     } else {
12745:                         if ($context eq 'coursedocs') {
12746:                             my $newidx=&LONCAPA::map::getresidx();
12747:                             my $url = '/uploaded/'.$docudom.'/'.$docuname.'/'.
12748:                                       $docstype.'/'.$mapinner{$outer}.'/'.$newidx.'/'.
12749:                                       $title;
12750:                             if (($outer !~ /\D/) && ($mapinner{$outer} !~ /\D/) && ($newidx !~ /\D/)) {
12751:                                 if (!-e "$prefix$dir/$docstype/$mapinner{$outer}") {
12752:                                     mkdir("$prefix$dir/$docstype/$mapinner{$outer}",0755);
12753:                                 }
12754:                                 if (!-e "$prefix$dir/$docstype/$mapinner{$outer}/$newidx") {
12755:                                     mkdir("$prefix$dir/$docstype/$mapinner{$outer}/$newidx");
12756:                                 }
12757:                                 if (-e "$prefix$dir/$docstype/$mapinner{$outer}/$newidx") {
12758:                                     if (rename("$prefix$path","$prefix$dir/$docstype/$mapinner{$outer}/$newidx/$title")) {
12759:                                         $newdest{$i} = "$prefix$dir/$docstype/$mapinner{$outer}/$newidx";
12760:                                         unless ($ishome) {
12761:                                             my $fetch = "$newdest{$i}/$title";
12762:                                             $fetch =~ s/^\Q$prefix$dir\E//;
12763:                                             $prompttofetch{$fetch} = 1;
12764:                                         }
12765:                                    }
12766:                                 }
12767:                                 $LONCAPA::map::resources[$newidx]=
12768:                                     $docstitle.':'.$url.':false:normal:res';
12769:                                 push(@LONCAPA::map::order, $newidx);
12770:                                 my ($outtext,$errtext)=
12771:                                     &LONCAPA::map::storemap('/uploaded/'.$docudom.'/'.
12772:                                                             $docuname.'/'.$folders{$outer}.
12773:                                                             '.'.$containers{$outer},1,1);
12774:                                 unless ($errtext) {
12775:                                     if (-e "$prefix$dir/$docstype/$mapinner{$outer}/$newidx/$title") {
12776:                                         $result .= '<li>'.&mt('File: [_1] added to course',
12777:                                                               &HTML::Entities::encode($docstitle,'<>&"')).
12778:                                                    '</li>'."\n";
12779:                                     }
12780:                                 }
12781:                             } else {
12782:                                 $warning .= &mt('Item extracted from archive: [_1] has unexpected path.',
12783:                                                 &HTML::Entities::encode($path,'<>&"')).'<br />';
12784:                             }
12785:                         }
12786:                     }
12787:                 }
12788:             } else {
12789:                 $warning .= &mt('Item extracted from archive: [_1] has unexpected path.',
12790:                                 &HTML::Entities::encode($path,'<>&"')).'<br />';
12791:             }
12792:         }
12793:         for (my $i=1; $i<=$numitems; $i++) {
12794:             next unless ($env{'form.archive_'.$i} eq 'dependency');
12795:             my $path = $env{'form.archive_content_'.$i};
12796:             if ($path =~ /^\Q$pathtocheck\E/) {
12797:                 my ($title) = ($path =~ m{/([^/]+)$});
12798:                 $referrer{$i} = $env{'form.archive_dependent_on_'.$i};
12799:                 if ($env{'form.archive_'.$referrer{$i}} eq 'display') {
12800:                     if (ref($dirorder{$i}) eq 'ARRAY') {
12801:                         my ($itemidx,$fullpath,$relpath);
12802:                         if (ref($dirorder{$referrer{$i}}) eq 'ARRAY') {
12803:                             my $container = $dirorder{$referrer{$i}}->[-1];
12804:                             for (my $j=0; $j<@{$dirorder{$i}}; $j++) {
12805:                                 if ($dirorder{$i}->[$j] eq $container) {
12806:                                     $itemidx = $j;
12807:                                 }
12808:                             }
12809:                         }
12810:                         if ($itemidx eq '') {
12811:                             $itemidx =  0;
12812:                         }
12813:                         if (grep(/^\Q$referrer{$i}\E$/,@archdirs)) {
12814:                             if ($mapinner{$referrer{$i}}) {
12815:                                 $fullpath = "$prefix$dir/$docstype/$mapinner{$referrer{$i}}";
12816:                                 for (my $j=$itemidx; $j<@{$dirorder{$i}}; $j++) {
12817:                                     if (grep(/^\Q$dirorder{$i}->[$j]\E$/,@archdirs)) {
12818:                                         unless (defined($newseqid{$dirorder{$i}->[$j]})) {
12819:                                             $fullpath .= '/'.$titles{$dirorder{$i}->[$j]};
12820:                                             $relpath .= '/'.$titles{$dirorder{$i}->[$j]};
12821:                                             if (!-e $fullpath) {
12822:                                                 mkdir($fullpath,0755);
12823:                                             }
12824:                                         }
12825:                                     } else {
12826:                                         last;
12827:                                     }
12828:                                 }
12829:                             }
12830:                         } elsif ($newdest{$referrer{$i}}) {
12831:                             $fullpath = $newdest{$referrer{$i}};
12832:                             for (my $j=$itemidx; $j<@{$dirorder{$i}}; $j++) {
12833:                                 if ($env{'form.archive_'.$dirorder{$i}->[$j]} eq 'discard') {
12834:                                     $orphaned{$i} = $env{'form.archive_'.$dirorder{$i}->[$j]};
12835:                                     last;
12836:                                 } elsif (grep(/^\Q$dirorder{$i}->[$j]\E$/,@archdirs)) {
12837:                                     unless (defined($newseqid{$dirorder{$i}->[$j]})) {
12838:                                         $fullpath .= '/'.$titles{$dirorder{$i}->[$j]};
12839:                                         $relpath .= '/'.$titles{$dirorder{$i}->[$j]};
12840:                                         if (!-e $fullpath) {
12841:                                             mkdir($fullpath,0755);
12842:                                         }
12843:                                     }
12844:                                 } else {
12845:                                     last;
12846:                                 }
12847:                             }
12848:                         }
12849:                         if ($fullpath ne '') {
12850:                             if (-e "$prefix$path") {
12851:                                 unless (rename("$prefix$path","$fullpath/$title")) {
12852:                                      $warning .= &mt('Failed to rename dependency').'<br />';
12853:                                 }
12854:                             }
12855:                             if (-e "$fullpath/$title") {
12856:                                 my $showpath;
12857:                                 if ($relpath ne '') {
12858:                                     $showpath = "$relpath/$title";
12859:                                 } else {
12860:                                     $showpath = "/$title";
12861:                                 }
12862:                                 $result .= '<li>'.&mt('[_1] included as a dependency',
12863:                                                       &HTML::Entities::encode($showpath,'<>&"')).
12864:                                            '</li>'."\n";
12865:                                 unless ($ishome) {
12866:                                     my $fetch = "$fullpath/$title";
12867:                                     $fetch =~ s/^\Q$prefix$dir\E//;
12868:                                     $prompttofetch{$fetch} = 1;
12869:                                 }
12870:                             }
12871:                         }
12872:                     }
12873:                 } elsif ($env{'form.archive_'.$referrer{$i}} eq 'discard') {
12874:                     $warning .= &mt('[_1] is a dependency of [_2], which was discarded.',
12875:                                     &HTML::Entities::encode($path,'<>&"'),
12876:                                     &HTML::Entities::encode($env{'form.archive_content_'.$referrer{$i}},'<>&"')).
12877:                                 '<br />';
12878:                 }
12879:             } else {
12880:                 $warning .= &mt('Item extracted from archive: [_1] has unexpected path.',
12881:                                 &HTML::Entities::encode($path)).'<br />';
12882:             }
12883:         }
12884:         if (keys(%todelete)) {
12885:             foreach my $key (keys(%todelete)) {
12886:                 unlink($key);
12887:             }
12888:         }
12889:         if (keys(%todeletedir)) {
12890:             foreach my $key (keys(%todeletedir)) {
12891:                 rmdir($key);
12892:             }
12893:         }
12894:         foreach my $dir (sort(keys(%is_dir))) {
12895:             if (($pathtocheck ne '') && ($dir ne ''))  {
12896:                 &cleanup_empty_dirs($prefix."$pathtocheck/$dir");
12897:             }
12898:         }
12899:         if ($result ne '') {
12900:             $output .= '<ul>'."\n".
12901:                        $result."\n".
12902:                        '</ul>';
12903:         }
12904:         unless ($ishome) {
12905:             my $replicationfail;
12906:             foreach my $item (keys(%prompttofetch)) {
12907:                 my $fetchresult= &Apache::lonnet::reply('fetchuserfile:'.$item,$docuhome);
12908:                 unless ($fetchresult eq 'ok') {
12909:                     $replicationfail .= '<li>'.$item.'</li>'."\n";
12910:                 }
12911:             }
12912:             if ($replicationfail) {
12913:                 $output .= '<p class="LC_error">'.
12914:                            &mt('Course home server failed to retrieve:').'<ul>'.
12915:                            $replicationfail.
12916:                            '</ul></p>';
12917:             }
12918:         }
12919:     } else {
12920:         $warning = &mt('No items found in archive.');
12921:     }
12922:     if ($error) {
12923:         $output .= '<p class="LC_error">'.&mt('Not extracted.').'<br />'.
12924:                    $error.'</p>'."\n";
12925:     }
12926:     if ($warning) {
12927:         $output .= '<p class="LC_warning">'.$warning.'</p>'."\n";
12928:     }
12929:     return $output;
12930: }
12931: 
12932: sub cleanup_empty_dirs {
12933:     my ($path) = @_;
12934:     if (($path ne '') && (-d $path)) {
12935:         if (opendir(my $dirh,$path)) {
12936:             my @dircontents = grep(!/^\./,readdir($dirh));
12937:             my $numitems = 0;
12938:             foreach my $item (@dircontents) {
12939:                 if (-d "$path/$item") {
12940:                     &cleanup_empty_dirs("$path/$item");
12941:                     if (-e "$path/$item") {
12942:                         $numitems ++;
12943:                     }
12944:                 } else {
12945:                     $numitems ++;
12946:                 }
12947:             }
12948:             if ($numitems == 0) {
12949:                 rmdir($path);
12950:             }
12951:             closedir($dirh);
12952:         }
12953:     }
12954:     return;
12955: }
12956: 
12957: =pod
12958: 
12959: =item * &get_folder_hierarchy()
12960: 
12961: Provides hierarchy of names of folders/sub-folders containing the current
12962: item,
12963: 
12964: Inputs: 3
12965:      - $navmap - navmaps object
12966: 
12967:      - $map - url for map (either the trigger itself, or map containing
12968:                            the resource, which is the trigger).
12969: 
12970:      - $showitem - 1 => show title for map itself; 0 => do not show.
12971: 
12972: Outputs: 1 @pathitems - array of folder/subfolder names.
12973: 
12974: =cut
12975: 
12976: sub get_folder_hierarchy {
12977:     my ($navmap,$map,$showitem) = @_;
12978:     my @pathitems;
12979:     if (ref($navmap)) {
12980:         my $mapres = $navmap->getResourceByUrl($map);
12981:         if (ref($mapres)) {
12982:             my $pcslist = $mapres->map_hierarchy();
12983:             if ($pcslist ne '') {
12984:                 my @pcs = split(/,/,$pcslist);
12985:                 foreach my $pc (@pcs) {
12986:                     if ($pc == 1) {
12987:                         push(@pathitems,&mt('Main Content'));
12988:                     } else {
12989:                         my $res = $navmap->getByMapPc($pc);
12990:                         if (ref($res)) {
12991:                             my $title = $res->compTitle();
12992:                             $title =~ s/\W+/_/g;
12993:                             if ($title ne '') {
12994:                                 push(@pathitems,$title);
12995:                             }
12996:                         }
12997:                     }
12998:                 }
12999:             }
13000:             if ($showitem) {
13001:                 if ($mapres->{ID} eq '0.0') {
13002:                     push(@pathitems,&mt('Main Content'));
13003:                 } else {
13004:                     my $maptitle = $mapres->compTitle();
13005:                     $maptitle =~ s/\W+/_/g;
13006:                     if ($maptitle ne '') {
13007:                         push(@pathitems,$maptitle);
13008:                     }
13009:                 }
13010:             }
13011:         }
13012:     }
13013:     return @pathitems;
13014: }
13015: 
13016: =pod
13017: 
13018: =item * &get_turnedin_filepath()
13019: 
13020: Determines path in a user's portfolio file for storage of files uploaded
13021: to a specific essayresponse or dropbox item.
13022: 
13023: Inputs: 3 required + 1 optional.
13024: $symb is symb for resource, $uname and $udom are for current user (required).
13025: $caller is optional (can be "submission", if routine is called when storing
13026: an upoaded file when "Submit Answer" button was pressed).
13027: 
13028: Returns array containing $path and $multiresp. 
13029: $path is path in portfolio.  $multiresp is 1 if this resource contains more
13030: than one file upload item.  Callers of routine should append partid as a 
13031: subdirectory to $path in cases where $multiresp is 1.
13032: 
13033: Called by: homework/essayresponse.pm and homework/structuretags.pm
13034: 
13035: =cut
13036: 
13037: sub get_turnedin_filepath {
13038:     my ($symb,$uname,$udom,$caller) = @_;
13039:     my ($map,$resid,$resurl)=&Apache::lonnet::decode_symb($symb);
13040:     my $turnindir;
13041:     my %userhash = &Apache::lonnet::userenvironment($udom,$uname,'turnindir');
13042:     $turnindir = $userhash{'turnindir'};
13043:     my ($path,$multiresp);
13044:     if ($turnindir eq '') {
13045:         if ($caller eq 'submission') {
13046:             $turnindir = &mt('turned in');
13047:             $turnindir =~ s/\W+/_/g;
13048:             my %newhash = (
13049:                             'turnindir' => $turnindir,
13050:                           );
13051:             &Apache::lonnet::put('environment',\%newhash,$udom,$uname);
13052:         }
13053:     }
13054:     if ($turnindir ne '') {
13055:         $path = '/'.$turnindir.'/';
13056:         my ($multipart,$turnin,@pathitems);
13057:         my $navmap = Apache::lonnavmaps::navmap->new();
13058:         if (defined($navmap)) {
13059:             my $mapres = $navmap->getResourceByUrl($map);
13060:             if (ref($mapres)) {
13061:                 my $pcslist = $mapres->map_hierarchy();
13062:                 if ($pcslist ne '') {
13063:                     foreach my $pc (split(/,/,$pcslist)) {
13064:                         my $res = $navmap->getByMapPc($pc);
13065:                         if (ref($res)) {
13066:                             my $title = $res->compTitle();
13067:                             $title =~ s/\W+/_/g;
13068:                             if ($title ne '') {
13069:                                 if (($pc > 1) && (length($title) > 12)) {
13070:                                     $title = substr($title,0,12);
13071:                                 }
13072:                                 push(@pathitems,$title);
13073:                             }
13074:                         }
13075:                     }
13076:                 }
13077:                 my $maptitle = $mapres->compTitle();
13078:                 $maptitle =~ s/\W+/_/g;
13079:                 if ($maptitle ne '') {
13080:                     if (length($maptitle) > 12) {
13081:                         $maptitle = substr($maptitle,0,12);
13082:                     }
13083:                     push(@pathitems,$maptitle);
13084:                 }
13085:                 unless ($env{'request.state'} eq 'construct') {
13086:                     my $res = $navmap->getBySymb($symb);
13087:                     if (ref($res)) {
13088:                         my $partlist = $res->parts();
13089:                         my $totaluploads = 0;
13090:                         if (ref($partlist) eq 'ARRAY') {
13091:                             foreach my $part (@{$partlist}) {
13092:                                 my @types = $res->responseType($part);
13093:                                 my @ids = $res->responseIds($part);
13094:                                 for (my $i=0; $i < scalar(@ids); $i++) {
13095:                                     if ($types[$i] eq 'essay') {
13096:                                         my $partid = $part.'_'.$ids[$i];
13097:                                         if (&Apache::lonnet::EXT("resource.$partid.uploadedfiletypes") ne '') {
13098:                                             $totaluploads ++;
13099:                                         }
13100:                                     }
13101:                                 }
13102:                             }
13103:                             if ($totaluploads > 1) {
13104:                                 $multiresp = 1;
13105:                             }
13106:                         }
13107:                     }
13108:                 }
13109:             } else {
13110:                 return;
13111:             }
13112:         } else {
13113:             return;
13114:         }
13115:         my $restitle=&Apache::lonnet::gettitle($symb);
13116:         $restitle =~ s/\W+/_/g;
13117:         if ($restitle eq '') {
13118:             $restitle = ($resurl =~ m{/[^/]+$});
13119:             if ($restitle eq '') {
13120:                 $restitle = time;
13121:             }
13122:         }
13123:         if (length($restitle) > 12) {
13124:             $restitle = substr($restitle,0,12);
13125:         }
13126:         push(@pathitems,$restitle);
13127:         $path .= join('/',@pathitems);
13128:     }
13129:     return ($path,$multiresp);
13130: }
13131: 
13132: =pod
13133: 
13134: =back
13135: 
13136: =head1 CSV Upload/Handling functions
13137: 
13138: =over 4
13139: 
13140: =item * &upfile_store($r)
13141: 
13142: Store uploaded file, $r should be the HTTP Request object,
13143: needs $env{'form.upfile'}
13144: returns $datatoken to be put into hidden field
13145: 
13146: =cut
13147: 
13148: sub upfile_store {
13149:     my $r=shift;
13150:     $env{'form.upfile'}=~s/\r/\n/gs;
13151:     $env{'form.upfile'}=~s/\f/\n/gs;
13152:     $env{'form.upfile'}=~s/\n+/\n/gs;
13153:     $env{'form.upfile'}=~s/\n+$//gs;
13154: 
13155:     my $datatoken = &valid_datatoken($env{'user.name'}.'_'.$env{'user.domain'}.
13156:                                      '_enroll_'.$env{'request.course.id'}.'_'.
13157:                                      time.'_'.$$);
13158:     return if ($datatoken eq '');
13159: 
13160:     {
13161:         my $datafile = $r->dir_config('lonDaemons').
13162:                            '/tmp/'.$datatoken.'.tmp';
13163:         if ( open(my $fh,'>',$datafile) ) {
13164:             print $fh $env{'form.upfile'};
13165:             close($fh);
13166:         }
13167:     }
13168:     return $datatoken;
13169: }
13170: 
13171: =pod
13172: 
13173: =item * &load_tmp_file($r,$datatoken)
13174: 
13175: Load uploaded file from tmp, $r should be the HTTP Request object,
13176: $datatoken is the name to assign to the temporary file.
13177: sets $env{'form.upfile'} to the contents of the file
13178: 
13179: =cut
13180: 
13181: sub load_tmp_file {
13182:     my ($r,$datatoken) = @_;
13183:     return if ($datatoken eq '');
13184:     my @studentdata=();
13185:     {
13186:         my $studentfile = $r->dir_config('lonDaemons').
13187:                               '/tmp/'.$datatoken.'.tmp';
13188:         if ( open(my $fh,'<',$studentfile) ) {
13189:             @studentdata=<$fh>;
13190:             close($fh);
13191:         }
13192:     }
13193:     $env{'form.upfile'}=join('',@studentdata);
13194: }
13195: 
13196: sub valid_datatoken {
13197:     my ($datatoken) = @_;
13198:     if ($datatoken =~ /^$match_username\_$match_domain\_enroll_$match_domain\_$match_courseid\_\d+_\d+$/) {
13199:         return $datatoken;
13200:     }
13201:     return;
13202: }
13203: 
13204: =pod
13205: 
13206: =item * &upfile_record_sep()
13207: 
13208: Separate uploaded file into records
13209: returns array of records,
13210: needs $env{'form.upfile'} and $env{'form.upfiletype'}
13211: 
13212: =cut
13213: 
13214: sub upfile_record_sep {
13215:     if ($env{'form.upfiletype'} eq 'xml') {
13216:     } else {
13217: 	my @records;
13218: 	foreach my $line (split(/\n/,$env{'form.upfile'})) {
13219: 	    if ($line=~/^\s*$/) { next; }
13220: 	    push(@records,$line);
13221: 	}
13222: 	return @records;
13223:     }
13224: }
13225: 
13226: =pod
13227: 
13228: =item * &record_sep($record)
13229: 
13230: Separate a record into fields $record should be an item from the upfile_record_sep(), needs $env{'form.upfiletype'}
13231: 
13232: =cut
13233: 
13234: sub takeleft {
13235:     my $index=shift;
13236:     return substr('0000'.$index,-4,4);
13237: }
13238: 
13239: sub record_sep {
13240:     my $record=shift;
13241:     my %components=();
13242:     if ($env{'form.upfiletype'} eq 'xml') {
13243:     } elsif ($env{'form.upfiletype'} eq 'space') {
13244:         my $i=0;
13245:         foreach my $field (split(/\s+/,$record)) {
13246:             $field=~s/^(\"|\')//;
13247:             $field=~s/(\"|\')$//;
13248:             $components{&takeleft($i)}=$field;
13249:             $i++;
13250:         }
13251:     } elsif ($env{'form.upfiletype'} eq 'tab') {
13252:         my $i=0;
13253:         foreach my $field (split(/\t/,$record)) {
13254:             $field=~s/^(\"|\')//;
13255:             $field=~s/(\"|\')$//;
13256:             $components{&takeleft($i)}=$field;
13257:             $i++;
13258:         }
13259:     } else {
13260:         my $separator=',';
13261:         if ($env{'form.upfiletype'} eq 'semisv') {
13262:             $separator=';';
13263:         }
13264:         my $i=0;
13265: # the character we are looking for to indicate the end of a quote or a record 
13266:         my $looking_for=$separator;
13267: # do not add the characters to the fields
13268:         my $ignore=0;
13269: # we just encountered a separator (or the beginning of the record)
13270:         my $just_found_separator=1;
13271: # store the field we are working on here
13272:         my $field='';
13273: # work our way through all characters in record
13274:         foreach my $character ($record=~/(.)/g) {
13275:             if ($character eq $looking_for) {
13276:                if ($character ne $separator) {
13277: # Found the end of a quote, again looking for separator
13278:                   $looking_for=$separator;
13279:                   $ignore=1;
13280:                } else {
13281: # Found a separator, store away what we got
13282:                   $components{&takeleft($i)}=$field;
13283: 	          $i++;
13284:                   $just_found_separator=1;
13285:                   $ignore=0;
13286:                   $field='';
13287:                }
13288:                next;
13289:             }
13290: # single or double quotation marks after a separator indicate beginning of a quote
13291: # we are now looking for the end of the quote and need to ignore separators
13292:             if ((($character eq '"') || ($character eq "'")) && ($just_found_separator))  {
13293:                $looking_for=$character;
13294:                next;
13295:             }
13296: # ignore would be true after we reached the end of a quote
13297:             if ($ignore) { next; }
13298:             if (($just_found_separator) && ($character=~/\s/)) { next; }
13299:             $field.=$character;
13300:             $just_found_separator=0; 
13301:         }
13302: # catch the very last entry, since we never encountered the separator
13303:         $components{&takeleft($i)}=$field;
13304:     }
13305:     return %components;
13306: }
13307: 
13308: ######################################################
13309: ######################################################
13310: 
13311: =pod
13312: 
13313: =item * &upfile_select_html()
13314: 
13315: Return HTML code to select a file from the users machine and specify 
13316: the file type.
13317: 
13318: =cut
13319: 
13320: ######################################################
13321: ######################################################
13322: sub upfile_select_html {
13323:     my %Types = (
13324:                  csv   => &mt('CSV (comma separated values, spreadsheet)'),
13325:                  semisv => &mt('Semicolon separated values'),
13326:                  space => &mt('Space separated'),
13327:                  tab   => &mt('Tabulator separated'),
13328: #                 xml   => &mt('HTML/XML'),
13329:                  );
13330:     my $Str = '<input type="file" name="upfile" size="50" />'.
13331:         '<br />'.&mt('Type').': <select name="upfiletype">';
13332:     foreach my $type (sort(keys(%Types))) {
13333:         $Str .= '<option value="'.$type.'" >'.$Types{$type}."</option>\n";
13334:     }
13335:     $Str .= "</select>\n";
13336:     return $Str;
13337: }
13338: 
13339: sub get_samples {
13340:     my ($records,$toget) = @_;
13341:     my @samples=({});
13342:     my $got=0;
13343:     foreach my $rec (@$records) {
13344: 	my %temp = &record_sep($rec);
13345: 	if (! grep(/\S/, values(%temp))) { next; }
13346: 	if (%temp) {
13347: 	    $samples[$got]=\%temp;
13348: 	    $got++;
13349: 	    if ($got == $toget) { last; }
13350: 	}
13351:     }
13352:     return \@samples;
13353: }
13354: 
13355: ######################################################
13356: ######################################################
13357: 
13358: =pod
13359: 
13360: =item * &csv_print_samples($r,$records)
13361: 
13362: Prints a table of sample values from each column uploaded $r is an
13363: Apache Request ref, $records is an arrayref from
13364: &Apache::loncommon::upfile_record_sep
13365: 
13366: =cut
13367: 
13368: ######################################################
13369: ######################################################
13370: sub csv_print_samples {
13371:     my ($r,$records) = @_;
13372:     my $samples = &get_samples($records,5);
13373: 
13374:     $r->print(&mt('Samples').'<br />'.&start_data_table().
13375:               &start_data_table_header_row());
13376:     foreach my $sample (sort({$a <=> $b} keys(%{ $samples->[0] }))) { 
13377:         $r->print('<th>'.&mt('Column [_1]',($sample+1)).'</th>'); }
13378:     $r->print(&end_data_table_header_row());
13379:     foreach my $hash (@$samples) {
13380: 	$r->print(&start_data_table_row());
13381: 	foreach my $sample (sort({$a <=> $b} keys(%{ $samples->[0] }))) {
13382: 	    $r->print('<td>');
13383: 	    if (defined($$hash{$sample})) { $r->print($$hash{$sample}); }
13384: 	    $r->print('</td>');
13385: 	}
13386: 	$r->print(&end_data_table_row());
13387:     }
13388:     $r->print(&end_data_table().'<br />'."\n");
13389: }
13390: 
13391: ######################################################
13392: ######################################################
13393: 
13394: =pod
13395: 
13396: =item * &csv_print_select_table($r,$records,$d)
13397: 
13398: Prints a table to create associations between values and table columns.
13399: 
13400: $r is an Apache Request ref,
13401: $records is an arrayref from &Apache::loncommon::upfile_record_sep,
13402: $d is an array of 2 element arrays (internal name, displayed name,defaultcol)
13403: 
13404: =cut
13405: 
13406: ######################################################
13407: ######################################################
13408: sub csv_print_select_table {
13409:     my ($r,$records,$d) = @_;
13410:     my $i=0;
13411:     my $samples = &get_samples($records,1);
13412:     $r->print(&mt('Associate columns with student attributes.')."\n".
13413: 	      &start_data_table().&start_data_table_header_row().
13414:               '<th>'.&mt('Attribute').'</th>'.
13415:               '<th>'.&mt('Column').'</th>'.
13416:               &end_data_table_header_row()."\n");
13417:     foreach my $array_ref (@$d) {
13418: 	my ($value,$display,$defaultcol)=@{ $array_ref };
13419: 	$r->print(&start_data_table_row().'<td>'.$display.'</td>');
13420: 
13421: 	$r->print('<td><select name="f'.$i.'"'.
13422: 		  ' onchange="javascript:flip(this.form,'.$i.');">');
13423: 	$r->print('<option value="none"></option>');
13424: 	foreach my $sample (sort({$a <=> $b} keys(%{ $samples->[0] }))) {
13425: 	    $r->print('<option value="'.$sample.'"'.
13426:                       ($sample eq $defaultcol ? ' selected="selected" ' : '').
13427:                       '>'.&mt('Column [_1]',($sample+1)).'</option>');
13428: 	}
13429: 	$r->print('</select></td>'.&end_data_table_row()."\n");
13430: 	$i++;
13431:     }
13432:     $r->print(&end_data_table());
13433:     $i--;
13434:     return $i;
13435: }
13436: 
13437: ######################################################
13438: ######################################################
13439: 
13440: =pod
13441: 
13442: =item * &csv_samples_select_table($r,$records,$d)
13443: 
13444: Prints a table of sample values from the upload and can make associate samples to internal names.
13445: 
13446: $r is an Apache Request ref,
13447: $records is an arrayref from &Apache::loncommon::upfile_record_sep,
13448: $d is an array of 2 element arrays (internal name, displayed name)
13449: 
13450: =cut
13451: 
13452: ######################################################
13453: ######################################################
13454: sub csv_samples_select_table {
13455:     my ($r,$records,$d) = @_;
13456:     my $i=0;
13457:     #
13458:     my $max_samples = 5;
13459:     my $samples = &get_samples($records,$max_samples);
13460:     $r->print(&start_data_table().
13461:               &start_data_table_header_row().'<th>'.
13462:               &mt('Field').'</th><th>'.&mt('Samples').'</th>'.
13463:               &end_data_table_header_row());
13464: 
13465:     foreach my $key (sort(keys(%{ $samples->[0] }))) {
13466: 	$r->print(&start_data_table_row().'<td><select name="f'.$i.'"'.
13467: 		  ' onchange="javascript:flip(this.form,'.$i.');">');
13468: 	foreach my $option (@$d) {
13469: 	    my ($value,$display,$defaultcol)=@{ $option };
13470: 	    $r->print('<option value="'.$value.'"'.
13471:                       ($i eq $defaultcol ? ' selected="selected" ':'').'>'.
13472:                       $display.'</option>');
13473: 	}
13474: 	$r->print('</select></td><td>');
13475: 	foreach my $line (0..($max_samples-1)) {
13476: 	    if (defined($samples->[$line]{$key})) { 
13477: 		$r->print($samples->[$line]{$key}."<br />\n"); 
13478: 	    }
13479: 	}
13480: 	$r->print('</td>'.&end_data_table_row());
13481: 	$i++;
13482:     }
13483:     $r->print(&end_data_table());
13484:     $i--;
13485:     return($i);
13486: }
13487: 
13488: ######################################################
13489: ######################################################
13490: 
13491: =pod
13492: 
13493: =item * &clean_excel_name($name)
13494: 
13495: Returns a replacement for $name which does not contain any illegal characters.
13496: 
13497: =cut
13498: 
13499: ######################################################
13500: ######################################################
13501: sub clean_excel_name {
13502:     my ($name) = @_;
13503:     $name =~ s/[:\*\?\/\\]//g;
13504:     if (length($name) > 31) {
13505:         $name = substr($name,0,31);
13506:     }
13507:     return $name;
13508: }
13509: 
13510: =pod
13511: 
13512: =item * &check_if_partid_hidden($id,$symb,$udom,$uname)
13513: 
13514: Returns either 1 or undef
13515: 
13516: 1 if the part is to be hidden, undef if it is to be shown
13517: 
13518: Arguments are:
13519: 
13520: $id the id of the part to be checked
13521: $symb, optional the symb of the resource to check
13522: $udom, optional the domain of the user to check for
13523: $uname, optional the username of the user to check for
13524: 
13525: =cut
13526: 
13527: sub check_if_partid_hidden {
13528:     my ($id,$symb,$udom,$uname) = @_;
13529:     my $hiddenparts=&Apache::lonnet::EXT('resource.0.hiddenparts',
13530: 					 $symb,$udom,$uname);
13531:     my $truth=1;
13532:     #if the string starts with !, then the list is the list to show not hide
13533:     if ($hiddenparts=~s/^\s*!//) { $truth=undef; }
13534:     my @hiddenlist=split(/,/,$hiddenparts);
13535:     foreach my $checkid (@hiddenlist) {
13536: 	if ($checkid =~ /^\s*\Q$id\E\s*$/) { return $truth; }
13537:     }
13538:     return !$truth;
13539: }
13540: 
13541: 
13542: ############################################################
13543: ############################################################
13544: 
13545: =pod
13546: 
13547: =back 
13548: 
13549: =head1 cgi-bin script and graphing routines
13550: 
13551: =over 4
13552: 
13553: =item * &get_cgi_id()
13554: 
13555: Inputs: none
13556: 
13557: Returns an id which can be used to pass environment variables
13558: to various cgi-bin scripts.  These environment variables will
13559: be removed from the users environment after a given time by
13560: the routine &Apache::lonnet::transfer_profile_to_env.
13561: 
13562: =cut
13563: 
13564: ############################################################
13565: ############################################################
13566: my $uniq=0;
13567: sub get_cgi_id {
13568:     $uniq=($uniq+1)%100000;
13569:     return (time.'_'.$$.'_'.$uniq);
13570: }
13571: 
13572: ############################################################
13573: ############################################################
13574: 
13575: =pod
13576: 
13577: =item * &DrawBarGraph()
13578: 
13579: Facilitates the plotting of data in a (stacked) bar graph.
13580: Puts plot definition data into the users environment in order for 
13581: graph.png to plot it.  Returns an <img> tag for the plot.
13582: The bars on the plot are labeled '1','2',...,'n'.
13583: 
13584: Inputs:
13585: 
13586: =over 4
13587: 
13588: =item $Title: string, the title of the plot
13589: 
13590: =item $xlabel: string, text describing the X-axis of the plot
13591: 
13592: =item $ylabel: string, text describing the Y-axis of the plot
13593: 
13594: =item $Max: scalar, the maximum Y value to use in the plot
13595: If $Max is < any data point, the graph will not be rendered.
13596: 
13597: =item $colors: array ref holding the colors to be used for the data sets when
13598: they are plotted.  If undefined, default values will be used.
13599: 
13600: =item $labels: array ref holding the labels to use on the x-axis for the bars.
13601: 
13602: =item @Values: An array of array references.  Each array reference holds data
13603: to be plotted in a stacked bar chart.
13604: 
13605: =item If the final element of @Values is a hash reference the key/value
13606: pairs will be added to the graph definition.
13607: 
13608: =back
13609: 
13610: Returns:
13611: 
13612: An <img> tag which references graph.png and the appropriate identifying
13613: information for the plot.
13614: 
13615: =cut
13616: 
13617: ############################################################
13618: ############################################################
13619: sub DrawBarGraph {
13620:     my ($Title,$xlabel,$ylabel,$Max,$colors,$labels,@Values)=@_;
13621:     #
13622:     if (! defined($colors)) {
13623:         $colors = ['#33ff00', 
13624:                   '#0033cc', '#990000', '#aaaa66', '#663399', '#ff9933',
13625:                   '#66ccff', '#ff9999', '#cccc33', '#660000', '#33cc66',
13626:                   ]; 
13627:     }
13628:     my $extra_settings = {};
13629:     if (ref($Values[-1]) eq 'HASH') {
13630:         $extra_settings = pop(@Values);
13631:     }
13632:     #
13633:     my $identifier = &get_cgi_id();
13634:     my $id = 'cgi.'.$identifier;        
13635:     if (! @Values || ref($Values[0]) ne 'ARRAY') {
13636:         return '';
13637:     }
13638:     #
13639:     my @Labels;
13640:     if (defined($labels)) {
13641:         @Labels = @$labels;
13642:     } else {
13643:         for (my $i=0;$i<@{$Values[0]};$i++) {
13644:             push(@Labels,$i+1);
13645:         }
13646:     }
13647:     #
13648:     my $NumBars = scalar(@{$Values[0]});
13649:     if ($NumBars < scalar(@Labels)) { $NumBars = scalar(@Labels); }
13650:     my %ValuesHash;
13651:     my $NumSets=1;
13652:     foreach my $array (@Values) {
13653:         next if (! ref($array));
13654:         $ValuesHash{$id.'.data.'.$NumSets++} = 
13655:             join(',',@$array);
13656:     }
13657:     #
13658:     my ($height,$width,$xskip,$bar_width) = (200,120,1,15);
13659:     if ($NumBars < 3) {
13660:         $width = 120+$NumBars*32;
13661:         $xskip = 1;
13662:         $bar_width = 30;
13663:     } elsif ($NumBars < 5) {
13664:         $width = 120+$NumBars*20;
13665:         $xskip = 1;
13666:         $bar_width = 20;
13667:     } elsif ($NumBars < 10) {
13668:         $width = 120+$NumBars*15;
13669:         $xskip = 1;
13670:         $bar_width = 15;
13671:     } elsif ($NumBars <= 25) {
13672:         $width = 120+$NumBars*11;
13673:         $xskip = 5;
13674:         $bar_width = 8;
13675:     } elsif ($NumBars <= 50) {
13676:         $width = 120+$NumBars*8;
13677:         $xskip = 5;
13678:         $bar_width = 4;
13679:     } else {
13680:         $width = 120+$NumBars*8;
13681:         $xskip = 5;
13682:         $bar_width = 4;
13683:     }
13684:     #
13685:     $Max = 1 if ($Max < 1);
13686:     if ( int($Max) < $Max ) {
13687:         $Max++;
13688:         $Max = int($Max);
13689:     }
13690:     $Title  = '' if (! defined($Title));
13691:     $xlabel = '' if (! defined($xlabel));
13692:     $ylabel = '' if (! defined($ylabel));
13693:     $ValuesHash{$id.'.title'}    = &escape($Title);
13694:     $ValuesHash{$id.'.xlabel'}   = &escape($xlabel);
13695:     $ValuesHash{$id.'.ylabel'}   = &escape($ylabel);
13696:     $ValuesHash{$id.'.y_max_value'} = $Max;
13697:     $ValuesHash{$id.'.NumBars'}  = $NumBars;
13698:     $ValuesHash{$id.'.NumSets'}  = $NumSets;
13699:     $ValuesHash{$id.'.PlotType'} = 'bar';
13700:     $ValuesHash{$id.'.Colors'}   = join(',',@{$colors});
13701:     $ValuesHash{$id.'.height'}   = $height;
13702:     $ValuesHash{$id.'.width'}    = $width;
13703:     $ValuesHash{$id.'.xskip'}    = $xskip;
13704:     $ValuesHash{$id.'.bar_width'} = $bar_width;
13705:     $ValuesHash{$id.'.labels'} = join(',',@Labels);
13706:     #
13707:     # Deal with other parameters
13708:     while (my ($key,$value) = each(%$extra_settings)) {
13709:         $ValuesHash{$id.'.'.$key} = $value;
13710:     }
13711:     #
13712:     &Apache::lonnet::appenv(\%ValuesHash);
13713:     return '<img src="/cgi-bin/graph.png?'.$identifier.'" border="1" />';
13714: }
13715: 
13716: ############################################################
13717: ############################################################
13718: 
13719: =pod
13720: 
13721: =item * &DrawXYGraph()
13722: 
13723: Facilitates the plotting of data in an XY graph.
13724: Puts plot definition data into the users environment in order for 
13725: graph.png to plot it.  Returns an <img> tag for the plot.
13726: 
13727: Inputs:
13728: 
13729: =over 4
13730: 
13731: =item $Title: string, the title of the plot
13732: 
13733: =item $xlabel: string, text describing the X-axis of the plot
13734: 
13735: =item $ylabel: string, text describing the Y-axis of the plot
13736: 
13737: =item $Max: scalar, the maximum Y value to use in the plot
13738: If $Max is < any data point, the graph will not be rendered.
13739: 
13740: =item $colors: Array ref containing the hex color codes for the data to be 
13741: plotted in.  If undefined, default values will be used.
13742: 
13743: =item $Xlabels: Array ref containing the labels to be used for the X-axis.
13744: 
13745: =item $Ydata: Array ref containing Array refs.  
13746: Each of the contained arrays will be plotted as a separate curve.
13747: 
13748: =item %Values: hash indicating or overriding any default values which are 
13749: passed to graph.png.  
13750: Possible values are: width, xskip, x_ticks, x_tick_offset, among others.
13751: 
13752: =back
13753: 
13754: Returns:
13755: 
13756: An <img> tag which references graph.png and the appropriate identifying
13757: information for the plot.
13758: 
13759: =cut
13760: 
13761: ############################################################
13762: ############################################################
13763: sub DrawXYGraph {
13764:     my ($Title,$xlabel,$ylabel,$Max,$colors,$Xlabels,$Ydata,%Values)=@_;
13765:     #
13766:     # Create the identifier for the graph
13767:     my $identifier = &get_cgi_id();
13768:     my $id = 'cgi.'.$identifier;
13769:     #
13770:     $Title  = '' if (! defined($Title));
13771:     $xlabel = '' if (! defined($xlabel));
13772:     $ylabel = '' if (! defined($ylabel));
13773:     my %ValuesHash = 
13774:         (
13775:          $id.'.title'  => &escape($Title),
13776:          $id.'.xlabel' => &escape($xlabel),
13777:          $id.'.ylabel' => &escape($ylabel),
13778:          $id.'.y_max_value'=> $Max,
13779:          $id.'.labels'     => join(',',@$Xlabels),
13780:          $id.'.PlotType'   => 'XY',
13781:          );
13782:     #
13783:     if (defined($colors) && ref($colors) eq 'ARRAY') {
13784:         $ValuesHash{$id.'.Colors'}   = join(',',@{$colors});
13785:     }
13786:     #
13787:     if (! ref($Ydata) || ref($Ydata) ne 'ARRAY') {
13788:         return '';
13789:     }
13790:     my $NumSets=1;
13791:     foreach my $array (@{$Ydata}){
13792:         next if (! ref($array));
13793:         $ValuesHash{$id.'.data.'.$NumSets++} = join(',',@$array);
13794:     }
13795:     $ValuesHash{$id.'.NumSets'} = $NumSets-1;
13796:     #
13797:     # Deal with other parameters
13798:     while (my ($key,$value) = each(%Values)) {
13799:         $ValuesHash{$id.'.'.$key} = $value;
13800:     }
13801:     #
13802:     &Apache::lonnet::appenv(\%ValuesHash);
13803:     return '<img src="/cgi-bin/graph.png?'.$identifier.'" border="1" />';
13804: }
13805: 
13806: ############################################################
13807: ############################################################
13808: 
13809: =pod
13810: 
13811: =item * &DrawXYYGraph()
13812: 
13813: Facilitates the plotting of data in an XY graph with two Y axes.
13814: Puts plot definition data into the users environment in order for 
13815: graph.png to plot it.  Returns an <img> tag for the plot.
13816: 
13817: Inputs:
13818: 
13819: =over 4
13820: 
13821: =item $Title: string, the title of the plot
13822: 
13823: =item $xlabel: string, text describing the X-axis of the plot
13824: 
13825: =item $ylabel: string, text describing the Y-axis of the plot
13826: 
13827: =item $colors: Array ref containing the hex color codes for the data to be 
13828: plotted in.  If undefined, default values will be used.
13829: 
13830: =item $Xlabels: Array ref containing the labels to be used for the X-axis.
13831: 
13832: =item $Ydata1: The first data set
13833: 
13834: =item $Min1: The minimum value of the left Y-axis
13835: 
13836: =item $Max1: The maximum value of the left Y-axis
13837: 
13838: =item $Ydata2: The second data set
13839: 
13840: =item $Min2: The minimum value of the right Y-axis
13841: 
13842: =item $Max2: The maximum value of the left Y-axis
13843: 
13844: =item %Values: hash indicating or overriding any default values which are 
13845: passed to graph.png.  
13846: Possible values are: width, xskip, x_ticks, x_tick_offset, among others.
13847: 
13848: =back
13849: 
13850: Returns:
13851: 
13852: An <img> tag which references graph.png and the appropriate identifying
13853: information for the plot.
13854: 
13855: =cut
13856: 
13857: ############################################################
13858: ############################################################
13859: sub DrawXYYGraph {
13860:     my ($Title,$xlabel,$ylabel,$colors,$Xlabels,$Ydata1,$Min1,$Max1,
13861:                                         $Ydata2,$Min2,$Max2,%Values)=@_;
13862:     #
13863:     # Create the identifier for the graph
13864:     my $identifier = &get_cgi_id();
13865:     my $id = 'cgi.'.$identifier;
13866:     #
13867:     $Title  = '' if (! defined($Title));
13868:     $xlabel = '' if (! defined($xlabel));
13869:     $ylabel = '' if (! defined($ylabel));
13870:     my %ValuesHash = 
13871:         (
13872:          $id.'.title'  => &escape($Title),
13873:          $id.'.xlabel' => &escape($xlabel),
13874:          $id.'.ylabel' => &escape($ylabel),
13875:          $id.'.labels' => join(',',@$Xlabels),
13876:          $id.'.PlotType' => 'XY',
13877:          $id.'.NumSets' => 2,
13878:          $id.'.two_axes' => 1,
13879:          $id.'.y1_max_value' => $Max1,
13880:          $id.'.y1_min_value' => $Min1,
13881:          $id.'.y2_max_value' => $Max2,
13882:          $id.'.y2_min_value' => $Min2,
13883:          );
13884:     #
13885:     if (defined($colors) && ref($colors) eq 'ARRAY') {
13886:         $ValuesHash{$id.'.Colors'}   = join(',',@{$colors});
13887:     }
13888:     #
13889:     if (! ref($Ydata1) || ref($Ydata1) ne 'ARRAY' ||
13890:         ! ref($Ydata2) || ref($Ydata2) ne 'ARRAY'){
13891:         return '';
13892:     }
13893:     my $NumSets=1;
13894:     foreach my $array ($Ydata1,$Ydata2){
13895:         next if (! ref($array));
13896:         $ValuesHash{$id.'.data.'.$NumSets++} = join(',',@$array);
13897:     }
13898:     #
13899:     # Deal with other parameters
13900:     while (my ($key,$value) = each(%Values)) {
13901:         $ValuesHash{$id.'.'.$key} = $value;
13902:     }
13903:     #
13904:     &Apache::lonnet::appenv(\%ValuesHash);
13905:     return '<img src="/cgi-bin/graph.png?'.$identifier.'" border="1" />';
13906: }
13907: 
13908: ############################################################
13909: ############################################################
13910: 
13911: =pod
13912: 
13913: =back 
13914: 
13915: =head1 Statistics helper routines?  
13916: 
13917: Bad place for them but what the hell.
13918: 
13919: =over 4
13920: 
13921: =item * &chartlink()
13922: 
13923: Returns a link to the chart for a specific student.  
13924: 
13925: Inputs:
13926: 
13927: =over 4
13928: 
13929: =item $linktext: The text of the link
13930: 
13931: =item $sname: The students username
13932: 
13933: =item $sdomain: The students domain
13934: 
13935: =back
13936: 
13937: =back
13938: 
13939: =cut
13940: 
13941: ############################################################
13942: ############################################################
13943: sub chartlink {
13944:     my ($linktext, $sname, $sdomain) = @_;
13945:     my $link = '<a href="/adm/statistics?reportSelected=student_assessment'.
13946:         '&amp;SelectedStudent='.&escape($sname.':'.$sdomain).
13947:         '&amp;chartoutputmode='.HTML::Entities::encode('html, with all links').
13948:        '">'.$linktext.'</a>';
13949: }
13950: 
13951: #######################################################
13952: #######################################################
13953: 
13954: =pod
13955: 
13956: =head1 Course Environment Routines
13957: 
13958: =over 4
13959: 
13960: =item * &restore_course_settings()
13961: 
13962: =item * &store_course_settings()
13963: 
13964: Restores/Store indicated form parameters from the course environment.
13965: Will not overwrite existing values of the form parameters.
13966: 
13967: Inputs: 
13968: a scalar describing the data (e.g. 'chart', 'problem_analysis')
13969: 
13970: a hash ref describing the data to be stored.  For example:
13971:    
13972: %Save_Parameters = ('Status' => 'scalar',
13973:     'chartoutputmode' => 'scalar',
13974:     'chartoutputdata' => 'scalar',
13975:     'Section' => 'array',
13976:     'Group' => 'array',
13977:     'StudentData' => 'array',
13978:     'Maps' => 'array');
13979: 
13980: Returns: both routines return nothing
13981: 
13982: =back
13983: 
13984: =cut
13985: 
13986: #######################################################
13987: #######################################################
13988: sub store_course_settings {
13989:     return &store_settings($env{'request.course.id'},@_);
13990: }
13991: 
13992: sub store_settings {
13993:     # save to the environment
13994:     # appenv the same items, just to be safe
13995:     my $udom  = $env{'user.domain'};
13996:     my $uname = $env{'user.name'};
13997:     my ($context,$prefix,$Settings) = @_;
13998:     my %SaveHash;
13999:     my %AppHash;
14000:     while (my ($setting,$type) = each(%$Settings)) {
14001:         my $basename = join('.','internal',$context,$prefix,$setting);
14002:         my $envname = 'environment.'.$basename;
14003:         if (exists($env{'form.'.$setting})) {
14004:             # Save this value away
14005:             if ($type eq 'scalar' &&
14006:                 (! exists($env{$envname}) || 
14007:                  $env{$envname} ne $env{'form.'.$setting})) {
14008:                 $SaveHash{$basename} = $env{'form.'.$setting};
14009:                 $AppHash{$envname}   = $env{'form.'.$setting};
14010:             } elsif ($type eq 'array') {
14011:                 my $stored_form;
14012:                 if (ref($env{'form.'.$setting})) {
14013:                     $stored_form = join(',',
14014:                                         map {
14015:                                             &escape($_);
14016:                                         } sort(@{$env{'form.'.$setting}}));
14017:                 } else {
14018:                     $stored_form = 
14019:                         &escape($env{'form.'.$setting});
14020:                 }
14021:                 # Determine if the array contents are the same.
14022:                 if ($stored_form ne $env{$envname}) {
14023:                     $SaveHash{$basename} = $stored_form;
14024:                     $AppHash{$envname}   = $stored_form;
14025:                 }
14026:             }
14027:         }
14028:     }
14029:     my $put_result = &Apache::lonnet::put('environment',\%SaveHash,
14030:                                           $udom,$uname);
14031:     if ($put_result !~ /^(ok|delayed)/) {
14032:         &Apache::lonnet::logthis('unable to save form parameters, '.
14033:                                  'got error:'.$put_result);
14034:     }
14035:     # Make sure these settings stick around in this session, too
14036:     &Apache::lonnet::appenv(\%AppHash);
14037:     return;
14038: }
14039: 
14040: sub restore_course_settings {
14041:     return &restore_settings($env{'request.course.id'},@_);
14042: }
14043: 
14044: sub restore_settings {
14045:     my ($context,$prefix,$Settings) = @_;
14046:     while (my ($setting,$type) = each(%$Settings)) {
14047:         next if (exists($env{'form.'.$setting}));
14048:         my $envname = 'environment.internal.'.$context.'.'.$prefix.
14049:             '.'.$setting;
14050:         if (exists($env{$envname})) {
14051:             if ($type eq 'scalar') {
14052:                 $env{'form.'.$setting} = $env{$envname};
14053:             } elsif ($type eq 'array') {
14054:                 $env{'form.'.$setting} = [ 
14055:                                            map { 
14056:                                                &unescape($_); 
14057:                                            } split(',',$env{$envname})
14058:                                            ];
14059:             }
14060:         }
14061:     }
14062: }
14063: 
14064: #######################################################
14065: #######################################################
14066: 
14067: =pod
14068: 
14069: =head1 Domain E-mail Routines  
14070: 
14071: =over 4
14072: 
14073: =item * &build_recipient_list()
14074: 
14075: Build recipient lists for following types of e-mail:
14076: (a) Error Reports, (b) Package Updates, (c) lonstatus warnings/errors
14077: (d) Help requests, (e) Course requests needing approval, (f) loncapa
14078: module change checking, student/employee ID conflict checks, as
14079: generated by lonerrorhandler.pm, CHECKRPMS, loncron,
14080: lonsupportreq.pm, loncoursequeueadmin.pm, searchcat.pl respectively.
14081: 
14082: Inputs:
14083: defmail (scalar - email address of default recipient),
14084: mailing type (scalar: errormail, packagesmail, helpdeskmail,
14085: requestsmail, updatesmail, or idconflictsmail).
14086: 
14087: defdom (domain for which to retrieve configuration settings),
14088: 
14089: origmail (scalar - email address of recipient from loncapa.conf,
14090: i.e., predates configuration by DC via domainprefs.pm
14091: 
14092: Returns: comma separated list of addresses to which to send e-mail.
14093: 
14094: =back
14095: 
14096: =cut
14097: 
14098: ############################################################
14099: ############################################################
14100: sub build_recipient_list {
14101:     my ($defmail,$mailing,$defdom,$origmail) = @_;
14102:     my @recipients;
14103:     my ($otheremails,$lastresort,$allbcc,$addtext);
14104:     my %domconfig =
14105:         &Apache::lonnet::get_dom('configuration',['contacts'],$defdom);
14106:     if (ref($domconfig{'contacts'}) eq 'HASH') {
14107:         if (exists($domconfig{'contacts'}{$mailing})) {
14108:             if (ref($domconfig{'contacts'}{$mailing}) eq 'HASH') {
14109:                 my @contacts = ('adminemail','supportemail');
14110:                 foreach my $item (@contacts) {
14111:                     if ($domconfig{'contacts'}{$mailing}{$item}) {
14112:                         my $addr = $domconfig{'contacts'}{$item}; 
14113:                         if (!grep(/^\Q$addr\E$/,@recipients)) {
14114:                             push(@recipients,$addr);
14115:                         }
14116:                     }
14117:                 }
14118:                 $otheremails = $domconfig{'contacts'}{$mailing}{'others'};
14119:                 if ($mailing eq 'helpdeskmail') {
14120:                     if ($domconfig{'contacts'}{$mailing}{'bcc'}) {
14121:                         my @bccs = split(/,/,$domconfig{'contacts'}{$mailing}{'bcc'});
14122:                         my @ok_bccs;
14123:                         foreach my $bcc (@bccs) {
14124:                             $bcc =~ s/^\s+//g;
14125:                             $bcc =~ s/\s+$//g;
14126:                             if ($bcc =~ m/^[^\@]+\@[^\@]+$/) {
14127:                                 if (!(grep(/^\Q$bcc\E$/,@ok_bccs))) {
14128:                                     push(@ok_bccs,$bcc);
14129:                                 }
14130:                             }
14131:                         }
14132:                         if (@ok_bccs > 0) {
14133:                             $allbcc = join(', ',@ok_bccs);
14134:                         }
14135:                     }
14136:                     $addtext = $domconfig{'contacts'}{$mailing}{'include'};
14137:                 }
14138:             }
14139:         } elsif ($origmail ne '') {
14140:             $lastresort = $origmail;
14141:         }
14142:     } elsif ($origmail ne '') {
14143:         $lastresort = $origmail;
14144:     }
14145: 
14146:     if (($mailing eq 'helpdeskmail') && ($lastresort ne '')) {
14147:         unless (grep(/^\Q$defdom\E$/,&Apache::lonnet::current_machine_domains())) {
14148:             my $lonhost = $Apache::lonnet::perlvar{'lonHostID'};
14149:             my $machinedom = $Apache::lonnet::perlvar{'lonDefDomain'};
14150:             my %what = (
14151:                           perlvar => 1,
14152:                        );
14153:             my $primary = &Apache::lonnet::domain($defdom,'primary');
14154:             if ($primary) {
14155:                 my $gotaddr;
14156:                 my ($result,$returnhash) =
14157:                     &Apache::lonnet::get_remote_globals($primary,{ perlvar => 1 });
14158:                 if (($result eq 'ok') && (ref($returnhash) eq 'HASH')) {
14159:                     if ($returnhash->{'lonSupportEMail'} =~ /^[^\@]+\@[^\@]+$/) {
14160:                         $lastresort = $returnhash->{'lonSupportEMail'};
14161:                         $gotaddr = 1;
14162:                     }
14163:                 }
14164:                 unless ($gotaddr) {
14165:                     my $uintdom = &Apache::lonnet::internet_dom($primary);
14166:                     my $intdom = &Apache::lonnet::internet_dom($lonhost);
14167:                     unless ($uintdom eq $intdom) {
14168:                         my %domconfig =
14169:                             &Apache::lonnet::get_dom('configuration',['contacts'],$machinedom);
14170:                         if (ref($domconfig{'contacts'}) eq 'HASH') {
14171:                             if (ref($domconfig{'contacts'}{'otherdomsmail'}) eq 'HASH') {
14172:                                 my @contacts = ('adminemail','supportemail');
14173:                                 foreach my $item (@contacts) {
14174:                                     if ($domconfig{'contacts'}{'otherdomsmail'}{$item}) {
14175:                                         my $addr = $domconfig{'contacts'}{$item};
14176:                                         if (!grep(/^\Q$addr\E$/,@recipients)) {
14177:                                             push(@recipients,$addr);
14178:                                         }
14179:                                     }
14180:                                 }
14181:                                 if ($domconfig{'contacts'}{'otherdomsmail'}{'others'}) {
14182:                                     $otheremails = $domconfig{'contacts'}{'otherdomsmail'}{'others'};
14183:                                 }
14184:                                 if ($domconfig{'contacts'}{'otherdomsmail'}{'bcc'}) {
14185:                                     my @bccs = split(/,/,$domconfig{'contacts'}{'otherdomsmail'}{'bcc'});
14186:                                     my @ok_bccs;
14187:                                     foreach my $bcc (@bccs) {
14188:                                         $bcc =~ s/^\s+//g;
14189:                                         $bcc =~ s/\s+$//g;
14190:                                         if ($bcc =~ m/^[^\@]+\@[^\@]+$/) {
14191:                                             if (!(grep(/^\Q$bcc\E$/,@ok_bccs))) {
14192:                                                 push(@ok_bccs,$bcc);
14193:                                             }
14194:                                         }
14195:                                     }
14196:                                     if (@ok_bccs > 0) {
14197:                                         $allbcc = join(', ',@ok_bccs);
14198:                                     }
14199:                                 }
14200:                                 $addtext = $domconfig{'contacts'}{'otherdomsmail'}{'include'};
14201:                             }
14202:                         }
14203:                     }
14204:                 }
14205:             }
14206:         }
14207:     }
14208:     if (defined($defmail)) {
14209:         if ($defmail ne '') {
14210:             push(@recipients,$defmail);
14211:         }
14212:     }
14213:     if ($otheremails) {
14214:         my @others;
14215:         if ($otheremails =~ /,/) {
14216:             @others = split(/,/,$otheremails);
14217:         } else {
14218:             push(@others,$otheremails);
14219:         }
14220:         foreach my $addr (@others) {
14221:             if (!grep(/^\Q$addr\E$/,@recipients)) {
14222:                 push(@recipients,$addr);
14223:             }
14224:         }
14225:     }
14226:     if ($mailing eq 'helpdeskmail') {
14227:         if ((!@recipients) && ($lastresort ne '')) {
14228:             push(@recipients,$lastresort);
14229:         }
14230:     } elsif ($lastresort ne '') {
14231:         if (!grep(/^\Q$lastresort\E$/,@recipients)) {
14232:             push(@recipients,$lastresort);
14233:         }
14234:     }
14235:     my $recipientlist = join(',',@recipients);
14236:     if (wantarray) {
14237:         return ($recipientlist,$allbcc,$addtext);
14238:     } else {
14239:         return $recipientlist;
14240:     }
14241: }
14242: 
14243: ############################################################
14244: ############################################################
14245: 
14246: =pod
14247: 
14248: =head1 Course Catalog Routines
14249: 
14250: =over 4
14251: 
14252: =item * &gather_categories()
14253: 
14254: Converts category definitions - keys of categories hash stored in  
14255: coursecategories in configuration.db on the primary library server in a 
14256: domain - to an array.  Also generates javascript and idx hash used to 
14257: generate Domain Coordinator interface for editing Course Categories.
14258: 
14259: Inputs:
14260: 
14261: categories (reference to hash of category definitions).
14262: 
14263: cats (reference to array of arrays/hashes which encapsulates hierarchy of
14264:       categories and subcategories).
14265: 
14266: idx (reference to hash of counters used in Domain Coordinator interface for 
14267:       editing Course Categories).
14268: 
14269: jsarray (reference to array of categories used to create Javascript arrays for
14270:          Domain Coordinator interface for editing Course Categories).
14271: 
14272: Returns: nothing
14273: 
14274: Side effects: populates cats, idx and jsarray. 
14275: 
14276: =cut
14277: 
14278: sub gather_categories {
14279:     my ($categories,$cats,$idx,$jsarray) = @_;
14280:     my %counters;
14281:     my $num = 0;
14282:     foreach my $item (keys(%{$categories})) {
14283:         my ($cat,$container,$depth) = map { &unescape($_); } split(/:/,$item);
14284:         if ($container eq '' && $depth == 0) {
14285:             $cats->[$depth][$categories->{$item}] = $cat;
14286:         } else {
14287:             $cats->[$depth]{$container}[$categories->{$item}] = $cat;
14288:         }
14289:         my ($escitem,$tail) = split(/:/,$item,2);
14290:         if ($counters{$tail} eq '') {
14291:             $counters{$tail} = $num;
14292:             $num ++;
14293:         }
14294:         if (ref($idx) eq 'HASH') {
14295:             $idx->{$item} = $counters{$tail};
14296:         }
14297:         if (ref($jsarray) eq 'ARRAY') {
14298:             push(@{$jsarray->[$counters{$tail}]},$item);
14299:         }
14300:     }
14301:     return;
14302: }
14303: 
14304: =pod
14305: 
14306: =item * &extract_categories()
14307: 
14308: Used to generate breadcrumb trails for course categories.
14309: 
14310: Inputs:
14311: 
14312: categories (reference to hash of category definitions).
14313: 
14314: cats (reference to array of arrays/hashes which encapsulates hierarchy of
14315:       categories and subcategories).
14316: 
14317: trails (reference to array of breacrumb trails for each category).
14318: 
14319: allitems (reference to hash - key is category key 
14320:          (format: escaped(name):escaped(parent category):depth in hierarchy).
14321: 
14322: idx (reference to hash of counters used in Domain Coordinator interface for
14323:       editing Course Categories).
14324: 
14325: jsarray (reference to array of categories used to create Javascript arrays for
14326:          Domain Coordinator interface for editing Course Categories).
14327: 
14328: subcats (reference to hash of arrays containing all subcategories within each 
14329:          category, -recursive)
14330: 
14331: Returns: nothing
14332: 
14333: Side effects: populates trails and allitems hash references.
14334: 
14335: =cut
14336: 
14337: sub extract_categories {
14338:     my ($categories,$cats,$trails,$allitems,$idx,$jsarray,$subcats) = @_;
14339:     if (ref($categories) eq 'HASH') {
14340:         &gather_categories($categories,$cats,$idx,$jsarray);
14341:         if (ref($cats->[0]) eq 'ARRAY') {
14342:             for (my $i=0; $i<@{$cats->[0]}; $i++) {
14343:                 my $name = $cats->[0][$i];
14344:                 my $item = &escape($name).'::0';
14345:                 my $trailstr;
14346:                 if ($name eq 'instcode') {
14347:                     $trailstr = &mt('Official courses (with institutional codes)');
14348:                 } elsif ($name eq 'communities') {
14349:                     $trailstr = &mt('Communities');
14350:                 } else {
14351:                     $trailstr = $name;
14352:                 }
14353:                 if ($allitems->{$item} eq '') {
14354:                     push(@{$trails},$trailstr);
14355:                     $allitems->{$item} = scalar(@{$trails})-1;
14356:                 }
14357:                 my @parents = ($name);
14358:                 if (ref($cats->[1]{$name}) eq 'ARRAY') {
14359:                     for (my $j=0; $j<@{$cats->[1]{$name}}; $j++) {
14360:                         my $category = $cats->[1]{$name}[$j];
14361:                         if (ref($subcats) eq 'HASH') {
14362:                             push(@{$subcats->{$item}},&escape($category).':'.&escape($name).':1');
14363:                         }
14364:                         &recurse_categories($cats,2,$category,$trails,$allitems,\@parents,$subcats);
14365:                     }
14366:                 } else {
14367:                     if (ref($subcats) eq 'HASH') {
14368:                         $subcats->{$item} = [];
14369:                     }
14370:                 }
14371:             }
14372:         }
14373:     }
14374:     return;
14375: }
14376: 
14377: =pod
14378: 
14379: =item * &recurse_categories()
14380: 
14381: Recursively used to generate breadcrumb trails for course categories.
14382: 
14383: Inputs:
14384: 
14385: cats (reference to array of arrays/hashes which encapsulates hierarchy of
14386:       categories and subcategories).
14387: 
14388: depth (current depth in hierarchy of categories and sub-categories - 0 indexed).
14389: 
14390: category (current course category, for which breadcrumb trail is being generated).
14391: 
14392: trails (reference to array of breadcrumb trails for each category).
14393: 
14394: allitems (reference to hash - key is category key
14395:          (format: escaped(name):escaped(parent category):depth in hierarchy).
14396: 
14397: parents (array containing containers directories for current category, 
14398:          back to top level). 
14399: 
14400: Returns: nothing
14401: 
14402: Side effects: populates trails and allitems hash references
14403: 
14404: =cut
14405: 
14406: sub recurse_categories {
14407:     my ($cats,$depth,$category,$trails,$allitems,$parents,$subcats) = @_;
14408:     my $shallower = $depth - 1;
14409:     if (ref($cats->[$depth]{$category}) eq 'ARRAY') {
14410:         for (my $k=0; $k<@{$cats->[$depth]{$category}}; $k++) {
14411:             my $name = $cats->[$depth]{$category}[$k];
14412:             my $item = &escape($category).':'.&escape($parents->[-1]).':'.$shallower;
14413:             my $trailstr = join(' -&gt; ',(@{$parents},$category));
14414:             if ($allitems->{$item} eq '') {
14415:                 push(@{$trails},$trailstr);
14416:                 $allitems->{$item} = scalar(@{$trails})-1;
14417:             }
14418:             my $deeper = $depth+1;
14419:             push(@{$parents},$category);
14420:             if (ref($subcats) eq 'HASH') {
14421:                 my $subcat = &escape($name).':'.$category.':'.$depth;
14422:                 for (my $j=@{$parents}; $j>=0; $j--) {
14423:                     my $higher;
14424:                     if ($j > 0) {
14425:                         $higher = &escape($parents->[$j]).':'.
14426:                                   &escape($parents->[$j-1]).':'.$j;
14427:                     } else {
14428:                         $higher = &escape($parents->[$j]).'::'.$j;
14429:                     }
14430:                     push(@{$subcats->{$higher}},$subcat);
14431:                 }
14432:             }
14433:             &recurse_categories($cats,$deeper,$name,$trails,$allitems,$parents,
14434:                                 $subcats);
14435:             pop(@{$parents});
14436:         }
14437:     } else {
14438:         my $item = &escape($category).':'.&escape($parents->[-1]).':'.$shallower;
14439:         my $trailstr = join(' -&gt; ',(@{$parents},$category));
14440:         if ($allitems->{$item} eq '') {
14441:             push(@{$trails},$trailstr);
14442:             $allitems->{$item} = scalar(@{$trails})-1;
14443:         }
14444:     }
14445:     return;
14446: }
14447: 
14448: =pod
14449: 
14450: =item * &assign_categories_table()
14451: 
14452: Create a datatable for display of hierarchical categories in a domain,
14453: with checkboxes to allow a course to be categorized. 
14454: 
14455: Inputs:
14456: 
14457: cathash - reference to hash of categories defined for the domain (from
14458:           configuration.db)
14459: 
14460: currcat - scalar with an & separated list of categories assigned to a course. 
14461: 
14462: type    - scalar contains course type (Course or Community).
14463: 
14464: disabled - scalar (optional) contains disabled="disabled" if input elements are
14465:            to be readonly (e.g., Domain Helpdesk role viewing course settings).
14466: 
14467: Returns: $output (markup to be displayed) 
14468: 
14469: =cut
14470: 
14471: sub assign_categories_table {
14472:     my ($cathash,$currcat,$type,$disabled) = @_;
14473:     my $output;
14474:     if (ref($cathash) eq 'HASH') {
14475:         my (@cats,@trails,%allitems,%idx,@jsarray,@path,$maxdepth);
14476:         &extract_categories($cathash,\@cats,\@trails,\%allitems,\%idx,\@jsarray);
14477:         $maxdepth = scalar(@cats);
14478:         if (@cats > 0) {
14479:             my $itemcount = 0;
14480:             if (ref($cats[0]) eq 'ARRAY') {
14481:                 my @currcategories;
14482:                 if ($currcat ne '') {
14483:                     @currcategories = split('&',$currcat);
14484:                 }
14485:                 my $table;
14486:                 for (my $i=0; $i<@{$cats[0]}; $i++) {
14487:                     my $parent = $cats[0][$i];
14488:                     next if ($parent eq 'instcode');
14489:                     if ($type eq 'Community') {
14490:                         next unless ($parent eq 'communities');
14491:                     } else {
14492:                         next if ($parent eq 'communities');
14493:                     }
14494:                     my $css_class = $itemcount%2?' class="LC_odd_row"':'';
14495:                     my $item = &escape($parent).'::0';
14496:                     my $checked = '';
14497:                     if (@currcategories > 0) {
14498:                         if (grep(/^\Q$item\E$/,@currcategories)) {
14499:                             $checked = ' checked="checked"';
14500:                         }
14501:                     }
14502:                     my $parent_title = $parent;
14503:                     if ($parent eq 'communities') {
14504:                         $parent_title = &mt('Communities');
14505:                     }
14506:                     $table .= '<tr '.$css_class.'><td><span class="LC_nobreak">'.
14507:                               '<input type="checkbox" name="usecategory" value="'.
14508:                               $item.'"'.$checked.$disabled.' />'.$parent_title.'</span>'.
14509:                               '<input type="hidden" name="catname" value="'.$parent.'" /></td>';
14510:                     my $depth = 1;
14511:                     push(@path,$parent);
14512:                     $table .= &assign_category_rows($itemcount,\@cats,$depth,$parent,\@path,\@currcategories,$disabled);
14513:                     pop(@path);
14514:                     $table .= '</tr><tr><td colspan="'.$maxdepth.'" class="LC_row_separator"></td></tr>';
14515:                     $itemcount ++;
14516:                 }
14517:                 if ($itemcount) {
14518:                     $output = &Apache::loncommon::start_data_table().
14519:                               $table.
14520:                               &Apache::loncommon::end_data_table();
14521:                 }
14522:             }
14523:         }
14524:     }
14525:     return $output;
14526: }
14527: 
14528: =pod
14529: 
14530: =item * &assign_category_rows()
14531: 
14532: Create a datatable row for display of nested categories in a domain,
14533: with checkboxes to allow a course to be categorized,called recursively.
14534: 
14535: Inputs:
14536: 
14537: itemcount - track row number for alternating colors
14538: 
14539: cats - reference to array of arrays/hashes which encapsulates hierarchy of
14540:       categories and subcategories.
14541: 
14542: depth - current depth in hierarchy of categories and sub-categories - 0 indexed.
14543: 
14544: parent - parent of current category item
14545: 
14546: path - Array containing all categories back up through the hierarchy from the
14547:        current category to the top level.
14548: 
14549: currcategories - reference to array of current categories assigned to the course
14550: 
14551: disabled - scalar (optional) contains disabled="disabled" if input elements are
14552:            to be readonly (e.g., Domain Helpdesk role viewing course settings).
14553: 
14554: Returns: $output (markup to be displayed).
14555: 
14556: =cut
14557: 
14558: sub assign_category_rows {
14559:     my ($itemcount,$cats,$depth,$parent,$path,$currcategories,$disabled) = @_;
14560:     my ($text,$name,$item,$chgstr);
14561:     if (ref($cats) eq 'ARRAY') {
14562:         my $maxdepth = scalar(@{$cats});
14563:         if (ref($cats->[$depth]) eq 'HASH') {
14564:             if (ref($cats->[$depth]{$parent}) eq 'ARRAY') {
14565:                 my $numchildren = @{$cats->[$depth]{$parent}};
14566:                 my $css_class = $itemcount%2?' class="LC_odd_row"':'';
14567:                 $text .= '<td><table class="LC_data_table">';
14568:                 for (my $j=0; $j<$numchildren; $j++) {
14569:                     $name = $cats->[$depth]{$parent}[$j];
14570:                     $item = &escape($name).':'.&escape($parent).':'.$depth;
14571:                     my $deeper = $depth+1;
14572:                     my $checked = '';
14573:                     if (ref($currcategories) eq 'ARRAY') {
14574:                         if (@{$currcategories} > 0) {
14575:                             if (grep(/^\Q$item\E$/,@{$currcategories})) {
14576:                                 $checked = ' checked="checked"';
14577:                             }
14578:                         }
14579:                     }
14580:                     $text .= '<tr><td><span class="LC_nobreak"><label>'.
14581:                              '<input type="checkbox" name="usecategory" value="'.
14582:                              $item.'"'.$checked.$disabled.' />'.$name.'</label></span>'.
14583:                              '<input type="hidden" name="catname" value="'.$name.'" />'.
14584:                              '</td><td>';
14585:                     if (ref($path) eq 'ARRAY') {
14586:                         push(@{$path},$name);
14587:                         $text .= &assign_category_rows($itemcount,$cats,$deeper,$name,$path,$currcategories,$disabled);
14588:                         pop(@{$path});
14589:                     }
14590:                     $text .= '</td></tr>';
14591:                 }
14592:                 $text .= '</table></td>';
14593:             }
14594:         }
14595:     }
14596:     return $text;
14597: }
14598: 
14599: =pod
14600: 
14601: =back
14602: 
14603: =cut
14604: 
14605: ############################################################
14606: ############################################################
14607: 
14608: 
14609: sub commit_customrole {
14610:     my ($udom,$uname,$url,$three,$four,$five,$start,$end,$context) = @_;
14611:     my $output = &mt('Assigning custom role').' "'.$five.'" by '.$four.':'.$three.' in '.$url.
14612:                          ($start?', '.&mt('starting').' '.localtime($start):'').
14613:                          ($end?', ending '.localtime($end):'').': <b>'.
14614:               &Apache::lonnet::assigncustomrole(
14615:                  $udom,$uname,$url,$three,$four,$five,$end,$start,undef,undef,$context).
14616:                  '</b><br />';
14617:     return $output;
14618: }
14619: 
14620: sub commit_standardrole {
14621:     my ($udom,$uname,$url,$three,$start,$end,$one,$two,$sec,$context,$credits) = @_;
14622:     my ($output,$logmsg,$linefeed);
14623:     if ($context eq 'auto') {
14624:         $linefeed = "\n";
14625:     } else {
14626:         $linefeed = "<br />\n";
14627:     }  
14628:     if ($three eq 'st') {
14629:         my $result = &commit_studentrole(\$logmsg,$udom,$uname,$url,$three,$start,$end,
14630:                                          $one,$two,$sec,$context,$credits);
14631:         if (($result =~ /^error/) || ($result eq 'not_in_class') || 
14632:             ($result eq 'unknown_course') || ($result eq 'refused')) {
14633:             $output = $logmsg.' '.&mt('Error: ').$result."\n"; 
14634:         } else {
14635:             $output = $logmsg.$linefeed.&mt('Assigning').' '.$three.' in '.$url.
14636:                ($start?', '.&mt('starting').' '.localtime($start):'').
14637:                ($end?', '.&mt('ending').' '.localtime($end):'').': ';
14638:             if ($context eq 'auto') {
14639:                 $output .= $result.$linefeed.&mt('Add to classlist').': ok';
14640:             } else {
14641:                $output .= '<b>'.$result.'</b>'.$linefeed.
14642:                &mt('Add to classlist').': <b>ok</b>';
14643:             }
14644:             $output .= $linefeed;
14645:         }
14646:     } else {
14647:         $output = &mt('Assigning').' '.$three.' in '.$url.
14648:                ($start?', '.&mt('starting').' '.localtime($start):'').
14649:                ($end?', '.&mt('ending').' '.localtime($end):'').': ';
14650:         my $result = &Apache::lonnet::assignrole($udom,$uname,$url,$three,$end,$start,'','',$context);
14651:         if ($context eq 'auto') {
14652:             $output .= $result.$linefeed;
14653:         } else {
14654:             $output .= '<b>'.$result.'</b>'.$linefeed;
14655:         }
14656:     }
14657:     return $output;
14658: }
14659: 
14660: sub commit_studentrole {
14661:     my ($logmsg,$udom,$uname,$url,$three,$start,$end,$one,$two,$sec,$context,
14662:         $credits) = @_;
14663:     my ($result,$linefeed,$oldsecurl,$newsecurl);
14664:     if ($context eq 'auto') {
14665:         $linefeed = "\n";
14666:     } else {
14667:         $linefeed = '<br />'."\n";
14668:     }
14669:     if (defined($one) && defined($two)) {
14670:         my $cid=$one.'_'.$two;
14671:         my $oldsec=&Apache::lonnet::getsection($udom,$uname,$cid);
14672:         my $secchange = 0;
14673:         my $expire_role_result;
14674:         my $modify_section_result;
14675:         if ($oldsec ne '-1') { 
14676:             if ($oldsec ne $sec) {
14677:                 $secchange = 1;
14678:                 my $now = time;
14679:                 my $uurl='/'.$cid;
14680:                 $uurl=~s/\_/\//g;
14681:                 if ($oldsec) {
14682:                     $uurl.='/'.$oldsec;
14683:                 }
14684:                 $oldsecurl = $uurl;
14685:                 $expire_role_result = 
14686:                     &Apache::lonnet::assignrole($udom,$uname,$uurl,'st',$now,'','',$context);
14687:                 if ($env{'request.course.sec'} ne '') { 
14688:                     if ($expire_role_result eq 'refused') {
14689:                         my @roles = ('st');
14690:                         my @statuses = ('previous');
14691:                         my @roledoms = ($one);
14692:                         my $withsec = 1;
14693:                         my %roleshash = 
14694:                             &Apache::lonnet::get_my_roles($uname,$udom,'userroles',
14695:                                               \@statuses,\@roles,\@roledoms,$withsec);
14696:                         if (defined ($roleshash{$two.':'.$one.':st:'.$oldsec})) {
14697:                             my ($oldstart,$oldend) = 
14698:                                 split(':',$roleshash{$two.':'.$one.':st:'.$oldsec});
14699:                             if ($oldend > 0 && $oldend <= $now) {
14700:                                 $expire_role_result = 'ok';
14701:                             }
14702:                         }
14703:                     }
14704:                 }
14705:                 $result = $expire_role_result;
14706:             }
14707:         }
14708:         if (($expire_role_result eq 'ok') || ($secchange == 0)) {
14709:             $modify_section_result = 
14710:                 &Apache::lonnet::modify_student_enrollment($udom,$uname,undef,undef,
14711:                                                            undef,undef,undef,$sec,
14712:                                                            $end,$start,'','',$cid,
14713:                                                            '',$context,$credits);
14714:             if ($modify_section_result =~ /^ok/) {
14715:                 if ($secchange == 1) {
14716:                     if ($sec eq '') {
14717:                         $$logmsg .= &mt('Section for [_1] switched from (possibly expired) old section: [_2] to student role without a section.',$uname,$oldsec).$linefeed;
14718:                     } else {
14719:                         $$logmsg .= &mt('Section for [_1] switched from (possibly expired) old section: [_2] to new section: [_3].',$uname,$oldsec,$sec).$linefeed;
14720:                     }
14721:                 } elsif ($oldsec eq '-1') {
14722:                     if ($sec eq '') {
14723:                         $$logmsg .= &mt('New student role without a section for [_1] in course [_2].',$uname,$cid).$linefeed;
14724:                     } else {
14725:                         $$logmsg .= &mt('New student role for [_1] in section [_2] in course [_3].',$uname,$sec,$cid).$linefeed;
14726:                     }
14727:                 } else {
14728:                     if ($sec eq '') {
14729:                         $$logmsg .= &mt('Student [_1] assigned to course [_2] without a section.',$uname,$cid).$linefeed;
14730:                     } else {
14731:                         $$logmsg .= &mt('Student [_1] assigned to section [_2] in course [_3].',$uname,$sec,$cid).$linefeed;
14732:                     }
14733:                 }
14734:             } else {
14735:                 if ($secchange) {       
14736:                     $$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;
14737:                 } else {
14738:                     $$logmsg .= &mt('Error when attempting to modify role for [_1] for section: "[_2]" in course [_3] -error:',$uname,$sec,$cid).' '.$modify_section_result.$linefeed;
14739:                 }
14740:             }
14741:             $result = $modify_section_result;
14742:         } elsif ($secchange == 1) {
14743:             if ($oldsec eq '') {
14744:                 $$logmsg .= &mt('Error when attempting to expire existing role without a section for [_1] in course [_2] -error: ',$uname,$cid).' '.$expire_role_result.$linefeed;
14745:             } else {
14746:                 $$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;
14747:             }
14748:             if ($expire_role_result eq 'refused') {
14749:                 my $newsecurl = '/'.$cid;
14750:                 $newsecurl =~ s/\_/\//g;
14751:                 if ($sec ne '') {
14752:                     $newsecurl.='/'.$sec;
14753:                 }
14754:                 if (&Apache::lonnet::allowed('cst',$newsecurl) && !(&Apache::lonnet::allowed('cst',$oldsecurl))) {
14755:                     if ($sec eq '') {
14756:                         $$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;
14757:                     } else {
14758:                         $$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;
14759:                     }
14760:                 }
14761:             }
14762:         }
14763:     } else {
14764:         $$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;
14765:         $result = "error: incomplete course id\n";
14766:     }
14767:     return $result;
14768: }
14769: 
14770: sub show_role_extent {
14771:     my ($scope,$context,$role) = @_;
14772:     $scope =~ s{^/}{};
14773:     my @courseroles = &Apache::lonuserutils::roles_by_context('course',1);
14774:     push(@courseroles,'co');
14775:     my @authorroles = &Apache::lonuserutils::roles_by_context('author');
14776:     if (($context eq 'course') || (grep(/^\Q$role\E/,@courseroles))) {
14777:         $scope =~ s{/}{_};
14778:         return '<span class="LC_cusr_emph">'.$env{'course.'.$scope.'.description'}.'</span>';
14779:     } elsif (($context eq 'author') || (grep(/^\Q$role\E/,@authorroles))) {
14780:         my ($audom,$auname) = split(/\//,$scope);
14781:         return &mt('[_1] Author Space','<span class="LC_cusr_emph">'.
14782:                    &Apache::loncommon::plainname($auname,$audom).'</span>');
14783:     } else {
14784:         $scope =~ s{/$}{};
14785:         return &mt('Domain: [_1]','<span class="LC_cusr_emph">'.
14786:                    &Apache::lonnet::domain($scope,'description').'</span>');
14787:     }
14788: }
14789: 
14790: ############################################################
14791: ############################################################
14792: 
14793: sub check_clone {
14794:     my ($args,$linefeed) = @_;
14795:     my $cloneid='/'.$args->{'clonedomain'}.'/'.$args->{'clonecourse'};
14796:     my ($clonecrsudom,$clonecrsunum)= &LONCAPA::split_courseid($cloneid);
14797:     my $clonehome=&Apache::lonnet::homeserver($clonecrsunum,$clonecrsudom);
14798:     my $clonemsg;
14799:     my $can_clone = 0;
14800:     my $lctype = lc($args->{'crstype'});
14801:     if ($lctype ne 'community') {
14802:         $lctype = 'course';
14803:     }
14804:     if ($clonehome eq 'no_host') {
14805:         if ($args->{'crstype'} eq 'Community') {
14806:             $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'});
14807:         } else {
14808:             $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'});
14809:         }     
14810:     } else {
14811: 	my %clonedesc = &Apache::lonnet::coursedescription($cloneid,{'one_time' => 1});
14812:         if ($args->{'crstype'} eq 'Community') {
14813:             if ($clonedesc{'type'} ne 'Community') {
14814:                  $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'});
14815:                 return ($can_clone, $clonemsg, $cloneid, $clonehome);
14816:             }
14817:         }
14818: 	if (($env{'request.role.domain'} eq $args->{'clonedomain'}) &&
14819:             (&Apache::lonnet::allowed('ccc',$env{'request.role.domain'}))) {
14820: 	    $can_clone = 1;
14821: 	} else {
14822: 	    my %clonehash = &Apache::lonnet::get('environment',['cloners','internal.coursecode'],
14823: 						 $args->{'clonedomain'},$args->{'clonecourse'});
14824:             if ($clonehash{'cloners'} eq '') {
14825:                 my %domdefs = &Apache::lonnet::get_domain_defaults($args->{'course_domain'});
14826:                 if ($domdefs{'canclone'}) {
14827:                     unless ($domdefs{'canclone'} eq 'none') {
14828:                         if ($domdefs{'canclone'} eq 'domain') {
14829:                             if ($args->{'ccdomain'} eq $args->{'clonedomain'}) {
14830:                                 $can_clone = 1;
14831:                             }
14832:                         } elsif (($clonehash{'internal.coursecode'}) && ($args->{'crscode'}) &&
14833:                                  ($args->{'clonedomain'} eq  $args->{'course_domain'})) {
14834:                             if (&Apache::lonnet::default_instcode_cloning($args->{'clonedomain'},$domdefs{'canclone'},
14835:                                                                           $clonehash{'internal.coursecode'},$args->{'crscode'})) {
14836:                                 $can_clone = 1;
14837:                             }
14838:                         }
14839:                     }
14840:                 }
14841:             } else {
14842: 	        my @cloners = split(/,/,$clonehash{'cloners'});
14843:                 if (grep(/^\*$/,@cloners)) {
14844:                     $can_clone = 1;
14845:                 } elsif (grep(/^\*\:\Q$args->{'ccdomain'}\E$/,@cloners)) {
14846:                     $can_clone = 1;
14847:                 } elsif (grep(/^\Q$args->{'ccuname'}\E:\Q$args->{'ccdomain'}\E$/,@cloners)) {
14848:                     $can_clone = 1;
14849:                 }
14850:                 unless ($can_clone) {
14851:                     if (($clonehash{'internal.coursecode'}) && ($args->{'crscode'}) &&
14852:                         ($args->{'clonedomain'} eq  $args->{'course_domain'})) {
14853:                         my (%gotdomdefaults,%gotcodedefaults);
14854:                         foreach my $cloner (@cloners) {
14855:                             if (($cloner ne '*') && ($cloner !~ /^\*\:$match_domain$/) &&
14856:                                 ($cloner !~ /^$match_username\:$match_domain$/) && ($cloner ne '')) {
14857:                                 my (%codedefaults,@code_order);
14858:                                 if (ref($gotcodedefaults{$args->{'clonedomain'}}) eq 'HASH') {
14859:                                     if (ref($gotcodedefaults{$args->{'clonedomain'}}{'defaults'}) eq 'HASH') {
14860:                                         %codedefaults = %{$gotcodedefaults{$args->{'clonedomain'}}{'defaults'}};
14861:                                     }
14862:                                     if (ref($gotcodedefaults{$args->{'clonedomain'}}{'order'}) eq 'ARRAY') {
14863:                                         @code_order = @{$gotcodedefaults{$args->{'clonedomain'}}{'order'}};
14864:                                     }
14865:                                 } else {
14866:                                     &Apache::lonnet::auto_instcode_defaults($args->{'clonedomain'},
14867:                                                                             \%codedefaults,
14868:                                                                             \@code_order);
14869:                                     $gotcodedefaults{$args->{'clonedomain'}}{'defaults'} = \%codedefaults;
14870:                                     $gotcodedefaults{$args->{'clonedomain'}}{'order'} = \@code_order;
14871:                                 }
14872:                                 if (@code_order > 0) {
14873:                                     if (&Apache::lonnet::check_instcode_cloning(\%codedefaults,\@code_order,
14874:                                                                                 $cloner,$clonehash{'internal.coursecode'},
14875:                                                                                 $args->{'crscode'})) {
14876:                                         $can_clone = 1;
14877:                                         last;
14878:                                     }
14879:                                 }
14880:                             }
14881:                         }
14882:                     }
14883:                 }
14884:             }
14885:             unless ($can_clone) {
14886:                 my $ccrole = 'cc';
14887:                 if ($args->{'crstype'} eq 'Community') {
14888:                     $ccrole = 'co';
14889:                 }
14890:                 my %roleshash =
14891:                     &Apache::lonnet::get_my_roles($args->{'ccuname'},
14892:                                                   $args->{'ccdomain'},
14893:                                                   'userroles',['active'],[$ccrole],
14894:                                                   [$args->{'clonedomain'}]);
14895:                 if ($roleshash{$args->{'clonecourse'}.':'.$args->{'clonedomain'}.':'.$ccrole}) {
14896:                     $can_clone = 1;
14897:                 } elsif (&Apache::lonnet::is_course_owner($args->{'clonedomain'},$args->{'clonecourse'},
14898:                                                           $args->{'ccuname'},$args->{'ccdomain'})) {
14899:                     $can_clone = 1;
14900:                 }
14901:             }
14902:             unless ($can_clone) {
14903:                 if ($args->{'crstype'} eq 'Community') {
14904:                     $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'});
14905:                 } else {
14906:                     $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'});
14907: 	        }
14908: 	    }
14909:         }
14910:     }
14911:     return ($can_clone, $clonemsg, $cloneid, $clonehome);
14912: }
14913: 
14914: sub construct_course {
14915:     my ($args,$logmsg,$courseid,$crsudom,$crsunum,$udom,$uname,$context,
14916:         $cnum,$category,$coderef) = @_;
14917:     my $outcome;
14918:     my $linefeed =  '<br />'."\n";
14919:     if ($context eq 'auto') {
14920:         $linefeed = "\n";
14921:     }
14922: 
14923: #
14924: # Are we cloning?
14925: #
14926:     my ($can_clone, $clonemsg, $cloneid, $clonehome);
14927:     if (($args->{'clonecourse'}) && ($args->{'clonedomain'})) {
14928: 	($can_clone, $clonemsg, $cloneid, $clonehome) = &check_clone($args,$linefeed);
14929: 	if ($context ne 'auto') {
14930:             if ($clonemsg ne '') {
14931: 	        $clonemsg = '<span class="LC_error">'.$clonemsg.'</span>';
14932:             }
14933: 	}
14934: 	$outcome .= $clonemsg.$linefeed;
14935: 
14936:         if (!$can_clone) {
14937: 	    return (0,$outcome);
14938: 	}
14939:     }
14940: 
14941: #
14942: # Open course
14943: #
14944:     my $crstype = lc($args->{'crstype'});
14945:     my %cenv=();
14946:     $$courseid=&Apache::lonnet::createcourse($args->{'course_domain'},
14947:                                              $args->{'cdescr'},
14948:                                              $args->{'curl'},
14949:                                              $args->{'course_home'},
14950:                                              $args->{'nonstandard'},
14951:                                              $args->{'crscode'},
14952:                                              $args->{'ccuname'}.':'.
14953:                                              $args->{'ccdomain'},
14954:                                              $args->{'crstype'},
14955:                                              $cnum,$context,$category);
14956: 
14957:     # Note: The testing routines depend on this being output; see 
14958:     # Utils::Course. This needs to at least be output as a comment
14959:     # if anyone ever decides to not show this, and Utils::Course::new
14960:     # will need to be suitably modified.
14961:     $outcome .= &mt('New LON-CAPA [_1] ID: [_2]',$crstype,$$courseid).$linefeed;
14962:     if ($$courseid =~ /^error:/) {
14963:         return (0,$outcome);
14964:     }
14965: 
14966: #
14967: # Check if created correctly
14968: #
14969:     ($$crsudom,$$crsunum)= &LONCAPA::split_courseid($$courseid);
14970:     my $crsuhome=&Apache::lonnet::homeserver($$crsunum,$$crsudom);
14971:     if ($crsuhome eq 'no_host') {
14972:         $outcome .= &mt('Course creation failed, unrecognized course home server.').$linefeed;
14973:         return (0,$outcome);
14974:     }
14975:     $outcome .= &mt('Created on').': '.$crsuhome.$linefeed;
14976: 
14977: #
14978: # Do the cloning
14979: #   
14980:     if ($can_clone && $cloneid) {
14981: 	$clonemsg = &mt('Cloning [_1] from [_2]',$crstype,$clonehome);
14982: 	if ($context ne 'auto') {
14983: 	    $clonemsg = '<span class="LC_success">'.$clonemsg.'</span>';
14984: 	}
14985: 	$outcome .= $clonemsg.$linefeed;
14986: 	my %oldcenv=&Apache::lonnet::dump('environment',$$crsudom,$$crsunum);
14987: # Copy all files
14988: 	&Apache::lonclonecourse::copycoursefiles($cloneid,$$courseid,$args->{'datemode'},$args->{'dateshift'});
14989: # Restore URL
14990: 	$cenv{'url'}=$oldcenv{'url'};
14991: # Restore title
14992: 	$cenv{'description'}=$oldcenv{'description'};
14993: # Restore creation date, creator and creation context.
14994:         $cenv{'internal.created'}=$oldcenv{'internal.created'};
14995:         $cenv{'internal.creator'}=$oldcenv{'internal.creator'};
14996:         $cenv{'internal.creationcontext'}=$oldcenv{'internal.creationcontext'};
14997: # Mark as cloned
14998: 	$cenv{'clonedfrom'}=$cloneid;
14999: # Need to clone grading mode
15000:         my %newenv=&Apache::lonnet::get('environment',['grading'],$$crsudom,$$crsunum);
15001:         $cenv{'grading'}=$newenv{'grading'};
15002: # Do not clone these environment entries
15003:         &Apache::lonnet::del('environment',
15004:                   ['default_enrollment_start_date',
15005:                    'default_enrollment_end_date',
15006:                    'question.email',
15007:                    'policy.email',
15008:                    'comment.email',
15009:                    'pch.users.denied',
15010:                    'plc.users.denied',
15011:                    'hidefromcat',
15012:                    'checkforpriv',
15013:                    'categories',
15014:                    'internal.uniquecode'],
15015:                    $$crsudom,$$crsunum);
15016:         if ($args->{'textbook'}) {
15017:             $cenv{'internal.textbook'} = $args->{'textbook'};
15018:         }
15019:     }
15020: 
15021: #
15022: # Set environment (will override cloned, if existing)
15023: #
15024:     my @sections = ();
15025:     my @xlists = ();
15026:     if ($args->{'crstype'}) {
15027:         $cenv{'type'}=$args->{'crstype'};
15028:     }
15029:     if ($args->{'crsid'}) {
15030:         $cenv{'courseid'}=$args->{'crsid'};
15031:     }
15032:     if ($args->{'crscode'}) {
15033:         $cenv{'internal.coursecode'}=$args->{'crscode'};
15034:     }
15035:     if ($args->{'crsquota'} ne '') {
15036:         $cenv{'internal.coursequota'}=$args->{'crsquota'};
15037:     } else {
15038:         $cenv{'internal.coursequota'}=$args->{'crsquota'} = 20;
15039:     }
15040:     if ($args->{'ccuname'}) {
15041:         $cenv{'internal.courseowner'} = $args->{'ccuname'}.
15042:                                         ':'.$args->{'ccdomain'};
15043:     } else {
15044:         $cenv{'internal.courseowner'} = $args->{'curruser'};
15045:     }
15046:     if ($args->{'defaultcredits'}) {
15047:         $cenv{'internal.defaultcredits'} = $args->{'defaultcredits'};
15048:     }
15049:     my @badclasses = (); # Used to accumulate sections/crosslistings that did not pass classlist access check for course owner.
15050:     if ($args->{'crssections'}) {
15051:         $cenv{'internal.sectionnums'} = '';
15052:         if ($args->{'crssections'} =~ m/,/) {
15053:             @sections = split/,/,$args->{'crssections'};
15054:         } else {
15055:             $sections[0] = $args->{'crssections'};
15056:         }
15057:         if (@sections > 0) {
15058:             foreach my $item (@sections) {
15059:                 my ($sec,$gp) = split/:/,$item;
15060:                 my $class = $args->{'crscode'}.$sec;
15061:                 my $addcheck = &Apache::lonnet::auto_new_course($$crsunum,$$crsudom,$class,$cenv{'internal.courseowner'});
15062:                 $cenv{'internal.sectionnums'} .= $item.',';
15063:                 unless ($addcheck eq 'ok') {
15064:                     push(@badclasses,$class);
15065:                 }
15066:             }
15067:             $cenv{'internal.sectionnums'} =~ s/,$//;
15068:         }
15069:     }
15070: # do not hide course coordinator from staff listing, 
15071: # even if privileged
15072:     $cenv{'nothideprivileged'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
15073: # add course coordinator's domain to domains to check for privileged users
15074: # if different to course domain
15075:     if ($$crsudom ne $args->{'ccdomain'}) {
15076:         $cenv{'checkforpriv'} = $args->{'ccdomain'};
15077:     }
15078: # add crosslistings
15079:     if ($args->{'crsxlist'}) {
15080:         $cenv{'internal.crosslistings'}='';
15081:         if ($args->{'crsxlist'} =~ m/,/) {
15082:             @xlists = split/,/,$args->{'crsxlist'};
15083:         } else {
15084:             $xlists[0] = $args->{'crsxlist'};
15085:         }
15086:         if (@xlists > 0) {
15087:             foreach my $item (@xlists) {
15088:                 my ($xl,$gp) = split/:/,$item;
15089:                 my $addcheck =  &Apache::lonnet::auto_new_course($$crsunum,$$crsudom,$xl,$cenv{'internal.courseowner'});
15090:                 $cenv{'internal.crosslistings'} .= $item.',';
15091:                 unless ($addcheck eq 'ok') {
15092:                     push(@badclasses,$xl);
15093:                 }
15094:             }
15095:             $cenv{'internal.crosslistings'} =~ s/,$//;
15096:         }
15097:     }
15098:     if ($args->{'autoadds'}) {
15099:         $cenv{'internal.autoadds'}=$args->{'autoadds'};
15100:     }
15101:     if ($args->{'autodrops'}) {
15102:         $cenv{'internal.autodrops'}=$args->{'autodrops'};
15103:     }
15104: # check for notification of enrollment changes
15105:     my @notified = ();
15106:     if ($args->{'notify_owner'}) {
15107:         if ($args->{'ccuname'} ne '') {
15108:             push(@notified,$args->{'ccuname'}.':'.$args->{'ccdomain'});
15109:         }
15110:     }
15111:     if ($args->{'notify_dc'}) {
15112:         if ($uname ne '') { 
15113:             push(@notified,$uname.':'.$udom);
15114:         }
15115:     }
15116:     if (@notified > 0) {
15117:         my $notifylist;
15118:         if (@notified > 1) {
15119:             $notifylist = join(',',@notified);
15120:         } else {
15121:             $notifylist = $notified[0];
15122:         }
15123:         $cenv{'internal.notifylist'} = $notifylist;
15124:     }
15125:     if (@badclasses > 0) {
15126:         my %lt=&Apache::lonlocal::texthash(
15127:                 'tclb' => 'The courses listed below were included as sections or crosslistings affiliated with your new LON-CAPA course.',
15128:                 'howi' => 'However, if automated course roster updates are enabled for this class, these particular sections/crosslistings are not guaranteed to contribute towards enrollment.',
15129:                 'itis' => 'It is possible that rights to access enrollment for these classes will be available through assignment of co-owners.',
15130:         );
15131:         my $badclass_msg = $lt{'tclb'}.$linefeed.$lt{'howi'}.$linefeed.
15132:                            &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'};
15133:         if ($context eq 'auto') {
15134:             $outcome .= $badclass_msg.$linefeed;
15135:         } else {
15136:             $outcome .= '<div class="LC_warning">'.$badclass_msg.$linefeed.'<ul>'."\n";
15137:         }
15138:         foreach my $item (@badclasses) {
15139:             if ($context eq 'auto') {
15140:                 $outcome .= " - $item\n";
15141:             } else {
15142:                 $outcome .= "<li>$item</li>\n";
15143:             }
15144:         }
15145:         if ($context eq 'auto') {
15146:             $outcome .= $linefeed;
15147:         } else {
15148:             $outcome .= "</ul><br /><br /></div>\n";
15149:         }
15150:     }
15151:     if ($args->{'no_end_date'}) {
15152:         $args->{'endaccess'} = 0;
15153:     }
15154:     $cenv{'internal.autostart'}=$args->{'enrollstart'};
15155:     $cenv{'internal.autoend'}=$args->{'enrollend'};
15156:     $cenv{'default_enrollment_start_date'}=$args->{'startaccess'};
15157:     $cenv{'default_enrollment_end_date'}=$args->{'endaccess'};
15158:     if ($args->{'showphotos'}) {
15159:       $cenv{'internal.showphotos'}=$args->{'showphotos'};
15160:     }
15161:     $cenv{'internal.authtype'} = $args->{'authtype'};
15162:     $cenv{'internal.autharg'} = $args->{'autharg'}; 
15163:     if ( ($cenv{'internal.authtype'} =~ /^krb/) && ($cenv{'internal.autoadds'} == 1)) {
15164:         if (! defined($cenv{'internal.autharg'}) || $cenv{'internal.autharg'}  eq '') {
15165:             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'); 
15166:             if ($context eq 'auto') {
15167:                 $outcome .= $krb_msg;
15168:             } else {
15169:                 $outcome .= '<span class="LC_error">'.$krb_msg.'</span>';
15170:             }
15171:             $outcome .= $linefeed;
15172:         }
15173:     }
15174:     if (($args->{'ccdomain'}) && ($args->{'ccuname'})) {
15175:        if ($args->{'setpolicy'}) {
15176:            $cenv{'policy.email'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
15177:        }
15178:        if ($args->{'setcontent'}) {
15179:            $cenv{'question.email'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
15180:        }
15181:        if ($args->{'setcomment'}) {
15182:            $cenv{'comment.email'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
15183:        }
15184:     }
15185:     if ($args->{'reshome'}) {
15186: 	$cenv{'reshome'}=$args->{'reshome'}.'/';
15187: 	$cenv{'reshome'}=~s/\/+$/\//;
15188:     }
15189: #
15190: # course has keyed access
15191: #
15192:     if ($args->{'setkeys'}) {
15193:        $cenv{'keyaccess'}='yes';
15194:     }
15195: # if specified, key authority is not course, but user
15196: # only active if keyaccess is yes
15197:     if ($args->{'keyauth'}) {
15198: 	my ($user,$domain) = split(':',$args->{'keyauth'});
15199: 	$user = &LONCAPA::clean_username($user);
15200: 	$domain = &LONCAPA::clean_username($domain);
15201: 	if ($user ne '' && $domain ne '') {
15202: 	    $cenv{'keyauth'}=$user.':'.$domain;
15203: 	}
15204:     }
15205: 
15206: #
15207: #  generate and store uniquecode (available to course requester), if course should have one.
15208: #
15209:     if ($args->{'uniquecode'}) {
15210:         my ($code,$error) = &make_unique_code($$crsudom,$$crsunum);
15211:         if ($code) {
15212:             $cenv{'internal.uniquecode'} = $code;
15213:             my %crsinfo =
15214:                 &Apache::lonnet::courseiddump($$crsudom,'.',1,'.','.',$$crsunum,undef,undef,'.');
15215:             if (ref($crsinfo{$$crsudom.'_'.$$crsunum}) eq 'HASH') {
15216:                 $crsinfo{$$crsudom.'_'.$$crsunum}{'uniquecode'} = $code;
15217:                 my $putres = &Apache::lonnet::courseidput($$crsudom,\%crsinfo,$crsuhome,'notime');
15218:             }
15219:             if (ref($coderef)) {
15220:                 $$coderef = $code;
15221:             }
15222:         }
15223:     }
15224: 
15225:     if ($args->{'disresdis'}) {
15226:         $cenv{'pch.roles.denied'}='st';
15227:     }
15228:     if ($args->{'disablechat'}) {
15229:         $cenv{'plc.roles.denied'}='st';
15230:     }
15231: 
15232:     # Record we've not yet viewed the Course Initialization Helper for this 
15233:     # course
15234:     $cenv{'course.helper.not.run'} = 1;
15235:     #
15236:     # Use new Randomseed
15237:     #
15238:     $cenv{'rndseed'}=&Apache::lonnet::latest_rnd_algorithm_id();;
15239:     $cenv{'receiptalg'}=&Apache::lonnet::latest_receipt_algorithm_id();;
15240:     #
15241:     # The encryption code and receipt prefix for this course
15242:     #
15243:     $cenv{'internal.encseed'}=$Apache::lonnet::perlvar{'lonReceipt'}.$$.time.int(rand(9999));
15244:     $cenv{'internal.encpref'}=100+int(9*rand(99));
15245:     #
15246:     # By default, use standard grading
15247:     if (!defined($cenv{'grading'})) { $cenv{'grading'} = 'standard'; }
15248: 
15249:     $outcome .= $linefeed.&mt('Setting environment').': '.                 
15250:           &Apache::lonnet::put('environment',\%cenv,$$crsudom,$$crsunum).$linefeed;
15251: #
15252: # Open all assignments
15253: #
15254:     if ($args->{'openall'}) {
15255:        my $storeunder=$$crsudom.'_'.$$crsunum.'.0.opendate';
15256:        my %storecontent = ($storeunder         => time,
15257:                            $storeunder.'.type' => 'date_start');
15258:        
15259:        $outcome .= &mt('Opening all assignments').': '.&Apache::lonnet::cput
15260:                  ('resourcedata',\%storecontent,$$crsudom,$$crsunum).$linefeed;
15261:    }
15262: #
15263: # Set first page
15264: #
15265:     unless (($args->{'nonstandard'}) || ($args->{'firstres'} eq 'blank')
15266: 	    || ($cloneid)) {
15267: 	use LONCAPA::map;
15268: 	$outcome .= &mt('Setting first resource').': ';
15269: 
15270: 	my $map = '/uploaded/'.$$crsudom.'/'.$$crsunum.'/default.sequence';
15271:         my ($errtext,$fatal)=&LONCAPA::map::mapread($map);
15272: 
15273:         $outcome .= ($fatal?$errtext:'read ok').' - ';
15274:         my $title; my $url;
15275:         if ($args->{'firstres'} eq 'syl') {
15276: 	    $title=&mt('Syllabus');
15277:             $url='/public/'.$$crsudom.'/'.$$crsunum.'/syllabus';
15278:         } else {
15279:             $title=&mt('Table of Contents');
15280:             $url='/adm/navmaps';
15281:         }
15282: 
15283:         $LONCAPA::map::resources[1]=$title.':'.$url.':false:start:res';
15284: 	(my $outtext,$errtext) = &LONCAPA::map::storemap($map,1);
15285: 
15286: 	if ($errtext) { $fatal=2; }
15287:         $outcome .= ($fatal?$errtext:'write ok').$linefeed;
15288:     }
15289: 
15290:     return (1,$outcome);
15291: }
15292: 
15293: sub make_unique_code {
15294:     my ($cdom,$cnum) = @_;
15295:     # get lock on uniquecodes db
15296:     my $lockhash = {
15297:                       $cnum."\0".'uniquecodes' => $env{'user.name'}.
15298:                                                   ':'.$env{'user.domain'},
15299:                    };
15300:     my $tries = 0;
15301:     my $gotlock = &Apache::lonnet::newput_dom('uniquecodes',$lockhash,$cdom);
15302:     my ($code,$error);
15303: 
15304:     while (($gotlock ne 'ok') && ($tries<3)) {
15305:         $tries ++;
15306:         sleep 1;
15307:         $gotlock = &Apache::lonnet::newput_dom('uniquecodes',$lockhash,$cdom);
15308:     }
15309:     if ($gotlock eq 'ok') {
15310:         my %currcodes = &Apache::lonnet::dump_dom('uniquecodes',$cdom);
15311:         my $gotcode;
15312:         my $attempts = 0;
15313:         while ((!$gotcode) && ($attempts < 100)) {
15314:             $code = &generate_code();
15315:             if (!exists($currcodes{$code})) {
15316:                 $gotcode = 1;
15317:                 unless (&Apache::lonnet::newput_dom('uniquecodes',{ $code => $cnum },$cdom) eq 'ok') {
15318:                     $error = 'nostore';
15319:                 }
15320:             }
15321:             $attempts ++;
15322:         }
15323:         my @del_lock = ($cnum."\0".'uniquecodes');
15324:         my $dellockoutcome = &Apache::lonnet::del_dom('uniquecodes',\@del_lock,$cdom);
15325:     } else {
15326:         $error = 'nolock';
15327:     }
15328:     return ($code,$error);
15329: }
15330: 
15331: sub generate_code {
15332:     my $code;
15333:     my @letts = qw(B C D G H J K M N P Q R S T V W X Z);
15334:     for (my $i=0; $i<6; $i++) {
15335:         my $lettnum = int (rand 2);
15336:         my $item = '';
15337:         if ($lettnum) {
15338:             $item = $letts[int( rand(18) )];
15339:         } else {
15340:             $item = 1+int( rand(8) );
15341:         }
15342:         $code .= $item;
15343:     }
15344:     return $code;
15345: }
15346: 
15347: ############################################################
15348: ############################################################
15349: 
15350: #SD
15351: # only Community and Course, or anything else?
15352: sub course_type {
15353:     my ($cid) = @_;
15354:     if (!defined($cid)) {
15355:         $cid = $env{'request.course.id'};
15356:     }
15357:     if (defined($env{'course.'.$cid.'.type'})) {
15358:         return $env{'course.'.$cid.'.type'};
15359:     } else {
15360:         return 'Course';
15361:     }
15362: }
15363: 
15364: sub group_term {
15365:     my $crstype = &course_type();
15366:     my %names = (
15367:                   'Course' => 'group',
15368:                   'Community' => 'group',
15369:                 );
15370:     return $names{$crstype};
15371: }
15372: 
15373: sub course_types {
15374:     my @types = ('official','unofficial','community','textbook');
15375:     my %typename = (
15376:                          official   => 'Official course',
15377:                          unofficial => 'Unofficial course',
15378:                          community  => 'Community',
15379:                          textbook   => 'Textbook course',
15380:                    );
15381:     return (\@types,\%typename);
15382: }
15383: 
15384: sub icon {
15385:     my ($file)=@_;
15386:     my $curfext = lc((split(/\./,$file))[-1]);
15387:     my $iconname=$Apache::lonnet::perlvar{'lonIconsURL'}.'/unknown.gif';
15388:     my $embstyle = &Apache::loncommon::fileembstyle($curfext);
15389:     if (!(!defined($embstyle) || $embstyle eq 'unk' || $embstyle eq 'hdn')) {
15390: 	if (-e  $Apache::lonnet::perlvar{'lonDocRoot'}.'/'.
15391: 	          $Apache::lonnet::perlvar{'lonIconsURL'}.'/'.
15392: 	            $curfext.".gif") {
15393: 	    $iconname=$Apache::lonnet::perlvar{'lonIconsURL'}.'/'.
15394: 		$curfext.".gif";
15395: 	}
15396:     }
15397:     return &lonhttpdurl($iconname);
15398: } 
15399: 
15400: sub lonhttpdurl {
15401: #
15402: # Had been used for "small fry" static images on separate port 8080.
15403: # Modify here if lightweight http functionality desired again.
15404: # Currently eliminated due to increasing firewall issues.
15405: #
15406:     my ($url)=@_;
15407:     return $url;
15408: }
15409: 
15410: sub connection_aborted {
15411:     my ($r)=@_;
15412:     $r->print(" ");$r->rflush();
15413:     my $c = $r->connection;
15414:     return $c->aborted();
15415: }
15416: 
15417: #    Escapes strings that may have embedded 's that will be put into
15418: #    strings as 'strings'.
15419: sub escape_single {
15420:     my ($input) = @_;
15421:     $input =~ s/\\/\\\\/g;	# Escape the \'s..(must be first)>
15422:     $input =~ s/\'/\\\'/g;	# Esacpe the 's....
15423:     return $input;
15424: }
15425: 
15426: #  Same as escape_single, but escape's "'s  This 
15427: #  can be used for  "strings"
15428: sub escape_double {
15429:     my ($input) = @_;
15430:     $input =~ s/\\/\\\\/g;	# Escape the /'s..(must be first)>
15431:     $input =~ s/\"/\\\"/g;	# Esacpe the "s....
15432:     return $input;
15433: }
15434:  
15435: #   Escapes the last element of a full URL.
15436: sub escape_url {
15437:     my ($url)   = @_;
15438:     my @urlslices = split(/\//, $url,-1);
15439:     my $lastitem = &escape(pop(@urlslices));
15440:     return &HTML::Entities::encode(join('/',@urlslices),"'").'/'.$lastitem;
15441: }
15442: 
15443: sub compare_arrays {
15444:     my ($arrayref1,$arrayref2) = @_;
15445:     my (@difference,%count);
15446:     @difference = ();
15447:     %count = ();
15448:     if ((ref($arrayref1) eq 'ARRAY') && (ref($arrayref2) eq 'ARRAY')) {
15449:         foreach my $element (@{$arrayref1}, @{$arrayref2}) { $count{$element}++; }
15450:         foreach my $element (keys(%count)) {
15451:             if ($count{$element} == 1) {
15452:                 push(@difference,$element);
15453:             }
15454:         }
15455:     }
15456:     return @difference;
15457: }
15458: 
15459: # -------------------------------------------------------- Initialize user login
15460: sub init_user_environment {
15461:     my ($r, $username, $domain, $authhost, $form, $args) = @_;
15462:     my $lonids=$Apache::lonnet::perlvar{'lonIDsDir'};
15463: 
15464:     my $public=($username eq 'public' && $domain eq 'public');
15465: 
15466: # See if old ID present, if so, remove
15467: 
15468:     my ($filename,$cookie,$userroles,$firstaccenv,$timerintenv);
15469:     my $now=time;
15470: 
15471:     if ($public) {
15472: 	my $max_public=100;
15473: 	my $oldest;
15474: 	my $oldest_time=0;
15475: 	for(my $next=1;$next<=$max_public;$next++) {
15476: 	    if (-e $lonids."/publicuser_$next.id") {
15477: 		my $mtime=(stat($lonids."/publicuser_$next.id"))[9];
15478: 		if ($mtime<$oldest_time || !$oldest_time) {
15479: 		    $oldest_time=$mtime;
15480: 		    $oldest=$next;
15481: 		}
15482: 	    } else {
15483: 		$cookie="publicuser_$next";
15484: 		last;
15485: 	    }
15486: 	}
15487: 	if (!$cookie) { $cookie="publicuser_$oldest"; }
15488:     } else {
15489: 	# if this isn't a robot, kill any existing non-robot sessions
15490: 	if (!$args->{'robot'}) {
15491: 	    opendir(DIR,$lonids);
15492: 	    while ($filename=readdir(DIR)) {
15493: 		if ($filename=~/^$username\_\d+\_$domain\_$authhost\.id$/) {
15494: 		    unlink($lonids.'/'.$filename);
15495: 		}
15496: 	    }
15497: 	    closedir(DIR);
15498: # If there is a undeleted lockfile for the user's paste buffer remove it.
15499:             my $namespace = 'nohist_courseeditor';
15500:             my $lockingkey = 'paste'."\0".'locked_num';
15501:             my %lockhash = &Apache::lonnet::get($namespace,[$lockingkey],
15502:                                                 $domain,$username);
15503:             if (exists($lockhash{$lockingkey})) {
15504:                 my $delresult = &Apache::lonnet::del($namespace,[$lockingkey],$domain,$username);
15505:                 unless ($delresult eq 'ok') {
15506:                     &Apache::lonnet::logthis("Failed to delete paste buffer locking key in $namespace for ".$username.":".$domain." Result was: $delresult");
15507:                 }
15508:             }
15509: 	}
15510: # Give them a new cookie
15511: 	my $id = ($args->{'robot'} ? 'robot'.$args->{'robot'}
15512: 		                   : $now.$$.int(rand(10000)));
15513: 	$cookie="$username\_$id\_$domain\_$authhost";
15514:     
15515: # Initialize roles
15516: 
15517: 	($userroles,$firstaccenv,$timerintenv) = 
15518:             &Apache::lonnet::rolesinit($domain,$username,$authhost);
15519:     }
15520: # ------------------------------------ Check browser type and MathML capability
15521: 
15522:     my ($httpbrowser,$clientbrowser,$clientversion,$clientmathml,$clientunicode,
15523:         $clientos,$clientmobile,$clientinfo,$clientosversion) = &decode_user_agent($r);
15524: 
15525: # ------------------------------------------------------------- Get environment
15526: 
15527:     my %userenv = &Apache::lonnet::dump('environment',$domain,$username);
15528:     my ($tmp) = keys(%userenv);
15529:     if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
15530:     } else {
15531: 	undef(%userenv);
15532:     }
15533:     if (($userenv{'interface'}) && (!$form->{'interface'})) {
15534: 	$form->{'interface'}=$userenv{'interface'};
15535:     }
15536:     if ($userenv{'texengine'} eq 'ttm') { $clientmathml=1; }
15537: 
15538: # --------------- Do not trust query string to be put directly into environment
15539:     foreach my $option ('interface','localpath','localres') {
15540:         $form->{$option}=~s/[\n\r\=]//gs;
15541:     }
15542: # --------------------------------------------------------- Write first profile
15543: 
15544:     {
15545: 	my %initial_env = 
15546: 	    ("user.name"          => $username,
15547: 	     "user.domain"        => $domain,
15548: 	     "user.home"          => $authhost,
15549: 	     "browser.type"       => $clientbrowser,
15550: 	     "browser.version"    => $clientversion,
15551: 	     "browser.mathml"     => $clientmathml,
15552: 	     "browser.unicode"    => $clientunicode,
15553: 	     "browser.os"         => $clientos,
15554:              "browser.mobile"     => $clientmobile,
15555:              "browser.info"       => $clientinfo,
15556:              "browser.osversion"  => $clientosversion,
15557: 	     "server.domain"      => $Apache::lonnet::perlvar{'lonDefDomain'},
15558: 	     "request.course.fn"  => '',
15559: 	     "request.course.uri" => '',
15560: 	     "request.course.sec" => '',
15561: 	     "request.role"       => 'cm',
15562: 	     "request.role.adv"   => $env{'user.adv'},
15563: 	     "request.host"       => $ENV{'REMOTE_ADDR'},);
15564: 
15565:         if ($form->{'localpath'}) {
15566: 	    $initial_env{"browser.localpath"}  = $form->{'localpath'};
15567: 	    $initial_env{"browser.localres"}   = $form->{'localres'};
15568:         }
15569: 	
15570: 	if ($form->{'interface'}) {
15571: 	    $form->{'interface'}=~s/\W//gs;
15572: 	    $initial_env{"browser.interface"} = $form->{'interface'};
15573: 	    $env{'browser.interface'}=$form->{'interface'};
15574: 	}
15575: 
15576:         if ($form->{'iptoken'}) {
15577:             my $lonhost = $r->dir_config('lonHostID');
15578:             $initial_env{"user.noloadbalance"} = $lonhost;
15579:             $env{'user.noloadbalance'} = $lonhost;
15580:         }
15581: 
15582:         if ($form->{'noloadbalance'}) {
15583:             my @hosts = &Apache::lonnet::current_machine_ids();
15584:             my $hosthere = $form->{'noloadbalance'};
15585:             if (grep(/^\Q$hosthere\E$/,@hosts)) {
15586:                 $initial_env{"user.noloadbalance"} = $hosthere;
15587:                 $env{'user.noloadbalance'} = $hosthere;
15588:             }
15589:         }
15590: 
15591:         unless ($domain eq 'public') {
15592:             my %is_adv = ( is_adv => $env{'user.adv'} );
15593:             my %domdef = &Apache::lonnet::get_domain_defaults($domain);
15594: 
15595:             foreach my $tool ('aboutme','blog','webdav','portfolio') {
15596:                 $userenv{'availabletools.'.$tool} = 
15597:                     &Apache::lonnet::usertools_access($username,$domain,$tool,'reload',
15598:                                                       undef,\%userenv,\%domdef,\%is_adv);
15599:             }
15600: 
15601:             foreach my $crstype ('official','unofficial','community','textbook') {
15602:                 $userenv{'canrequest.'.$crstype} =
15603:                     &Apache::lonnet::usertools_access($username,$domain,$crstype,
15604:                                                       'reload','requestcourses',
15605:                                                       \%userenv,\%domdef,\%is_adv);
15606:             }
15607: 
15608:             $userenv{'canrequest.author'} =
15609:                 &Apache::lonnet::usertools_access($username,$domain,'requestauthor',
15610:                                                   'reload','requestauthor',
15611:                                                   \%userenv,\%domdef,\%is_adv);
15612:             my %reqauthor = &Apache::lonnet::get('requestauthor',['author_status','author'],
15613:                                                  $domain,$username);
15614:             my $reqstatus = $reqauthor{'author_status'};
15615:             if ($reqstatus eq 'approval' || $reqstatus eq 'approved') {
15616:                 if (ref($reqauthor{'author'}) eq 'HASH') {
15617:                     $userenv{'requestauthorqueued'} = $reqstatus.':'.
15618:                                                       $reqauthor{'author'}{'timestamp'};
15619:                 }
15620:             }
15621:         }
15622: 
15623: 	$env{'user.environment'} = "$lonids/$cookie.id";
15624: 
15625: 	if (tie(my %disk_env,'GDBM_File',"$lonids/$cookie.id",
15626: 		 &GDBM_WRCREAT(),0640)) {
15627: 	    &_add_to_env(\%disk_env,\%initial_env);
15628: 	    &_add_to_env(\%disk_env,\%userenv,'environment.');
15629: 	    &_add_to_env(\%disk_env,$userroles);
15630:             if (ref($firstaccenv) eq 'HASH') {
15631:                 &_add_to_env(\%disk_env,$firstaccenv);
15632:             }
15633:             if (ref($timerintenv) eq 'HASH') {
15634:                 &_add_to_env(\%disk_env,$timerintenv);
15635:             }
15636: 	    if (ref($args->{'extra_env'})) {
15637: 		&_add_to_env(\%disk_env,$args->{'extra_env'});
15638: 	    }
15639: 	    untie(%disk_env);
15640: 	} else {
15641: 	    &Apache::lonnet::logthis("<span style=\"color:blue;\">WARNING: ".
15642: 			   'Could not create environment storage in lonauth: '.$!.'</span>');
15643: 	    return 'error: '.$!;
15644: 	}
15645:     }
15646:     $env{'request.role'}='cm';
15647:     $env{'request.role.adv'}=$env{'user.adv'};
15648:     $env{'browser.type'}=$clientbrowser;
15649: 
15650:     return $cookie;
15651: 
15652: }
15653: 
15654: sub _add_to_env {
15655:     my ($idf,$env_data,$prefix) = @_;
15656:     if (ref($env_data) eq 'HASH') {
15657:         while (my ($key,$value) = each(%$env_data)) {
15658: 	    $idf->{$prefix.$key} = $value;
15659: 	    $env{$prefix.$key}   = $value;
15660:         }
15661:     }
15662: }
15663: 
15664: # --- Get the symbolic name of a problem and the url
15665: sub get_symb {
15666:     my ($request,$silent) = @_;
15667:     (my $url=$env{'form.url'}) =~ s-^https?\://($ENV{'SERVER_NAME'}|$ENV{'HTTP_HOST'})--;
15668:     my $symb=($env{'form.symb'} ne '' ? $env{'form.symb'} : (&Apache::lonnet::symbread($url)));
15669:     if ($symb eq '') {
15670:         if (!$silent) {
15671:             if (ref($request)) { 
15672:                 $request->print("Unable to handle ambiguous references:$url:.");
15673:             }
15674:             return ();
15675:         }
15676:     }
15677:     &Apache::lonenc::check_decrypt(\$symb);
15678:     return ($symb);
15679: }
15680: 
15681: # --------------------------------------------------------------Get annotation
15682: 
15683: sub get_annotation {
15684:     my ($symb,$enc) = @_;
15685: 
15686:     my $key = $symb;
15687:     if (!$enc) {
15688:         $key =
15689:             &Apache::lonnet::clutter((&Apache::lonnet::decode_symb($symb))[2]);
15690:     }
15691:     my %annotation=&Apache::lonnet::get('nohist_annotations',[$key]);
15692:     return $annotation{$key};
15693: }
15694: 
15695: sub clean_symb {
15696:     my ($symb,$delete_enc) = @_;
15697: 
15698:     &Apache::lonenc::check_decrypt(\$symb);
15699:     my $enc = $env{'request.enc'};
15700:     if ($delete_enc) {
15701:         delete($env{'request.enc'});
15702:     }
15703: 
15704:     return ($symb,$enc);
15705: }
15706: 
15707: ############################################################
15708: ############################################################
15709: 
15710: =pod
15711: 
15712: =head1 Routines for building display used to search for courses
15713: 
15714: 
15715: =over 4
15716: 
15717: =item * &build_filters()
15718: 
15719: Create markup for a table used to set filters to use when selecting
15720: courses in a domain.  Used by lonpickcourse.pm, lonmodifycourse.pm
15721: and quotacheck.pl
15722: 
15723: 
15724: Inputs:
15725: 
15726: filterlist - anonymous array of fields to include as potential filters
15727: 
15728: crstype - course type
15729: 
15730: roleelement - fifth arg in selectcourse_link() populates fifth arg in javascript: opencrsbrowser() function, used
15731:               to pop-open a course selector (will contain "extra element").
15732: 
15733: multelement - if multiple course selections will be allowed, this will be a hidden form element: name: multiple; value: 1
15734: 
15735: filter - anonymous hash of criteria and their values
15736: 
15737: action - form action
15738: 
15739: numfiltersref - ref to scalar (count of number of elements in institutional codes -- e.g., 4 for year, semester, department, and number)
15740: 
15741: caller - caller context (e.g., set to 'modifycourse' when routine is called from lonmodifycourse.pm)
15742: 
15743: cloneruname - username of owner of new course who wants to clone
15744: 
15745: clonerudom - domain of owner of new course who wants to clone
15746: 
15747: typeelem - text to use for left column in row containing course type (i.e., Course, Community or Course/Community)
15748: 
15749: codetitlesref - reference to array of titles of components in institutional codes (official courses)
15750: 
15751: codedom - domain
15752: 
15753: formname - value of form element named "form".
15754: 
15755: fixeddom - domain, if fixed.
15756: 
15757: prevphase - value to assign to form element named "phase" when going back to the previous screen
15758: 
15759: cnameelement - name of form element in form on opener page which will receive title of selected course
15760: 
15761: cnumelement - name of form element in form on opener page which will receive courseID  of selected course
15762: 
15763: cdomelement - name of form element in form on opener page which will receive domain of selected course
15764: 
15765: setroles - includes access constraint identifier when setting a roles-based condition for acces to a portfolio file
15766: 
15767: clonetext - hidden form elements containing list of courses cloneable by intended course owner when DC creates a course
15768: 
15769: clonewarning - warning message about missing information for intended course owner when DC creates a course
15770: 
15771: 
15772: Returns: $output - HTML for display of search criteria, and hidden form elements.
15773: 
15774: 
15775: Side Effects: None
15776: 
15777: =cut
15778: 
15779: # ---------------------------------------------- search for courses based on last activity etc.
15780: 
15781: sub build_filters {
15782:     my ($filterlist,$crstype,$roleelement,$multelement,$filter,$action,
15783:         $numtitlesref,$caller,$cloneruname,$clonerudom,$typeelement,
15784:         $codetitlesref,$codedom,$formname,$fixeddom,$prevphase,
15785:         $cnameelement,$cnumelement,$cdomelement,$setroles,
15786:         $clonetext,$clonewarning) = @_;
15787:     my ($list,$jscript);
15788:     my $onchange = 'javascript:updateFilters(this)';
15789:     my ($domainselectform,$sincefilterform,$createdfilterform,
15790:         $ownerdomselectform,$persondomselectform,$instcodeform,
15791:         $typeselectform,$instcodetitle);
15792:     if ($formname eq '') {
15793:         $formname = $caller;
15794:     }
15795:     foreach my $item (@{$filterlist}) {
15796:         unless (($item eq 'descriptfilter') || ($item eq 'instcodefilter') ||
15797:                 ($item eq 'sincefilter') || ($item eq 'createdfilter')) {
15798:             if ($item eq 'domainfilter') {
15799:                 $filter->{$item} = &LONCAPA::clean_domain($filter->{$item});
15800:             } elsif ($item eq 'coursefilter') {
15801:                 $filter->{$item} = &LONCAPA::clean_courseid($filter->{$item});
15802:             } elsif ($item eq 'ownerfilter') {
15803:                 $filter->{$item} = &LONCAPA::clean_username($filter->{$item});
15804:             } elsif ($item eq 'ownerdomfilter') {
15805:                 $filter->{'ownerdomfilter'} =
15806:                     &LONCAPA::clean_domain($filter->{$item});
15807:                 $ownerdomselectform = &select_dom_form($filter->{'ownerdomfilter'},
15808:                                                        'ownerdomfilter',1);
15809:             } elsif ($item eq 'personfilter') {
15810:                 $filter->{$item} = &LONCAPA::clean_username($filter->{$item});
15811:             } elsif ($item eq 'persondomfilter') {
15812:                 $persondomselectform = &select_dom_form($filter->{'persondomfilter'},
15813:                                                         'persondomfilter',1);
15814:             } else {
15815:                 $filter->{$item} =~ s/\W//g;
15816:             }
15817:             if (!$filter->{$item}) {
15818:                 $filter->{$item} = '';
15819:             }
15820:         }
15821:         if ($item eq 'domainfilter') {
15822:             my $allow_blank = 1;
15823:             if ($formname eq 'portform') {
15824:                 $allow_blank=0;
15825:             } elsif ($formname eq 'studentform') {
15826:                 $allow_blank=0;
15827:             }
15828:             if ($fixeddom) {
15829:                 $domainselectform = '<input type="hidden" name="domainfilter"'.
15830:                                     ' value="'.$codedom.'" />'.
15831:                                     &Apache::lonnet::domain($codedom,'description');
15832:             } else {
15833:                 $domainselectform = &select_dom_form($filter->{$item},
15834:                                                      'domainfilter',
15835:                                                       $allow_blank,'',$onchange);
15836:             }
15837:         } else {
15838:             $list->{$item} = &HTML::Entities::encode($filter->{$item},'<>&"');
15839:         }
15840:     }
15841: 
15842:     # last course activity filter and selection
15843:     $sincefilterform = &timebased_select_form('sincefilter',$filter);
15844: 
15845:     # course created filter and selection
15846:     if (exists($filter->{'createdfilter'})) {
15847:         $createdfilterform = &timebased_select_form('createdfilter',$filter);
15848:     }
15849: 
15850:     my %lt = &Apache::lonlocal::texthash(
15851:                 'cac' => "$crstype Activity",
15852:                 'ccr' => "$crstype Created",
15853:                 'cde' => "$crstype Title",
15854:                 'cdo' => "$crstype Domain",
15855:                 'ins' => 'Institutional Code',
15856:                 'inc' => 'Institutional Categorization',
15857:                 'cow' => "$crstype Owner/Co-owner",
15858:                 'cop' => "$crstype Personnel Includes",
15859:                 'cog' => 'Type',
15860:              );
15861: 
15862:     if (($formname eq 'ccrs') || ($formname eq 'requestcrs')) {
15863:         my $typeval = 'Course';
15864:         if ($crstype eq 'Community') {
15865:             $typeval = 'Community';
15866:         }
15867:         $typeselectform = '<input type="hidden" name="type" value="'.$typeval.'" />';
15868:     } else {
15869:         $typeselectform =  '<select name="type" size="1"';
15870:         if ($onchange) {
15871:             $typeselectform .= ' onchange="'.$onchange.'"';
15872:         }
15873:         $typeselectform .= '>'."\n";
15874:         foreach my $posstype ('Course','Community') {
15875:             $typeselectform.='<option value="'.$posstype.'"'.
15876:                 ($posstype eq $crstype ? ' selected="selected" ' : ''). ">".&mt($posstype)."</option>\n";
15877:         }
15878:         $typeselectform.="</select>";
15879:     }
15880: 
15881:     my ($cloneableonlyform,$cloneabletitle);
15882:     if (exists($filter->{'cloneableonly'})) {
15883:         my $cloneableon = '';
15884:         my $cloneableoff = ' checked="checked"';
15885:         if ($filter->{'cloneableonly'}) {
15886:             $cloneableon = $cloneableoff;
15887:             $cloneableoff = '';
15888:         }
15889:         $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>';
15890:         if ($formname eq 'ccrs') {
15891:             $cloneabletitle = &mt('Cloneable for [_1]',$cloneruname.':'.$clonerudom);
15892:         } else {
15893:             $cloneabletitle = &mt('Cloneable by you');
15894:         }
15895:     }
15896:     my $officialjs;
15897:     if ($crstype eq 'Course') {
15898:         if (exists($filter->{'instcodefilter'})) {
15899: #            if (($fixeddom) || ($formname eq 'requestcrs') ||
15900: #                ($formname eq 'modifycourse') || ($formname eq 'filterpicker')) {
15901:             if ($codedom) {
15902:                 $officialjs = 1;
15903:                 ($instcodeform,$jscript,$$numtitlesref) =
15904:                     &Apache::courseclassifier::instcode_selectors($codedom,'filterpicker',
15905:                                                                   $officialjs,$codetitlesref);
15906:                 if ($jscript) {
15907:                     $jscript = '<script type="text/javascript">'."\n".
15908:                                '// <![CDATA['."\n".
15909:                                $jscript."\n".
15910:                                '// ]]>'."\n".
15911:                                '</script>'."\n";
15912:                 }
15913:             }
15914:             if ($instcodeform eq '') {
15915:                 $instcodeform =
15916:                     '<input type="text" name="instcodefilter" size="10" value="'.
15917:                     $list->{'instcodefilter'}.'" />';
15918:                 $instcodetitle = $lt{'ins'};
15919:             } else {
15920:                 $instcodetitle = $lt{'inc'};
15921:             }
15922:             if ($fixeddom) {
15923:                 $instcodetitle .= '<br />('.$codedom.')';
15924:             }
15925:         }
15926:     }
15927:     my $output = qq|
15928: <form method="post" name="filterpicker" action="$action">
15929: <input type="hidden" name="form" value="$formname" />
15930: |;
15931:     if ($formname eq 'modifycourse') {
15932:         $output .= '<input type="hidden" name="phase" value="courselist" />'."\n".
15933:                    '<input type="hidden" name="prevphase" value="'.
15934:                    $prevphase.'" />'."\n";
15935:     } elsif ($formname eq 'quotacheck') {
15936:         $output .= qq|
15937: <input type="hidden" name="sortby" value="" />
15938: <input type="hidden" name="sortorder" value="" />
15939: |;
15940:     } else {
15941:         my $name_input;
15942:         if ($cnameelement ne '') {
15943:             $name_input = '<input type="hidden" name="cnameelement" value="'.
15944:                           $cnameelement.'" />';
15945:         }
15946:         $output .= qq|
15947: <input type="hidden" name="cnumelement" value="$cnumelement" />
15948: <input type="hidden" name="cdomelement" value="$cdomelement" />
15949: $name_input
15950: $roleelement
15951: $multelement
15952: $typeelement
15953: |;
15954:         if ($formname eq 'portform') {
15955:             $output .= '<input type="hidden" name="setroles" value="'.$setroles.'" />'."\n";
15956:         }
15957:     }
15958:     if ($fixeddom) {
15959:         $output .= '<input type="hidden" name="fixeddom" value="'.$fixeddom.'" />'."\n";
15960:     }
15961:     $output .= "<br />\n".&Apache::lonhtmlcommon::start_pick_box();
15962:     if ($sincefilterform) {
15963:         $output .= &Apache::lonhtmlcommon::row_title($lt{'cac'})
15964:                   .$sincefilterform
15965:                   .&Apache::lonhtmlcommon::row_closure();
15966:     }
15967:     if ($createdfilterform) {
15968:         $output .= &Apache::lonhtmlcommon::row_title($lt{'ccr'})
15969:                   .$createdfilterform
15970:                   .&Apache::lonhtmlcommon::row_closure();
15971:     }
15972:     if ($domainselectform) {
15973:         $output .= &Apache::lonhtmlcommon::row_title($lt{'cdo'})
15974:                   .$domainselectform
15975:                   .&Apache::lonhtmlcommon::row_closure();
15976:     }
15977:     if ($typeselectform) {
15978:         if (($formname eq 'ccrs') || ($formname eq 'requestcrs')) {
15979:             $output .= $typeselectform;
15980:         } else {
15981:             $output .= &Apache::lonhtmlcommon::row_title($lt{'cog'})
15982:                       .$typeselectform
15983:                       .&Apache::lonhtmlcommon::row_closure();
15984:         }
15985:     }
15986:     if ($instcodeform) {
15987:         $output .= &Apache::lonhtmlcommon::row_title($instcodetitle)
15988:                   .$instcodeform
15989:                   .&Apache::lonhtmlcommon::row_closure();
15990:     }
15991:     if (exists($filter->{'ownerfilter'})) {
15992:         $output .= &Apache::lonhtmlcommon::row_title($lt{'cow'}).
15993:                    '<table><tr><td>'.&mt('Username').'<br />'.
15994:                    '<input type="text" name="ownerfilter" size="20" value="'.
15995:                    $list->{'ownerfilter'}.'" /></td><td>'.&mt('Domain').'<br />'.
15996:                    $ownerdomselectform.'</td></tr></table>'.
15997:                    &Apache::lonhtmlcommon::row_closure();
15998:     }
15999:     if (exists($filter->{'personfilter'})) {
16000:         $output .= &Apache::lonhtmlcommon::row_title($lt{'cop'}).
16001:                    '<table><tr><td>'.&mt('Username').'<br />'.
16002:                    '<input type="text" name="personfilter" size="20" value="'.
16003:                    $list->{'personfilter'}.'" /></td><td>'.&mt('Domain').'<br />'.
16004:                    $persondomselectform.'</td></tr></table>'.
16005:                    &Apache::lonhtmlcommon::row_closure();
16006:     }
16007:     if (exists($filter->{'coursefilter'})) {
16008:         $output .= &Apache::lonhtmlcommon::row_title(&mt('LON-CAPA course ID'))
16009:                   .'<input type="text" name="coursefilter" size="25" value="'
16010:                   .$list->{'coursefilter'}.'" />'
16011:                   .&Apache::lonhtmlcommon::row_closure();
16012:     }
16013:     if ($cloneableonlyform) {
16014:         $output .= &Apache::lonhtmlcommon::row_title($cloneabletitle).
16015:                    $cloneableonlyform.&Apache::lonhtmlcommon::row_closure();
16016:     }
16017:     if (exists($filter->{'descriptfilter'})) {
16018:         $output .= &Apache::lonhtmlcommon::row_title($lt{'cde'})
16019:                   .'<input type="text" name="descriptfilter" size="40" value="'
16020:                   .$list->{'descriptfilter'}.'" />'
16021:                   .&Apache::lonhtmlcommon::row_closure(1);
16022:     }
16023:     $output .= &Apache::lonhtmlcommon::end_pick_box().'<p>'.$clonetext."\n".
16024:                '<input type="hidden" name="updater" value="" />'."\n".
16025:                '<input type="submit" name="gosearch" value="'.
16026:                &mt('Search').'" /></p>'."\n".'</form>'."\n".'<hr />'."\n";
16027:     return $jscript.$clonewarning.$output;
16028: }
16029: 
16030: =pod
16031: 
16032: =item * &timebased_select_form()
16033: 
16034: Create markup for a dropdown list used to select a time-based
16035: filter e.g., Course Activity, Course Created, when searching for courses
16036: or communities
16037: 
16038: Inputs:
16039: 
16040: item - name of form element (sincefilter or createdfilter)
16041: 
16042: filter - anonymous hash of criteria and their values
16043: 
16044: Returns: HTML for a select box contained a blank, then six time selections,
16045:          with value set in incoming form variables currently selected.
16046: 
16047: Side Effects: None
16048: 
16049: =cut
16050: 
16051: sub timebased_select_form {
16052:     my ($item,$filter) = @_;
16053:     if (ref($filter) eq 'HASH') {
16054:         $filter->{$item} =~ s/[^\d-]//g;
16055:         if (!$filter->{$item}) { $filter->{$item}=-1; }
16056:         return &select_form(
16057:                             $filter->{$item},
16058:                             $item,
16059:                             {      '-1' => '',
16060:                                 '86400' => &mt('today'),
16061:                                '604800' => &mt('last week'),
16062:                               '2592000' => &mt('last month'),
16063:                               '7776000' => &mt('last three months'),
16064:                              '15552000' => &mt('last six months'),
16065:                              '31104000' => &mt('last year'),
16066:                     'select_form_order' =>
16067:                            ['-1','86400','604800','2592000','7776000',
16068:                             '15552000','31104000']});
16069:     }
16070: }
16071: 
16072: =pod
16073: 
16074: =item * &js_changer()
16075: 
16076: Create script tag containing Javascript used to submit course search form
16077: when course type or domain is changed, and also to hide 'Searching ...' on
16078: page load completion for page showing search result.
16079: 
16080: Inputs: None
16081: 
16082: Returns: markup containing updateFilters() and hideSearching() javascript functions.
16083: 
16084: Side Effects: None
16085: 
16086: =cut
16087: 
16088: sub js_changer {
16089:     return <<ENDJS;
16090: <script type="text/javascript">
16091: // <![CDATA[
16092: function updateFilters(caller) {
16093:     if (typeof(caller) != "undefined") {
16094:         document.filterpicker.updater.value = caller.name;
16095:     }
16096:     document.filterpicker.submit();
16097: }
16098: 
16099: function hideSearching() {
16100:     if (document.getElementById('searching')) {
16101:         document.getElementById('searching').style.display = 'none';
16102:     }
16103:     return;
16104: }
16105: 
16106: // ]]>
16107: </script>
16108: 
16109: ENDJS
16110: }
16111: 
16112: =pod
16113: 
16114: =item * &search_courses()
16115: 
16116: Process selected filters form course search form and pass to lonnet::courseiddump
16117: to retrieve a hash for which keys are courseIDs which match the selected filters.
16118: 
16119: Inputs:
16120: 
16121: dom - domain being searched
16122: 
16123: type - course type ('Course' or 'Community' or '.' if any).
16124: 
16125: filter - anonymous hash of criteria and their values
16126: 
16127: numtitles - for institutional codes - number of categories
16128: 
16129: cloneruname - optional username of new course owner
16130: 
16131: clonerudom - optional domain of new course owner
16132: 
16133: domcloner - optional "domcloner" flag; has value=1 if user has ccc priv in domain being filtered by,
16134:             (used when DC is using course creation form)
16135: 
16136: codetitles - reference to array of titles of components in institutional codes (official courses).
16137: 
16138: cc_clone - escaped comma separated list of courses for which course cloner has active CC role
16139:            (and so can clone automatically)
16140: 
16141: reqcrsdom - domain of new course, where search_courses is used to identify potential courses to clone
16142: 
16143: reqinstcode - institutional code of new course, where search_courses is used to identify potential
16144:               courses to clone
16145: 
16146: Returns: %courses - hash of courses satisfying search criteria, keys = course IDs, values are corresponding colon-separated escaped description, institutional code, owner and type.
16147: 
16148: 
16149: Side Effects: None
16150: 
16151: =cut
16152: 
16153: 
16154: sub search_courses {
16155:     my ($dom,$type,$filter,$numtitles,$cloneruname,$clonerudom,$domcloner,$codetitles,
16156:         $cc_clone,$reqcrsdom,$reqinstcode) = @_;
16157:     my (%courses,%showcourses,$cloner);
16158:     if (($filter->{'ownerfilter'} ne '') ||
16159:         ($filter->{'ownerdomfilter'} ne '')) {
16160:         $filter->{'combownerfilter'} = $filter->{'ownerfilter'}.':'.
16161:                                        $filter->{'ownerdomfilter'};
16162:     }
16163:     foreach my $item ('descriptfilter','coursefilter','combownerfilter') {
16164:         if (!$filter->{$item}) {
16165:             $filter->{$item}='.';
16166:         }
16167:     }
16168:     my $now = time;
16169:     my $timefilter =
16170:        ($filter->{'sincefilter'}==-1?1:$now-$filter->{'sincefilter'});
16171:     my ($createdbefore,$createdafter);
16172:     if (($filter->{'createdfilter'} ne '') && ($filter->{'createdfilter'} !=-1)) {
16173:         $createdbefore = $now;
16174:         $createdafter = $now-$filter->{'createdfilter'};
16175:     }
16176:     my ($instcodefilter,$regexpok);
16177:     if ($numtitles) {
16178:         if ($env{'form.official'} eq 'on') {
16179:             $instcodefilter =
16180:                 &Apache::courseclassifier::instcode_search_str($dom,$numtitles,$codetitles);
16181:             $regexpok = 1;
16182:         } elsif ($env{'form.official'} eq 'off') {
16183:             $instcodefilter = &Apache::courseclassifier::instcode_search_str($dom,$numtitles,$codetitles);
16184:             unless ($instcodefilter eq '') {
16185:                 $regexpok = -1;
16186:             }
16187:         }
16188:     } else {
16189:         $instcodefilter = $filter->{'instcodefilter'};
16190:     }
16191:     if ($instcodefilter eq '') { $instcodefilter = '.'; }
16192:     if ($type eq '') { $type = '.'; }
16193: 
16194:     if (($clonerudom ne '') && ($cloneruname ne '')) {
16195:         $cloner = $cloneruname.':'.$clonerudom;
16196:     }
16197:     %courses = &Apache::lonnet::courseiddump($dom,
16198:                                              $filter->{'descriptfilter'},
16199:                                              $timefilter,
16200:                                              $instcodefilter,
16201:                                              $filter->{'combownerfilter'},
16202:                                              $filter->{'coursefilter'},
16203:                                              undef,undef,$type,$regexpok,undef,undef,
16204:                                              undef,undef,$cloner,$cc_clone,
16205:                                              $filter->{'cloneableonly'},
16206:                                              $createdbefore,$createdafter,undef,
16207:                                              $domcloner,undef,$reqcrsdom,$reqinstcode);
16208:     if (($filter->{'personfilter'} ne '') && ($filter->{'persondomfilter'} ne '')) {
16209:         my $ccrole;
16210:         if ($type eq 'Community') {
16211:             $ccrole = 'co';
16212:         } else {
16213:             $ccrole = 'cc';
16214:         }
16215:         my %rolehash = &Apache::lonnet::get_my_roles($filter->{'personfilter'},
16216:                                                      $filter->{'persondomfilter'},
16217:                                                      'userroles',undef,
16218:                                                      [$ccrole,'in','ad','ep','ta','cr'],
16219:                                                      $dom);
16220:         foreach my $role (keys(%rolehash)) {
16221:             my ($cnum,$cdom,$courserole) = split(':',$role);
16222:             my $cid = $cdom.'_'.$cnum;
16223:             if (exists($courses{$cid})) {
16224:                 if (ref($courses{$cid}) eq 'HASH') {
16225:                     if (ref($courses{$cid}{roles}) eq 'ARRAY') {
16226:                         if (!grep(/^\Q$courserole\E$/,@{$courses{$cid}{roles}})) {
16227:                             push(@{$courses{$cid}{roles}},$courserole);
16228:                         }
16229:                     } else {
16230:                         $courses{$cid}{roles} = [$courserole];
16231:                     }
16232:                     $showcourses{$cid} = $courses{$cid};
16233:                 }
16234:             }
16235:         }
16236:         %courses = %showcourses;
16237:     }
16238:     return %courses;
16239: }
16240: 
16241: =pod
16242: 
16243: =back
16244: 
16245: =head1 Routines for version requirements for current course.
16246: 
16247: =over 4
16248: 
16249: =item * &check_release_required()
16250: 
16251: Compares required LON-CAPA version with version on server, and
16252: if required version is newer looks for a server with the required version.
16253: 
16254: Looks first at servers in user's owen domain; if none suitable, looks at
16255: servers in course's domain are permitted to host sessions for user's domain.
16256: 
16257: Inputs:
16258: 
16259: $loncaparev - Version on current server (format: Major.Minor.Subrelease-datestamp)
16260: 
16261: $courseid - Course ID of current course
16262: 
16263: $rolecode - User's current role in course (for switchserver query string).
16264: 
16265: $required - LON-CAPA version needed by course (format: Major.Minor).
16266: 
16267: 
16268: Returns:
16269: 
16270: $switchserver - query string tp append to /adm/switchserver call (if
16271:                 current server's LON-CAPA version is too old.
16272: 
16273: $warning - Message is displayed if no suitable server could be found.
16274: 
16275: =cut
16276: 
16277: sub check_release_required {
16278:     my ($loncaparev,$courseid,$rolecode,$required) = @_;
16279:     my ($switchserver,$warning);
16280:     if ($required ne '') {
16281:         my ($reqdmajor,$reqdminor) = ($required =~ /^(\d+)\.(\d+)$/);
16282:         my ($major,$minor) = ($loncaparev =~ /^\'?(\d+)\.(\d+)\.[\w.\-]+\'?$/);
16283:         if ($reqdmajor ne '' && $reqdminor ne '') {
16284:             my $otherserver;
16285:             if (($major eq '' && $minor eq '') ||
16286:                 (($reqdmajor > $major) || (($reqdmajor == $major) && ($reqdminor > $minor)))) {
16287:                 my ($userdomserver) = &Apache::lonnet::choose_server($env{'user.domain'},undef,$required,1);
16288:                 my $switchlcrev =
16289:                     &Apache::lonnet::get_server_loncaparev($env{'user.domain'},
16290:                                                            $userdomserver);
16291:                 my ($swmajor,$swminor) = ($switchlcrev =~ /^\'?(\d+)\.(\d+)\.[\w.\-]+\'?$/);
16292:                 if (($swmajor eq '' && $swminor eq '') || ($reqdmajor > $swmajor) ||
16293:                     (($reqdmajor == $swmajor) && ($reqdminor > $swminor))) {
16294:                     my $cdom = $env{'course.'.$courseid.'.domain'};
16295:                     if ($cdom ne $env{'user.domain'}) {
16296:                         my ($coursedomserver,$coursehostname) = &Apache::lonnet::choose_server($cdom,undef,$required,1);
16297:                         my $serverhomeID = &Apache::lonnet::get_server_homeID($coursehostname);
16298:                         my $serverhomedom = &Apache::lonnet::host_domain($serverhomeID);
16299:                         my %defdomdefaults = &Apache::lonnet::get_domain_defaults($serverhomedom);
16300:                         my %udomdefaults = &Apache::lonnet::get_domain_defaults($env{'user.domain'});
16301:                         my $remoterev = &Apache::lonnet::get_server_loncaparev($serverhomedom,$coursedomserver);
16302:                         my $canhost =
16303:                             &Apache::lonnet::can_host_session($env{'user.domain'},
16304:                                                               $coursedomserver,
16305:                                                               $remoterev,
16306:                                                               $udomdefaults{'remotesessions'},
16307:                                                               $defdomdefaults{'hostedsessions'});
16308: 
16309:                         if ($canhost) {
16310:                             $otherserver = $coursedomserver;
16311:                         } else {
16312:                             $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.");
16313:                         }
16314:                     } else {
16315:                         $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).");
16316:                     }
16317:                 } else {
16318:                     $otherserver = $userdomserver;
16319:                 }
16320:             }
16321:             if ($otherserver ne '') {
16322:                 $switchserver = 'otherserver='.$otherserver.'&amp;role='.$rolecode;
16323:             }
16324:         }
16325:     }
16326:     return ($switchserver,$warning);
16327: }
16328: 
16329: =pod
16330: 
16331: =item * &check_release_result()
16332: 
16333: Inputs:
16334: 
16335: $switchwarning - Warning message if no suitable server found to host session.
16336: 
16337: $switchserver - query string to append to /adm/switchserver containing lonHostID
16338:                 and current role.
16339: 
16340: Returns: HTML to display with information about requirement to switch server.
16341:          Either displaying warning with link to Roles/Courses screen or
16342:          display link to switchserver.
16343: 
16344: =cut
16345: 
16346: sub check_release_result {
16347:     my ($switchwarning,$switchserver) = @_;
16348:     my $output = &start_page('Selected course unavailable on this server').
16349:                  '<p class="LC_warning">';
16350:     if ($switchwarning) {
16351:         $output .= $switchwarning.'<br /><a href="/adm/roles">';
16352:         if (&show_course()) {
16353:             $output .= &mt('Display courses');
16354:         } else {
16355:             $output .= &mt('Display roles');
16356:         }
16357:         $output .= '</a>';
16358:     } elsif ($switchserver) {
16359:         $output .= &mt('This course requires a newer version of LON-CAPA than is installed on this server.').
16360:                    '<br />'.
16361:                    '<a href="/adm/switchserver?'.$switchserver.'">'.
16362:                    &mt('Switch Server').
16363:                    '</a>';
16364:     }
16365:     $output .= '</p>'.&end_page();
16366:     return $output;
16367: }
16368: 
16369: =pod
16370: 
16371: =item * &needs_coursereinit()
16372: 
16373: Determine if course contents stored for user's session needs to be
16374: refreshed, because content has changed since "Big Hash" last tied.
16375: 
16376: Check for change is made if time last checked is more than 10 minutes ago
16377: (by default).
16378: 
16379: Inputs:
16380: 
16381: $loncaparev - Version on current server (format: Major.Minor.Subrelease-datestamp)
16382: 
16383: $interval (optional) - Time which may elapse (in s) between last check for content
16384:                        change in current course. (default: 600 s).
16385: 
16386: Returns: an array; first element is:
16387: 
16388: =over 4
16389: 
16390: 'switch' - if content updates mean user's session
16391:            needs to be switched to a server running a newer LON-CAPA version
16392: 
16393: 'update' - if course session needs to be refreshed (i.e., Big Hash needs to be reloaded)
16394:            on current server hosting user's session
16395: 
16396: ''       - if no action required.
16397: 
16398: =back
16399: 
16400: If first item element is 'switch':
16401: 
16402: second item is $switchwarning - Warning message if no suitable server found to host session.
16403: 
16404: third item is $switchserver - query string to append to /adm/switchserver containing lonHostID
16405:                               and current role.
16406: 
16407: otherwise: no other elements returned.
16408: 
16409: =back
16410: 
16411: =cut
16412: 
16413: sub needs_coursereinit {
16414:     my ($loncaparev,$interval) = @_;
16415:     return() unless ($env{'request.course.id'} && $env{'request.course.tied'});
16416:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
16417:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
16418:     my $now = time;
16419:     if ($interval eq '') {
16420:         $interval = 600;
16421:     }
16422:     if (($now-$env{'request.course.timechecked'})>$interval) {
16423:         my $lastchange = &Apache::lonnet::get_coursechange($cdom,$cnum);
16424:         &Apache::lonnet::appenv({'request.course.timechecked'=>$now});
16425:         if ($lastchange > $env{'request.course.tied'}) {
16426:             my %curr_reqd_hash = &Apache::lonnet::userenvironment($cdom,$cnum,'internal.releaserequired');
16427:             if ($curr_reqd_hash{'internal.releaserequired'} ne '') {
16428:                 my $required = $env{'course.'.$cdom.'_'.$cnum.'.internal.releaserequired'};
16429:                 if ($curr_reqd_hash{'internal.releaserequired'} ne $required) {
16430:                     &Apache::lonnet::appenv({'course.'.$cdom.'_'.$cnum.'.internal.releaserequired' =>
16431:                                              $curr_reqd_hash{'internal.releaserequired'}});
16432:                     my ($switchserver,$switchwarning) =
16433:                         &check_release_required($loncaparev,$cdom.'_'.$cnum,$env{'request.role'},
16434:                                                 $curr_reqd_hash{'internal.releaserequired'});
16435:                     if ($switchwarning ne '' || $switchserver ne '') {
16436:                         return ('switch',$switchwarning,$switchserver);
16437:                     }
16438:                 }
16439:             }
16440:             return ('update');
16441:         }
16442:     }
16443:     return ();
16444: }
16445: 
16446: sub update_content_constraints {
16447:     my ($cdom,$cnum,$chome,$cid) = @_;
16448:     my %curr_reqd_hash = &Apache::lonnet::userenvironment($cdom,$cnum,'internal.releaserequired');
16449:     my ($reqdmajor,$reqdminor) = split(/\./,$curr_reqd_hash{'internal.releaserequired'});
16450:     my %checkresponsetypes;
16451:     foreach my $key (keys(%Apache::lonnet::needsrelease)) {
16452:         my ($item,$name,$value) = split(/:/,$key);
16453:         if ($item eq 'resourcetag') {
16454:             if ($name eq 'responsetype') {
16455:                 $checkresponsetypes{$value} = $Apache::lonnet::needsrelease{$key}
16456:             }
16457:         }
16458:     }
16459:     my $navmap = Apache::lonnavmaps::navmap->new();
16460:     if (defined($navmap)) {
16461:         my %allresponses;
16462:         foreach my $res ($navmap->retrieveResources(undef,sub { $_[0]->is_problem() },1,0)) {
16463:             my %responses = $res->responseTypes();
16464:             foreach my $key (keys(%responses)) {
16465:                 next unless(exists($checkresponsetypes{$key}));
16466:                 $allresponses{$key} += $responses{$key};
16467:             }
16468:         }
16469:         foreach my $key (keys(%allresponses)) {
16470:             my ($major,$minor) = split(/\./,$checkresponsetypes{$key});
16471:             if (($major > $reqdmajor) || ($major == $reqdmajor && $minor > $reqdminor)) {
16472:                 ($reqdmajor,$reqdminor) = ($major,$minor);
16473:             }
16474:         }
16475:         undef($navmap);
16476:     }
16477:     unless (($reqdmajor eq '') && ($reqdminor eq '')) {
16478:         &Apache::lonnet::update_released_required($reqdmajor.'.'.$reqdminor,$cdom,$cnum,$chome,$cid);
16479:     }
16480:     return;
16481: }
16482: 
16483: sub allmaps_incourse {
16484:     my ($cdom,$cnum,$chome,$cid) = @_;
16485:     if ($cdom eq '' || $cnum eq '' || $chome eq '' || $cid eq '') {
16486:         $cid = $env{'request.course.id'};
16487:         $cdom = $env{'course.'.$cid.'.domain'};
16488:         $cnum = $env{'course.'.$cid.'.num'};
16489:         $chome = $env{'course.'.$cid.'.home'};
16490:     }
16491:     my %allmaps = ();
16492:     my $lastchange =
16493:         &Apache::lonnet::get_coursechange($cdom,$cnum);
16494:     if ($lastchange > $env{'request.course.tied'}) {
16495:         my ($furl,$ferr) = &Apache::lonuserstate::readmap("$cdom/$cnum");
16496:         unless ($ferr) {
16497:             &update_content_constraints($cdom,$cnum,$chome,$cid);
16498:         }
16499:     }
16500:     my $navmap = Apache::lonnavmaps::navmap->new();
16501:     if (defined($navmap)) {
16502:         foreach my $res ($navmap->retrieveResources(undef,sub { $_[0]->is_map() },1,0,1)) {
16503:             $allmaps{$res->src()} = 1;
16504:         }
16505:     }
16506:     return \%allmaps;
16507: }
16508: 
16509: sub parse_supplemental_title {
16510:     my ($title) = @_;
16511: 
16512:     my ($foldertitle,$renametitle);
16513:     if ($title =~ /&amp;&amp;&amp;/) {
16514:         $title = &HTML::Entites::decode($title);
16515:     }
16516:     if ($title =~ m/^(\d+)___&&&___($match_username)___&&&___($match_domain)___&&&___(.*)$/) {
16517:         $renametitle=$4;
16518:         my ($time,$uname,$udom) = ($1,$2,$3);
16519:         $foldertitle=&Apache::lontexconvert::msgtexconverted($4);
16520:         my $name =  &plainname($uname,$udom);
16521:         $name = &HTML::Entities::encode($name,'"<>&\'');
16522:         $renametitle = &HTML::Entities::encode($renametitle,'"<>&\'');
16523:         $title='<i>'.&Apache::lonlocal::locallocaltime($time).'</i> '.
16524:             $name.': <br />'.$foldertitle;
16525:     }
16526:     if (wantarray) {
16527:         return ($title,$foldertitle,$renametitle);
16528:     }
16529:     return $title;
16530: }
16531: 
16532: sub recurse_supplemental {
16533:     my ($cnum,$cdom,$suppmap,$numfiles,$errors) = @_;
16534:     if ($suppmap) {
16535:         my ($errtext,$fatal) = &LONCAPA::map::mapread('/uploaded/'.$cdom.'/'.$cnum.'/'.$suppmap);
16536:         if ($fatal) {
16537:             $errors ++;
16538:         } else {
16539:             if ($#LONCAPA::map::resources > 0) {
16540:                 foreach my $res (@LONCAPA::map::resources) {
16541:                     my ($title,$src,$ext,$type,$status)=split(/\:/,$res);
16542:                     if (($src ne '') && ($status eq 'res')) {
16543:                         if ($src =~ m{^\Q/uploaded/$cdom/$cnum/\E(supplemental_\d+\.sequence)$}) {
16544:                             ($numfiles,$errors) = &recurse_supplemental($cnum,$cdom,$1,$numfiles,$errors);
16545:                         } else {
16546:                             $numfiles ++;
16547:                         }
16548:                     }
16549:                 }
16550:             }
16551:         }
16552:     }
16553:     return ($numfiles,$errors);
16554: }
16555: 
16556: sub symb_to_docspath {
16557:     my ($symb,$navmapref) = @_;
16558:     return unless ($symb && ref($navmapref));
16559:     my ($mapurl,$id,$resurl) = &Apache::lonnet::decode_symb($symb);
16560:     if ($resurl=~/\.(sequence|page)$/) {
16561:         $mapurl=$resurl;
16562:     } elsif ($resurl eq 'adm/navmaps') {
16563:         $mapurl=$env{'course.'.$env{'request.course.id'}.'.url'};
16564:     }
16565:     my $mapresobj;
16566:     unless (ref($$navmapref)) {
16567:         $$navmapref = Apache::lonnavmaps::navmap->new();
16568:     }
16569:     if (ref($$navmapref)) {
16570:         $mapresobj = $$navmapref->getResourceByUrl($mapurl);
16571:     }
16572:     $mapurl=~s{^.*/([^/]+)\.(\w+)$}{$1};
16573:     my $type=$2;
16574:     my $path;
16575:     if (ref($mapresobj)) {
16576:         my $pcslist = $mapresobj->map_hierarchy();
16577:         if ($pcslist ne '') {
16578:             foreach my $pc (split(/,/,$pcslist)) {
16579:                 next if ($pc <= 1);
16580:                 my $res = $$navmapref->getByMapPc($pc);
16581:                 if (ref($res)) {
16582:                     my $thisurl = $res->src();
16583:                     $thisurl=~s{^.*/([^/]+)\.\w+$}{$1};
16584:                     my $thistitle = $res->title();
16585:                     $path .= '&'.
16586:                              &Apache::lonhtmlcommon::entity_encode($thisurl).'&'.
16587:                              &escape($thistitle).
16588:                              ':'.$res->randompick().
16589:                              ':'.$res->randomout().
16590:                              ':'.$res->encrypted().
16591:                              ':'.$res->randomorder().
16592:                              ':'.$res->is_page();
16593:                 }
16594:             }
16595:         }
16596:         $path =~ s/^\&//;
16597:         my $maptitle = $mapresobj->title();
16598:         if ($mapurl eq 'default') {
16599:             $maptitle = 'Main Content';
16600:         }
16601:         $path .= (($path ne '')? '&' : '').
16602:                  &Apache::lonhtmlcommon::entity_encode($mapurl).'&'.
16603:                  &escape($maptitle).
16604:                  ':'.$mapresobj->randompick().
16605:                  ':'.$mapresobj->randomout().
16606:                  ':'.$mapresobj->encrypted().
16607:                  ':'.$mapresobj->randomorder().
16608:                  ':'.$mapresobj->is_page();
16609:     } else {
16610:         my $maptitle = &Apache::lonnet::gettitle($mapurl);
16611:         my $ispage = (($type eq 'page')? 1 : '');
16612:         if ($mapurl eq 'default') {
16613:             $maptitle = 'Main Content';
16614:         }
16615:         $path = &Apache::lonhtmlcommon::entity_encode($mapurl).'&'.
16616:                 &escape($maptitle).':::::'.$ispage;
16617:     }
16618:     unless ($mapurl eq 'default') {
16619:         $path = 'default&'.
16620:                 &escape('Main Content').
16621:                 ':::::&'.$path;
16622:     }
16623:     return $path;
16624: }
16625: 
16626: sub captcha_display {
16627:     my ($context,$lonhost) = @_;
16628:     my ($output,$error);
16629:     my ($captcha,$pubkey,$privkey,$version) =
16630:         &get_captcha_config($context,$lonhost);
16631:     if ($captcha eq 'original') {
16632:         $output = &create_captcha();
16633:         unless ($output) {
16634:             $error = 'captcha';
16635:         }
16636:     } elsif ($captcha eq 'recaptcha') {
16637:         $output = &create_recaptcha($pubkey,$version);
16638:         unless ($output) {
16639:             $error = 'recaptcha';
16640:         }
16641:     }
16642:     return ($output,$error,$captcha,$version);
16643: }
16644: 
16645: sub captcha_response {
16646:     my ($context,$lonhost) = @_;
16647:     my ($captcha_chk,$captcha_error);
16648:     my ($captcha,$pubkey,$privkey,$version) = &get_captcha_config($context,$lonhost);
16649:     if ($captcha eq 'original') {
16650:         ($captcha_chk,$captcha_error) = &check_captcha();
16651:     } elsif ($captcha eq 'recaptcha') {
16652:         $captcha_chk = &check_recaptcha($privkey,$version);
16653:     } else {
16654:         $captcha_chk = 1;
16655:     }
16656:     return ($captcha_chk,$captcha_error);
16657: }
16658: 
16659: sub get_captcha_config {
16660:     my ($context,$lonhost) = @_;
16661:     my ($captcha,$pubkey,$privkey,$version,$hashtocheck);
16662:     my $hostname = &Apache::lonnet::hostname($lonhost);
16663:     my $serverhomeID = &Apache::lonnet::get_server_homeID($hostname);
16664:     my $serverhomedom = &Apache::lonnet::host_domain($serverhomeID);
16665:     if ($context eq 'usercreation') {
16666:         my %domconfig = &Apache::lonnet::get_dom('configuration',[$context],$serverhomedom);
16667:         if (ref($domconfig{$context}) eq 'HASH') {
16668:             $hashtocheck = $domconfig{$context}{'cancreate'};
16669:             if (ref($hashtocheck) eq 'HASH') {
16670:                 if ($hashtocheck->{'captcha'} eq 'recaptcha') {
16671:                     if (ref($hashtocheck->{'recaptchakeys'}) eq 'HASH') {
16672:                         $pubkey = $hashtocheck->{'recaptchakeys'}{'public'};
16673:                         $privkey = $hashtocheck->{'recaptchakeys'}{'private'};
16674:                     }
16675:                     if ($privkey && $pubkey) {
16676:                         $captcha = 'recaptcha';
16677:                         $version = $hashtocheck->{'recaptchaversion'};
16678:                         if ($version ne '2') {
16679:                             $version = 1;
16680:                         }
16681:                     } else {
16682:                         $captcha = 'original';
16683:                     }
16684:                 } elsif ($hashtocheck->{'captcha'} ne 'notused') {
16685:                     $captcha = 'original';
16686:                 }
16687:             }
16688:         } else {
16689:             $captcha = 'captcha';
16690:         }
16691:     } elsif ($context eq 'login') {
16692:         my %domconfhash = &Apache::loncommon::get_domainconf($serverhomedom);
16693:         if ($domconfhash{$serverhomedom.'.login.captcha'} eq 'recaptcha') {
16694:             $pubkey = $domconfhash{$serverhomedom.'.login.recaptchakeys_public'};
16695:             $privkey = $domconfhash{$serverhomedom.'.login.recaptchakeys_private'};
16696:             if ($privkey && $pubkey) {
16697:                 $captcha = 'recaptcha';
16698:                 $version = $domconfhash{$serverhomedom.'.login.recaptchaversion'};
16699:                 if ($version ne '2') {
16700:                     $version = 1;
16701:                 }
16702:             } else {
16703:                 $captcha = 'original';
16704:             }
16705:         } elsif ($domconfhash{$serverhomedom.'.login.captcha'} eq 'original') {
16706:             $captcha = 'original';
16707:         }
16708:     }
16709:     return ($captcha,$pubkey,$privkey,$version);
16710: }
16711: 
16712: sub create_captcha {
16713:     my %captcha_params = &captcha_settings();
16714:     my ($output,$maxtries,$tries) = ('',10,0);
16715:     while ($tries < $maxtries) {
16716:         $tries ++;
16717:         my $captcha = Authen::Captcha->new (
16718:                                            output_folder => $captcha_params{'output_dir'},
16719:                                            data_folder   => $captcha_params{'db_dir'},
16720:                                           );
16721:         my $md5sum = $captcha->generate_code($captcha_params{'numchars'});
16722: 
16723:         if (-e $Apache::lonnet::perlvar{'lonCaptchaDir'}.'/'.$md5sum.'.png') {
16724:             $output = '<input type="hidden" name="crypt" value="'.$md5sum.'" />'."\n".
16725:                       &mt('Type in the letters/numbers shown below').'&nbsp;'.
16726:                       '<input type="text" size="5" name="code" value="" autocomplete="off" />'.
16727:                       '<br />'.
16728:                       '<img src="'.$captcha_params{'www_output_dir'}.'/'.$md5sum.'.png" alt="captcha" />';
16729:             last;
16730:         }
16731:     }
16732:     return $output;
16733: }
16734: 
16735: sub captcha_settings {
16736:     my %captcha_params = (
16737:                            output_dir     => $Apache::lonnet::perlvar{'lonCaptchaDir'},
16738:                            www_output_dir => "/captchaspool",
16739:                            db_dir         => $Apache::lonnet::perlvar{'lonCaptchaDb'},
16740:                            numchars       => '5',
16741:                          );
16742:     return %captcha_params;
16743: }
16744: 
16745: sub check_captcha {
16746:     my ($captcha_chk,$captcha_error);
16747:     my $code = $env{'form.code'};
16748:     my $md5sum = $env{'form.crypt'};
16749:     my %captcha_params = &captcha_settings();
16750:     my $captcha = Authen::Captcha->new(
16751:                       output_folder => $captcha_params{'output_dir'},
16752:                       data_folder   => $captcha_params{'db_dir'},
16753:                   );
16754:     $captcha_chk = $captcha->check_code($code,$md5sum);
16755:     my %captcha_hash = (
16756:                         0       => 'Code not checked (file error)',
16757:                        -1      => 'Failed: code expired',
16758:                        -2      => 'Failed: invalid code (not in database)',
16759:                        -3      => 'Failed: invalid code (code does not match crypt)',
16760:     );
16761:     if ($captcha_chk != 1) {
16762:         $captcha_error = $captcha_hash{$captcha_chk}
16763:     }
16764:     return ($captcha_chk,$captcha_error);
16765: }
16766: 
16767: sub create_recaptcha {
16768:     my ($pubkey,$version) = @_;
16769:     if ($version >= 2) {
16770:         return '<div class="g-recaptcha" data-sitekey="'.$pubkey.'"></div>';
16771:     } else {
16772:         my $use_ssl;
16773:         if ($ENV{'SERVER_PORT'} == 443) {
16774:             $use_ssl = 1;
16775:         }
16776:         my $captcha = Captcha::reCAPTCHA->new;
16777:         return $captcha->get_options_setter({theme => 'white'})."\n".
16778:                $captcha->get_html($pubkey,undef,$use_ssl).
16779:                &mt('If the text is hard to read, [_1] will replace them.',
16780:                    '<img src="/res/adm/pages/refresh.gif" alt="reCAPTCHA refresh" />').
16781:                '<br /><br />';
16782:      }
16783: }
16784: 
16785: sub check_recaptcha {
16786:     my ($privkey,$version) = @_;
16787:     my $captcha_chk;
16788:     if ($version >= 2) {
16789:         my $ua = LWP::UserAgent->new;
16790:         $ua->timeout(10);
16791:         my %info = (
16792:                      secret   => $privkey,
16793:                      response => $env{'form.g-recaptcha-response'},
16794:                      remoteip => $ENV{'REMOTE_ADDR'},
16795:                    );
16796:         my $response = $ua->post('https://www.google.com/recaptcha/api/siteverify',\%info);
16797:         if ($response->is_success)  {
16798:             my $data = JSON::DWIW->from_json($response->decoded_content);
16799:             if (ref($data) eq 'HASH') {
16800:                 if ($data->{'success'}) {
16801:                     $captcha_chk = 1;
16802:                 }
16803:             }
16804:         }
16805:     } else {
16806:         my $captcha = Captcha::reCAPTCHA->new;
16807:         my $captcha_result =
16808:             $captcha->check_answer(
16809:                                     $privkey,
16810:                                     $ENV{'REMOTE_ADDR'},
16811:                                     $env{'form.recaptcha_challenge_field'},
16812:                                     $env{'form.recaptcha_response_field'},
16813:                                   );
16814:         if ($captcha_result->{is_valid}) {
16815:             $captcha_chk = 1;
16816:         }
16817:     }
16818:     return $captcha_chk;
16819: }
16820: 
16821: sub emailusername_info {
16822:     my @fields = ('firstname','lastname','institution','web','location','officialemail','id');
16823:     my %titles = &Apache::lonlocal::texthash (
16824:                      lastname      => 'Last Name',
16825:                      firstname     => 'First Name',
16826:                      institution   => 'School/college/university',
16827:                      location      => "School's city, state/province, country",
16828:                      web           => "School's web address",
16829:                      officialemail => 'E-mail address at institution (if different)',
16830:                      id            => 'Student/Employee ID',
16831:                  );
16832:     return (\@fields,\%titles);
16833: }
16834: 
16835: sub cleanup_html {
16836:     my ($incoming) = @_;
16837:     my $outgoing;
16838:     if ($incoming ne '') {
16839:         $outgoing = $incoming;
16840:         $outgoing =~ s/;/&#059;/g;
16841:         $outgoing =~ s/\#/&#035;/g;
16842:         $outgoing =~ s/\&/&#038;/g;
16843:         $outgoing =~ s/</&#060;/g;
16844:         $outgoing =~ s/>/&#062;/g;
16845:         $outgoing =~ s/\(/&#040/g;
16846:         $outgoing =~ s/\)/&#041;/g;
16847:         $outgoing =~ s/"/&#034;/g;
16848:         $outgoing =~ s/'/&#039;/g;
16849:         $outgoing =~ s/\$/&#036;/g;
16850:         $outgoing =~ s{/}{&#047;}g;
16851:         $outgoing =~ s/=/&#061;/g;
16852:         $outgoing =~ s/\\/&#092;/g
16853:     }
16854:     return $outgoing;
16855: }
16856: 
16857: # Checks for critical messages and returns a redirect url if one exists.
16858: # $interval indicates how often to check for messages.
16859: sub critical_redirect {
16860:     my ($interval) = @_;
16861:     if ((time-$env{'user.criticalcheck.time'})>$interval) {
16862:         my @what=&Apache::lonnet::dump('critical', $env{'user.domain'},
16863:                                         $env{'user.name'});
16864:         &Apache::lonnet::appenv({'user.criticalcheck.time'=>time});
16865:         my $redirecturl;
16866:         if ($what[0]) {
16867:             if (($what[0] ne 'con_lost') && ($what[0]!~/^error\:/)) {
16868:                 $redirecturl='/adm/email?critical=display';
16869:                 my $url=&Apache::lonnet::absolute_url().$redirecturl;
16870:                 return (1, $url);
16871:             }
16872:         }
16873:     }
16874:     return ();
16875: }
16876: 
16877: # Use:
16878: #   my $answer=reply("encrypt:passwd:$udom:$uname:$upass",$tryserver);
16879: #
16880: ##################################################
16881: #          password associated functions         #
16882: ##################################################
16883: sub des_keys {
16884:     # Make a new key for DES encryption.
16885:     # Each key has two parts which are returned separately.
16886:     # Please note:  Each key must be passed through the &hex function
16887:     # before it is output to the web browser.  The hex versions cannot
16888:     # be used to decrypt.
16889:     my @hexstr=('0','1','2','3','4','5','6','7',
16890:                 '8','9','a','b','c','d','e','f');
16891:     my $lkey='';
16892:     for (0..7) {
16893:         $lkey.=$hexstr[rand(15)];
16894:     }
16895:     my $ukey='';
16896:     for (0..7) {
16897:         $ukey.=$hexstr[rand(15)];
16898:     }
16899:     return ($lkey,$ukey);
16900: }
16901: 
16902: sub des_decrypt {
16903:     my ($key,$cyphertext) = @_;
16904:     my $keybin=pack("H16",$key);
16905:     my $cypher;
16906:     if ($Crypt::DES::VERSION>=2.03) {
16907:         $cypher=new Crypt::DES $keybin;
16908:     } else {
16909:         $cypher=new DES $keybin;
16910:     }
16911:     my $plaintext='';
16912:     my $cypherlength = length($cyphertext);
16913:     my $numchunks = int($cypherlength/32);
16914:     for (my $j=0; $j<$numchunks; $j++) {
16915:         my $start = $j*32;
16916:         my $cypherblock = substr($cyphertext,$start,32);
16917:         my $chunk =
16918:             $cypher->decrypt(unpack("a8",pack("H16",substr($cypherblock,0,16))));
16919:         $chunk .=
16920:             $cypher->decrypt(unpack("a8",pack("H16",substr($cypherblock,16,16))));
16921:         $chunk=substr($chunk,1,ord(substr($chunk,0,1)) );
16922:         $plaintext .= $chunk;
16923:     }
16924:     return $plaintext;
16925: }
16926: 
16927: 1;
16928: __END__;
16929: 

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