File:  [LON-CAPA] / loncom / interface / loncommon.pm
Revision 1.1215: download - view: text, annotated - select for diffs
Tue Apr 7 15:12:26 2015 UTC (9 years, 1 month ago) by raeburn
Branches: MAIN
CVS tags: HEAD
- xhtml

    1: # The LearningOnline Network with CAPA
    2: # a pile of common routines
    3: #
    4: # $Id: loncommon.pm,v 1.1215 2015/04/07 15:12:26 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::Catalog;
   76: use Text::Aspell;
   77: use Authen::Captcha;
   78: use Captcha::reCAPTCHA;
   79: use Crypt::DES;
   80: use DynaLoader; # for Crypt::DES version
   81: 
   82: # ---------------------------------------------- Designs
   83: use vars qw(%defaultdesign);
   84: 
   85: my $readit;
   86: 
   87: 
   88: ##
   89: ## Global Variables
   90: ##
   91: 
   92: 
   93: # ----------------------------------------------- SSI with retries:
   94: #
   95: 
   96: =pod
   97: 
   98: =head1 Server Side include with retries:
   99: 
  100: =over 4
  101: 
  102: =item * &ssi_with_retries(resource,retries form)
  103: 
  104: Performs an ssi with some number of retries.  Retries continue either
  105: until the result is ok or until the retry count supplied by the
  106: caller is exhausted.  
  107: 
  108: Inputs:
  109: 
  110: =over 4
  111: 
  112: resource   - Identifies the resource to insert.
  113: 
  114: retries    - Count of the number of retries allowed.
  115: 
  116: form       - Hash that identifies the rendering options.
  117: 
  118: =back
  119: 
  120: Returns:
  121: 
  122: =over 4
  123: 
  124: content    - The content of the response.  If retries were exhausted this is empty.
  125: 
  126: response   - The response from the last attempt (which may or may not have been successful.
  127: 
  128: =back
  129: 
  130: =back
  131: 
  132: =cut
  133: 
  134: sub ssi_with_retries {
  135:     my ($resource, $retries, %form) = @_;
  136: 
  137: 
  138:     my $ok = 0;			# True if we got a good response.
  139:     my $content;
  140:     my $response;
  141: 
  142:     # Try to get the ssi done. within the retries count:
  143: 
  144:     do {
  145: 	($content, $response) = &Apache::lonnet::ssi($resource, %form);
  146: 	$ok      = $response->is_success;
  147:         if (!$ok) {
  148:             &Apache::lonnet::logthis("Failed ssi_with_retries on $resource: ".$response->is_success.', '.$response->code.', '.$response->message);
  149:         }
  150: 	$retries--;
  151:     } while (!$ok && ($retries > 0));
  152: 
  153:     if (!$ok) {
  154: 	$content = '';		# On error return an empty content.
  155:     }
  156:     return ($content, $response);
  157: 
  158: }
  159: 
  160: 
  161: 
  162: # ----------------------------------------------- Filetypes/Languages/Copyright
  163: my %language;
  164: my %supported_language;
  165: my %supported_codes;
  166: my %latex_language;		# For choosing hyphenation in <transl..>
  167: my %latex_language_bykey;	# for choosing hyphenation from metadata
  168: my %cprtag;
  169: my %scprtag;
  170: my %fe; my %fd; my %fm;
  171: my %category_extensions;
  172: 
  173: # ---------------------------------------------- Thesaurus variables
  174: #
  175: # %Keywords:
  176: #      A hash used by &keyword to determine if a word is considered a keyword.
  177: # $thesaurus_db_file 
  178: #      Scalar containing the full path to the thesaurus database.
  179: 
  180: my %Keywords;
  181: my $thesaurus_db_file;
  182: 
  183: #
  184: # Initialize values from language.tab, copyright.tab, filetypes.tab,
  185: # thesaurus.tab, and filecategories.tab.
  186: #
  187: BEGIN {
  188:     # Variable initialization
  189:     $thesaurus_db_file = $Apache::lonnet::perlvar{'lonTabDir'}."/thesaurus.db";
  190:     #
  191:     unless ($readit) {
  192: # ------------------------------------------------------------------- languages
  193:     {
  194:         my $langtabfile = $Apache::lonnet::perlvar{'lonTabDir'}.
  195:                                    '/language.tab';
  196:         if ( open(my $fh,"<$langtabfile") ) {
  197:             while (my $line = <$fh>) {
  198:                 next if ($line=~/^\#/);
  199:                 chomp($line);
  200:                 my ($key,$code,$country,$three,$enc,$val,$sup,$latex)=(split(/\t/,$line));
  201:                 $language{$key}=$val.' - '.$enc;
  202:                 if ($sup) {
  203:                     $supported_language{$key}=$sup;
  204: 		    $supported_codes{$key}   = $code;
  205:                 }
  206: 		if ($latex) {
  207: 		    $latex_language_bykey{$key} = $latex;
  208: 		    $latex_language{$code} = $latex;
  209: 		}
  210:             }
  211:             close($fh);
  212:         }
  213:     }
  214: # ------------------------------------------------------------------ copyrights
  215:     {
  216:         my $copyrightfile = $Apache::lonnet::perlvar{'lonIncludes'}.
  217:                                   '/copyright.tab';
  218:         if ( open (my $fh,"<$copyrightfile") ) {
  219:             while (my $line = <$fh>) {
  220:                 next if ($line=~/^\#/);
  221:                 chomp($line);
  222:                 my ($key,$val)=(split(/\s+/,$line,2));
  223:                 $cprtag{$key}=$val;
  224:             }
  225:             close($fh);
  226:         }
  227:     }
  228: # ----------------------------------------------------------- source copyrights
  229:     {
  230:         my $sourcecopyrightfile = $Apache::lonnet::perlvar{'lonIncludes'}.
  231:                                   '/source_copyright.tab';
  232:         if ( open (my $fh,"<$sourcecopyrightfile") ) {
  233:             while (my $line = <$fh>) {
  234:                 next if ($line =~ /^\#/);
  235:                 chomp($line);
  236:                 my ($key,$val)=(split(/\s+/,$line,2));
  237:                 $scprtag{$key}=$val;
  238:             }
  239:             close($fh);
  240:         }
  241:     }
  242: 
  243: # -------------------------------------------------------------- default domain designs
  244:     my $designdir=$Apache::lonnet::perlvar{'lonTabDir'}.'/lonDomColors';
  245:     my $designfile = $designdir.'/default.tab';
  246:     if ( open (my $fh,"<$designfile") ) {
  247:         while (my $line = <$fh>) {
  248:             next if ($line =~ /^\#/);
  249:             chomp($line);
  250:             my ($key,$val)=(split(/\=/,$line));
  251:             if ($val) { $defaultdesign{$key}=$val; }
  252:         }
  253:         close($fh);
  254:     }
  255: 
  256: # ------------------------------------------------------------- file categories
  257:     {
  258:         my $categoryfile = $Apache::lonnet::perlvar{'lonTabDir'}.
  259:                                   '/filecategories.tab';
  260:         if ( open (my $fh,"<$categoryfile") ) {
  261: 	    while (my $line = <$fh>) {
  262: 		next if ($line =~ /^\#/);
  263: 		chomp($line);
  264:                 my ($extension,$category)=(split(/\s+/,$line,2));
  265:                 push @{$category_extensions{lc($category)}},$extension;
  266:             }
  267:             close($fh);
  268:         }
  269: 
  270:     }
  271: # ------------------------------------------------------------------ file types
  272:     {
  273:         my $typesfile = $Apache::lonnet::perlvar{'lonTabDir'}.
  274:                '/filetypes.tab';
  275:         if ( open (my $fh,"<$typesfile") ) {
  276:             while (my $line = <$fh>) {
  277: 		next if ($line =~ /^\#/);
  278: 		chomp($line);
  279:                 my ($ending,$emb,$mime,$descr)=split(/\s+/,$line,4);
  280:                 if ($descr ne '') {
  281:                     $fe{$ending}=lc($emb);
  282:                     $fd{$ending}=$descr;
  283:                     if ($mime ne 'unk') { $fm{$ending}=$mime; }
  284:                 }
  285:             }
  286:             close($fh);
  287:         }
  288:     }
  289:     &Apache::lonnet::logthis(
  290:              "<span style='color:yellow;'>INFO: Read file types</span>");
  291:     $readit=1;
  292:     }  # end of unless($readit) 
  293:     
  294: }
  295: 
  296: ###############################################################
  297: ##           HTML and Javascript Helper Functions            ##
  298: ###############################################################
  299: 
  300: =pod 
  301: 
  302: =head1 HTML and Javascript Functions
  303: 
  304: =over 4
  305: 
  306: =item * &browser_and_searcher_javascript()
  307: 
  308: X<browsing, javascript>X<searching, javascript>Returns a string
  309: containing javascript with two functions, C<openbrowser> and
  310: C<opensearcher>. Returned string does not contain E<lt>scriptE<gt>
  311: tags.
  312: 
  313: =item * &openbrowser(formname,elementname,only,omit) [javascript]
  314: 
  315: inputs: formname, elementname, only, omit
  316: 
  317: formname and elementname indicate the name of the html form and name of
  318: the element that the results of the browsing selection are to be placed in. 
  319: 
  320: Specifying 'only' will restrict the browser to displaying only files
  321: with the given extension.  Can be a comma separated list.
  322: 
  323: Specifying 'omit' will restrict the browser to NOT displaying files
  324: with the given extension.  Can be a comma separated list.
  325: 
  326: =item * &opensearcher(formname,elementname) [javascript]
  327: 
  328: Inputs: formname, elementname
  329: 
  330: formname and elementname specify the name of the html form and the name
  331: of the element the selection from the search results will be placed in.
  332: 
  333: =cut
  334: 
  335: sub browser_and_searcher_javascript {
  336:     my ($mode)=@_;
  337:     if (!defined($mode)) { $mode='edit'; }
  338:     my $resurl=&escape_single(&lastresurl());
  339:     return <<END;
  340: // <!-- BEGIN LON-CAPA Internal
  341:     var editbrowser = null;
  342:     function openbrowser(formname,elementname,only,omit,titleelement) {
  343:         var url = '$resurl/?';
  344:         if (editbrowser == null) {
  345:             url += 'launch=1&';
  346:         }
  347:         url += 'catalogmode=interactive&';
  348:         url += 'mode=$mode&';
  349:         url += 'inhibitmenu=yes&';
  350:         url += 'form=' + formname + '&';
  351:         if (only != null) {
  352:             url += 'only=' + only + '&';
  353:         } else {
  354:             url += 'only=&';
  355: 	}
  356:         if (omit != null) {
  357:             url += 'omit=' + omit + '&';
  358:         } else {
  359:             url += 'omit=&';
  360: 	}
  361:         if (titleelement != null) {
  362:             url += 'titleelement=' + titleelement + '&';
  363:         } else {
  364: 	    url += 'titleelement=&';
  365: 	}
  366:         url += 'element=' + elementname + '';
  367:         var title = 'Browser';
  368:         var options = 'scrollbars=1,resizable=1,menubar=0,toolbar=1,location=1';
  369:         options += ',width=700,height=600';
  370:         editbrowser = open(url,title,options,'1');
  371:         editbrowser.focus();
  372:     }
  373:     var editsearcher;
  374:     function opensearcher(formname,elementname,titleelement) {
  375:         var url = '/adm/searchcat?';
  376:         if (editsearcher == null) {
  377:             url += 'launch=1&';
  378:         }
  379:         url += 'catalogmode=interactive&';
  380:         url += 'mode=$mode&';
  381:         url += 'form=' + formname + '&';
  382:         if (titleelement != null) {
  383:             url += 'titleelement=' + titleelement + '&';
  384:         } else {
  385: 	    url += 'titleelement=&';
  386: 	}
  387:         url += 'element=' + elementname + '';
  388:         var title = 'Search';
  389:         var options = 'scrollbars=1,resizable=1,menubar=0,toolbar=1,location=1';
  390:         options += ',width=700,height=600';
  391:         editsearcher = open(url,title,options,'1');
  392:         editsearcher.focus();
  393:     }
  394: // END LON-CAPA Internal -->
  395: END
  396: }
  397: 
  398: sub lastresurl {
  399:     if ($env{'environment.lastresurl'}) {
  400: 	return $env{'environment.lastresurl'}
  401:     } else {
  402: 	return '/res';
  403:     }
  404: }
  405: 
  406: sub storeresurl {
  407:     my $resurl=&Apache::lonnet::clutter(shift);
  408:     unless ($resurl=~/^\/res/) { return 0; }
  409:     $resurl=~s/\/$//;
  410:     &Apache::lonnet::put('environment',{'lastresurl' => $resurl});
  411:     &Apache::lonnet::appenv({'environment.lastresurl' => $resurl});
  412:     return 1;
  413: }
  414: 
  415: sub studentbrowser_javascript {
  416:    unless (
  417:             (($env{'request.course.id'}) && 
  418:              (&Apache::lonnet::allowed('srm',$env{'request.course.id'})
  419: 	      || &Apache::lonnet::allowed('srm',$env{'request.course.id'}.
  420: 					  '/'.$env{'request.course.sec'})
  421: 	      ))
  422:          || ($env{'request.role'}=~/^(au|dc|su)/)
  423:           ) { return ''; }  
  424:    return (<<'ENDSTDBRW');
  425: <script type="text/javascript" language="Javascript">
  426: // <![CDATA[
  427:     var stdeditbrowser;
  428:     function openstdbrowser(formname,uname,udom,clicker,roleflag,ignorefilter,courseadvonly) {
  429:         var url = '/adm/pickstudent?';
  430:         var filter;
  431: 	if (!ignorefilter) {
  432: 	    eval('filter=document.'+formname+'.'+uname+'.value;');
  433: 	}
  434:         if (filter != null) {
  435:            if (filter != '') {
  436:                url += 'filter='+filter+'&';
  437: 	   }
  438:         }
  439:         url += 'form=' + formname + '&unameelement='+uname+
  440:                                     '&udomelement='+udom+
  441:                                     '&clicker='+clicker;
  442: 	if (roleflag) { url+="&roles=1"; }
  443:         if (courseadvonly) { url+="&courseadvonly=1"; }
  444:         var title = 'Student_Browser';
  445:         var options = 'scrollbars=1,resizable=1,menubar=0';
  446:         options += ',width=700,height=600';
  447:         stdeditbrowser = open(url,title,options,'1');
  448:         stdeditbrowser.focus();
  449:     }
  450: // ]]>
  451: </script>
  452: ENDSTDBRW
  453: }
  454: 
  455: sub resourcebrowser_javascript {
  456:    unless ($env{'request.course.id'}) { return ''; }
  457:    return (<<'ENDRESBRW');
  458: <script type="text/javascript" language="Javascript">
  459: // <![CDATA[
  460:     var reseditbrowser;
  461:     function openresbrowser(formname,reslink) {
  462:         var url = '/adm/pickresource?form='+formname+'&reslink='+reslink;
  463:         var title = 'Resource_Browser';
  464:         var options = 'scrollbars=1,resizable=1,menubar=0';
  465:         options += ',width=700,height=500';
  466:         reseditbrowser = open(url,title,options,'1');
  467:         reseditbrowser.focus();
  468:     }
  469: // ]]>
  470: </script>
  471: ENDRESBRW
  472: }
  473: 
  474: sub selectstudent_link {
  475:    my ($form,$unameele,$udomele,$courseadvonly,$clickerid)=@_;
  476:    my $callargs = "'".&Apache::lonhtmlcommon::entity_encode($form)."','".
  477:                       &Apache::lonhtmlcommon::entity_encode($unameele)."','".
  478:                       &Apache::lonhtmlcommon::entity_encode($udomele)."'";
  479:    if ($env{'request.course.id'}) {  
  480:        if (!&Apache::lonnet::allowed('srm',$env{'request.course.id'})
  481: 	   && !&Apache::lonnet::allowed('srm',$env{'request.course.id'}.
  482: 					'/'.$env{'request.course.sec'})) {
  483: 	   return '';
  484:        }
  485:        $callargs.=",'".&Apache::lonhtmlcommon::entity_encode($clickerid)."'";
  486:        if ($courseadvonly)  {
  487:            $callargs .= ",'',1,1";
  488:        }
  489:        return '<span class="LC_nobreak">'.
  490:               '<a href="javascript:openstdbrowser('.$callargs.');">'.
  491:               &mt('Select User').'</a></span>';
  492:    }
  493:    if ($env{'request.role'}=~/^(au|dc|su)/) {
  494:        $callargs .= ",'',1"; 
  495:        return '<span class="LC_nobreak">'.
  496:               '<a href="javascript:openstdbrowser('.$callargs.');">'.
  497:               &mt('Select User').'</a></span>';
  498:    }
  499:    return '';
  500: }
  501: 
  502: sub selectresource_link {
  503:    my ($form,$reslink,$arg)=@_;
  504:    
  505:    my $callargs = "'".&Apache::lonhtmlcommon::entity_encode($form)."','".
  506:                       &Apache::lonhtmlcommon::entity_encode($reslink)."'";
  507:    unless ($env{'request.course.id'}) { return $arg; }
  508:    return '<span class="LC_nobreak">'.
  509:               '<a href="javascript:openresbrowser('.$callargs.');">'.
  510:               $arg.'</a></span>';
  511: }
  512: 
  513: 
  514: 
  515: sub authorbrowser_javascript {
  516:     return <<"ENDAUTHORBRW";
  517: <script type="text/javascript" language="JavaScript">
  518: // <![CDATA[
  519: var stdeditbrowser;
  520: 
  521: function openauthorbrowser(formname,udom) {
  522:     var url = '/adm/pickauthor?';
  523:     url += 'form='+formname+'&roledom='+udom;
  524:     var title = 'Author_Browser';
  525:     var options = 'scrollbars=1,resizable=1,menubar=0';
  526:     options += ',width=700,height=600';
  527:     stdeditbrowser = open(url,title,options,'1');
  528:     stdeditbrowser.focus();
  529: }
  530: 
  531: // ]]>
  532: </script>
  533: ENDAUTHORBRW
  534: }
  535: 
  536: sub coursebrowser_javascript {
  537:     my ($domainfilter,$sec_element,$formname,$role_element,$crstype,
  538:         $credits_element) = @_;
  539:     my $wintitle = 'Course_Browser';
  540:     if ($crstype eq 'Community') {
  541:         $wintitle = 'Community_Browser';
  542:     }
  543:     my $id_functions = &javascript_index_functions();
  544:     my $output = '
  545: <script type="text/javascript" language="JavaScript">
  546: // <![CDATA[
  547:     var stdeditbrowser;'."\n";
  548: 
  549:     $output .= <<"ENDSTDBRW";
  550:     function opencrsbrowser(formname,uname,udom,desc,extra_element,multflag,type,type_elem) {
  551:         var url = '/adm/pickcourse?';
  552:         var formid = getFormIdByName(formname);
  553:         var domainfilter = getDomainFromSelectbox(formname,udom);
  554:         if (domainfilter != null) {
  555:            if (domainfilter != '') {
  556:                url += 'domainfilter='+domainfilter+'&';
  557: 	   }
  558:         }
  559:         url += 'form=' + formname + '&cnumelement='+uname+
  560: 	                            '&cdomelement='+udom+
  561:                                     '&cnameelement='+desc;
  562:         if (extra_element !=null && extra_element != '') {
  563:             if (formname == 'rolechoice' || formname == 'studentform') {
  564:                 url += '&roleelement='+extra_element;
  565:                 if (domainfilter == null || domainfilter == '') {
  566:                     url += '&domainfilter='+extra_element;
  567:                 }
  568:             }
  569:             else {
  570:                 if (formname == 'portform') {
  571:                     url += '&setroles='+extra_element;
  572:                 } else {
  573:                     if (formname == 'rules') {
  574:                         url += '&fixeddom='+extra_element; 
  575:                     }
  576:                 }
  577:             }     
  578:         }
  579:         if (type != null && type != '') {
  580:             url += '&type='+type;
  581:         }
  582:         if (type_elem != null && type_elem != '') {
  583:             url += '&typeelement='+type_elem;
  584:         }
  585:         if (formname == 'ccrs') {
  586:             var ownername = document.forms[formid].ccuname.value;
  587:             var ownerdom =  document.forms[formid].ccdomain.options[document.forms[formid].ccdomain.selectedIndex].value;
  588:             url += '&cloner='+ownername+':'+ownerdom;
  589:         }
  590:         if (multflag !=null && multflag != '') {
  591:             url += '&multiple='+multflag;
  592:         }
  593:         var title = '$wintitle';
  594:         var options = 'scrollbars=1,resizable=1,menubar=0';
  595:         options += ',width=700,height=600';
  596:         stdeditbrowser = open(url,title,options,'1');
  597:         stdeditbrowser.focus();
  598:     }
  599: $id_functions
  600: ENDSTDBRW
  601:     if (($sec_element ne '') || ($role_element ne '') || ($credits_element ne '')) {
  602:         $output .= &setsec_javascript($sec_element,$formname,$role_element,
  603:                                       $credits_element);
  604:     }
  605:     $output .= '
  606: // ]]>
  607: </script>';
  608:     return $output;
  609: }
  610: 
  611: sub javascript_index_functions {
  612:     return <<"ENDJS";
  613: 
  614: function getFormIdByName(formname) {
  615:     for (var i=0;i<document.forms.length;i++) {
  616:         if (document.forms[i].name == formname) {
  617:             return i;
  618:         }
  619:     }
  620:     return -1;
  621: }
  622: 
  623: function getIndexByName(formid,item) {
  624:     for (var i=0;i<document.forms[formid].elements.length;i++) {
  625:         if (document.forms[formid].elements[i].name == item) {
  626:             return i;
  627:         }
  628:     }
  629:     return -1;
  630: }
  631: 
  632: function getDomainFromSelectbox(formname,udom) {
  633:     var userdom;
  634:     var formid = getFormIdByName(formname);
  635:     if (formid > -1) {
  636:         var domid = getIndexByName(formid,udom);
  637:         if (domid > -1) {
  638:             if (document.forms[formid].elements[domid].type == 'select-one') {
  639:                 userdom=document.forms[formid].elements[domid].options[document.forms[formid].elements[domid].selectedIndex].value;
  640:             }
  641:             if (document.forms[formid].elements[domid].type == 'hidden') {
  642:                 userdom=document.forms[formid].elements[domid].value;
  643:             }
  644:         }
  645:     }
  646:     return userdom;
  647: }
  648: 
  649: ENDJS
  650: 
  651: }
  652: 
  653: sub javascript_array_indexof {
  654:     return <<ENDJS;
  655: <script type="text/javascript" language="JavaScript">
  656: // <![CDATA[
  657: 
  658: if (!Array.prototype.indexOf) {
  659:     Array.prototype.indexOf = function (searchElement /*, fromIndex */ ) {
  660:         "use strict";
  661:         if (this === void 0 || this === null) {
  662:             throw new TypeError();
  663:         }
  664:         var t = Object(this);
  665:         var len = t.length >>> 0;
  666:         if (len === 0) {
  667:             return -1;
  668:         }
  669:         var n = 0;
  670:         if (arguments.length > 0) {
  671:             n = Number(arguments[1]);
  672:             if (n !== n) { // shortcut for verifying if it is NaN
  673:                 n = 0;
  674:             } else if (n !== 0 && n !== (1 / 0) && n !== -(1 / 0)) {
  675:                 n = (n > 0 || -1) * Math.floor(Math.abs(n));
  676:             }
  677:         }
  678:         if (n >= len) {
  679:             return -1;
  680:         }
  681:         var k = n >= 0 ? n : Math.max(len - Math.abs(n), 0);
  682:         for (; k < len; k++) {
  683:             if (k in t && t[k] === searchElement) {
  684:                 return k;
  685:             }
  686:         }
  687:         return -1;
  688:     }
  689: }
  690: 
  691: // ]]>
  692: </script>
  693: 
  694: ENDJS
  695: 
  696: }
  697: 
  698: sub userbrowser_javascript {
  699:     my $id_functions = &javascript_index_functions();
  700:     return <<"ENDUSERBRW";
  701: 
  702: function openuserbrowser(formname,uname,udom,ulast,ufirst,uemail,hideudom,crsdom,caller) {
  703:     var url = '/adm/pickuser?';
  704:     var userdom = getDomainFromSelectbox(formname,udom);
  705:     if (userdom != null) {
  706:        if (userdom != '') {
  707:            url += 'srchdom='+userdom+'&';
  708:        }
  709:     }
  710:     url += 'form=' + formname + '&unameelement='+uname+
  711:                                 '&udomelement='+udom+
  712:                                 '&ulastelement='+ulast+
  713:                                 '&ufirstelement='+ufirst+
  714:                                 '&uemailelement='+uemail+
  715:                                 '&hideudomelement='+hideudom+
  716:                                 '&coursedom='+crsdom;
  717:     if ((caller != null) && (caller != undefined)) {
  718:         url += '&caller='+caller;
  719:     }
  720:     var title = 'User_Browser';
  721:     var options = 'scrollbars=1,resizable=1,menubar=0';
  722:     options += ',width=700,height=600';
  723:     var stdeditbrowser = open(url,title,options,'1');
  724:     stdeditbrowser.focus();
  725: }
  726: 
  727: function fix_domain (formname,udom,origdom,uname) {
  728:     var formid = getFormIdByName(formname);
  729:     if (formid > -1) {
  730:         var unameid = getIndexByName(formid,uname);
  731:         var domid = getIndexByName(formid,udom);
  732:         var hidedomid = getIndexByName(formid,origdom);
  733:         if (hidedomid > -1) {
  734:             var fixeddom = document.forms[formid].elements[hidedomid].value;
  735:             var unameval = document.forms[formid].elements[unameid].value;
  736:             if ((fixeddom != '') && (fixeddom != undefined) && (fixeddom != null) && (unameval != '') && (unameval != undefined) && (unameval != null)) {
  737:                 if (domid > -1) {
  738:                     var slct = document.forms[formid].elements[domid];
  739:                     if (slct.type == 'select-one') {
  740:                         var i;
  741:                         for (i=0;i<slct.length;i++) {
  742:                             if (slct.options[i].value==fixeddom) { slct.selectedIndex=i; }
  743:                         }
  744:                     }
  745:                     if (slct.type == 'hidden') {
  746:                         slct.value = fixeddom;
  747:                     }
  748:                 }
  749:             }
  750:         }
  751:     }
  752:     return;
  753: }
  754: 
  755: $id_functions
  756: ENDUSERBRW
  757: }
  758: 
  759: sub setsec_javascript {
  760:     my ($sec_element,$formname,$role_element,$credits_element) = @_;
  761:     my (@courserolenames,@communityrolenames,$rolestr,$courserolestr,
  762:         $communityrolestr);
  763:     if ($role_element ne '') {
  764:         my @allroles = ('st','ta','ep','in','ad');
  765:         foreach my $crstype ('Course','Community') {
  766:             if ($crstype eq 'Community') {
  767:                 foreach my $role (@allroles) {
  768:                     push(@communityrolenames,&Apache::lonnet::plaintext($role,$crstype));
  769:                 }
  770:                 push(@communityrolenames,&Apache::lonnet::plaintext('co'));
  771:             } else {
  772:                 foreach my $role (@allroles) {
  773:                     push(@courserolenames,&Apache::lonnet::plaintext($role,$crstype));
  774:                 }
  775:                 push(@courserolenames,&Apache::lonnet::plaintext('cc'));
  776:             }
  777:         }
  778:         $rolestr = '"'.join('","',@allroles).'"';
  779:         $courserolestr = '"'.join('","',@courserolenames).'"';
  780:         $communityrolestr = '"'.join('","',@communityrolenames).'"';
  781:     }
  782:     my $setsections = qq|
  783: function setSect(sectionlist) {
  784:     var sectionsArray = new Array();
  785:     if ((sectionlist != '') && (typeof sectionlist != "undefined")) {
  786:         sectionsArray = sectionlist.split(",");
  787:     }
  788:     var numSections = sectionsArray.length;
  789:     document.$formname.$sec_element.length = 0;
  790:     if (numSections == 0) {
  791:         document.$formname.$sec_element.multiple=false;
  792:         document.$formname.$sec_element.size=1;
  793:         document.$formname.$sec_element.options[0] = new Option('No existing sections','',false,false)
  794:     } else {
  795:         if (numSections == 1) {
  796:             document.$formname.$sec_element.multiple=false;
  797:             document.$formname.$sec_element.size=1;
  798:             document.$formname.$sec_element.options[0] = new Option('Select','',true,true);
  799:             document.$formname.$sec_element.options[1] = new Option('No section','',false,false)
  800:             document.$formname.$sec_element.options[2] = new Option(sectionsArray[0],sectionsArray[0],false,false);
  801:         } else {
  802:             for (var i=0; i<numSections; i++) {
  803:                 document.$formname.$sec_element.options[i] = new Option(sectionsArray[i],sectionsArray[i],false,false)
  804:             }
  805:             document.$formname.$sec_element.multiple=true
  806:             if (numSections < 3) {
  807:                 document.$formname.$sec_element.size=numSections;
  808:             } else {
  809:                 document.$formname.$sec_element.size=3;
  810:             }
  811:             document.$formname.$sec_element.options[0].selected = false
  812:         }
  813:     }
  814: }
  815: 
  816: function setRole(crstype) {
  817: |;
  818:     if ($role_element eq '') {
  819:         $setsections .= '    return;
  820: }
  821: ';
  822:     } else {
  823:         $setsections .= qq|
  824:     var elementLength = document.$formname.$role_element.length;
  825:     var allroles = Array($rolestr);
  826:     var courserolenames = Array($courserolestr);
  827:     var communityrolenames = Array($communityrolestr);
  828:     if (elementLength != undefined) {
  829:         if (document.$formname.$role_element.options[5].value == 'cc') {
  830:             if (crstype == 'Course') {
  831:                 return;
  832:             } else {
  833:                 allroles[5] = 'co';
  834:                 for (var i=0; i<6; i++) {
  835:                     document.$formname.$role_element.options[i].value = allroles[i];
  836:                     document.$formname.$role_element.options[i].text = communityrolenames[i];
  837:                 }
  838:             }
  839:         } else {
  840:             if (crstype == 'Community') {
  841:                 return;
  842:             } else {
  843:                 allroles[5] = 'cc';
  844:                 for (var i=0; i<6; i++) {
  845:                     document.$formname.$role_element.options[i].value = allroles[i];
  846:                     document.$formname.$role_element.options[i].text = courserolenames[i];
  847:                 }
  848:             }
  849:         }
  850:     }
  851:     return;
  852: }
  853: |;
  854:     }
  855:     if ($credits_element) {
  856:         $setsections .= qq|
  857: function setCredits(defaultcredits) {
  858:     document.$formname.$credits_element.value = defaultcredits;
  859:     return;
  860: }
  861: |;
  862:     }
  863:     return $setsections;
  864: }
  865: 
  866: sub selectcourse_link {
  867:    my ($form,$unameele,$udomele,$desc,$extra_element,$multflag,$selecttype,
  868:        $typeelement) = @_;
  869:    my $type = $selecttype;
  870:    my $linktext = &mt('Select Course');
  871:    if ($selecttype eq 'Community') {
  872:        $linktext = &mt('Select Community');
  873:    } elsif ($selecttype eq 'Course/Community') {
  874:        $linktext = &mt('Select Course/Community');
  875:        $type = '';
  876:    } elsif ($selecttype eq 'Select') {
  877:        $linktext = &mt('Select');
  878:        $type = '';
  879:    }
  880:    return '<span class="LC_nobreak">'
  881:          ."<a href='"
  882:          .'javascript:opencrsbrowser("'.$form.'","'.$unameele
  883:          .'","'.$udomele.'","'.$desc.'","'.$extra_element
  884:          .'","'.$multflag.'","'.$type.'","'.$typeelement.'");'
  885:          ."'>".$linktext.'</a>'
  886:          .'</span>';
  887: }
  888: 
  889: sub selectauthor_link {
  890:    my ($form,$udom)=@_;
  891:    return '<a href="javascript:openauthorbrowser('."'$form','$udom'".');">'.
  892:           &mt('Select Author').'</a>';
  893: }
  894: 
  895: sub selectuser_link {
  896:     my ($form,$unameelem,$domelem,$lastelem,$firstelem,$emailelem,$hdomelem,
  897:         $coursedom,$linktext,$caller) = @_;
  898:     return '<a href="javascript:openuserbrowser('."'$form','$unameelem','$domelem',".
  899:            "'$lastelem','$firstelem','$emailelem','$hdomelem','$coursedom','$caller'".
  900:            ');">'.$linktext.'</a>';
  901: }
  902: 
  903: sub check_uncheck_jscript {
  904:     my $jscript = <<"ENDSCRT";
  905: function checkAll(field) {
  906:     if (field.length > 0) {
  907:         for (i = 0; i < field.length; i++) {
  908:             if (!field[i].disabled) { 
  909:                 field[i].checked = true;
  910:             }
  911:         }
  912:     } else {
  913:         if (!field.disabled) { 
  914:             field.checked = true;
  915:         }
  916:     }
  917: }
  918:  
  919: function uncheckAll(field) {
  920:     if (field.length > 0) {
  921:         for (i = 0; i < field.length; i++) {
  922:             field[i].checked = false ;
  923:         }
  924:     } else {
  925:         field.checked = false ;
  926:     }
  927: }
  928: ENDSCRT
  929:     return $jscript;
  930: }
  931: 
  932: sub select_timezone {
  933:    my ($name,$selected,$onchange,$includeempty)=@_;
  934:    my $output='<select name="'.$name.'" '.$onchange.'>'."\n";
  935:    if ($includeempty) {
  936:        $output .= '<option value=""';
  937:        if (($selected eq '') || ($selected eq 'local')) {
  938:            $output .= ' selected="selected" ';
  939:        }
  940:        $output .= '> </option>';
  941:    }
  942:    my @timezones = DateTime::TimeZone->all_names;
  943:    foreach my $tzone (@timezones) {
  944:        $output.= '<option value="'.$tzone.'"';
  945:        if ($tzone eq $selected) {
  946:            $output.=' selected="selected"';
  947:        }
  948:        $output.=">$tzone</option>\n";
  949:    }
  950:    $output.="</select>";
  951:    return $output;
  952: }
  953: 
  954: sub select_datelocale {
  955:     my ($name,$selected,$onchange,$includeempty)=@_;
  956:     my $output='<select name="'.$name.'" '.$onchange.'>'."\n";
  957:     if ($includeempty) {
  958:         $output .= '<option value=""';
  959:         if ($selected eq '') {
  960:             $output .= ' selected="selected" ';
  961:         }
  962:         $output .= '> </option>';
  963:     }
  964:     my (@possibles,%locale_names);
  965:     my @locales = DateTime::Locale::Catalog::Locales;
  966:     foreach my $locale (@locales) {
  967:         if (ref($locale) eq 'HASH') {
  968:             my $id = $locale->{'id'};
  969:             if ($id ne '') {
  970:                 my $en_terr = $locale->{'en_territory'};
  971:                 my $native_terr = $locale->{'native_territory'};
  972:                 my @languages = &Apache::lonlocal::preferred_languages();
  973:                 if (grep(/^en$/,@languages) || !@languages) {
  974:                     if ($en_terr ne '') {
  975:                         $locale_names{$id} = '('.$en_terr.')';
  976:                     } elsif ($native_terr ne '') {
  977:                         $locale_names{$id} = $native_terr;
  978:                     }
  979:                 } else {
  980:                     if ($native_terr ne '') {
  981:                         $locale_names{$id} = $native_terr.' ';
  982:                     } elsif ($en_terr ne '') {
  983:                         $locale_names{$id} = '('.$en_terr.')';
  984:                     }
  985:                 }
  986:                 push (@possibles,$id);
  987:             }
  988:         }
  989:     }
  990:     foreach my $item (sort(@possibles)) {
  991:         $output.= '<option value="'.$item.'"';
  992:         if ($item eq $selected) {
  993:             $output.=' selected="selected"';
  994:         }
  995:         $output.=">$item";
  996:         if ($locale_names{$item} ne '') {
  997:             $output.="  $locale_names{$item}</option>\n";
  998:         }
  999:         $output.="</option>\n";
 1000:     }
 1001:     $output.="</select>";
 1002:     return $output;
 1003: }
 1004: 
 1005: sub select_language {
 1006:     my ($name,$selected,$includeempty) = @_;
 1007:     my %langchoices;
 1008:     if ($includeempty) {
 1009:         %langchoices = ('' => 'No language preference');
 1010:     }
 1011:     foreach my $id (&languageids()) {
 1012:         my $code = &supportedlanguagecode($id);
 1013:         if ($code) {
 1014:             $langchoices{$code} = &plainlanguagedescription($id);
 1015:         }
 1016:     }
 1017:     %langchoices = &Apache::lonlocal::texthash(%langchoices);
 1018:     return &select_form($selected,$name,\%langchoices);
 1019: }
 1020: 
 1021: =pod
 1022: 
 1023: 
 1024: =item * &list_languages()
 1025: 
 1026: Returns an array reference that is suitable for use in language prompters.
 1027: Each array element is itself a two element array.  The first element
 1028: is the language code.  The second element a descsriptiuon of the 
 1029: language itself.  This is suitable for use in e.g.
 1030: &Apache::edit::select_arg (once dereferenced that is).
 1031: 
 1032: =cut 
 1033: 
 1034: sub list_languages {
 1035:     my @lang_choices;
 1036: 
 1037:     foreach my $id (&languageids()) {
 1038: 	my $code = &supportedlanguagecode($id);
 1039: 	if ($code) {
 1040: 	    my $selector    = $supported_codes{$id};
 1041: 	    my $description = &plainlanguagedescription($id);
 1042: 	    push (@lang_choices, [$selector, $description]);
 1043: 	}
 1044:     }
 1045:     return \@lang_choices;
 1046: }
 1047: 
 1048: =pod
 1049: 
 1050: =item * &linked_select_forms(...)
 1051: 
 1052: linked_select_forms returns a string containing a <script></script> block
 1053: and html for two <select> menus.  The select menus will be linked in that
 1054: changing the value of the first menu will result in new values being placed
 1055: in the second menu.  The values in the select menu will appear in alphabetical
 1056: order unless a defined order is provided.
 1057: 
 1058: linked_select_forms takes the following ordered inputs:
 1059: 
 1060: =over 4
 1061: 
 1062: =item * $formname, the name of the <form> tag
 1063: 
 1064: =item * $middletext, the text which appears between the <select> tags
 1065: 
 1066: =item * $firstdefault, the default value for the first menu
 1067: 
 1068: =item * $firstselectname, the name of the first <select> tag
 1069: 
 1070: =item * $secondselectname, the name of the second <select> tag
 1071: 
 1072: =item * $hashref, a reference to a hash containing the data for the menus.
 1073: 
 1074: =item * $menuorder, the order of values in the first menu
 1075: 
 1076: =item * $onchangefirst, additional javascript call to execute for an onchange
 1077:         event for the first <select> tag
 1078: 
 1079: =item * $onchangesecond, additional javascript call to execute for an onchange
 1080:         event for the second <select> tag
 1081: 
 1082: =back 
 1083: 
 1084: Below is an example of such a hash.  Only the 'text', 'default', and 
 1085: 'select2' keys must appear as stated.  keys(%menu) are the possible 
 1086: values for the first select menu.  The text that coincides with the 
 1087: first menu value is given in $menu{$choice1}->{'text'}.  The values 
 1088: and text for the second menu are given in the hash pointed to by 
 1089: $menu{$choice1}->{'select2'}.  
 1090: 
 1091:  my %menu = ( A1 => { text =>"Choice A1" ,
 1092:                        default => "B3",
 1093:                        select2 => { 
 1094:                            B1 => "Choice B1",
 1095:                            B2 => "Choice B2",
 1096:                            B3 => "Choice B3",
 1097:                            B4 => "Choice B4"
 1098:                            },
 1099:                        order => ['B4','B3','B1','B2'],
 1100:                    },
 1101:                A2 => { text =>"Choice A2" ,
 1102:                        default => "C2",
 1103:                        select2 => { 
 1104:                            C1 => "Choice C1",
 1105:                            C2 => "Choice C2",
 1106:                            C3 => "Choice C3"
 1107:                            },
 1108:                        order => ['C2','C1','C3'],
 1109:                    },
 1110:                A3 => { text =>"Choice A3" ,
 1111:                        default => "D6",
 1112:                        select2 => { 
 1113:                            D1 => "Choice D1",
 1114:                            D2 => "Choice D2",
 1115:                            D3 => "Choice D3",
 1116:                            D4 => "Choice D4",
 1117:                            D5 => "Choice D5",
 1118:                            D6 => "Choice D6",
 1119:                            D7 => "Choice D7"
 1120:                            },
 1121:                        order => ['D4','D3','D2','D1','D7','D6','D5'],
 1122:                    }
 1123:                );
 1124: 
 1125: =cut
 1126: 
 1127: sub linked_select_forms {
 1128:     my ($formname,
 1129:         $middletext,
 1130:         $firstdefault,
 1131:         $firstselectname,
 1132:         $secondselectname, 
 1133:         $hashref,
 1134:         $menuorder,
 1135:         $onchangefirst,
 1136:         $onchangesecond
 1137:         ) = @_;
 1138:     my $second = "document.$formname.$secondselectname";
 1139:     my $first = "document.$formname.$firstselectname";
 1140:     # output the javascript to do the changing
 1141:     my $result = '';
 1142:     $result.='<script type="text/javascript" language="JavaScript">'."\n";
 1143:     $result.="// <![CDATA[\n";
 1144:     $result.="var select2data = new Object();\n";
 1145:     $" = '","';
 1146:     my $debug = '';
 1147:     foreach my $s1 (sort(keys(%$hashref))) {
 1148:         $result.="select2data.d_$s1 = new Object();\n";        
 1149:         $result.="select2data.d_$s1.def = new String('".
 1150:             $hashref->{$s1}->{'default'}."');\n";
 1151:         $result.="select2data.d_$s1.values = new Array(";
 1152:         my @s2values = sort(keys( %{ $hashref->{$s1}->{'select2'} } ));
 1153:         if (ref($hashref->{$s1}->{'order'}) eq 'ARRAY') {
 1154:             @s2values = @{$hashref->{$s1}->{'order'}};
 1155:         }
 1156:         $result.="\"@s2values\");\n";
 1157:         $result.="select2data.d_$s1.texts = new Array(";        
 1158:         my @s2texts;
 1159:         foreach my $value (@s2values) {
 1160:             push @s2texts, $hashref->{$s1}->{'select2'}->{$value};
 1161:         }
 1162:         $result.="\"@s2texts\");\n";
 1163:     }
 1164:     $"=' ';
 1165:     $result.= <<"END";
 1166: 
 1167: function select1_changed() {
 1168:     // Determine new choice
 1169:     var newvalue = "d_" + $first.value;
 1170:     // update select2
 1171:     var values     = select2data[newvalue].values;
 1172:     var texts      = select2data[newvalue].texts;
 1173:     var select2def = select2data[newvalue].def;
 1174:     var i;
 1175:     // out with the old
 1176:     for (i = 0; i < $second.options.length; i++) {
 1177:         $second.options[i] = null;
 1178:     }
 1179:     // in with the nuclear
 1180:     for (i=0;i<values.length; i++) {
 1181:         $second.options[i] = new Option(values[i]);
 1182:         $second.options[i].value = values[i];
 1183:         $second.options[i].text = texts[i];
 1184:         if (values[i] == select2def) {
 1185:             $second.options[i].selected = true;
 1186:         }
 1187:     }
 1188: }
 1189: // ]]>
 1190: </script>
 1191: END
 1192:     # output the initial values for the selection lists
 1193:     $result .= "<select size=\"1\" name=\"$firstselectname\" onchange=\"select1_changed();$onchangefirst\">\n";
 1194:     my @order = sort(keys(%{$hashref}));
 1195:     if (ref($menuorder) eq 'ARRAY') {
 1196:         @order = @{$menuorder};
 1197:     }
 1198:     foreach my $value (@order) {
 1199:         $result.="    <option value=\"$value\" ";
 1200:         $result.=" selected=\"selected\" " if ($value eq $firstdefault);
 1201:         $result.=">".&mt($hashref->{$value}->{'text'})."</option>\n";
 1202:     }
 1203:     $result .= "</select>\n";
 1204:     my %select2 = %{$hashref->{$firstdefault}->{'select2'}};
 1205:     $result .= $middletext;
 1206:     $result .= "<select size=\"1\" name=\"$secondselectname\"";
 1207:     if ($onchangesecond) {
 1208:         $result .= ' onchange="'.$onchangesecond.'"';
 1209:     }
 1210:     $result .= ">\n";
 1211:     my $seconddefault = $hashref->{$firstdefault}->{'default'};
 1212:     
 1213:     my @secondorder = sort(keys(%select2));
 1214:     if (ref($hashref->{$firstdefault}->{'order'}) eq 'ARRAY') {
 1215:         @secondorder = @{$hashref->{$firstdefault}->{'order'}};
 1216:     }
 1217:     foreach my $value (@secondorder) {
 1218:         $result.="    <option value=\"$value\" ";        
 1219:         $result.=" selected=\"selected\" " if ($value eq $seconddefault);
 1220:         $result.=">".&mt($select2{$value})."</option>\n";
 1221:     }
 1222:     $result .= "</select>\n";
 1223:     #    return $debug;
 1224:     return $result;
 1225: }   #  end of sub linked_select_forms {
 1226: 
 1227: =pod
 1228: 
 1229: =item * &help_open_topic($topic,$text,$stayOnPage,$width,$height,$imgid)
 1230: 
 1231: Returns a string corresponding to an HTML link to the given help
 1232: $topic, where $topic corresponds to the name of a .tex file in
 1233: /home/httpd/html/adm/help/tex, with underscores replaced by
 1234: spaces. 
 1235: 
 1236: $text will optionally be linked to the same topic, allowing you to
 1237: link text in addition to the graphic. If you do not want to link
 1238: text, but wish to specify one of the later parameters, pass an
 1239: empty string. 
 1240: 
 1241: $stayOnPage is a value that will be interpreted as a boolean. If true,
 1242: the link will not open a new window. If false, the link will open
 1243: a new window using Javascript. (Default is false.) 
 1244: 
 1245: $width and $height are optional numerical parameters that will
 1246: override the width and height of the popped up window, which may
 1247: be useful for certain help topics with big pictures included.
 1248: 
 1249: $imgid is the id of the img tag used for the help icon. This may be
 1250: used in a javascript call to switch the image src.  See 
 1251: lonhtmlcommon::htmlareaselectactive() for an example.
 1252: 
 1253: =cut
 1254: 
 1255: sub help_open_topic {
 1256:     my ($topic, $text, $stayOnPage, $width, $height, $imgid) = @_;
 1257:     $text = "" if (not defined $text);
 1258:     $stayOnPage = 0 if (not defined $stayOnPage);
 1259:     $width = 500 if (not defined $width);
 1260:     $height = 400 if (not defined $height);
 1261:     my $filename = $topic;
 1262:     $filename =~ s/ /_/g;
 1263: 
 1264:     my $template = "";
 1265:     my $link;
 1266:     
 1267:     $topic=~s/\W/\_/g;
 1268: 
 1269:     if (!$stayOnPage) {
 1270: 	$link = "javascript:openMyModal('/adm/help/${filename}.hlp',$width,$height,'yes');";
 1271:     } elsif ($stayOnPage eq 'popup') {
 1272:         $link = "javascript:void(open('/adm/help/${filename}.hlp', 'Help_for_$topic', 'menubar=0,toolbar=1,scrollbars=1,width=$width,height=$height,resizable=yes'))";
 1273:     } else {
 1274: 	$link = "/adm/help/${filename}.hlp";
 1275:     }
 1276: 
 1277:     # Add the text
 1278:     if ($text ne "") {	
 1279: 	$template.='<span class="LC_help_open_topic">'
 1280:                   .'<a target="_top" href="'.$link.'">'
 1281:                   .$text.'</a>';
 1282:     }
 1283: 
 1284:     # (Always) Add the graphic
 1285:     my $title = &mt('Online Help');
 1286:     my $helpicon=&lonhttpdurl("/adm/help/help.png");
 1287:     if ($imgid ne '') {
 1288:         $imgid = ' id="'.$imgid.'"';
 1289:     }
 1290:     $template.=' <a target="_top" href="'.$link.'" title="'.$title.'">'
 1291:               .'<img src="'.$helpicon.'" border="0"'
 1292:               .' alt="'.&mt('Help: [_1]',$topic).'"'
 1293:               .' title="'.$title.'" style="vertical-align:middle;"'.$imgid 
 1294:               .' /></a>';
 1295:     if ($text ne "") {	
 1296:         $template.='</span>';
 1297:     }
 1298:     return $template;
 1299: 
 1300: }
 1301: 
 1302: # This is a quicky function for Latex cheatsheet editing, since it 
 1303: # appears in at least four places
 1304: sub helpLatexCheatsheet {
 1305:     my ($topic,$text,$not_author,$stayOnPage) = @_;
 1306:     my $out;
 1307:     my $addOther = '';
 1308:     if ($topic) {
 1309: 	$addOther = '<span>'.&help_open_topic($topic,&mt($text),$stayOnPage, undef, 600).'</span> ';
 1310:     }
 1311:     $out = '<span>' # Start cheatsheet
 1312: 	  .$addOther
 1313:           .'<span>'
 1314: 	  .&help_open_topic('Greek_Symbols',&mt('Greek Symbols'),$stayOnPage,undef,600)
 1315: 	  .'</span> <span>'
 1316: 	  .&help_open_topic('Other_Symbols',&mt('Other Symbols'),$stayOnPage,undef,600)
 1317: 	  .'</span>';
 1318:     unless ($not_author) {
 1319:         $out .= '<span>'
 1320:                .&help_open_topic('Authoring_Output_Tags',&mt('Output Tags'),$stayOnPage,undef,600)
 1321:                .'</span> <span>'
 1322:                .&help_open_topic('Authoring_Multilingual_Problems',&mt('How to create problems in different languages'),$stayOnPage,undef,600)
 1323: 	       .'</span>';
 1324:     }
 1325:     $out .= '</span>'; # End cheatsheet
 1326:     return $out;
 1327: }
 1328: 
 1329: sub general_help {
 1330:     my $helptopic='Student_Intro';
 1331:     if ($env{'request.role'}=~/^(ca|au)/) {
 1332: 	$helptopic='Authoring_Intro';
 1333:     } elsif ($env{'request.role'}=~/^(cc|co)/) {
 1334: 	$helptopic='Course_Coordination_Intro';
 1335:     } elsif ($env{'request.role'}=~/^dc/) {
 1336:         $helptopic='Domain_Coordination_Intro';
 1337:     }
 1338:     return $helptopic;
 1339: }
 1340: 
 1341: sub update_help_link {
 1342:     my ($topic,$component_help,$faq,$bug,$stayOnPage) = @_;
 1343:     my $origurl = $ENV{'REQUEST_URI'};
 1344:     $origurl=~s|^/~|/priv/|;
 1345:     my $timestamp = time;
 1346:     foreach my $datum (\$topic,\$component_help,\$faq,\$bug,\$origurl) {
 1347:         $$datum = &escape($$datum);
 1348:     }
 1349: 
 1350:     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";
 1351:     my $output .= <<"ENDOUTPUT";
 1352: <script type="text/javascript">
 1353: // <![CDATA[
 1354: banner_link = '$banner_link';
 1355: // ]]>
 1356: </script>
 1357: ENDOUTPUT
 1358:     return $output;
 1359: }
 1360: 
 1361: # now just updates the help link and generates a blue icon
 1362: sub help_open_menu {
 1363:     my ($topic,$component_help,$faq,$bug,$stayOnPage,$width,$height,$text) 
 1364: 	= @_;    
 1365:     $stayOnPage = 1;
 1366:     my $output;
 1367:     if ($component_help) {
 1368: 	if (!$text) {
 1369: 	    $output=&help_open_topic($component_help,undef,$stayOnPage,
 1370: 				       $width,$height);
 1371: 	} else {
 1372: 	    my $help_text;
 1373: 	    $help_text=&unescape($topic);
 1374: 	    $output='<table><tr><td>'.
 1375: 		&help_open_topic($component_help,$help_text,$stayOnPage,
 1376: 				 $width,$height).'</td></tr></table>';
 1377: 	}
 1378:     }
 1379:     my $banner_link = &update_help_link($topic,$component_help,$faq,$bug,$stayOnPage);
 1380:     return $output.$banner_link;
 1381: }
 1382: 
 1383: sub top_nav_help {
 1384:     my ($text) = @_;
 1385:     $text = &mt($text);
 1386:     my $stay_on_page = 1;
 1387: 
 1388:     my ($link,$banner_link);
 1389:     unless ($env{'request.noversionuri'} =~ m{^/adm/helpmenu}) {
 1390:         $link = ($stay_on_page) ? "javascript:helpMenu('display')"
 1391: 	                         : "javascript:helpMenu('open')";
 1392:         $banner_link = &update_help_link(undef,undef,undef,undef,$stay_on_page);
 1393:     }
 1394:     my $title = &mt('Get help');
 1395:     if ($link) {
 1396:         return <<"END";
 1397: $banner_link
 1398: <a href="$link" title="$title">$text</a>
 1399: END
 1400:     } else {
 1401:         return '&nbsp;'.$text.'&nbsp;';
 1402:     }
 1403: }
 1404: 
 1405: sub help_menu_js {
 1406:     my ($httphost) = @_;
 1407:     my $stayOnPage = 1;
 1408:     my $width = 620;
 1409:     my $height = 600;
 1410:     my $helptopic=&general_help();
 1411:     my $details_link = $httphost.'/adm/help/'.$helptopic.'.hlp';
 1412:     my $nothing=&Apache::lonhtmlcommon::javascript_nothing();
 1413:     my $start_page =
 1414:         &Apache::loncommon::start_page('Help Menu', undef,
 1415: 				       {'frameset'    => 1,
 1416: 					'js_ready'    => 1,
 1417:                                         'use_absolute' => $httphost,
 1418: 					'add_entries' => {
 1419: 					    'border' => '0', 
 1420: 					    'rows'   => "110,*",},});
 1421:     my $end_page =
 1422:         &Apache::loncommon::end_page({'frameset' => 1,
 1423: 				      'js_ready' => 1,});
 1424: 
 1425:     my $template .= <<"ENDTEMPLATE";
 1426: <script type="text/javascript">
 1427: // <![CDATA[
 1428: // <!-- BEGIN LON-CAPA Internal
 1429: var banner_link = '';
 1430: function helpMenu(target) {
 1431:     var caller = this;
 1432:     if (target == 'open') {
 1433:         var newWindow = null;
 1434:         try {
 1435:             newWindow =  window.open($nothing,"helpmenu","HEIGHT=$height,WIDTH=$width,resizable=yes,scrollbars=yes" )
 1436:         }
 1437:         catch(error) {
 1438:             writeHelp(caller);
 1439:             return;
 1440:         }
 1441:         if (newWindow) {
 1442:             caller = newWindow;
 1443:         }
 1444:     }
 1445:     writeHelp(caller);
 1446:     return;
 1447: }
 1448: function writeHelp(caller) {
 1449:     caller.document.writeln('$start_page\\n<frame name="bannerframe" src="'+banner_link+'" marginwidth="0" marginheight="0" frameborder="0">\\n');
 1450:     caller.document.writeln('<frame name="bodyframe" src="$details_link" marginwidth="0" marginheight="0" frameborder="0">\\n$end_page');
 1451:     caller.document.close();
 1452:     caller.focus();
 1453: }
 1454: // END LON-CAPA Internal -->
 1455: // ]]>
 1456: </script>
 1457: ENDTEMPLATE
 1458:     return $template;
 1459: }
 1460: 
 1461: sub help_open_bug {
 1462:     my ($topic, $text, $stayOnPage, $width, $height) = @_;
 1463:     unless ($env{'user.adv'}) { return ''; }
 1464:     unless ($Apache::lonnet::perlvar{'BugzillaHost'}) { return ''; }
 1465:     $text = "" if (not defined $text);
 1466: 	$stayOnPage=1;
 1467:     $width = 600 if (not defined $width);
 1468:     $height = 600 if (not defined $height);
 1469: 
 1470:     $topic=~s/\W+/\+/g;
 1471:     my $link='';
 1472:     my $template='';
 1473:     my $url=$Apache::lonnet::perlvar{'BugzillaHost'}.'enter_bug.cgi?product=LON-CAPA&amp;bug_file_loc='.
 1474: 	&escape($ENV{'REQUEST_URI'}).'&amp;component='.$topic;
 1475:     if (!$stayOnPage)
 1476:     {
 1477: 	$link = "javascript:void(open('$url', 'Bugzilla', 'menubar=0,toolbar=1,scrollbars=1,width=$width,height=$height,resizable=yes'))";
 1478:     }
 1479:     else
 1480:     {
 1481: 	$link = $url;
 1482:     }
 1483:     # Add the text
 1484:     if ($text ne "")
 1485:     {
 1486: 	$template .= 
 1487:   "<table bgcolor='#AA3333' cellspacing='1' cellpadding='1' border='0'><tr>".
 1488:   "<td bgcolor='#FF5555'><a target=\"_top\" href=\"$link\"><span style=\"color:#FFFFFF;font-size:10pt;\">$text</span></a>";
 1489:     }
 1490: 
 1491:     # Add the graphic
 1492:     my $title = &mt('Report a Bug');
 1493:     my $bugicon=&lonhttpdurl("/adm/lonMisc/smallBug.gif");
 1494:     $template .= <<"ENDTEMPLATE";
 1495:  <a target="_top" href="$link" title="$title"><img src="$bugicon" border="0" alt="(Bug: $topic)" /></a>
 1496: ENDTEMPLATE
 1497:     if ($text ne '') { $template.='</td></tr></table>' };
 1498:     return $template;
 1499: 
 1500: }
 1501: 
 1502: sub help_open_faq {
 1503:     my ($topic, $text, $stayOnPage, $width, $height) = @_;
 1504:     unless ($env{'user.adv'}) { return ''; }
 1505:     unless ($Apache::lonnet::perlvar{'FAQHost'}) { return ''; }
 1506:     $text = "" if (not defined $text);
 1507: 	$stayOnPage=1;
 1508:     $width = 350 if (not defined $width);
 1509:     $height = 400 if (not defined $height);
 1510: 
 1511:     $topic=~s/\W+/\+/g;
 1512:     my $link='';
 1513:     my $template='';
 1514:     my $url=$Apache::lonnet::perlvar{'FAQHost'}.'/fom/cache/'.$topic.'.html';
 1515:     if (!$stayOnPage)
 1516:     {
 1517: 	$link = "javascript:void(open('$url', 'FAQ-O-Matic', 'menubar=0,toolbar=1,scrollbars=1,width=$width,height=$height,resizable=yes'))";
 1518:     }
 1519:     else
 1520:     {
 1521: 	$link = $url;
 1522:     }
 1523: 
 1524:     # Add the text
 1525:     if ($text ne "")
 1526:     {
 1527: 	$template .= 
 1528:   "<table bgcolor='#337733' cellspacing='1' cellpadding='1' border='0'><tr>".
 1529:   "<td bgcolor='#448844'><a target=\"_top\" href=\"$link\"><span style=\"color:#FFFFFF; font-size:10pt;\">$text</span></a>";
 1530:     }
 1531: 
 1532:     # Add the graphic
 1533:     my $title = &mt('View the FAQ');
 1534:     my $faqicon=&lonhttpdurl("/adm/lonMisc/smallFAQ.gif");
 1535:     $template .= <<"ENDTEMPLATE";
 1536:  <a target="_top" href="$link" title="$title"><img src="$faqicon" border="0" alt="(FAQ: $topic)" /></a>
 1537: ENDTEMPLATE
 1538:     if ($text ne '') { $template.='</td></tr></table>' };
 1539:     return $template;
 1540: 
 1541: }
 1542: 
 1543: ###############################################################
 1544: ###############################################################
 1545: 
 1546: =pod
 1547: 
 1548: =item * &change_content_javascript():
 1549: 
 1550: This and the next function allow you to create small sections of an
 1551: otherwise static HTML page that you can update on the fly with
 1552: Javascript, even in Netscape 4.
 1553: 
 1554: The Javascript fragment returned by this function (no E<lt>scriptE<gt> tag)
 1555: must be written to the HTML page once. It will prove the Javascript
 1556: function "change(name, content)". Calling the change function with the
 1557: name of the section 
 1558: you want to update, matching the name passed to C<changable_area>, and
 1559: the new content you want to put in there, will put the content into
 1560: that area.
 1561: 
 1562: B<Note>: Netscape 4 only reserves enough space for the changable area
 1563: to contain room for the original contents. You need to "make space"
 1564: for whatever changes you wish to make, and be B<sure> to check your
 1565: code in Netscape 4. This feature in Netscape 4 is B<not> powerful;
 1566: it's adequate for updating a one-line status display, but little more.
 1567: This script will set the space to 100% width, so you only need to
 1568: worry about height in Netscape 4.
 1569: 
 1570: Modern browsers are much less limiting, and if you can commit to the
 1571: user not using Netscape 4, this feature may be used freely with
 1572: pretty much any HTML.
 1573: 
 1574: =cut
 1575: 
 1576: sub change_content_javascript {
 1577:     # If we're on Netscape 4, we need to use Layer-based code
 1578:     if ($env{'browser.type'} eq 'netscape' &&
 1579: 	$env{'browser.version'} =~ /^4\./) {
 1580: 	return (<<NETSCAPE4);
 1581: 	function change(name, content) {
 1582: 	    doc = document.layers[name+"___escape"].layers[0].document;
 1583: 	    doc.open();
 1584: 	    doc.write(content);
 1585: 	    doc.close();
 1586: 	}
 1587: NETSCAPE4
 1588:     } else {
 1589: 	# Otherwise, we need to use semi-standards-compliant code
 1590: 	# (technically, "innerHTML" isn't standard but the equivalent
 1591: 	# is really scary, and every useful browser supports it
 1592: 	return (<<DOMBASED);
 1593: 	function change(name, content) {
 1594: 	    element = document.getElementById(name);
 1595: 	    element.innerHTML = content;
 1596: 	}
 1597: DOMBASED
 1598:     }
 1599: }
 1600: 
 1601: =pod
 1602: 
 1603: =item * &changable_area($name,$origContent):
 1604: 
 1605: This provides a "changable area" that can be modified on the fly via
 1606: the Javascript code provided in C<change_content_javascript>. $name is
 1607: the name you will use to reference the area later; do not repeat the
 1608: same name on a given HTML page more then once. $origContent is what
 1609: the area will originally contain, which can be left blank.
 1610: 
 1611: =cut
 1612: 
 1613: sub changable_area {
 1614:     my ($name, $origContent) = @_;
 1615: 
 1616:     if ($env{'browser.type'} eq 'netscape' &&
 1617: 	$env{'browser.version'} =~ /^4\./) {
 1618: 	# If this is netscape 4, we need to use the Layer tag
 1619: 	return "<ilayer width='100%' id='${name}___escape' overflow='none'><layer width='100%' id='$name' overflow='none'>$origContent</layer></ilayer>";
 1620:     } else {
 1621: 	return "<span id='$name'>$origContent</span>";
 1622:     }
 1623: }
 1624: 
 1625: =pod
 1626: 
 1627: =item * &viewport_geometry_js 
 1628: 
 1629: Provides javascript object (Geometry) which can provide information about the viewport geometry for the client browser.
 1630: 
 1631: =cut
 1632: 
 1633: 
 1634: sub viewport_geometry_js { 
 1635:     return <<"GEOMETRY";
 1636: var Geometry = {};
 1637: function init_geometry() {
 1638:     if (Geometry.init) { return };
 1639:     Geometry.init=1;
 1640:     if (window.innerHeight) {
 1641:         Geometry.getViewportHeight   = function() { return window.innerHeight; };
 1642:         Geometry.getViewportWidth   = function() { return window.innerWidth; };
 1643:         Geometry.getHorizontalScroll = function() { return window.pageXOffset; };
 1644:         Geometry.getVerticalScroll   = function() { return window.pageYOffset; };
 1645:     }
 1646:     else if (document.documentElement && document.documentElement.clientHeight) {
 1647:         Geometry.getViewportHeight =
 1648:             function() { return document.documentElement.clientHeight; };
 1649:         Geometry.getViewportWidth =
 1650:             function() { return document.documentElement.clientWidth; };
 1651: 
 1652:         Geometry.getHorizontalScroll =
 1653:             function() { return document.documentElement.scrollLeft; };
 1654:         Geometry.getVerticalScroll =
 1655:             function() { return document.documentElement.scrollTop; };
 1656:     }
 1657:     else if (document.body.clientHeight) {
 1658:         Geometry.getViewportHeight =
 1659:             function() { return document.body.clientHeight; };
 1660:         Geometry.getViewportWidth =
 1661:             function() { return document.body.clientWidth; };
 1662:         Geometry.getHorizontalScroll =
 1663:             function() { return document.body.scrollLeft; };
 1664:         Geometry.getVerticalScroll =
 1665:             function() { return document.body.scrollTop; };
 1666:     }
 1667: }
 1668: 
 1669: GEOMETRY
 1670: }
 1671: 
 1672: =pod
 1673: 
 1674: =item * &viewport_size_js()
 1675: 
 1676: 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. 
 1677: 
 1678: =cut
 1679: 
 1680: sub viewport_size_js {
 1681:     my $geometry = &viewport_geometry_js();
 1682:     return <<"DIMS";
 1683: 
 1684: $geometry
 1685: 
 1686: function getViewportDims(width,height) {
 1687:     init_geometry();
 1688:     width.value = Geometry.getViewportWidth();
 1689:     height.value = Geometry.getViewportHeight();
 1690:     return;
 1691: }
 1692: 
 1693: DIMS
 1694: }
 1695: 
 1696: =pod
 1697: 
 1698: =item * &resize_textarea_js()
 1699: 
 1700: emits the needed javascript to resize a textarea to be as big as possible
 1701: 
 1702: creates a function resize_textrea that takes two IDs first should be
 1703: the id of the element to resize, second should be the id of a div that
 1704: surrounds everything that comes after the textarea, this routine needs
 1705: to be attached to the <body> for the onload and onresize events.
 1706: 
 1707: =back
 1708: 
 1709: =cut
 1710: 
 1711: sub resize_textarea_js {
 1712:     my $geometry = &viewport_geometry_js();
 1713:     return <<"RESIZE";
 1714:     <script type="text/javascript">
 1715: // <![CDATA[
 1716: $geometry
 1717: 
 1718: function getX(element) {
 1719:     var x = 0;
 1720:     while (element) {
 1721: 	x += element.offsetLeft;
 1722: 	element = element.offsetParent;
 1723:     }
 1724:     return x;
 1725: }
 1726: function getY(element) {
 1727:     var y = 0;
 1728:     while (element) {
 1729: 	y += element.offsetTop;
 1730: 	element = element.offsetParent;
 1731:     }
 1732:     return y;
 1733: }
 1734: 
 1735: 
 1736: function resize_textarea(textarea_id,bottom_id) {
 1737:     init_geometry();
 1738:     var textarea        = document.getElementById(textarea_id);
 1739:     //alert(textarea);
 1740: 
 1741:     var textarea_top    = getY(textarea);
 1742:     var textarea_height = textarea.offsetHeight;
 1743:     var bottom          = document.getElementById(bottom_id);
 1744:     var bottom_top      = getY(bottom);
 1745:     var bottom_height   = bottom.offsetHeight;
 1746:     var window_height   = Geometry.getViewportHeight();
 1747:     var fudge           = 23;
 1748:     var new_height      = window_height-fudge-textarea_top-bottom_height;
 1749:     if (new_height < 300) {
 1750: 	new_height = 300;
 1751:     }
 1752:     textarea.style.height=new_height+'px';
 1753: }
 1754: // ]]>
 1755: </script>
 1756: RESIZE
 1757: 
 1758: }
 1759: 
 1760: sub colorfuleditor_js {
 1761:     return <<"COLORFULEDIT"
 1762: <script type="text/javascript">
 1763: // <![CDATA[>
 1764:     function fold_box(curDepth, lastresource){
 1765: 
 1766:     // we need a list because there can be several blocks you need to fold in one tag
 1767:         var block = document.getElementsByName('foldblock_'+curDepth);
 1768:     // but there is only one folding button per tag
 1769:         var foldbutton = document.getElementById('folding_btn_'+curDepth);
 1770: 
 1771:         if(block.item(0).style.display == 'none'){
 1772: 
 1773:             foldbutton.value = '@{[&mt("Hide")]}';
 1774:             for (i = 0; i < block.length; i++){
 1775:                 block.item(i).style.display = '';
 1776:             }
 1777:         }else{
 1778: 
 1779:             foldbutton.value = '@{[&mt("Show")]}';
 1780:             for (i = 0; i < block.length; i++){
 1781:                 // block.item(i).style.visibility = 'collapse';
 1782:                 block.item(i).style.display = 'none';
 1783:             }
 1784:         };
 1785:         saveState(lastresource);
 1786:     }
 1787: 
 1788:     function saveState (lastresource) {
 1789: 
 1790:         var tag_list = getTagList();
 1791:         if(tag_list != null){
 1792:             var timestamp = new Date().getTime();
 1793:             var key = lastresource;
 1794: 
 1795:             // the value pattern is: 'time;key1,value1;key2,value2; ... '
 1796:             // starting with timestamp
 1797:             var value = timestamp+';';
 1798: 
 1799:             // building the list of key-value pairs
 1800:             for(var i = 0; i < tag_list.length; i++){
 1801:                 value += tag_list[i]+',';
 1802:                 value += document.getElementsByName(tag_list[i])[0].style.display+';';
 1803:             }
 1804: 
 1805:             // only iterate whole storage if nothing to override
 1806:             if(localStorage.getItem(key) == null){        
 1807: 
 1808:                 // prevent storage from growing large
 1809:                 if(localStorage.length > 50){
 1810:                     var regex_getTimestamp = /^(?:\d)+;/;
 1811:                     var oldest_timestamp = regex_getTimestamp.exec(localStorage.key(0));
 1812:                     var oldest_key;
 1813:                     
 1814:                     for(var i = 1; i < localStorage.length; i++){
 1815:                         if (regex_getTimestamp.exec(localStorage.key(i)) < oldest_timestamp) {
 1816:                             oldest_key = localStorage.key(i);
 1817:                             oldest_timestamp = regex_getTimestamp.exec(oldest_key);
 1818:                         }
 1819:                     }
 1820:                     localStorage.removeItem(oldest_key);
 1821:                 }
 1822:             }
 1823:             localStorage.setItem(key,value);
 1824:         }
 1825:     }
 1826: 
 1827:     // restore folding status of blocks (on page load)
 1828:     function restoreState (lastresource) {
 1829:         if(localStorage.getItem(lastresource) != null){
 1830:             var key = lastresource;
 1831:             var value = localStorage.getItem(key);
 1832:             var regex_delTimestamp = /^\d+;/;
 1833: 
 1834:             value.replace(regex_delTimestamp, '');
 1835: 
 1836:             var valueArr = value.split(';');
 1837:             var pairs;
 1838:             var elements;
 1839:             for (var i = 0; i < valueArr.length; i++){
 1840:                 pairs = valueArr[i].split(',');
 1841:                 elements = document.getElementsByName(pairs[0]);
 1842: 
 1843:                 for (var j = 0; j < elements.length; j++){  
 1844:                     elements[j].style.display = pairs[1];
 1845:                     if (pairs[1] == "none"){
 1846:                         var regex_id = /([_\\d]+)\$/;
 1847:                         regex_id.exec(pairs[0]);
 1848:                         document.getElementById("folding_btn"+RegExp.\$1).value = "Show";
 1849:                     }
 1850:                 }
 1851:             }
 1852:         }
 1853:     }
 1854: 
 1855:     function getTagList () {
 1856:         
 1857:         var stringToSearch = document.lonhomework.innerHTML;
 1858: 
 1859:         var ret = new Array();
 1860:         var regex_findBlock = /(foldblock_.*?)"/g;
 1861:         var tag_list = stringToSearch.match(regex_findBlock);
 1862: 
 1863:         if(tag_list != null){
 1864:             for(var i = 0; i < tag_list.length; i++){            
 1865:                 ret.push(tag_list[i].replace(/"/, ''));
 1866:             }
 1867:         }
 1868:         return ret;
 1869:     }
 1870: 
 1871:     function saveScrollPosition (resource) {
 1872:         var tag_list = getTagList();
 1873: 
 1874:         // we dont always want to jump to the first block
 1875:         // 170 is roughly above the "Problem Editing" header. we just want to save if the user scrolled down further than this
 1876:         if(\$(window).scrollTop() > 170){
 1877:             if(tag_list != null){
 1878:                 var result;
 1879:                 for(var i = 0; i < tag_list.length; i++){
 1880:                     if(isElementInViewport(tag_list[i])){
 1881:                         result += tag_list[i]+';';
 1882:                     }
 1883:                 }
 1884:                 sessionStorage.setItem('anchor_'+resource, result);
 1885:             }
 1886:         } else {
 1887:             // we dont need to save zero, just delete the item to leave everything tidy
 1888:             sessionStorage.removeItem('anchor_'+resource);
 1889:         }
 1890:     }
 1891: 
 1892:     function restoreScrollPosition(resource){
 1893: 
 1894:         var elem = sessionStorage.getItem('anchor_'+resource);
 1895:         if(elem != null){
 1896:             var tag_list = elem.split(';');
 1897:             var elem_list;
 1898: 
 1899:             for(var i = 0; i < tag_list.length; i++){
 1900:                 elem_list = document.getElementsByName(tag_list[i]);
 1901:                 
 1902:                 if(elem_list.length > 0){
 1903:                     elem = elem_list[0];
 1904:                     break;
 1905:                 }
 1906:             }
 1907:             elem.scrollIntoView();
 1908:         }
 1909:     }
 1910: 
 1911:     function isElementInViewport(el) {
 1912: 
 1913:         // change to last element instead of first
 1914:         var elem = document.getElementsByName(el);
 1915:         var rect = elem[0].getBoundingClientRect();
 1916: 
 1917:         return (
 1918:             rect.top >= 0 &&
 1919:             rect.left >= 0 &&
 1920:             rect.bottom <= (window.innerHeight || document.documentElement.clientHeight) && /*or $(window).height() */
 1921:             rect.right <= (window.innerWidth || document.documentElement.clientWidth) /*or $(window).width() */
 1922:         );
 1923:     }
 1924:     
 1925:     function autosize(depth){
 1926:         var cmInst = window['cm'+depth];
 1927:         var fitsizeButton = document.getElementById('fitsize'+depth);
 1928: 
 1929:         // is fixed size, switching to dynamic
 1930:         if (sessionStorage.getItem("autosized_"+depth) == null) {
 1931:             cmInst.setSize("","auto");
 1932:             fitsizeButton.value = "@{[&mt('Fixed size')]}";
 1933:             sessionStorage.setItem("autosized_"+depth, "yes");
 1934: 
 1935:         // is dynamic size, switching to fixed
 1936:         } else {
 1937:             cmInst.setSize("","300px");
 1938:             fitsizeButton.value = "@{[&mt('Dynamic size')]}";
 1939:             sessionStorage.removeItem("autosized_"+depth);
 1940:         }
 1941:     }
 1942: 
 1943: 
 1944: 
 1945: // ]]>
 1946: </script>
 1947: COLORFULEDIT
 1948: }
 1949: 
 1950: sub xmleditor_js {
 1951:     return <<XMLEDIT
 1952: <script type="text/javascript" src="/adm/jQuery/addons/jquery-scrolltofixed.js"></script>
 1953: <script type="text/javascript">
 1954: // <![CDATA[>
 1955: 
 1956:     function saveScrollPosition (resource) {
 1957: 
 1958:         var scrollPos = \$(window).scrollTop();
 1959:         sessionStorage.setItem(resource,scrollPos);
 1960:     }
 1961: 
 1962:     function restoreScrollPosition(resource){
 1963: 
 1964:         var scrollPos = sessionStorage.getItem(resource);
 1965:         \$(window).scrollTop(scrollPos);
 1966:     }
 1967: 
 1968:     // unless internet explorer
 1969:     if (!(window.navigator.appName == "Microsoft Internet Explorer" && (document.documentMode || document.compatMode))){
 1970: 
 1971:         \$(document).ready(function() {
 1972:              \$(".LC_edit_actionbar").scrollToFixed(\{zIndex: 100\});
 1973:         });
 1974:     }
 1975: 
 1976:     // inserts text at cursor position into codemirror (xml editor only)
 1977:     function insertText(text){
 1978:         cm.focus();
 1979:         var curPos = cm.getCursor();
 1980:         cm.replaceRange(text.replace(/ESCAPEDSCRIPT/g,'script'), {line: curPos.line,ch: curPos.ch});
 1981:     }
 1982: // ]]>
 1983: </script>
 1984: XMLEDIT
 1985: }
 1986: 
 1987: sub insert_folding_button {
 1988:     my $curDepth = $Apache::lonxml::curdepth;
 1989:     my $lastresource = $env{'request.ambiguous'};
 1990: 
 1991:     return "<input type=\"button\" id=\"folding_btn_$curDepth\" 
 1992:             value=\"".&mt('Hide')."\" onclick=\"fold_box('$curDepth','$lastresource')\">";
 1993: }
 1994: 
 1995: =pod
 1996: 
 1997: =head1 Excel and CSV file utility routines
 1998: 
 1999: =cut
 2000: 
 2001: ###############################################################
 2002: ###############################################################
 2003: 
 2004: =pod
 2005: 
 2006: =over 4
 2007: 
 2008: =item * &csv_translate($text) 
 2009: 
 2010: Translate $text to allow it to be output as a 'comma separated values' 
 2011: format.
 2012: 
 2013: =cut
 2014: 
 2015: ###############################################################
 2016: ###############################################################
 2017: sub csv_translate {
 2018:     my $text = shift;
 2019:     $text =~ s/\"/\"\"/g;
 2020:     $text =~ s/\n/ /g;
 2021:     return $text;
 2022: }
 2023: 
 2024: ###############################################################
 2025: ###############################################################
 2026: 
 2027: =pod
 2028: 
 2029: =item * &define_excel_formats()
 2030: 
 2031: Define some commonly used Excel cell formats.
 2032: 
 2033: Currently supported formats:
 2034: 
 2035: =over 4
 2036: 
 2037: =item header
 2038: 
 2039: =item bold
 2040: 
 2041: =item h1
 2042: 
 2043: =item h2
 2044: 
 2045: =item h3
 2046: 
 2047: =item h4
 2048: 
 2049: =item i
 2050: 
 2051: =item date
 2052: 
 2053: =back
 2054: 
 2055: Inputs: $workbook
 2056: 
 2057: Returns: $format, a hash reference.
 2058: 
 2059: 
 2060: =cut
 2061: 
 2062: ###############################################################
 2063: ###############################################################
 2064: sub define_excel_formats {
 2065:     my ($workbook) = @_;
 2066:     my $format;
 2067:     $format->{'header'} = $workbook->add_format(bold      => 1, 
 2068:                                                 bottom    => 1,
 2069:                                                 align     => 'center');
 2070:     $format->{'bold'} = $workbook->add_format(bold=>1);
 2071:     $format->{'h1'}   = $workbook->add_format(bold=>1, size=>18);
 2072:     $format->{'h2'}   = $workbook->add_format(bold=>1, size=>16);
 2073:     $format->{'h3'}   = $workbook->add_format(bold=>1, size=>14);
 2074:     $format->{'h4'}   = $workbook->add_format(bold=>1, size=>12);
 2075:     $format->{'i'}    = $workbook->add_format(italic=>1);
 2076:     $format->{'date'} = $workbook->add_format(num_format=>
 2077:                                             'mm/dd/yyyy hh:mm:ss');
 2078:     return $format;
 2079: }
 2080: 
 2081: ###############################################################
 2082: ###############################################################
 2083: 
 2084: =pod
 2085: 
 2086: =item * &create_workbook()
 2087: 
 2088: Create an Excel worksheet.  If it fails, output message on the
 2089: request object and return undefs.
 2090: 
 2091: Inputs: Apache request object
 2092: 
 2093: Returns (undef) on failure, 
 2094:     Excel worksheet object, scalar with filename, and formats 
 2095:     from &Apache::loncommon::define_excel_formats on success
 2096: 
 2097: =cut
 2098: 
 2099: ###############################################################
 2100: ###############################################################
 2101: sub create_workbook {
 2102:     my ($r) = @_;
 2103:         #
 2104:     # Create the excel spreadsheet
 2105:     my $filename = '/prtspool/'.
 2106:         $env{'user.name'}.'_'.$env{'user.domain'}.'_'.
 2107:         time.'_'.rand(1000000000).'.xls';
 2108:     my $workbook  = Spreadsheet::WriteExcel->new('/home/httpd'.$filename);
 2109:     if (! defined($workbook)) {
 2110:         $r->log_error("Error creating excel spreadsheet $filename: $!");
 2111:         $r->print(
 2112:             '<p class="LC_error">'
 2113:            .&mt('Problems occurred in creating the new Excel file.')
 2114:            .' '.&mt('This error has been logged.')
 2115:            .' '.&mt('Please alert your LON-CAPA administrator.')
 2116:            .'</p>'
 2117:         );
 2118:         return (undef);
 2119:     }
 2120:     #
 2121:     $workbook->set_tempdir(LONCAPA::tempdir());
 2122:     #
 2123:     my $format = &Apache::loncommon::define_excel_formats($workbook);
 2124:     return ($workbook,$filename,$format);
 2125: }
 2126: 
 2127: ###############################################################
 2128: ###############################################################
 2129: 
 2130: =pod
 2131: 
 2132: =item * &create_text_file()
 2133: 
 2134: Create a file to write to and eventually make available to the user.
 2135: If file creation fails, outputs an error message on the request object and 
 2136: return undefs.
 2137: 
 2138: Inputs: Apache request object, and file suffix
 2139: 
 2140: Returns (undef) on failure, 
 2141:     Filehandle and filename on success.
 2142: 
 2143: =cut
 2144: 
 2145: ###############################################################
 2146: ###############################################################
 2147: sub create_text_file {
 2148:     my ($r,$suffix) = @_;
 2149:     if (! defined($suffix)) { $suffix = 'txt'; };
 2150:     my $fh;
 2151:     my $filename = '/prtspool/'.
 2152:         $env{'user.name'}.'_'.$env{'user.domain'}.'_'.
 2153:         time.'_'.rand(1000000000).'.'.$suffix;
 2154:     $fh = Apache::File->new('>/home/httpd'.$filename);
 2155:     if (! defined($fh)) {
 2156:         $r->log_error("Couldn't open $filename for output $!");
 2157:         $r->print(
 2158:             '<p class="LC_error">'
 2159:            .&mt('Problems occurred in creating the output file.')
 2160:            .' '.&mt('This error has been logged.')
 2161:            .' '.&mt('Please alert your LON-CAPA administrator.')
 2162:            .'</p>'
 2163:         );
 2164:     }
 2165:     return ($fh,$filename)
 2166: }
 2167: 
 2168: 
 2169: =pod 
 2170: 
 2171: =back
 2172: 
 2173: =cut
 2174: 
 2175: ###############################################################
 2176: ##        Home server <option> list generating code          ##
 2177: ###############################################################
 2178: 
 2179: # ------------------------------------------
 2180: 
 2181: sub domain_select {
 2182:     my ($name,$value,$multiple)=@_;
 2183:     my %domains=map { 
 2184: 	$_ => $_.' '. &Apache::lonnet::domain($_,'description') 
 2185:     } &Apache::lonnet::all_domains();
 2186:     if ($multiple) {
 2187: 	$domains{''}=&mt('Any domain');
 2188: 	$domains{'select_form_order'} = [sort {lc($a) cmp lc($b) } (keys(%domains))];
 2189: 	return &multiple_select_form($name,$value,4,\%domains);
 2190:     } else {
 2191: 	$domains{'select_form_order'} = [sort {lc($a) cmp lc($b) } (keys(%domains))];
 2192: 	return &select_form($name,$value,\%domains);
 2193:     }
 2194: }
 2195: 
 2196: #-------------------------------------------
 2197: 
 2198: =pod
 2199: 
 2200: =head1 Routines for form select boxes
 2201: 
 2202: =over 4
 2203: 
 2204: =item * &multiple_select_form($name,$value,$size,$hash,$order)
 2205: 
 2206: Returns a string containing a <select> element int multiple mode
 2207: 
 2208: 
 2209: Args:
 2210:   $name - name of the <select> element
 2211:   $value - scalar or array ref of values that should already be selected
 2212:   $size - number of rows long the select element is
 2213:   $hash - the elements should be 'option' => 'shown text'
 2214:           (shown text should already have been &mt())
 2215:   $order - (optional) array ref of the order to show the elements in
 2216: 
 2217: =cut
 2218: 
 2219: #-------------------------------------------
 2220: sub multiple_select_form {
 2221:     my ($name,$value,$size,$hash,$order)=@_;
 2222:     my %selected = map { $_ => 1 } ref($value)?@{$value}:($value);
 2223:     my $output='';
 2224:     if (! defined($size)) {
 2225:         $size = 4;
 2226:         if (scalar(keys(%$hash))<4) {
 2227:             $size = scalar(keys(%$hash));
 2228:         }
 2229:     }
 2230:     $output.="\n".'<select name="'.$name.'" size="'.$size.'" multiple="multiple">';
 2231:     my @order;
 2232:     if (ref($order) eq 'ARRAY')  {
 2233:         @order = @{$order};
 2234:     } else {
 2235:         @order = sort(keys(%$hash));
 2236:     }
 2237:     if (exists($$hash{'select_form_order'})) {
 2238:         @order = @{$$hash{'select_form_order'}};
 2239:     }
 2240:         
 2241:     foreach my $key (@order) {
 2242:         $output.='<option value="'.&HTML::Entities::encode($key,'"<>&').'" ';
 2243:         $output.='selected="selected" ' if ($selected{$key});
 2244:         $output.='>'.$hash->{$key}."</option>\n";
 2245:     }
 2246:     $output.="</select>\n";
 2247:     return $output;
 2248: }
 2249: 
 2250: #-------------------------------------------
 2251: 
 2252: =pod
 2253: 
 2254: =item * &select_form($defdom,$name,$hashref,$onchange)
 2255: 
 2256: Returns a string containing a <select name='$name' size='1'> form to 
 2257: allow a user to select options from a ref to a hash containing:
 2258: option_name => displayed text. An optional $onchange can include
 2259: a javascript onchange item, e.g., onchange="this.form.submit();"  
 2260: 
 2261: See lonrights.pm for an example invocation and use.
 2262: 
 2263: =cut
 2264: 
 2265: #-------------------------------------------
 2266: sub select_form {
 2267:     my ($def,$name,$hashref,$onchange) = @_;
 2268:     return unless (ref($hashref) eq 'HASH');
 2269:     if ($onchange) {
 2270:         $onchange = ' onchange="'.$onchange.'"';
 2271:     }
 2272:     my $selectform = "<select name=\"$name\" size=\"1\"$onchange>\n";
 2273:     my @keys;
 2274:     if (exists($hashref->{'select_form_order'})) {
 2275: 	@keys=@{$hashref->{'select_form_order'}};
 2276:     } else {
 2277: 	@keys=sort(keys(%{$hashref}));
 2278:     }
 2279:     foreach my $key (@keys) {
 2280:         $selectform.=
 2281: 	    '<option value="'.&HTML::Entities::encode($key,'"<>&').'" '.
 2282:             ($key eq $def ? 'selected="selected" ' : '').
 2283:                 ">".$hashref->{$key}."</option>\n";
 2284:     }
 2285:     $selectform.="</select>";
 2286:     return $selectform;
 2287: }
 2288: 
 2289: # For display filters
 2290: 
 2291: sub display_filter {
 2292:     my ($context) = @_;
 2293:     if (!$env{'form.show'}) { $env{'form.show'}=10; }
 2294:     if (!$env{'form.displayfilter'}) { $env{'form.displayfilter'}='currentfolder'; }
 2295:     my $phraseinput = 'hidden';
 2296:     my $includeinput = 'hidden';
 2297:     my ($checked,$includetypestext);
 2298:     if ($env{'form.displayfilter'} eq 'containing') {
 2299:         $phraseinput = 'text'; 
 2300:         if ($context eq 'parmslog') {
 2301:             $includeinput = 'checkbox';
 2302:             if ($env{'form.includetypes'}) {
 2303:                 $checked = ' checked="checked"';
 2304:             }
 2305:             $includetypestext = &mt('Include parameter types');
 2306:         }
 2307:     } else {
 2308:         $includetypestext = '&nbsp;';
 2309:     }
 2310:     my ($additional,$secondid,$thirdid);
 2311:     if ($context eq 'parmslog') {
 2312:         $additional = 
 2313:             '<label><input type="'.$includeinput.'" name="includetypes"'. 
 2314:             $checked.' name="includetypes" value="1" id="includetypes" />'.
 2315:             '&nbsp;<span id="includetypestext">'.$includetypestext.'</span>'.
 2316:             '</label>';
 2317:         $secondid = 'includetypes';
 2318:         $thirdid = 'includetypestext';
 2319:     }
 2320:     my $onchange = "javascript:toggleHistoryOptions(this,'containingphrase','$context',
 2321:                                                     '$secondid','$thirdid')";
 2322:     return '<span class="LC_nobreak"><label>'.&mt('Records: [_1]',
 2323: 			       &Apache::lonmeta::selectbox('show',$env{'form.show'},undef,
 2324: 							   (&mt('all'),10,20,50,100,1000,10000))).
 2325: 	   '</label></span> <span class="LC_nobreak">'.
 2326:            &mt('Filter: [_1]',
 2327: 	   &select_form($env{'form.displayfilter'},
 2328: 			'displayfilter',
 2329: 			{'currentfolder' => 'Current folder/page',
 2330: 			 'containing' => 'Containing phrase',
 2331: 			 'none' => 'None'},$onchange)).'&nbsp;'.
 2332: 			 '<input type="'.$phraseinput.'" name="containingphrase" id="containingphrase" size="30" value="'.
 2333:                          &HTML::Entities::encode($env{'form.containingphrase'}).
 2334:                          '" />'.$additional;
 2335: }
 2336: 
 2337: sub display_filter_js {
 2338:     my $includetext = &mt('Include parameter types');
 2339:     return <<"ENDJS";
 2340:   
 2341: function toggleHistoryOptions(setter,firstid,context,secondid,thirdid) {
 2342:     var firstType = 'hidden';
 2343:     if (setter.options[setter.selectedIndex].value == 'containing') {
 2344:         firstType = 'text';
 2345:     }
 2346:     firstObject = document.getElementById(firstid);
 2347:     if (typeof(firstObject) == 'object') {
 2348:         if (firstObject.type != firstType) {
 2349:             changeInputType(firstObject,firstType);
 2350:         }
 2351:     }
 2352:     if (context == 'parmslog') {
 2353:         var secondType = 'hidden';
 2354:         if (firstType == 'text') {
 2355:             secondType = 'checkbox';
 2356:         }
 2357:         secondObject = document.getElementById(secondid);  
 2358:         if (typeof(secondObject) == 'object') {
 2359:             if (secondObject.type != secondType) {
 2360:                 changeInputType(secondObject,secondType);
 2361:             }
 2362:         }
 2363:         var textItem = document.getElementById(thirdid);
 2364:         var currtext = textItem.innerHTML;
 2365:         var newtext;
 2366:         if (firstType == 'text') {
 2367:             newtext = '$includetext';
 2368:         } else {
 2369:             newtext = '&nbsp;';
 2370:         }
 2371:         if (currtext != newtext) {
 2372:             textItem.innerHTML = newtext;
 2373:         }
 2374:     }
 2375:     return;
 2376: }
 2377: 
 2378: function changeInputType(oldObject,newType) {
 2379:     var newObject = document.createElement('input');
 2380:     newObject.type = newType;
 2381:     if (oldObject.size) {
 2382:         newObject.size = oldObject.size;
 2383:     }
 2384:     if (oldObject.value) {
 2385:         newObject.value = oldObject.value;
 2386:     }
 2387:     if (oldObject.name) {
 2388:         newObject.name = oldObject.name;
 2389:     }
 2390:     if (oldObject.id) {
 2391:         newObject.id = oldObject.id;
 2392:     }
 2393:     oldObject.parentNode.replaceChild(newObject,oldObject);
 2394:     return;
 2395: }
 2396: 
 2397: ENDJS
 2398: }
 2399: 
 2400: sub gradeleveldescription {
 2401:     my $gradelevel=shift;
 2402:     my %gradelevels=(0 => 'Not specified',
 2403: 		     1 => 'Grade 1',
 2404: 		     2 => 'Grade 2',
 2405: 		     3 => 'Grade 3',
 2406: 		     4 => 'Grade 4',
 2407: 		     5 => 'Grade 5',
 2408: 		     6 => 'Grade 6',
 2409: 		     7 => 'Grade 7',
 2410: 		     8 => 'Grade 8',
 2411: 		     9 => 'Grade 9',
 2412: 		     10 => 'Grade 10',
 2413: 		     11 => 'Grade 11',
 2414: 		     12 => 'Grade 12',
 2415: 		     13 => 'Grade 13',
 2416: 		     14 => '100 Level',
 2417: 		     15 => '200 Level',
 2418: 		     16 => '300 Level',
 2419: 		     17 => '400 Level',
 2420: 		     18 => 'Graduate Level');
 2421:     return &mt($gradelevels{$gradelevel});
 2422: }
 2423: 
 2424: sub select_level_form {
 2425:     my ($deflevel,$name)=@_;
 2426:     unless ($deflevel) { $deflevel=0; }
 2427:     my $selectform = "<select name=\"$name\" size=\"1\">\n";
 2428:     for (my $i=0; $i<=18; $i++) {
 2429:         $selectform.="<option value=\"$i\" ".
 2430:             ($i==$deflevel ? 'selected="selected" ' : '').
 2431:                 ">".&gradeleveldescription($i)."</option>\n";
 2432:     }
 2433:     $selectform.="</select>";
 2434:     return $selectform;
 2435: }
 2436: 
 2437: #-------------------------------------------
 2438: 
 2439: =pod
 2440: 
 2441: =item * &select_dom_form($defdom,$name,$includeempty,$showdomdesc,$onchange,$incdoms,$excdoms)
 2442: 
 2443: Returns a string containing a <select name='$name' size='1'> form to 
 2444: allow a user to select the domain to preform an operation in.  
 2445: See loncreateuser.pm for an example invocation and use.
 2446: 
 2447: If the $includeempty flag is set, it also includes an empty choice ("no domain
 2448: selected");
 2449: 
 2450: If the $showdomdesc flag is set, the domain name is followed by the domain description.
 2451: 
 2452: 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.
 2453: 
 2454: The optional $incdoms is a reference to an array of domains which will be the only available options.
 2455: 
 2456: The optional $excdoms is a reference to an array of domains which will be excluded from the available options.
 2457: 
 2458: =cut
 2459: 
 2460: #-------------------------------------------
 2461: sub select_dom_form {
 2462:     my ($defdom,$name,$includeempty,$showdomdesc,$onchange,$incdoms,$excdoms) = @_;
 2463:     if ($onchange) {
 2464:         $onchange = ' onchange="'.$onchange.'"';
 2465:     }
 2466:     my (@domains,%exclude);
 2467:     if (ref($incdoms) eq 'ARRAY') {
 2468:         @domains = sort {lc($a) cmp lc($b)} (@{$incdoms});
 2469:     } else {
 2470:         @domains = sort {lc($a) cmp lc($b)} (&Apache::lonnet::all_domains());
 2471:     }
 2472:     if ($includeempty) { @domains=('',@domains); }
 2473:     if (ref($excdoms) eq 'ARRAY') {
 2474:         map { $exclude{$_} = 1; } @{$excdoms}; 
 2475:     }
 2476:     my $selectdomain = "<select name=\"$name\" size=\"1\"$onchange>\n";
 2477:     foreach my $dom (@domains) {
 2478:         next if ($exclude{$dom});
 2479:         $selectdomain.="<option value=\"$dom\" ".
 2480:             ($dom eq $defdom ? 'selected="selected" ' : '').'>'.$dom;
 2481:         if ($showdomdesc) {
 2482:             if ($dom ne '') {
 2483:                 my $domdesc = &Apache::lonnet::domain($dom,'description');
 2484:                 if ($domdesc ne '') {
 2485:                     $selectdomain .= ' ('.$domdesc.')';
 2486:                 }
 2487:             } 
 2488:         }
 2489:         $selectdomain .= "</option>\n";
 2490:     }
 2491:     $selectdomain.="</select>";
 2492:     return $selectdomain;
 2493: }
 2494: 
 2495: #-------------------------------------------
 2496: 
 2497: =pod
 2498: 
 2499: =item * &home_server_form_item($domain,$name,$defaultflag)
 2500: 
 2501: input: 4 arguments (two required, two optional) - 
 2502:     $domain - domain of new user
 2503:     $name - name of form element
 2504:     $default - Value of 'default' causes a default item to be first 
 2505:                             option, and selected by default. 
 2506:     $hide - Value of 'hide' causes hiding of the name of the server, 
 2507:                             if 1 server found, or default, if 0 found.
 2508: output: returns 2 items: 
 2509: (a) form element which contains either:
 2510:    (i) <select name="$name">
 2511:         <option value="$hostid1">$hostid $servers{$hostid}</option>
 2512:         <option value="$hostid2">$hostid $servers{$hostid}</option>       
 2513:        </select>
 2514:        form item if there are multiple library servers in $domain, or
 2515:    (ii) an <input type="hidden" name="$name" value="$hostid" /> form item 
 2516:        if there is only one library server in $domain.
 2517: 
 2518: (b) number of library servers found.
 2519: 
 2520: See loncreateuser.pm for example of use.
 2521: 
 2522: =cut
 2523: 
 2524: #-------------------------------------------
 2525: sub home_server_form_item {
 2526:     my ($domain,$name,$default,$hide) = @_;
 2527:     my %servers = &Apache::lonnet::get_servers($domain,'library');
 2528:     my $result;
 2529:     my $numlib = keys(%servers);
 2530:     if ($numlib > 1) {
 2531:         $result .= '<select name="'.$name.'" />'."\n";
 2532:         if ($default) {
 2533:             $result .= '<option value="default" selected="selected">'.&mt('default').
 2534:                        '</option>'."\n";
 2535:         }
 2536:         foreach my $hostid (sort(keys(%servers))) {
 2537:             $result.= '<option value="'.$hostid.'">'.
 2538: 	              $hostid.' '.$servers{$hostid}."</option>\n";
 2539:         }
 2540:         $result .= '</select>'."\n";
 2541:     } elsif ($numlib == 1) {
 2542:         my $hostid;
 2543:         foreach my $item (keys(%servers)) {
 2544:             $hostid = $item;
 2545:         }
 2546:         $result .= '<input type="hidden" name="'.$name.'" value="'.
 2547:                    $hostid.'" />';
 2548:                    if (!$hide) {
 2549:                        $result .= $hostid.' '.$servers{$hostid};
 2550:                    }
 2551:                    $result .= "\n";
 2552:     } elsif ($default) {
 2553:         $result .= '<input type="hidden" name="'.$name.
 2554:                    '" value="default" />';
 2555:                    if (!$hide) {
 2556:                        $result .= &mt('default');
 2557:                    }
 2558:                    $result .= "\n";
 2559:     }
 2560:     return ($result,$numlib);
 2561: }
 2562: 
 2563: =pod
 2564: 
 2565: =back 
 2566: 
 2567: =cut
 2568: 
 2569: ###############################################################
 2570: ##                  Decoding User Agent                      ##
 2571: ###############################################################
 2572: 
 2573: =pod
 2574: 
 2575: =head1 Decoding the User Agent
 2576: 
 2577: =over 4
 2578: 
 2579: =item * &decode_user_agent()
 2580: 
 2581: Inputs: $r
 2582: 
 2583: Outputs:
 2584: 
 2585: =over 4
 2586: 
 2587: =item * $httpbrowser
 2588: 
 2589: =item * $clientbrowser
 2590: 
 2591: =item * $clientversion
 2592: 
 2593: =item * $clientmathml
 2594: 
 2595: =item * $clientunicode
 2596: 
 2597: =item * $clientos
 2598: 
 2599: =item * $clientmobile
 2600: 
 2601: =item * $clientinfo
 2602: 
 2603: =item * $clientosversion
 2604: 
 2605: =back
 2606: 
 2607: =back 
 2608: 
 2609: =cut
 2610: 
 2611: ###############################################################
 2612: ###############################################################
 2613: sub decode_user_agent {
 2614:     my ($r)=@_;
 2615:     my @browsertype=split(/\&/,$Apache::lonnet::perlvar{"lonBrowsDet"});
 2616:     my %mathcap=split(/\&/,$$Apache::lonnet::perlvar{"lonMathML"});
 2617:     my $httpbrowser=$ENV{"HTTP_USER_AGENT"};
 2618:     if (!$httpbrowser && $r) { $httpbrowser=$r->header_in('User-Agent'); }
 2619:     my $clientbrowser='unknown';
 2620:     my $clientversion='0';
 2621:     my $clientmathml='';
 2622:     my $clientunicode='0';
 2623:     my $clientmobile=0;
 2624:     my $clientosversion='';
 2625:     for (my $i=0;$i<=$#browsertype;$i++) {
 2626:         my ($bname,$match,$notmatch,$vreg,$minv,$univ)=split(/\%/,$browsertype[$i]);
 2627: 	if (($httpbrowser=~/$match/i)  && ($httpbrowser!~/$notmatch/i)) {
 2628: 	    $clientbrowser=$bname;
 2629:             $httpbrowser=~/$vreg/i;
 2630: 	    $clientversion=$1;
 2631:             $clientmathml=($clientversion>=$minv);
 2632:             $clientunicode=($clientversion>=$univ);
 2633: 	}
 2634:     }
 2635:     my $clientos='unknown';
 2636:     my $clientinfo;
 2637:     if (($httpbrowser=~/linux/i) ||
 2638:         ($httpbrowser=~/unix/i) ||
 2639:         ($httpbrowser=~/ux/i) ||
 2640:         ($httpbrowser=~/solaris/i)) { $clientos='unix'; }
 2641:     if (($httpbrowser=~/vax/i) ||
 2642:         ($httpbrowser=~/vms/i)) { $clientos='vms'; }
 2643:     if ($httpbrowser=~/next/i) { $clientos='next'; }
 2644:     if (($httpbrowser=~/mac/i) ||
 2645:         ($httpbrowser=~/powerpc/i)) { $clientos='mac'; }
 2646:     if ($httpbrowser=~/win/i) {
 2647:         $clientos='win';
 2648:         if ($httpbrowser =~/Windows\s+NT\s+(\d+\.\d+)/i) {
 2649:             $clientosversion = $1;
 2650:         }
 2651:     }
 2652:     if ($httpbrowser=~/embed/i) { $clientos='pda'; }
 2653:     if ($httpbrowser=~/(Android|iPod|iPad|iPhone|webOS|Blackberry|Windows Phone|Opera m(?:ob|in)|Fennec)/i) {
 2654:         $clientmobile=lc($1);
 2655:     }
 2656:     if ($httpbrowser=~ m{Firefox/(\d+\.\d+)}) {
 2657:         $clientinfo = 'firefox-'.$1;
 2658:     } elsif ($httpbrowser=~ m{chromeframe/(\d+\.\d+)\.}) {
 2659:         $clientinfo = 'chromeframe-'.$1;
 2660:     }
 2661:     return ($httpbrowser,$clientbrowser,$clientversion,$clientmathml,
 2662:             $clientunicode,$clientos,$clientmobile,$clientinfo,
 2663:             $clientosversion);
 2664: }
 2665: 
 2666: ###############################################################
 2667: ##    Authentication changing form generation subroutines    ##
 2668: ###############################################################
 2669: ##
 2670: ## All of the authform_xxxxxxx subroutines take their inputs in a
 2671: ## hash, and have reasonable default values.
 2672: ##
 2673: ##    formname = the name given in the <form> tag.
 2674: #-------------------------------------------
 2675: 
 2676: =pod
 2677: 
 2678: =head1 Authentication Routines
 2679: 
 2680: =over 4
 2681: 
 2682: =item * &authform_xxxxxx()
 2683: 
 2684: The authform_xxxxxx subroutines provide javascript and html forms which 
 2685: handle some of the conveniences required for authentication forms.  
 2686: This is not an optimal method, but it works.  
 2687: 
 2688: =over 4
 2689: 
 2690: =item * authform_header
 2691: 
 2692: =item * authform_authorwarning
 2693: 
 2694: =item * authform_nochange
 2695: 
 2696: =item * authform_kerberos
 2697: 
 2698: =item * authform_internal
 2699: 
 2700: =item * authform_filesystem
 2701: 
 2702: =back
 2703: 
 2704: See loncreateuser.pm for invocation and use examples.
 2705: 
 2706: =cut
 2707: 
 2708: #-------------------------------------------
 2709: sub authform_header{  
 2710:     my %in = (
 2711:         formname => 'cu',
 2712:         kerb_def_dom => '',
 2713:         @_,
 2714:     );
 2715:     $in{'formname'} = 'document.' . $in{'formname'};
 2716:     my $result='';
 2717: 
 2718: #---------------------------------------------- Code for upper case translation
 2719:     my $Javascript_toUpperCase;
 2720:     unless ($in{kerb_def_dom}) {
 2721:         $Javascript_toUpperCase =<<"END";
 2722:         switch (choice) {
 2723:            case 'krb': currentform.elements[choicearg].value =
 2724:                currentform.elements[choicearg].value.toUpperCase();
 2725:                break;
 2726:            default:
 2727:         }
 2728: END
 2729:     } else {
 2730:         $Javascript_toUpperCase = "";
 2731:     }
 2732: 
 2733:     my $radioval = "'nochange'";
 2734:     if (defined($in{'curr_authtype'})) {
 2735:         if ($in{'curr_authtype'} ne '') {
 2736:             $radioval = "'".$in{'curr_authtype'}."arg'";
 2737:         }
 2738:     }
 2739:     my $argfield = 'null';
 2740:     if (defined($in{'mode'})) {
 2741:         if ($in{'mode'} eq 'modifycourse')  {
 2742:             if (defined($in{'curr_autharg'})) {
 2743:                 if ($in{'curr_autharg'} ne '') {
 2744:                     $argfield = "'$in{'curr_autharg'}'";
 2745:                 }
 2746:             }
 2747:         }
 2748:     }
 2749: 
 2750:     $result.=<<"END";
 2751: var current = new Object();
 2752: current.radiovalue = $radioval;
 2753: current.argfield = $argfield;
 2754: 
 2755: function changed_radio(choice,currentform) {
 2756:     var choicearg = choice + 'arg';
 2757:     // If a radio button in changed, we need to change the argfield
 2758:     if (current.radiovalue != choice) {
 2759:         current.radiovalue = choice;
 2760:         if (current.argfield != null) {
 2761:             currentform.elements[current.argfield].value = '';
 2762:         }
 2763:         if (choice == 'nochange') {
 2764:             current.argfield = null;
 2765:         } else {
 2766:             current.argfield = choicearg;
 2767:             switch(choice) {
 2768:                 case 'krb': 
 2769:                     currentform.elements[current.argfield].value = 
 2770:                         "$in{'kerb_def_dom'}";
 2771:                 break;
 2772:               default:
 2773:                 break;
 2774:             }
 2775:         }
 2776:     }
 2777:     return;
 2778: }
 2779: 
 2780: function changed_text(choice,currentform) {
 2781:     var choicearg = choice + 'arg';
 2782:     if (currentform.elements[choicearg].value !='') {
 2783:         $Javascript_toUpperCase
 2784:         // clear old field
 2785:         if ((current.argfield != choicearg) && (current.argfield != null)) {
 2786:             currentform.elements[current.argfield].value = '';
 2787:         }
 2788:         current.argfield = choicearg;
 2789:     }
 2790:     set_auth_radio_buttons(choice,currentform);
 2791:     return;
 2792: }
 2793: 
 2794: function set_auth_radio_buttons(newvalue,currentform) {
 2795:     var numauthchoices = currentform.login.length;
 2796:     if (typeof numauthchoices  == "undefined") {
 2797:         return;
 2798:     } 
 2799:     var i=0;
 2800:     while (i < numauthchoices) {
 2801:         if (currentform.login[i].value == newvalue) { break; }
 2802:         i++;
 2803:     }
 2804:     if (i == numauthchoices) {
 2805:         return;
 2806:     }
 2807:     current.radiovalue = newvalue;
 2808:     currentform.login[i].checked = true;
 2809:     return;
 2810: }
 2811: END
 2812:     return $result;
 2813: }
 2814: 
 2815: sub authform_authorwarning {
 2816:     my $result='';
 2817:     $result='<i>'.
 2818:         &mt('As a general rule, only authors or co-authors should be '.
 2819:             'filesystem authenticated '.
 2820:             '(which allows access to the server filesystem).')."</i>\n";
 2821:     return $result;
 2822: }
 2823: 
 2824: sub authform_nochange {
 2825:     my %in = (
 2826:               formname => 'document.cu',
 2827:               kerb_def_dom => 'MSU.EDU',
 2828:               @_,
 2829:           );
 2830:     my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
 2831:     my $result;
 2832:     if (!$authnum) {
 2833:         $result = &mt('Under your current role you are not permitted to change login settings for this user');
 2834:     } else {
 2835:         $result = '<label>'.&mt('[_1] Do not change login data',
 2836:                   '<input type="radio" name="login" value="nochange" '.
 2837:                   'checked="checked" onclick="'.
 2838:             "javascript:changed_radio('nochange',$in{'formname'});".'" />').
 2839: 	    '</label>';
 2840:     }
 2841:     return $result;
 2842: }
 2843: 
 2844: sub authform_kerberos {
 2845:     my %in = (
 2846:               formname => 'document.cu',
 2847:               kerb_def_dom => 'MSU.EDU',
 2848:               kerb_def_auth => 'krb4',
 2849:               @_,
 2850:               );
 2851:     my ($check4,$check5,$krbcheck,$krbarg,$krbver,$result,$authtype,
 2852:         $autharg,$jscall);
 2853:     my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
 2854:     if ($in{'kerb_def_auth'} eq 'krb5') {
 2855:        $check5 = ' checked="checked"';
 2856:     } else {
 2857:        $check4 = ' checked="checked"';
 2858:     }
 2859:     $krbarg = $in{'kerb_def_dom'};
 2860:     if (defined($in{'curr_authtype'})) {
 2861:         if ($in{'curr_authtype'} eq 'krb') {
 2862:             $krbcheck = ' checked="checked"';
 2863:             if (defined($in{'mode'})) {
 2864:                 if ($in{'mode'} eq 'modifyuser') {
 2865:                     $krbcheck = '';
 2866:                 }
 2867:             }
 2868:             if (defined($in{'curr_kerb_ver'})) {
 2869:                 if ($in{'curr_krb_ver'} eq '5') {
 2870:                     $check5 = ' checked="checked"';
 2871:                     $check4 = '';
 2872:                 } else {
 2873:                     $check4 = ' checked="checked"';
 2874:                     $check5 = '';
 2875:                 }
 2876:             }
 2877:             if (defined($in{'curr_autharg'})) {
 2878:                 $krbarg = $in{'curr_autharg'};
 2879:             }
 2880:             if (!$can_assign{'krb4'} && !$can_assign{'krb5'}) {
 2881:                 if (defined($in{'curr_autharg'})) {
 2882:                     $result = 
 2883:     &mt('Currently Kerberos authenticated with domain [_1] Version [_2].',
 2884:         $in{'curr_autharg'},$krbver);
 2885:                 } else {
 2886:                     $result =
 2887:     &mt('Currently Kerberos authenticated, Version [_1].',$krbver);
 2888:                 }
 2889:                 return $result; 
 2890:             }
 2891:         }
 2892:     } else {
 2893:         if ($authnum == 1) {
 2894:             $authtype = '<input type="hidden" name="login" value="krb" />';
 2895:         }
 2896:     }
 2897:     if (!$can_assign{'krb4'} && !$can_assign{'krb5'}) {
 2898:         return;
 2899:     } elsif ($authtype eq '') {
 2900:         if (defined($in{'mode'})) {
 2901:             if ($in{'mode'} eq 'modifycourse') {
 2902:                 if ($authnum == 1) {
 2903:                     $authtype = '<input type="radio" name="login" value="krb" />';
 2904:                 }
 2905:             }
 2906:         }
 2907:     }
 2908:     $jscall = "javascript:changed_radio('krb',$in{'formname'});";
 2909:     if ($authtype eq '') {
 2910:         $authtype = '<input type="radio" name="login" value="krb" '.
 2911:                     'onclick="'.$jscall.'" onchange="'.$jscall.'"'.
 2912:                     $krbcheck.' />';
 2913:     }
 2914:     if (($can_assign{'krb4'} && $can_assign{'krb5'}) ||
 2915:         ($can_assign{'krb4'} && !$can_assign{'krb5'} &&
 2916:          $in{'curr_authtype'} eq 'krb5') ||
 2917:         (!$can_assign{'krb4'} && $can_assign{'krb5'} &&
 2918:          $in{'curr_authtype'} eq 'krb4')) {
 2919:         $result .= &mt
 2920:         ('[_1] Kerberos authenticated with domain [_2] '.
 2921:          '[_3] Version 4 [_4] Version 5 [_5]',
 2922:          '<label>'.$authtype,
 2923:          '</label><input type="text" size="10" name="krbarg" '.
 2924:              'value="'.$krbarg.'" '.
 2925:              'onchange="'.$jscall.'" />',
 2926:          '<label><input type="radio" name="krbver" value="4" '.$check4.' />',
 2927:          '</label><label><input type="radio" name="krbver" value="5" '.$check5.' />',
 2928: 	 '</label>');
 2929:     } elsif ($can_assign{'krb4'}) {
 2930:         $result .= &mt
 2931:         ('[_1] Kerberos authenticated with domain [_2] '.
 2932:          '[_3] Version 4 [_4]',
 2933:          '<label>'.$authtype,
 2934:          '</label><input type="text" size="10" name="krbarg" '.
 2935:              'value="'.$krbarg.'" '.
 2936:              'onchange="'.$jscall.'" />',
 2937:          '<label><input type="hidden" name="krbver" value="4" />',
 2938:          '</label>');
 2939:     } elsif ($can_assign{'krb5'}) {
 2940:         $result .= &mt
 2941:         ('[_1] Kerberos authenticated with domain [_2] '.
 2942:          '[_3] Version 5 [_4]',
 2943:          '<label>'.$authtype,
 2944:          '</label><input type="text" size="10" name="krbarg" '.
 2945:              'value="'.$krbarg.'" '.
 2946:              'onchange="'.$jscall.'" />',
 2947:          '<label><input type="hidden" name="krbver" value="5" />',
 2948:          '</label>');
 2949:     }
 2950:     return $result;
 2951: }
 2952: 
 2953: sub authform_internal {
 2954:     my %in = (
 2955:                 formname => 'document.cu',
 2956:                 kerb_def_dom => 'MSU.EDU',
 2957:                 @_,
 2958:                 );
 2959:     my ($intcheck,$intarg,$result,$authtype,$autharg,$jscall);
 2960:     my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
 2961:     if (defined($in{'curr_authtype'})) {
 2962:         if ($in{'curr_authtype'} eq 'int') {
 2963:             if ($can_assign{'int'}) {
 2964:                 $intcheck = 'checked="checked" ';
 2965:                 if (defined($in{'mode'})) {
 2966:                     if ($in{'mode'} eq 'modifyuser') {
 2967:                         $intcheck = '';
 2968:                     }
 2969:                 }
 2970:                 if (defined($in{'curr_autharg'})) {
 2971:                     $intarg = $in{'curr_autharg'};
 2972:                 }
 2973:             } else {
 2974:                 $result = &mt('Currently internally authenticated.');
 2975:                 return $result;
 2976:             }
 2977:         }
 2978:     } else {
 2979:         if ($authnum == 1) {
 2980:             $authtype = '<input type="hidden" name="login" value="int" />';
 2981:         }
 2982:     }
 2983:     if (!$can_assign{'int'}) {
 2984:         return;
 2985:     } elsif ($authtype eq '') {
 2986:         if (defined($in{'mode'})) {
 2987:             if ($in{'mode'} eq 'modifycourse') {
 2988:                 if ($authnum == 1) {
 2989:                     $authtype = '<input type="radio" name="login" value="int" />';
 2990:                 }
 2991:             }
 2992:         }
 2993:     }
 2994:     $jscall = "javascript:changed_radio('int',$in{'formname'});";
 2995:     if ($authtype eq '') {
 2996:         $authtype = '<input type="radio" name="login" value="int" '.$intcheck.
 2997:                     ' onchange="'.$jscall.'" onclick="'.$jscall.'" />';
 2998:     }
 2999:     $autharg = '<input type="password" size="10" name="intarg" value="'.
 3000:                $intarg.'" onchange="'.$jscall.'" />';
 3001:     $result = &mt
 3002:         ('[_1] Internally authenticated (with initial password [_2])',
 3003:          '<label>'.$authtype,'</label>'.$autharg);
 3004:     $result.="<label><input type=\"checkbox\" name=\"visible\" onclick='if (this.checked) { this.form.intarg.type=\"text\" } else { this.form.intarg.type=\"password\" }' />".&mt('Visible input').'</label>';
 3005:     return $result;
 3006: }
 3007: 
 3008: sub authform_local {
 3009:     my %in = (
 3010:               formname => 'document.cu',
 3011:               kerb_def_dom => 'MSU.EDU',
 3012:               @_,
 3013:               );
 3014:     my ($loccheck,$locarg,$result,$authtype,$autharg,$jscall);
 3015:     my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
 3016:     if (defined($in{'curr_authtype'})) {
 3017:         if ($in{'curr_authtype'} eq 'loc') {
 3018:             if ($can_assign{'loc'}) {
 3019:                 $loccheck = 'checked="checked" ';
 3020:                 if (defined($in{'mode'})) {
 3021:                     if ($in{'mode'} eq 'modifyuser') {
 3022:                         $loccheck = '';
 3023:                     }
 3024:                 }
 3025:                 if (defined($in{'curr_autharg'})) {
 3026:                     $locarg = $in{'curr_autharg'};
 3027:                 }
 3028:             } else {
 3029:                 $result = &mt('Currently using local (institutional) authentication.');
 3030:                 return $result;
 3031:             }
 3032:         }
 3033:     } else {
 3034:         if ($authnum == 1) {
 3035:             $authtype = '<input type="hidden" name="login" value="loc" />';
 3036:         }
 3037:     }
 3038:     if (!$can_assign{'loc'}) {
 3039:         return;
 3040:     } elsif ($authtype eq '') {
 3041:         if (defined($in{'mode'})) {
 3042:             if ($in{'mode'} eq 'modifycourse') {
 3043:                 if ($authnum == 1) {
 3044:                     $authtype = '<input type="radio" name="login" value="loc" />';
 3045:                 }
 3046:             }
 3047:         }
 3048:     }
 3049:     $jscall = "javascript:changed_radio('loc',$in{'formname'});";
 3050:     if ($authtype eq '') {
 3051:         $authtype = '<input type="radio" name="login" value="loc" '.
 3052:                     $loccheck.' onchange="'.$jscall.'" onclick="'.
 3053:                     $jscall.'" />';
 3054:     }
 3055:     $autharg = '<input type="text" size="10" name="locarg" value="'.
 3056:                $locarg.'" onchange="'.$jscall.'" />';
 3057:     $result = &mt('[_1] Local Authentication with argument [_2]',
 3058:                   '<label>'.$authtype,'</label>'.$autharg);
 3059:     return $result;
 3060: }
 3061: 
 3062: sub authform_filesystem {
 3063:     my %in = (
 3064:               formname => 'document.cu',
 3065:               kerb_def_dom => 'MSU.EDU',
 3066:               @_,
 3067:               );
 3068:     my ($fsyscheck,$result,$authtype,$autharg,$jscall);
 3069:     my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
 3070:     if (defined($in{'curr_authtype'})) {
 3071:         if ($in{'curr_authtype'} eq 'fsys') {
 3072:             if ($can_assign{'fsys'}) {
 3073:                 $fsyscheck = 'checked="checked" ';
 3074:                 if (defined($in{'mode'})) {
 3075:                     if ($in{'mode'} eq 'modifyuser') {
 3076:                         $fsyscheck = '';
 3077:                     }
 3078:                 }
 3079:             } else {
 3080:                 $result = &mt('Currently Filesystem Authenticated.');
 3081:                 return $result;
 3082:             }           
 3083:         }
 3084:     } else {
 3085:         if ($authnum == 1) {
 3086:             $authtype = '<input type="hidden" name="login" value="fsys" />';
 3087:         }
 3088:     }
 3089:     if (!$can_assign{'fsys'}) {
 3090:         return;
 3091:     } elsif ($authtype eq '') {
 3092:         if (defined($in{'mode'})) {
 3093:             if ($in{'mode'} eq 'modifycourse') {
 3094:                 if ($authnum == 1) {
 3095:                     $authtype = '<input type="radio" name="login" value="fsys" />';
 3096:                 }
 3097:             }
 3098:         }
 3099:     }
 3100:     $jscall = "javascript:changed_radio('fsys',$in{'formname'});";
 3101:     if ($authtype eq '') {
 3102:         $authtype = '<input type="radio" name="login" value="fsys" '.
 3103:                     $fsyscheck.' onchange="'.$jscall.'" onclick="'.
 3104:                     $jscall.'" />';
 3105:     }
 3106:     $autharg = '<input type="text" size="10" name="fsysarg" value=""'.
 3107:                ' onchange="'.$jscall.'" />';
 3108:     $result = &mt
 3109:         ('[_1] Filesystem Authenticated (with initial password [_2])',
 3110:          '<label><input type="radio" name="login" value="fsys" '.
 3111:          $fsyscheck.'onchange="'.$jscall.'" onclick="'.$jscall.'" />',
 3112:          '</label><input type="password" size="10" name="fsysarg" value="" '.
 3113:                   'onchange="'.$jscall.'" />');
 3114:     return $result;
 3115: }
 3116: 
 3117: sub get_assignable_auth {
 3118:     my ($dom) = @_;
 3119:     if ($dom eq '') {
 3120:         $dom = $env{'request.role.domain'};
 3121:     }
 3122:     my %can_assign = (
 3123:                           krb4 => 1,
 3124:                           krb5 => 1,
 3125:                           int  => 1,
 3126:                           loc  => 1,
 3127:                      );
 3128:     my %domconfig = &Apache::lonnet::get_dom('configuration',['usercreation'],$dom);
 3129:     if (ref($domconfig{'usercreation'}) eq 'HASH') {
 3130:         if (ref($domconfig{'usercreation'}{'authtypes'}) eq 'HASH') {
 3131:             my $authhash = $domconfig{'usercreation'}{'authtypes'};
 3132:             my $context;
 3133:             if ($env{'request.role'} =~ /^au/) {
 3134:                 $context = 'author';
 3135:             } elsif ($env{'request.role'} =~ /^dc/) {
 3136:                 $context = 'domain';
 3137:             } elsif ($env{'request.course.id'}) {
 3138:                 $context = 'course';
 3139:             }
 3140:             if ($context) {
 3141:                 if (ref($authhash->{$context}) eq 'HASH') {
 3142:                    %can_assign = %{$authhash->{$context}}; 
 3143:                 }
 3144:             }
 3145:         }
 3146:     }
 3147:     my $authnum = 0;
 3148:     foreach my $key (keys(%can_assign)) {
 3149:         if ($can_assign{$key}) {
 3150:             $authnum ++;
 3151:         }
 3152:     }
 3153:     if ($can_assign{'krb4'} && $can_assign{'krb5'}) {
 3154:         $authnum --;
 3155:     }
 3156:     return ($authnum,%can_assign);
 3157: }
 3158: 
 3159: ###############################################################
 3160: ##    Get Kerberos Defaults for Domain                 ##
 3161: ###############################################################
 3162: ##
 3163: ## Returns default kerberos version and an associated argument
 3164: ## as listed in file domain.tab. If not listed, provides
 3165: ## appropriate default domain and kerberos version.
 3166: ##
 3167: #-------------------------------------------
 3168: 
 3169: =pod
 3170: 
 3171: =item * &get_kerberos_defaults()
 3172: 
 3173: get_kerberos_defaults($target_domain) returns the default kerberos
 3174: version and domain. If not found, it defaults to version 4 and the 
 3175: domain of the server.
 3176: 
 3177: =over 4
 3178: 
 3179: ($def_version, $def_krb_domain) = &get_kerberos_defaults($target_domain);
 3180: 
 3181: =back
 3182: 
 3183: =back
 3184: 
 3185: =cut
 3186: 
 3187: #-------------------------------------------
 3188: sub get_kerberos_defaults {
 3189:     my $domain=shift;
 3190:     my ($krbdef,$krbdefdom);
 3191:     my %domdefaults = &Apache::lonnet::get_domain_defaults($domain);
 3192:     if (($domdefaults{'auth_def'} =~/^krb(4|5)$/) && ($domdefaults{'auth_arg_def'} ne '')) {
 3193:         $krbdef = $domdefaults{'auth_def'};
 3194:         $krbdefdom = $domdefaults{'auth_arg_def'};
 3195:     } else {
 3196:         $ENV{'SERVER_NAME'}=~/(\w+\.\w+)$/;
 3197:         my $krbdefdom=$1;
 3198:         $krbdefdom=~tr/a-z/A-Z/;
 3199:         $krbdef = "krb4";
 3200:     }
 3201:     return ($krbdef,$krbdefdom);
 3202: }
 3203: 
 3204: 
 3205: ###############################################################
 3206: ##                Thesaurus Functions                        ##
 3207: ###############################################################
 3208: 
 3209: =pod
 3210: 
 3211: =head1 Thesaurus Functions
 3212: 
 3213: =over 4
 3214: 
 3215: =item * &initialize_keywords()
 3216: 
 3217: Initializes the package variable %Keywords if it is empty.  Uses the
 3218: package variable $thesaurus_db_file.
 3219: 
 3220: =cut
 3221: 
 3222: ###################################################
 3223: 
 3224: sub initialize_keywords {
 3225:     return 1 if (scalar keys(%Keywords));
 3226:     # If we are here, %Keywords is empty, so fill it up
 3227:     #   Make sure the file we need exists...
 3228:     if (! -e $thesaurus_db_file) {
 3229:         &Apache::lonnet::logthis("Attempt to access $thesaurus_db_file".
 3230:                                  " failed because it does not exist");
 3231:         return 0;
 3232:     }
 3233:     #   Set up the hash as a database
 3234:     my %thesaurus_db;
 3235:     if (! tie(%thesaurus_db,'GDBM_File',
 3236:               $thesaurus_db_file,&GDBM_READER(),0640)){
 3237:         &Apache::lonnet::logthis("Could not tie \%thesaurus_db to ".
 3238:                                  $thesaurus_db_file);
 3239:         return 0;
 3240:     } 
 3241:     #  Get the average number of appearances of a word.
 3242:     my $avecount = $thesaurus_db{'average.count'};
 3243:     #  Put keywords (those that appear > average) into %Keywords
 3244:     while (my ($word,$data)=each (%thesaurus_db)) {
 3245:         my ($count,undef) = split /:/,$data;
 3246:         $Keywords{$word}++ if ($count > $avecount);
 3247:     }
 3248:     untie %thesaurus_db;
 3249:     # Remove special values from %Keywords.
 3250:     foreach my $value ('total.count','average.count') {
 3251:         delete($Keywords{$value}) if (exists($Keywords{$value}));
 3252:   }
 3253:     return 1;
 3254: }
 3255: 
 3256: ###################################################
 3257: 
 3258: =pod
 3259: 
 3260: =item * &keyword($word)
 3261: 
 3262: Returns true if $word is a keyword.  A keyword is a word that appears more 
 3263: than the average number of times in the thesaurus database.  Calls 
 3264: &initialize_keywords
 3265: 
 3266: =cut
 3267: 
 3268: ###################################################
 3269: 
 3270: sub keyword {
 3271:     return if (!&initialize_keywords());
 3272:     my $word=lc(shift());
 3273:     $word=~s/\W//g;
 3274:     return exists($Keywords{$word});
 3275: }
 3276: 
 3277: ###############################################################
 3278: 
 3279: =pod 
 3280: 
 3281: =item * &get_related_words()
 3282: 
 3283: Look up a word in the thesaurus.  Takes a scalar argument and returns
 3284: an array of words.  If the keyword is not in the thesaurus, an empty array
 3285: will be returned.  The order of the words returned is determined by the
 3286: database which holds them.
 3287: 
 3288: Uses global $thesaurus_db_file.
 3289: 
 3290: 
 3291: =cut
 3292: 
 3293: ###############################################################
 3294: sub get_related_words {
 3295:     my $keyword = shift;
 3296:     my %thesaurus_db;
 3297:     if (! -e $thesaurus_db_file) {
 3298:         &Apache::lonnet::logthis("Attempt to access $thesaurus_db_file ".
 3299:                                  "failed because the file does not exist");
 3300:         return ();
 3301:     }
 3302:     if (! tie(%thesaurus_db,'GDBM_File',
 3303:               $thesaurus_db_file,&GDBM_READER(),0640)){
 3304:         return ();
 3305:     } 
 3306:     my @Words=();
 3307:     my $count=0;
 3308:     if (exists($thesaurus_db{$keyword})) {
 3309: 	# The first element is the number of times
 3310: 	# the word appears.  We do not need it now.
 3311: 	my (undef,@RelatedWords) = (split(/:/,$thesaurus_db{$keyword}));
 3312: 	my (undef,$mostfrequentcount)=split(/\,/,$RelatedWords[0]);
 3313: 	my $threshold=$mostfrequentcount/10;
 3314:         foreach my $possibleword (@RelatedWords) {
 3315:             my ($word,$wordcount)=split(/\,/,$possibleword);
 3316:             if ($wordcount>$threshold) {
 3317: 		push(@Words,$word);
 3318:                 $count++;
 3319:                 if ($count>10) { last; }
 3320: 	    }
 3321:         }
 3322:     }
 3323:     untie %thesaurus_db;
 3324:     return @Words;
 3325: }
 3326: ###############################################################
 3327: #
 3328: #  Spell checking
 3329: #
 3330: 
 3331: =pod
 3332: 
 3333: =back
 3334: 
 3335: =head1 Spell checking
 3336: 
 3337: =over 4
 3338: 
 3339: =item * &check_spelling($wordlist $language)
 3340: 
 3341: Takes a string containing words and feeds it to an external
 3342: spellcheck program via a pipeline. Returns a string containing
 3343: them mis-spelled words.
 3344: 
 3345: Parameters:
 3346: 
 3347: =over 4
 3348: 
 3349: =item - $wordlist
 3350: 
 3351: String that will be fed into the spellcheck program.
 3352: 
 3353: =item - $language
 3354: 
 3355: Language string that specifies the language for which the spell
 3356: check will be performed.
 3357: 
 3358: =back
 3359: 
 3360: =back
 3361: 
 3362: Note: This sub assumes that aspell is installed.
 3363: 
 3364: 
 3365: =cut
 3366: 
 3367: 
 3368: sub check_spelling {
 3369:     my ($wordlist, $language) = @_;
 3370:     my @misspellings;
 3371:     
 3372:     # Generate the speller and set the langauge.
 3373:     # if explicitly selected:
 3374: 
 3375:     my $speller = Text::Aspell->new;
 3376:     if ($language) {
 3377: 	$speller->set_option('lang', $language);
 3378:     }
 3379: 
 3380:     # Turn the word list into an array of words by splittingon whitespace
 3381: 
 3382:     my @words = split(/\s+/, $wordlist);
 3383: 
 3384:     foreach my $word (@words) {
 3385: 	if(! $speller->check($word)) {
 3386: 	    push(@misspellings, $word);
 3387: 	}
 3388:     }
 3389:     return join(' ', @misspellings);
 3390:     
 3391: }
 3392: 
 3393: # -------------------------------------------------------------- Plaintext name
 3394: =pod
 3395: 
 3396: =head1 User Name Functions
 3397: 
 3398: =over 4
 3399: 
 3400: =item * &plainname($uname,$udom,$first)
 3401: 
 3402: Takes a users logon name and returns it as a string in
 3403: "first middle last generation" form 
 3404: if $first is set to 'lastname' then it returns it as
 3405: 'lastname generation, firstname middlename' if their is a lastname
 3406: 
 3407: =cut
 3408: 
 3409: 
 3410: ###############################################################
 3411: sub plainname {
 3412:     my ($uname,$udom,$first)=@_;
 3413:     return if (!defined($uname) || !defined($udom));
 3414:     my %names=&getnames($uname,$udom);
 3415:     my $name=&Apache::lonnet::format_name($names{'firstname'},
 3416: 					  $names{'middlename'},
 3417: 					  $names{'lastname'},
 3418: 					  $names{'generation'},$first);
 3419:     $name=~s/^\s+//;
 3420:     $name=~s/\s+$//;
 3421:     $name=~s/\s+/ /g;
 3422:     if ($name !~ /\S/) { $name=$uname.':'.$udom; }
 3423:     return $name;
 3424: }
 3425: 
 3426: # -------------------------------------------------------------------- Nickname
 3427: =pod
 3428: 
 3429: =item * &nickname($uname,$udom)
 3430: 
 3431: Gets a users name and returns it as a string as
 3432: 
 3433: "&quot;nickname&quot;"
 3434: 
 3435: if the user has a nickname or
 3436: 
 3437: "first middle last generation"
 3438: 
 3439: if the user does not
 3440: 
 3441: =cut
 3442: 
 3443: sub nickname {
 3444:     my ($uname,$udom)=@_;
 3445:     return if (!defined($uname) || !defined($udom));
 3446:     my %names=&getnames($uname,$udom);
 3447:     my $name=$names{'nickname'};
 3448:     if ($name) {
 3449:        $name='&quot;'.$name.'&quot;'; 
 3450:     } else {
 3451:        $name=$names{'firstname'}.' '.$names{'middlename'}.' '.
 3452: 	     $names{'lastname'}.' '.$names{'generation'};
 3453:        $name=~s/\s+$//;
 3454:        $name=~s/\s+/ /g;
 3455:     }
 3456:     return $name;
 3457: }
 3458: 
 3459: sub getnames {
 3460:     my ($uname,$udom)=@_;
 3461:     return if (!defined($uname) || !defined($udom));
 3462:     if ($udom eq 'public' && $uname eq 'public') {
 3463: 	return ('lastname' => &mt('Public'));
 3464:     }
 3465:     my $id=$uname.':'.$udom;
 3466:     my ($names,$cached)=&Apache::lonnet::is_cached_new('namescache',$id);
 3467:     if ($cached) {
 3468: 	return %{$names};
 3469:     } else {
 3470: 	my %loadnames=&Apache::lonnet::get('environment',
 3471:                     ['firstname','middlename','lastname','generation','nickname'],
 3472: 					 $udom,$uname);
 3473: 	&Apache::lonnet::do_cache_new('namescache',$id,\%loadnames);
 3474: 	return %loadnames;
 3475:     }
 3476: }
 3477: 
 3478: # -------------------------------------------------------------------- getemails
 3479: 
 3480: =pod
 3481: 
 3482: =item * &getemails($uname,$udom)
 3483: 
 3484: Gets a user's email information and returns it as a hash with keys:
 3485: notification, critnotification, permanentemail
 3486: 
 3487: For notification and critnotification, values are comma-separated lists 
 3488: of e-mail addresses; for permanentemail, value is a single e-mail address.
 3489:  
 3490: 
 3491: =cut
 3492: 
 3493: 
 3494: sub getemails {
 3495:     my ($uname,$udom)=@_;
 3496:     if ($udom eq 'public' && $uname eq 'public') {
 3497: 	return;
 3498:     }
 3499:     if (!$udom) { $udom=$env{'user.domain'}; }
 3500:     if (!$uname) { $uname=$env{'user.name'}; }
 3501:     my $id=$uname.':'.$udom;
 3502:     my ($names,$cached)=&Apache::lonnet::is_cached_new('emailscache',$id);
 3503:     if ($cached) {
 3504: 	return %{$names};
 3505:     } else {
 3506: 	my %loadnames=&Apache::lonnet::get('environment',
 3507:                     			   ['notification','critnotification',
 3508: 					    'permanentemail'],
 3509: 					   $udom,$uname);
 3510: 	&Apache::lonnet::do_cache_new('emailscache',$id,\%loadnames);
 3511: 	return %loadnames;
 3512:     }
 3513: }
 3514: 
 3515: sub flush_email_cache {
 3516:     my ($uname,$udom)=@_;
 3517:     if (!$udom)  { $udom =$env{'user.domain'}; }
 3518:     if (!$uname) { $uname=$env{'user.name'};   }
 3519:     return if ($udom eq 'public' && $uname eq 'public');
 3520:     my $id=$uname.':'.$udom;
 3521:     &Apache::lonnet::devalidate_cache_new('emailscache',$id);
 3522: }
 3523: 
 3524: # -------------------------------------------------------------------- getlangs
 3525: 
 3526: =pod
 3527: 
 3528: =item * &getlangs($uname,$udom)
 3529: 
 3530: Gets a user's language preference and returns it as a hash with key:
 3531: language.
 3532: 
 3533: =cut
 3534: 
 3535: 
 3536: sub getlangs {
 3537:     my ($uname,$udom) = @_;
 3538:     if (!$udom)  { $udom =$env{'user.domain'}; }
 3539:     if (!$uname) { $uname=$env{'user.name'};   }
 3540:     my $id=$uname.':'.$udom;
 3541:     my ($langs,$cached)=&Apache::lonnet::is_cached_new('userlangs',$id);
 3542:     if ($cached) {
 3543:         return %{$langs};
 3544:     } else {
 3545:         my %loadlangs=&Apache::lonnet::get('environment',['languages'],
 3546:                                            $udom,$uname);
 3547:         &Apache::lonnet::do_cache_new('userlangs',$id,\%loadlangs);
 3548:         return %loadlangs;
 3549:     }
 3550: }
 3551: 
 3552: sub flush_langs_cache {
 3553:     my ($uname,$udom)=@_;
 3554:     if (!$udom)  { $udom =$env{'user.domain'}; }
 3555:     if (!$uname) { $uname=$env{'user.name'};   }
 3556:     return if ($udom eq 'public' && $uname eq 'public');
 3557:     my $id=$uname.':'.$udom;
 3558:     &Apache::lonnet::devalidate_cache_new('userlangs',$id);
 3559: }
 3560: 
 3561: # ------------------------------------------------------------------ Screenname
 3562: 
 3563: =pod
 3564: 
 3565: =item * &screenname($uname,$udom)
 3566: 
 3567: Gets a users screenname and returns it as a string
 3568: 
 3569: =cut
 3570: 
 3571: sub screenname {
 3572:     my ($uname,$udom)=@_;
 3573:     if ($uname eq $env{'user.name'} &&
 3574: 	$udom eq $env{'user.domain'}) {return $env{'environment.screenname'};}
 3575:     my %names=&Apache::lonnet::get('environment',['screenname'],$udom,$uname);
 3576:     return $names{'screenname'};
 3577: }
 3578: 
 3579: 
 3580: # ------------------------------------------------------------- Confirm Wrapper
 3581: =pod
 3582: 
 3583: =item * &confirmwrapper($message)
 3584: 
 3585: Wrap messages about completion of operation in box
 3586: 
 3587: =cut
 3588: 
 3589: sub confirmwrapper {
 3590:     my ($message)=@_;
 3591:     if ($message) {
 3592:         return "\n".'<div class="LC_confirm_box">'."\n"
 3593:                .$message."\n"
 3594:                .'</div>'."\n";
 3595:     } else {
 3596:         return $message;
 3597:     }
 3598: }
 3599: 
 3600: # ------------------------------------------------------------- Message Wrapper
 3601: 
 3602: sub messagewrapper {
 3603:     my ($link,$username,$domain,$subject,$text)=@_;
 3604:     return 
 3605:         '<a href="/adm/email?compose=individual&amp;'.
 3606:         'recname='.$username.'&amp;recdom='.$domain.
 3607: 	'&amp;subject='.&escape($subject).'&amp;text='.&escape($text).'" '.
 3608:         'title="'.&mt('Send message').'">'.$link.'</a>';
 3609: }
 3610: 
 3611: # --------------------------------------------------------------- Notes Wrapper
 3612: 
 3613: sub noteswrapper {
 3614:     my ($link,$un,$do)=@_;
 3615:     return 
 3616: "<a href='/adm/email?recordftf=retrieve&amp;recname=$un&amp;recdom=$do'>$link</a>";
 3617: }
 3618: 
 3619: # ------------------------------------------------------------- Aboutme Wrapper
 3620: 
 3621: sub aboutmewrapper {
 3622:     my ($link,$username,$domain,$target,$class)=@_;
 3623:     if (!defined($username)  && !defined($domain)) {
 3624:         return;
 3625:     }
 3626:     return '<a href="/adm/'.$domain.'/'.$username.'/aboutme"'.
 3627: 	($target?' target="'.$target.'"':'').($class?' class="'.$class.'"':'').' title="'.&mt("View this user's personal information page").'">'.$link.'</a>';
 3628: }
 3629: 
 3630: # ------------------------------------------------------------ Syllabus Wrapper
 3631: 
 3632: sub syllabuswrapper {
 3633:     my ($linktext,$coursedir,$domain)=@_;
 3634:     return qq{<a href="/public/$domain/$coursedir/syllabus">$linktext</a>};
 3635: }
 3636: 
 3637: # -----------------------------------------------------------------------------
 3638: 
 3639: sub track_student_link {
 3640:     my ($linktext,$sname,$sdom,$target,$start,$only_body) = @_;
 3641:     my $link ="/adm/trackstudent?";
 3642:     my $title = 'View recent activity';
 3643:     if (defined($sname) && $sname !~ /^\s*$/ &&
 3644:         defined($sdom)  && $sdom  !~ /^\s*$/) {
 3645:         $link .= "selected_student=$sname:$sdom";
 3646:         $title .= ' of this student';
 3647:     } 
 3648:     if (defined($target) && $target !~ /^\s*$/) {
 3649:         $target = qq{target="$target"};
 3650:     } else {
 3651:         $target = '';
 3652:     }
 3653:     if ($start) { $link.='&amp;start='.$start; }
 3654:     if ($only_body) { $link .= '&amp;only_body=1'; }
 3655:     $title = &mt($title);
 3656:     $linktext = &mt($linktext);
 3657:     return qq{<a href="$link" title="$title" $target>$linktext</a>}.
 3658: 	&help_open_topic('View_recent_activity');
 3659: }
 3660: 
 3661: sub slot_reservations_link {
 3662:     my ($linktext,$sname,$sdom,$target) = @_;
 3663:     my $link ="/adm/slotrequest?command=showresv&amp;origin=aboutme";
 3664:     my $title = 'View slot reservation history';
 3665:     if (defined($sname) && $sname !~ /^\s*$/ &&
 3666:         defined($sdom)  && $sdom  !~ /^\s*$/) {
 3667:         $link .= "&amp;uname=$sname&amp;udom=$sdom";
 3668:         $title .= ' of this student';
 3669:     }
 3670:     if (defined($target) && $target !~ /^\s*$/) {
 3671:         $target = qq{target="$target"};
 3672:     } else {
 3673:         $target = '';
 3674:     }
 3675:     $title = &mt($title);
 3676:     $linktext = &mt($linktext);
 3677:     return qq{<a href="$link" title="$title" $target>$linktext</a>};
 3678: # FIXME uncomment when help item created: &help_open_topic('Slot_Reservation_History');
 3679: 
 3680: }
 3681: 
 3682: # ===================================================== Display a student photo
 3683: 
 3684: 
 3685: sub student_image_tag {
 3686:     my ($domain,$user)=@_;
 3687:     my $imgsrc=&Apache::lonnet::studentphoto($domain,$user,'jpg');
 3688:     if (($imgsrc) && ($imgsrc ne '/adm/lonKaputt/lonlogo_broken.gif')) {
 3689: 	return '<img src="'.$imgsrc.'" align="right" />';
 3690:     } else {
 3691: 	return '';
 3692:     }
 3693: }
 3694: 
 3695: =pod
 3696: 
 3697: =back
 3698: 
 3699: =head1 Access .tab File Data
 3700: 
 3701: =over 4
 3702: 
 3703: =item * &languageids() 
 3704: 
 3705: returns list of all language ids
 3706: 
 3707: =cut
 3708: 
 3709: sub languageids {
 3710:     return sort(keys(%language));
 3711: }
 3712: 
 3713: =pod
 3714: 
 3715: =item * &languagedescription() 
 3716: 
 3717: returns description of a specified language id
 3718: 
 3719: =cut
 3720: 
 3721: sub languagedescription {
 3722:     my $code=shift;
 3723:     return  ($supported_language{$code}?'* ':'').
 3724:             $language{$code}.
 3725: 	    ($supported_language{$code}?' ('.&mt('interface available').')':'');
 3726: }
 3727: 
 3728: =pod
 3729: 
 3730: =item * &plainlanguagedescription
 3731: 
 3732: Returns both the plain language description (e.g. 'Creoles and Pidgins, English-based (Other)')
 3733: and the language character encoding (e.g. ISO) separated by a ' - ' string.
 3734: 
 3735: =cut
 3736: 
 3737: sub plainlanguagedescription {
 3738:     my $code=shift;
 3739:     return $language{$code};
 3740: }
 3741: 
 3742: =pod
 3743: 
 3744: =item * &supportedlanguagecode
 3745: 
 3746: Returns the supported language code (e.g. sptutf maps to pt) given a language
 3747: code.
 3748: 
 3749: =cut
 3750: 
 3751: sub supportedlanguagecode {
 3752:     my $code=shift;
 3753:     return $supported_language{$code};
 3754: }
 3755: 
 3756: =pod
 3757: 
 3758: =item * &latexlanguage()
 3759: 
 3760: Given a language key code returns the correspondnig language to use
 3761: to select the correct hyphenation on LaTeX printouts.  This is undef if there
 3762: is no supported hyphenation for the language code.
 3763: 
 3764: =cut
 3765: 
 3766: sub latexlanguage {
 3767:     my $code = shift;
 3768:     return $latex_language{$code};
 3769: }
 3770: 
 3771: =pod
 3772: 
 3773: =item * &latexhyphenation()
 3774: 
 3775: Same as above but what's supplied is the language as it might be stored
 3776: in the metadata.
 3777: 
 3778: =cut
 3779: 
 3780: sub latexhyphenation {
 3781:     my $key = shift;
 3782:     return $latex_language_bykey{$key};
 3783: }
 3784: 
 3785: =pod
 3786: 
 3787: =item * &copyrightids() 
 3788: 
 3789: returns list of all copyrights
 3790: 
 3791: =cut
 3792: 
 3793: sub copyrightids {
 3794:     return sort(keys(%cprtag));
 3795: }
 3796: 
 3797: =pod
 3798: 
 3799: =item * &copyrightdescription() 
 3800: 
 3801: returns description of a specified copyright id
 3802: 
 3803: =cut
 3804: 
 3805: sub copyrightdescription {
 3806:     return &mt($cprtag{shift(@_)});
 3807: }
 3808: 
 3809: =pod
 3810: 
 3811: =item * &source_copyrightids() 
 3812: 
 3813: returns list of all source copyrights
 3814: 
 3815: =cut
 3816: 
 3817: sub source_copyrightids {
 3818:     return sort(keys(%scprtag));
 3819: }
 3820: 
 3821: =pod
 3822: 
 3823: =item * &source_copyrightdescription() 
 3824: 
 3825: returns description of a specified source copyright id
 3826: 
 3827: =cut
 3828: 
 3829: sub source_copyrightdescription {
 3830:     return &mt($scprtag{shift(@_)});
 3831: }
 3832: 
 3833: =pod
 3834: 
 3835: =item * &filecategories() 
 3836: 
 3837: returns list of all file categories
 3838: 
 3839: =cut
 3840: 
 3841: sub filecategories {
 3842:     return sort(keys(%category_extensions));
 3843: }
 3844: 
 3845: =pod
 3846: 
 3847: =item * &filecategorytypes() 
 3848: 
 3849: returns list of file types belonging to a given file
 3850: category
 3851: 
 3852: =cut
 3853: 
 3854: sub filecategorytypes {
 3855:     my ($cat) = @_;
 3856:     return @{$category_extensions{lc($cat)}};
 3857: }
 3858: 
 3859: =pod
 3860: 
 3861: =item * &fileembstyle() 
 3862: 
 3863: returns embedding style for a specified file type
 3864: 
 3865: =cut
 3866: 
 3867: sub fileembstyle {
 3868:     return $fe{lc(shift(@_))};
 3869: }
 3870: 
 3871: sub filemimetype {
 3872:     return $fm{lc(shift(@_))};
 3873: }
 3874: 
 3875: 
 3876: sub filecategoryselect {
 3877:     my ($name,$value)=@_;
 3878:     return &select_form($value,$name,
 3879:                         {'' => &mt('Any category'), map { $_,$_ } sort(keys(%category_extensions))});
 3880: }
 3881: 
 3882: =pod
 3883: 
 3884: =item * &filedescription() 
 3885: 
 3886: returns description for a specified file type
 3887: 
 3888: =cut
 3889: 
 3890: sub filedescription {
 3891:     my $file_description = $fd{lc(shift())};
 3892:     $file_description =~ s:([\[\]]):~$1:g;
 3893:     return &mt($file_description);
 3894: }
 3895: 
 3896: =pod
 3897: 
 3898: =item * &filedescriptionex() 
 3899: 
 3900: returns description for a specified file type with
 3901: extra formatting
 3902: 
 3903: =cut
 3904: 
 3905: sub filedescriptionex {
 3906:     my $ex=shift;
 3907:     my $file_description = $fd{lc($ex)};
 3908:     $file_description =~ s:([\[\]]):~$1:g;
 3909:     return '.'.$ex.' '.&mt($file_description);
 3910: }
 3911: 
 3912: # End of .tab access
 3913: =pod
 3914: 
 3915: =back
 3916: 
 3917: =cut
 3918: 
 3919: # ------------------------------------------------------------------ File Types
 3920: sub fileextensions {
 3921:     return sort(keys(%fe));
 3922: }
 3923: 
 3924: # ----------------------------------------------------------- Display Languages
 3925: # returns a hash with all desired display languages
 3926: #
 3927: 
 3928: sub display_languages {
 3929:     my %languages=();
 3930:     foreach my $lang (&Apache::lonlocal::preferred_languages()) {
 3931: 	$languages{$lang}=1;
 3932:     }
 3933:     &get_unprocessed_cgi($ENV{'QUERY_STRING'},['displaylanguage']);
 3934:     if ($env{'form.displaylanguage'}) {
 3935: 	foreach my $lang (split(/\s*(\,|\;|\:)\s*/,$env{'form.displaylanguage'})) {
 3936: 	    $languages{$lang}=1;
 3937:         }
 3938:     }
 3939:     return %languages;
 3940: }
 3941: 
 3942: sub languages {
 3943:     my ($possible_langs) = @_;
 3944:     my @preferred_langs = &Apache::lonlocal::preferred_languages();
 3945:     if (!ref($possible_langs)) {
 3946: 	if( wantarray ) {
 3947: 	    return @preferred_langs;
 3948: 	} else {
 3949: 	    return $preferred_langs[0];
 3950: 	}
 3951:     }
 3952:     my %possibilities = map { $_ => 1 } (@$possible_langs);
 3953:     my @preferred_possibilities;
 3954:     foreach my $preferred_lang (@preferred_langs) {
 3955: 	if (exists($possibilities{$preferred_lang})) {
 3956: 	    push(@preferred_possibilities, $preferred_lang);
 3957: 	}
 3958:     }
 3959:     if( wantarray ) {
 3960: 	return @preferred_possibilities;
 3961:     }
 3962:     return $preferred_possibilities[0];
 3963: }
 3964: 
 3965: sub user_lang {
 3966:     my ($touname,$toudom,$fromcid) = @_;
 3967:     my @userlangs;
 3968:     if (($fromcid ne '') && ($env{'course.'.$fromcid.'.languages'} ne '')) {
 3969:         @userlangs=(@userlangs,split(/\s*(\,|\;|\:)\s*/,
 3970:                     $env{'course.'.$fromcid.'.languages'}));
 3971:     } else {
 3972:         my %langhash = &getlangs($touname,$toudom);
 3973:         if ($langhash{'languages'} ne '') {
 3974:             @userlangs = split(/\s*(\,|\;|\:)\s*/,$langhash{'languages'});
 3975:         } else {
 3976:             my %domdefs = &Apache::lonnet::get_domain_defaults($toudom);
 3977:             if ($domdefs{'lang_def'} ne '') {
 3978:                 @userlangs = ($domdefs{'lang_def'});
 3979:             }
 3980:         }
 3981:     }
 3982:     my @languages=&Apache::lonlocal::get_genlanguages(@userlangs);
 3983:     my $user_lh = Apache::localize->get_handle(@languages);
 3984:     return $user_lh;
 3985: }
 3986: 
 3987: 
 3988: ###############################################################
 3989: ##               Student Answer Attempts                     ##
 3990: ###############################################################
 3991: 
 3992: =pod
 3993: 
 3994: =head1 Alternate Problem Views
 3995: 
 3996: =over 4
 3997: 
 3998: =item * &get_previous_attempt($symb, $username, $domain, $course,
 3999:     $getattempt, $regexp, $gradesub, $usec, $identifier)
 4000: 
 4001: Return string with previous attempt on problem. Arguments:
 4002: 
 4003: =over 4
 4004: 
 4005: =item * $symb: Problem, including path
 4006: 
 4007: =item * $username: username of the desired student
 4008: 
 4009: =item * $domain: domain of the desired student
 4010: 
 4011: =item * $course: Course ID
 4012: 
 4013: =item * $getattempt: Leave blank for all attempts, otherwise put
 4014:     something
 4015: 
 4016: =item * $regexp: if string matches this regexp, the string will be
 4017:     sent to $gradesub
 4018: 
 4019: =item * $gradesub: routine that processes the string if it matches $regexp
 4020: 
 4021: =item * $usec: section of the desired student
 4022: 
 4023: =item * $identifier: counter for student (multiple students one problem) or 
 4024:     problem (one student; whole sequence).
 4025: 
 4026: =back
 4027: 
 4028: The output string is a table containing all desired attempts, if any.
 4029: 
 4030: =cut
 4031: 
 4032: sub get_previous_attempt {
 4033:   my ($symb,$username,$domain,$course,$getattempt,$regexp,$gradesub,$usec,$identifier)=@_;
 4034:   my $prevattempts='';
 4035:   no strict 'refs';
 4036:   if ($symb) {
 4037:     my (%returnhash)=
 4038:       &Apache::lonnet::restore($symb,$course,$domain,$username);
 4039:     if ($returnhash{'version'}) {
 4040:       my %lasthash=();
 4041:       my $version;
 4042:       for ($version=1;$version<=$returnhash{'version'};$version++) {
 4043:         foreach my $key (reverse(sort(split(/\:/,$returnhash{$version.':keys'})))) {
 4044:             if ($key =~ /\.rawrndseed$/) {
 4045:                 my ($id) = ($key =~ /^(.+)\.rawrndseed$/);
 4046:                 $lasthash{$id.'.rndseed'} = $returnhash{$version.':'.$key};
 4047:             } else {
 4048:                 $lasthash{$key}=$returnhash{$version.':'.$key};
 4049:             }
 4050:         }
 4051:       }
 4052:       $prevattempts=&start_data_table().&start_data_table_header_row();
 4053:       $prevattempts.='<th>'.&mt('History').'</th>';
 4054:       my (%typeparts,%lasthidden,%regraded,%hidestatus);
 4055:       my $showsurv=&Apache::lonnet::allowed('vas',$env{'request.course.id'});
 4056:       foreach my $key (sort(keys(%lasthash))) {
 4057: 	my ($ign,@parts) = split(/\./,$key);
 4058: 	if ($#parts > 0) {
 4059: 	  my $data=$parts[-1];
 4060:           next if ($data eq 'foilorder');
 4061: 	  pop(@parts);
 4062:           $prevattempts.='<th>'.&mt('Part ').join('.',@parts).'<br />'.$data.'&nbsp;</th>';
 4063:           if ($data eq 'type') {
 4064:               unless ($showsurv) {
 4065:                   my $id = join(',',@parts);
 4066:                   $typeparts{$ign.'.'.$id} = $lasthash{$key};
 4067:                   if (($lasthash{$key} eq 'anonsurvey') || ($lasthash{$key} eq 'anonsurveycred')) {
 4068:                       $lasthidden{$ign.'.'.$id} = 1;
 4069:                   }
 4070:               }
 4071:               if ($identifier ne '') {
 4072:                   my $id = join(',',@parts);
 4073:                   if (&Apache::lonnet::EXT("resource.$id.problemstatus",$symb,
 4074:                                                $domain,$username,$usec,undef,$course) =~ /^no/) {
 4075:                       $hidestatus{$ign.'.'.$id} = 1;
 4076:                   }
 4077:               }
 4078:           } elsif ($data eq 'regrader') {
 4079:               if (($identifier ne '') && (@parts)) {
 4080:                   my $id = join(',',@parts);
 4081:                   $regraded{$ign.'.'.$id} = 1;
 4082:               }
 4083:           } 
 4084: 	} else {
 4085: 	  if ($#parts == 0) {
 4086: 	    $prevattempts.='<th>'.$parts[0].'</th>';
 4087: 	  } else {
 4088: 	    $prevattempts.='<th>'.$ign.'</th>';
 4089: 	  }
 4090: 	}
 4091:       }
 4092:       $prevattempts.=&end_data_table_header_row();
 4093:       if ($getattempt eq '') {
 4094:         my (%solved,%resets,%probstatus);
 4095:         if (($identifier ne '') && (keys(%regraded) > 0)) {
 4096:             for ($version=1;$version<=$returnhash{'version'};$version++) {
 4097:                 foreach my $id (keys(%regraded)) {
 4098:                     if (($returnhash{$version.':'.$id.'.regrader'}) &&
 4099:                         ($returnhash{$version.':'.$id.'.tries'} eq '') &&
 4100:                         ($returnhash{$version.':'.$id.'.award'} eq '')) {
 4101:                         push(@{$resets{$id}},$version);
 4102:                     }
 4103:                 }
 4104:             }
 4105:         }
 4106: 	for ($version=1;$version<=$returnhash{'version'};$version++) {
 4107:             my (@hidden,@unsolved);
 4108:             if (%typeparts) {
 4109:                 foreach my $id (keys(%typeparts)) {
 4110:                     if (($returnhash{$version.':'.$id.'.type'} eq 'anonsurvey') || 
 4111:                         ($returnhash{$version.':'.$id.'.type'} eq 'anonsurveycred')) {
 4112:                         push(@hidden,$id);
 4113:                     } elsif ($identifier ne '') {
 4114:                         unless (($returnhash{$version.':'.$id.'.type'} eq 'survey') ||
 4115:                                 ($returnhash{$version.':'.$id.'.type'} eq 'surveycred') ||
 4116:                                 ($hidestatus{$id})) {
 4117:                             next if ((ref($resets{$id}) eq 'ARRAY') && grep(/^\Q$version\E$/,@{$resets{$id}}));
 4118:                             if ($returnhash{$version.':'.$id.'.solved'} eq 'correct_by_student') {
 4119:                                 push(@{$solved{$id}},$version);
 4120:                             } elsif (($returnhash{$version.':'.$id.'.solved'} ne '') &&
 4121:                                      (ref($solved{$id}) eq 'ARRAY')) {
 4122:                                 my $skip;
 4123:                                 if (ref($resets{$id}) eq 'ARRAY') {
 4124:                                     foreach my $reset (@{$resets{$id}}) {
 4125:                                         if ($reset > $solved{$id}[-1]) {
 4126:                                             $skip=1;
 4127:                                             last;
 4128:                                         }
 4129:                                     }
 4130:                                 }
 4131:                                 unless ($skip) {
 4132:                                     my ($ign,$partslist) = split(/\./,$id,2);
 4133:                                     push(@unsolved,$partslist);
 4134:                                 }
 4135:                             }
 4136:                         }
 4137:                     }
 4138:                 }
 4139:             }
 4140:             $prevattempts.=&start_data_table_row().
 4141:                            '<td>'.&mt('Transaction [_1]',$version);
 4142:             if (@unsolved) {
 4143:                 $prevattempts .= '<span class="LC_nobreak"><label>'.
 4144:                                  '<input type="checkbox" name="HIDE'.$identifier.'" value="'.$version.':'.join('_',@unsolved).'" />'.
 4145:                                  &mt('Hide').'</label></span>';
 4146:             }
 4147:             $prevattempts .= '</td>';
 4148:             if (@hidden) {
 4149:                 foreach my $key (sort(keys(%lasthash))) {
 4150:                     next if ($key =~ /\.foilorder$/);
 4151:                     my $hide;
 4152:                     foreach my $id (@hidden) {
 4153:                         if ($key =~ /^\Q$id\E/) {
 4154:                             $hide = 1;
 4155:                             last;
 4156:                         }
 4157:                     }
 4158:                     if ($hide) {
 4159:                         my ($id,$data) = ($key =~ /^(.+)\.([^.]+)$/);
 4160:                         if (($data eq 'award') || ($data eq 'awarddetail')) {
 4161:                             my $value = &format_previous_attempt_value($key,
 4162:                                              $returnhash{$version.':'.$key});
 4163:                             $prevattempts.='<td>'.$value.'&nbsp;</td>';
 4164:                         } else {
 4165:                             $prevattempts.='<td>&nbsp;</td>';
 4166:                         }
 4167:                     } else {
 4168:                         if ($key =~ /\./) {
 4169:                             my $value = $returnhash{$version.':'.$key};
 4170:                             if ($key =~ /\.rndseed$/) {
 4171:                                 my ($id) = ($key =~ /^(.+)\.[^.]+$/);
 4172:                                 if (exists($returnhash{$version.':'.$id.'.rawrndseed'})) {
 4173:                                     $value = $returnhash{$version.':'.$id.'.rawrndseed'};
 4174:                                 }
 4175:                             }
 4176:                             $prevattempts.='<td>'.&format_previous_attempt_value($key,$value).
 4177:                                            '&nbsp;</td>';
 4178:                         } else {
 4179:                             $prevattempts.='<td>&nbsp;</td>';
 4180:                         }
 4181:                     }
 4182:                 }
 4183:             } else {
 4184: 	        foreach my $key (sort(keys(%lasthash))) {
 4185:                     next if ($key =~ /\.foilorder$/);
 4186:                     my $value = $returnhash{$version.':'.$key};
 4187:                     if ($key =~ /\.rndseed$/) {
 4188:                         my ($id) = ($key =~ /^(.+)\.[^.]+$/);
 4189:                         if (exists($returnhash{$version.':'.$id.'.rawrndseed'})) {
 4190:                             $value = $returnhash{$version.':'.$id.'.rawrndseed'};
 4191:                         }
 4192:                     }
 4193:                     $prevattempts.='<td>'.&format_previous_attempt_value($key,$value).
 4194:                                    '&nbsp;</td>';
 4195: 	        }
 4196:             }
 4197: 	    $prevattempts.=&end_data_table_row();
 4198: 	 }
 4199:       }
 4200:       my @currhidden = keys(%lasthidden);
 4201:       $prevattempts.=&start_data_table_row().'<td>'.&mt('Current').'</td>';
 4202:       foreach my $key (sort(keys(%lasthash))) {
 4203:           next if ($key =~ /\.foilorder$/);
 4204:           if (%typeparts) {
 4205:               my $hidden;
 4206:               foreach my $id (@currhidden) {
 4207:                   if ($key =~ /^\Q$id\E/) {
 4208:                       $hidden = 1;
 4209:                       last;
 4210:                   }
 4211:               }
 4212:               if ($hidden) {
 4213:                   my ($id,$data) = ($key =~ /^(.+)\.([^.]+)$/);
 4214:                   if (($data eq 'award') || ($data eq 'awarddetail')) {
 4215:                       my $value = &format_previous_attempt_value($key,$lasthash{$key});
 4216:                       if ($key =~/$regexp$/ && (defined &$gradesub)) {
 4217:                           $value = &$gradesub($value);
 4218:                       }
 4219:                       $prevattempts.='<td>'. $value.'&nbsp;</td>';
 4220:                   } else {
 4221:                       $prevattempts.='<td>&nbsp;</td>';
 4222:                   }
 4223:               } else {
 4224:                   my $value = &format_previous_attempt_value($key,$lasthash{$key});
 4225:                   if ($key =~/$regexp$/ && (defined &$gradesub)) {
 4226:                       $value = &$gradesub($value);
 4227:                   }
 4228:                   $prevattempts.='<td>'.$value.'&nbsp;</td>';
 4229:               }
 4230:           } else {
 4231: 	      my $value = &format_previous_attempt_value($key,$lasthash{$key});
 4232: 	      if ($key =~/$regexp$/ && (defined &$gradesub)) {
 4233:                   $value = &$gradesub($value);
 4234:               }
 4235: 	     $prevattempts.='<td>'.$value.'&nbsp;</td>';
 4236:           }
 4237:       }
 4238:       $prevattempts.= &end_data_table_row().&end_data_table();
 4239:     } else {
 4240:       $prevattempts=
 4241: 	  &start_data_table().&start_data_table_row().
 4242: 	  '<td>'.&mt('Nothing submitted - no attempts.').'</td>'.
 4243: 	  &end_data_table_row().&end_data_table();
 4244:     }
 4245:   } else {
 4246:     $prevattempts=
 4247: 	  &start_data_table().&start_data_table_row().
 4248: 	  '<td>'.&mt('No data.').'</td>'.
 4249: 	  &end_data_table_row().&end_data_table();
 4250:   }
 4251: }
 4252: 
 4253: sub format_previous_attempt_value {
 4254:     my ($key,$value) = @_;
 4255:     if (($key =~ /timestamp/) || ($key=~/duedate/)) {
 4256:         $value = &Apache::lonlocal::locallocaltime($value);
 4257:     } elsif (ref($value) eq 'ARRAY') {
 4258:         $value = &HTML::Entities::encode('('.join(', ', @{ $value }).')','"<>&');
 4259:     } elsif ($key =~ /answerstring$/) {
 4260:         my %answers = &Apache::lonnet::str2hash($value);
 4261:         my @answer = %answers;
 4262:         %answers = map {&HTML::Entities::encode($_, '"<>&')} @answer;
 4263:         my @anskeys = sort(keys(%answers));
 4264:         if (@anskeys == 1) {
 4265:             my $answer = $answers{$anskeys[0]};
 4266:             if ($answer =~ m{\0}) {
 4267:                 $answer =~ s{\0}{,}g;
 4268:             }
 4269:             my $tag_internal_answer_name = 'INTERNAL';
 4270:             if ($anskeys[0] eq $tag_internal_answer_name) {
 4271:                 $value = $answer; 
 4272:             } else {
 4273:                 $value = $anskeys[0].'='.$answer;
 4274:             }
 4275:         } else {
 4276:             foreach my $ans (@anskeys) {
 4277:                 my $answer = $answers{$ans};
 4278:                 if ($answer =~ m{\0}) {
 4279:                     $answer =~ s{\0}{,}g;
 4280:                 }
 4281:                 $value .=  $ans.'='.$answer.'<br />';;
 4282:             } 
 4283:         }
 4284:     } else {
 4285:         $value = &HTML::Entities::encode(&unescape($value), '"<>&');
 4286:     }
 4287:     return $value;
 4288: }
 4289: 
 4290: 
 4291: sub relative_to_absolute {
 4292:     my ($url,$output)=@_;
 4293:     my $parser=HTML::TokeParser->new(\$output);
 4294:     my $token;
 4295:     my $thisdir=$url;
 4296:     my @rlinks=();
 4297:     while ($token=$parser->get_token) {
 4298: 	if ($token->[0] eq 'S') {
 4299: 	    if ($token->[1] eq 'a') {
 4300: 		if ($token->[2]->{'href'}) {
 4301: 		    $rlinks[$#rlinks+1]=$token->[2]->{'href'};
 4302: 		}
 4303: 	    } elsif ($token->[1] eq 'img' || $token->[1] eq 'embed' ) {
 4304: 		$rlinks[$#rlinks+1]=$token->[2]->{'src'};
 4305: 	    } elsif ($token->[1] eq 'base') {
 4306: 		$thisdir=$token->[2]->{'href'};
 4307: 	    }
 4308: 	}
 4309:     }
 4310:     $thisdir=~s-/[^/]*$--;
 4311:     foreach my $link (@rlinks) {
 4312: 	unless (($link=~/^https?\:\/\//i) ||
 4313: 		($link=~/^\//) ||
 4314: 		($link=~/^javascript:/i) ||
 4315: 		($link=~/^mailto:/i) ||
 4316: 		($link=~/^\#/)) {
 4317: 	    my $newlocation=&Apache::lonnet::hreflocation($thisdir,$link);
 4318: 	    $output=~s/(\"|\'|\=\s*)\Q$link\E(\"|\'|\s|\>)/$1$newlocation$2/;
 4319: 	}
 4320:     }
 4321: # -------------------------------------------------- Deal with Applet codebases
 4322:     $output=~s/(\<applet[^\>]+)(codebase\=[^\S\>]+)*([^\>]*)\>/$1.($2?$2:' codebase="'.$thisdir.'"').$3.'>'/gei;
 4323:     return $output;
 4324: }
 4325: 
 4326: =pod
 4327: 
 4328: =item * &get_student_view()
 4329: 
 4330: show a snapshot of what student was looking at
 4331: 
 4332: =cut
 4333: 
 4334: sub get_student_view {
 4335:   my ($symb,$username,$domain,$courseid,$target,$moreenv) = @_;
 4336:   my ($map,$id,$feedurl) = &Apache::lonnet::decode_symb($symb);
 4337:   my (%form);
 4338:   my @elements=('symb','courseid','domain','username');
 4339:   foreach my $element (@elements) {
 4340:       $form{'grade_'.$element}=eval '$'.$element #'
 4341:   }
 4342:   if (defined($moreenv)) {
 4343:       %form=(%form,%{$moreenv});
 4344:   }
 4345:   if (defined($target)) { $form{'grade_target'} = $target; }
 4346:   $feedurl=&Apache::lonnet::clutter($feedurl);
 4347:   my ($userview,$response)=&Apache::lonnet::ssi_body($feedurl,%form);
 4348:   $userview=~s/\<body[^\>]*\>//gi;
 4349:   $userview=~s/\<\/body\>//gi;
 4350:   $userview=~s/\<html\>//gi;
 4351:   $userview=~s/\<\/html\>//gi;
 4352:   $userview=~s/\<head\>//gi;
 4353:   $userview=~s/\<\/head\>//gi;
 4354:   $userview=~s/action\s*\=/would_be_action\=/gi;
 4355:   $userview=&relative_to_absolute($feedurl,$userview);
 4356:   if (wantarray) {
 4357:      return ($userview,$response);
 4358:   } else {
 4359:      return $userview;
 4360:   }
 4361: }
 4362: 
 4363: sub get_student_view_with_retries {
 4364:   my ($symb,$retries,$username,$domain,$courseid,$target,$moreenv) = @_;
 4365: 
 4366:     my $ok = 0;                 # True if we got a good response.
 4367:     my $content;
 4368:     my $response;
 4369: 
 4370:     # Try to get the student_view done. within the retries count:
 4371:     
 4372:     do {
 4373:          ($content, $response) = &get_student_view($symb,$username,$domain,$courseid,$target,$moreenv);
 4374:          $ok      = $response->is_success;
 4375:          if (!$ok) {
 4376:             &Apache::lonnet::logthis("Failed get_student_view_with_retries on $symb: ".$response->is_success.', '.$response->code.', '.$response->message);
 4377:          }
 4378:          $retries--;
 4379:     } while (!$ok && ($retries > 0));
 4380:     
 4381:     if (!$ok) {
 4382:        $content = '';          # On error return an empty content.
 4383:     }
 4384:     if (wantarray) {
 4385:        return ($content, $response);
 4386:     } else {
 4387:        return $content;
 4388:     }
 4389: }
 4390: 
 4391: =pod
 4392: 
 4393: =item * &get_student_answers() 
 4394: 
 4395: show a snapshot of how student was answering problem
 4396: 
 4397: =cut
 4398: 
 4399: sub get_student_answers {
 4400:   my ($symb,$username,$domain,$courseid,%form) = @_;
 4401:   my ($map,$id,$feedurl) = &Apache::lonnet::decode_symb($symb);
 4402:   my (%moreenv);
 4403:   my @elements=('symb','courseid','domain','username');
 4404:   foreach my $element (@elements) {
 4405:     $moreenv{'grade_'.$element}=eval '$'.$element #'
 4406:   }
 4407:   $moreenv{'grade_target'}='answer';
 4408:   %moreenv=(%form,%moreenv);
 4409:   $feedurl = &Apache::lonnet::clutter($feedurl);
 4410:   my $userview=&Apache::lonnet::ssi($feedurl,%moreenv);
 4411:   return $userview;
 4412: }
 4413: 
 4414: =pod
 4415: 
 4416: =item * &submlink()
 4417: 
 4418: Inputs: $text $uname $udom $symb $target
 4419: 
 4420: Returns: A link to grades.pm such as to see the SUBM view of a student
 4421: 
 4422: =cut
 4423: 
 4424: ###############################################
 4425: sub submlink {
 4426:     my ($text,$uname,$udom,$symb,$target)=@_;
 4427:     if (!($uname && $udom)) {
 4428: 	(my $cursymb, my $courseid,$udom,$uname)=
 4429: 	    &Apache::lonnet::whichuser($symb);
 4430: 	if (!$symb) { $symb=$cursymb; }
 4431:     }
 4432:     if (!$symb) { $symb=&Apache::lonnet::symbread(); }
 4433:     $symb=&escape($symb);
 4434:     if ($target) { $target=" target=\"$target\""; }
 4435:     return
 4436:         '<a href="/adm/grades?command=submission'.
 4437:         '&amp;symb='.$symb.
 4438:         '&amp;student='.$uname.
 4439:         '&amp;userdom='.$udom.'"'.
 4440:         $target.'>'.$text.'</a>';
 4441: }
 4442: ##############################################
 4443: 
 4444: =pod
 4445: 
 4446: =item * &pgrdlink()
 4447: 
 4448: Inputs: $text $uname $udom $symb $target
 4449: 
 4450: Returns: A link to grades.pm such as to see the PGRD view of a student
 4451: 
 4452: =cut
 4453: 
 4454: ###############################################
 4455: sub pgrdlink {
 4456:     my $link=&submlink(@_);
 4457:     $link=~s/(&command=submission)/$1&showgrading=yes/;
 4458:     return $link;
 4459: }
 4460: ##############################################
 4461: 
 4462: =pod
 4463: 
 4464: =item * &pprmlink()
 4465: 
 4466: Inputs: $text $uname $udom $symb $target
 4467: 
 4468: Returns: A link to parmset.pm such as to see the PPRM view of a
 4469: student and a specific resource
 4470: 
 4471: =cut
 4472: 
 4473: ###############################################
 4474: sub pprmlink {
 4475:     my ($text,$uname,$udom,$symb,$target)=@_;
 4476:     if (!($uname && $udom)) {
 4477: 	(my $cursymb, my $courseid,$udom,$uname)=
 4478: 	    &Apache::lonnet::whichuser($symb);
 4479: 	if (!$symb) { $symb=$cursymb; }
 4480:     }
 4481:     if (!$symb) { $symb=&Apache::lonnet::symbread(); }
 4482:     $symb=&escape($symb);
 4483:     if ($target) { $target="target=\"$target\""; }
 4484:     return '<a href="/adm/parmset?command=set&amp;'.
 4485: 	'symb='.$symb.'&amp;uname='.$uname.
 4486: 	'&amp;udom='.$udom.'" '.$target.'>'.$text.'</a>';
 4487: }
 4488: ##############################################
 4489: 
 4490: =pod
 4491: 
 4492: =back
 4493: 
 4494: =cut
 4495: 
 4496: ###############################################
 4497: 
 4498: 
 4499: sub timehash {
 4500:     my ($thistime) = @_;
 4501:     my $timezone = &Apache::lonlocal::gettimezone();
 4502:     my $dt = DateTime->from_epoch(epoch => $thistime)
 4503:                      ->set_time_zone($timezone);
 4504:     my $wday = $dt->day_of_week();
 4505:     if ($wday == 7) { $wday = 0; }
 4506:     return ( 'second' => $dt->second(),
 4507:              'minute' => $dt->minute(),
 4508:              'hour'   => $dt->hour(),
 4509:              'day'     => $dt->day_of_month(),
 4510:              'month'   => $dt->month(),
 4511:              'year'    => $dt->year(),
 4512:              'weekday' => $wday,
 4513:              'dayyear' => $dt->day_of_year(),
 4514:              'dlsav'   => $dt->is_dst() );
 4515: }
 4516: 
 4517: sub utc_string {
 4518:     my ($date)=@_;
 4519:     return strftime("%Y%m%dT%H%M%SZ",gmtime($date));
 4520: }
 4521: 
 4522: sub maketime {
 4523:     my %th=@_;
 4524:     my ($epoch_time,$timezone,$dt);
 4525:     $timezone = &Apache::lonlocal::gettimezone();
 4526:     eval {
 4527:         $dt = DateTime->new( year   => $th{'year'},
 4528:                              month  => $th{'month'},
 4529:                              day    => $th{'day'},
 4530:                              hour   => $th{'hour'},
 4531:                              minute => $th{'minute'},
 4532:                              second => $th{'second'},
 4533:                              time_zone => $timezone,
 4534:                          );
 4535:     };
 4536:     if (!$@) {
 4537:         $epoch_time = $dt->epoch;
 4538:         if ($epoch_time) {
 4539:             return $epoch_time;
 4540:         }
 4541:     }
 4542:     return POSIX::mktime(
 4543:         ($th{'seconds'},$th{'minutes'},$th{'hours'},
 4544:          $th{'day'},$th{'month'}-1,$th{'year'}-1900,0,0,-1));
 4545: }
 4546: 
 4547: #########################################
 4548: 
 4549: sub findallcourses {
 4550:     my ($roles,$uname,$udom) = @_;
 4551:     my %roles;
 4552:     if (ref($roles)) { %roles = map { $_ => 1 } @{$roles}; }
 4553:     my %courses;
 4554:     my $now=time;
 4555:     if (!defined($uname)) {
 4556:         $uname = $env{'user.name'};
 4557:     }
 4558:     if (!defined($udom)) {
 4559:         $udom = $env{'user.domain'};
 4560:     }
 4561:     if (($uname ne $env{'user.name'}) || ($udom ne $env{'user.domain'})) {
 4562:         my %roleshash = &Apache::lonnet::dump('roles',$udom,$uname);
 4563:         if (!%roles) {
 4564:             %roles = (
 4565:                        cc => 1,
 4566:                        co => 1,
 4567:                        in => 1,
 4568:                        ep => 1,
 4569:                        ta => 1,
 4570:                        cr => 1,
 4571:                        st => 1,
 4572:              );
 4573:         }
 4574:         foreach my $entry (keys(%roleshash)) {
 4575:             my ($trole,$tend,$tstart) = split(/_/,$roleshash{$entry});
 4576:             if ($trole =~ /^cr/) { 
 4577:                 next if (!exists($roles{$trole}) && !exists($roles{'cr'}));
 4578:             } else {
 4579:                 next if (!exists($roles{$trole}));
 4580:             }
 4581:             if ($tend) {
 4582:                 next if ($tend < $now);
 4583:             }
 4584:             if ($tstart) {
 4585:                 next if ($tstart > $now);
 4586:             }
 4587:             my ($cdom,$cnum,$sec,$cnumpart,$secpart,$role);
 4588:             (undef,$cdom,$cnumpart,$secpart) = split(/\//,$entry);
 4589:             my $value = $trole.'/'.$cdom.'/';
 4590:             if ($secpart eq '') {
 4591:                 ($cnum,$role) = split(/_/,$cnumpart); 
 4592:                 $sec = 'none';
 4593:                 $value .= $cnum.'/';
 4594:             } else {
 4595:                 $cnum = $cnumpart;
 4596:                 ($sec,$role) = split(/_/,$secpart);
 4597:                 $value .= $cnum.'/'.$sec;
 4598:             }
 4599:             if (ref($courses{$cdom.'_'.$cnum}{$sec}) eq 'ARRAY') {
 4600:                 unless (grep(/^\Q$value\E$/,@{$courses{$cdom.'_'.$cnum}{$sec}})) {
 4601:                     push(@{$courses{$cdom.'_'.$cnum}{$sec}},$value);
 4602:                 }
 4603:             } else {
 4604:                 @{$courses{$cdom.'_'.$cnum}{$sec}} = ($value);
 4605:             }
 4606:         }
 4607:     } else {
 4608:         foreach my $key (keys(%env)) {
 4609: 	    if ( $key=~m{^user\.role\.(\w+)\./($match_domain)/($match_courseid)/?(\w*)$} ||
 4610:                  $key=~m{^user\.role\.(cr/$match_domain/$match_username/\w+)\./($match_domain)/($match_courseid)/?(\w*)$}) {
 4611: 	        my ($role,$cdom,$cnum,$sec) = ($1,$2,$3,$4);
 4612: 	        next if ($role eq 'ca' || $role eq 'aa');
 4613: 	        next if (%roles && !exists($roles{$role}));
 4614: 	        my ($starttime,$endtime)=split(/\./,$env{$key});
 4615:                 my $active=1;
 4616:                 if ($starttime) {
 4617: 		    if ($now<$starttime) { $active=0; }
 4618:                 }
 4619:                 if ($endtime) {
 4620:                     if ($now>$endtime) { $active=0; }
 4621:                 }
 4622:                 if ($active) {
 4623:                     my $value = $role.'/'.$cdom.'/'.$cnum.'/';
 4624:                     if ($sec eq '') {
 4625:                         $sec = 'none';
 4626:                     } else {
 4627:                         $value .= $sec;
 4628:                     }
 4629:                     if (ref($courses{$cdom.'_'.$cnum}{$sec}) eq 'ARRAY') {
 4630:                         unless (grep(/^\Q$value\E$/,@{$courses{$cdom.'_'.$cnum}{$sec}})) {
 4631:                             push(@{$courses{$cdom.'_'.$cnum}{$sec}},$value);
 4632:                         }
 4633:                     } else {
 4634:                         @{$courses{$cdom.'_'.$cnum}{$sec}} = ($value);
 4635:                     }
 4636:                 }
 4637:             }
 4638:         }
 4639:     }
 4640:     return %courses;
 4641: }
 4642: 
 4643: ###############################################
 4644: 
 4645: sub blockcheck {
 4646:     my ($setters,$activity,$uname,$udom,$url,$is_course) = @_;
 4647: 
 4648:     if (defined($udom) && defined($uname)) {
 4649:         # If uname and udom are for a course, check for blocks in the course.
 4650:         if (($is_course) || (&Apache::lonnet::is_course($udom,$uname))) {
 4651:             my ($startblock,$endblock,$triggerblock) =
 4652:                 &get_blocks($setters,$activity,$udom,$uname,$url);
 4653:             return ($startblock,$endblock,$triggerblock);
 4654:         }
 4655:     } else {
 4656:         $udom = $env{'user.domain'};
 4657:         $uname = $env{'user.name'};
 4658:     }
 4659: 
 4660:     my $startblock = 0;
 4661:     my $endblock = 0;
 4662:     my $triggerblock = '';
 4663:     my %live_courses = &findallcourses(undef,$uname,$udom);
 4664: 
 4665:     # If uname is for a user, and activity is course-specific, i.e.,
 4666:     # boards, chat or groups, check for blocking in current course only.
 4667: 
 4668:     if (($activity eq 'boards' || $activity eq 'chat' ||
 4669:          $activity eq 'groups' || $activity eq 'printout') &&
 4670:         ($env{'request.course.id'})) {
 4671:         foreach my $key (keys(%live_courses)) {
 4672:             if ($key ne $env{'request.course.id'}) {
 4673:                 delete($live_courses{$key});
 4674:             }
 4675:         }
 4676:     }
 4677: 
 4678:     my $otheruser = 0;
 4679:     my %own_courses;
 4680:     if ((($uname ne $env{'user.name'})) || ($udom ne $env{'user.domain'})) {
 4681:         # Resource belongs to user other than current user.
 4682:         $otheruser = 1;
 4683:         # Gather courses for current user
 4684:         %own_courses = 
 4685:             &findallcourses(undef,$env{'user.name'},$env{'user.domain'});
 4686:     }
 4687: 
 4688:     # Gather active course roles - course coordinator, instructor, 
 4689:     # exam proctor, ta, student, or custom role.
 4690: 
 4691:     foreach my $course (keys(%live_courses)) {
 4692:         my ($cdom,$cnum);
 4693:         if ((defined($env{'course.'.$course.'.domain'})) && (defined($env{'course.'.$course.'.num'}))) {
 4694:             $cdom = $env{'course.'.$course.'.domain'};
 4695:             $cnum = $env{'course.'.$course.'.num'};
 4696:         } else {
 4697:             ($cdom,$cnum) = split(/_/,$course); 
 4698:         }
 4699:         my $no_ownblock = 0;
 4700:         my $no_userblock = 0;
 4701:         if ($otheruser && $activity ne 'com') {
 4702:             # Check if current user has 'evb' priv for this
 4703:             if (defined($own_courses{$course})) {
 4704:                 foreach my $sec (keys(%{$own_courses{$course}})) {
 4705:                     my $checkrole = 'cm./'.$cdom.'/'.$cnum;
 4706:                     if ($sec ne 'none') {
 4707:                         $checkrole .= '/'.$sec;
 4708:                     }
 4709:                     if (&Apache::lonnet::allowed('evb',undef,undef,$checkrole)) {
 4710:                         $no_ownblock = 1;
 4711:                         last;
 4712:                     }
 4713:                 }
 4714:             }
 4715:             # if they have 'evb' priv and are currently not playing student
 4716:             next if (($no_ownblock) &&
 4717:                  ($env{'request.role'} !~ m{^st\./$cdom/$cnum}));
 4718:         }
 4719:         foreach my $sec (keys(%{$live_courses{$course}})) {
 4720:             my $checkrole = 'cm./'.$cdom.'/'.$cnum;
 4721:             if ($sec ne 'none') {
 4722:                 $checkrole .= '/'.$sec;
 4723:             }
 4724:             if ($otheruser) {
 4725:                 # Resource belongs to user other than current user.
 4726:                 # Assemble privs for that user, and check for 'evb' priv.
 4727:                 my (%allroles,%userroles);
 4728:                 if (ref($live_courses{$course}{$sec}) eq 'ARRAY') {
 4729:                     foreach my $entry (@{$live_courses{$course}{$sec}}) { 
 4730:                         my ($trole,$tdom,$tnum,$tsec);
 4731:                         if ($entry =~ /^cr/) {
 4732:                             ($trole,$tdom,$tnum,$tsec) = 
 4733:                                 ($entry =~ m|^(cr/$match_domain/$match_username/\w+)\./($match_domain)/($match_username)/?(\w*)$|);
 4734:                         } else {
 4735:                            ($trole,$tdom,$tnum,$tsec) = split(/\//,$entry);
 4736:                         }
 4737:                         my ($spec,$area,$trest);
 4738:                         $area = '/'.$tdom.'/'.$tnum;
 4739:                         $trest = $tnum;
 4740:                         if ($tsec ne '') {
 4741:                             $area .= '/'.$tsec;
 4742:                             $trest .= '/'.$tsec;
 4743:                         }
 4744:                         $spec = $trole.'.'.$area;
 4745:                         if ($trole =~ /^cr/) {
 4746:                             &Apache::lonnet::custom_roleprivs(\%allroles,$trole,
 4747:                                                               $tdom,$spec,$trest,$area);
 4748:                         } else {
 4749:                             &Apache::lonnet::standard_roleprivs(\%allroles,$trole,
 4750:                                                                 $tdom,$spec,$trest,$area);
 4751:                         }
 4752:                     }
 4753:                     my ($author,$adv) = &Apache::lonnet::set_userprivs(\%userroles,\%allroles);
 4754:                     if ($userroles{'user.priv.'.$checkrole} =~ /evb\&([^\:]*)/) {
 4755:                         if ($1) {
 4756:                             $no_userblock = 1;
 4757:                             last;
 4758:                         }
 4759:                     }
 4760:                 }
 4761:             } else {
 4762:                 # Resource belongs to current user
 4763:                 # Check for 'evb' priv via lonnet::allowed().
 4764:                 if (&Apache::lonnet::allowed('evb',undef,undef,$checkrole)) {
 4765:                     $no_ownblock = 1;
 4766:                     last;
 4767:                 }
 4768:             }
 4769:         }
 4770:         # if they have the evb priv and are currently not playing student
 4771:         next if (($no_ownblock) &&
 4772:                  ($env{'request.role'} !~ m{^st\./\Q$cdom\E/\Q$cnum\E}));
 4773:         next if ($no_userblock);
 4774: 
 4775:         # Retrieve blocking times and identity of locker for course
 4776:         # of specified user, unless user has 'evb' privilege.
 4777:         
 4778:         my ($start,$end,$trigger) = 
 4779:             &get_blocks($setters,$activity,$cdom,$cnum,$url);
 4780:         if (($start != 0) && 
 4781:             (($startblock == 0) || ($startblock > $start))) {
 4782:             $startblock = $start;
 4783:             if ($trigger ne '') {
 4784:                 $triggerblock = $trigger;
 4785:             }
 4786:         }
 4787:         if (($end != 0)  &&
 4788:             (($endblock == 0) || ($endblock < $end))) {
 4789:             $endblock = $end;
 4790:             if ($trigger ne '') {
 4791:                 $triggerblock = $trigger;
 4792:             }
 4793:         }
 4794:     }
 4795:     return ($startblock,$endblock,$triggerblock);
 4796: }
 4797: 
 4798: sub get_blocks {
 4799:     my ($setters,$activity,$cdom,$cnum,$url) = @_;
 4800:     my $startblock = 0;
 4801:     my $endblock = 0;
 4802:     my $triggerblock = '';
 4803:     my $course = $cdom.'_'.$cnum;
 4804:     $setters->{$course} = {};
 4805:     $setters->{$course}{'staff'} = [];
 4806:     $setters->{$course}{'times'} = [];
 4807:     $setters->{$course}{'triggers'} = [];
 4808:     my (@blockers,%triggered);
 4809:     my $now = time;
 4810:     my %commblocks = &Apache::lonnet::get_comm_blocks($cdom,$cnum);
 4811:     if ($activity eq 'docs') {
 4812:         @blockers = &Apache::lonnet::has_comm_blocking('bre',undef,$url,\%commblocks);
 4813:         foreach my $block (@blockers) {
 4814:             if ($block =~ /^firstaccess____(.+)$/) {
 4815:                 my $item = $1;
 4816:                 my $type = 'map';
 4817:                 my $timersymb = $item;
 4818:                 if ($item eq 'course') {
 4819:                     $type = 'course';
 4820:                 } elsif ($item =~ /___\d+___/) {
 4821:                     $type = 'resource';
 4822:                 } else {
 4823:                     $timersymb = &Apache::lonnet::symbread($item);
 4824:                 }
 4825:                 my $start = $env{'course.'.$cdom.'_'.$cnum.'.firstaccess.'.$timersymb};
 4826:                 my $end = $start + $env{'course.'.$cdom.'_'.$cnum.'.timerinterval.'.$timersymb};
 4827:                 $triggered{$block} = {
 4828:                                        start => $start,
 4829:                                        end   => $end,
 4830:                                        type  => $type,
 4831:                                      };
 4832:             }
 4833:         }
 4834:     } else {
 4835:         foreach my $block (keys(%commblocks)) {
 4836:             if ($block =~ m/^(\d+)____(\d+)$/) { 
 4837:                 my ($start,$end) = ($1,$2);
 4838:                 if ($start <= time && $end >= time) {
 4839:                     if (ref($commblocks{$block}) eq 'HASH') {
 4840:                         if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
 4841:                             if ($commblocks{$block}{'blocks'}{$activity} eq 'on') {
 4842:                                 unless(grep(/^\Q$block\E$/,@blockers)) {
 4843:                                     push(@blockers,$block);
 4844:                                 }
 4845:                             }
 4846:                         }
 4847:                     }
 4848:                 }
 4849:             } elsif ($block =~ /^firstaccess____(.+)$/) {
 4850:                 my $item = $1;
 4851:                 my $timersymb = $item; 
 4852:                 my $type = 'map';
 4853:                 if ($item eq 'course') {
 4854:                     $type = 'course';
 4855:                 } elsif ($item =~ /___\d+___/) {
 4856:                     $type = 'resource';
 4857:                 } else {
 4858:                     $timersymb = &Apache::lonnet::symbread($item);
 4859:                 }
 4860:                 my $start = $env{'course.'.$cdom.'_'.$cnum.'.firstaccess.'.$timersymb};
 4861:                 my $end = $start + $env{'course.'.$cdom.'_'.$cnum.'.timerinterval.'.$timersymb}; 
 4862:                 if ($start && $end) {
 4863:                     if (($start <= time) && ($end >= time)) {
 4864:                         unless (grep(/^\Q$block\E$/,@blockers)) {
 4865:                             push(@blockers,$block);
 4866:                             $triggered{$block} = {
 4867:                                                    start => $start,
 4868:                                                    end   => $end,
 4869:                                                    type  => $type,
 4870:                                                  };
 4871:                         }
 4872:                     }
 4873:                 }
 4874:             }
 4875:         }
 4876:     }
 4877:     foreach my $blocker (@blockers) {
 4878:         my ($staff_name,$staff_dom,$title,$blocks) =
 4879:             &parse_block_record($commblocks{$blocker});
 4880:         push(@{$$setters{$course}{'staff'}},[$staff_name,$staff_dom]);
 4881:         my ($start,$end,$triggertype);
 4882:         if ($blocker =~ m/^(\d+)____(\d+)$/) {
 4883:             ($start,$end) = ($1,$2);
 4884:         } elsif (ref($triggered{$blocker}) eq 'HASH') {
 4885:             $start = $triggered{$blocker}{'start'};
 4886:             $end = $triggered{$blocker}{'end'};
 4887:             $triggertype = $triggered{$blocker}{'type'};
 4888:         }
 4889:         if ($start) {
 4890:             push(@{$$setters{$course}{'times'}}, [$start,$end]);
 4891:             if ($triggertype) {
 4892:                 push(@{$$setters{$course}{'triggers'}},$triggertype);
 4893:             } else {
 4894:                 push(@{$$setters{$course}{'triggers'}},0);
 4895:             }
 4896:             if ( ($startblock == 0) || ($startblock > $start) ) {
 4897:                 $startblock = $start;
 4898:                 if ($triggertype) {
 4899:                     $triggerblock = $blocker;
 4900:                 }
 4901:             }
 4902:             if ( ($endblock == 0) || ($endblock < $end) ) {
 4903:                $endblock = $end;
 4904:                if ($triggertype) {
 4905:                    $triggerblock = $blocker;
 4906:                }
 4907:             }
 4908:         }
 4909:     }
 4910:     return ($startblock,$endblock,$triggerblock);
 4911: }
 4912: 
 4913: sub parse_block_record {
 4914:     my ($record) = @_;
 4915:     my ($setuname,$setudom,$title,$blocks);
 4916:     if (ref($record) eq 'HASH') {
 4917:         ($setuname,$setudom) = split(/:/,$record->{'setter'});
 4918:         $title = &unescape($record->{'event'});
 4919:         $blocks = $record->{'blocks'};
 4920:     } else {
 4921:         my @data = split(/:/,$record,3);
 4922:         if (scalar(@data) eq 2) {
 4923:             $title = $data[1];
 4924:             ($setuname,$setudom) = split(/@/,$data[0]);
 4925:         } else {
 4926:             ($setuname,$setudom,$title) = @data;
 4927:         }
 4928:         $blocks = { 'com' => 'on' };
 4929:     }
 4930:     return ($setuname,$setudom,$title,$blocks);
 4931: }
 4932: 
 4933: sub blocking_status {
 4934:     my ($activity,$uname,$udom,$url,$is_course) = @_;
 4935:     my %setters;
 4936: 
 4937: # check for active blocking
 4938:     my ($startblock,$endblock,$triggerblock) = 
 4939:         &blockcheck(\%setters,$activity,$uname,$udom,$url,$is_course);
 4940:     my $blocked = 0;
 4941:     if ($startblock && $endblock) {
 4942:         $blocked = 1;
 4943:     }
 4944: 
 4945: # caller just wants to know whether a block is active
 4946:     if (!wantarray) { return $blocked; }
 4947: 
 4948: # build a link to a popup window containing the details
 4949:     my $querystring  = "?activity=$activity";
 4950: # $uname and $udom decide whose portfolio the user is trying to look at
 4951:     if ($activity eq 'port') {
 4952:         $querystring .= "&amp;udom=$udom"      if $udom;
 4953:         $querystring .= "&amp;uname=$uname"    if $uname;
 4954:     } elsif ($activity eq 'docs') {
 4955:         $querystring .= '&amp;url='.&HTML::Entities::encode($url,'&"');
 4956:     }
 4957: 
 4958:     my $output .= <<'END_MYBLOCK';
 4959: function openWindow(url, wdwName, w, h, toolbar,scrollbar) {
 4960:     var options = "width=" + w + ",height=" + h + ",";
 4961:     options += "resizable=yes,scrollbars="+scrollbar+",status=no,";
 4962:     options += "menubar=no,toolbar="+toolbar+",location=no,directories=no";
 4963:     var newWin = window.open(url, wdwName, options);
 4964:     newWin.focus();
 4965: }
 4966: END_MYBLOCK
 4967: 
 4968:     $output = Apache::lonhtmlcommon::scripttag($output);
 4969:   
 4970:     my $popupUrl = "/adm/blockingstatus/$querystring";
 4971:     my $text = &mt('Communication Blocked');
 4972:     if ($activity eq 'docs') {
 4973:         $text = &mt('Content Access Blocked');
 4974:     } elsif ($activity eq 'printout') {
 4975:         $text = &mt('Printing Blocked');
 4976:     }
 4977:     $output .= <<"END_BLOCK";
 4978: <div class='LC_comblock'>
 4979:   <a onclick='openWindow("$popupUrl","Blocking Table",600,300,"no","no");return false;' href='/adm/blockingstatus/$querystring'
 4980:   title='$text'>
 4981:   <img class='LC_noBorder LC_middle' title='$text' src='/res/adm/pages/comblock.png' alt='$text'/></a>
 4982:   <a onclick='openWindow("$popupUrl","Blocking Table",600,300,"no","no");return false;' href='/adm/blockingstatus/$querystring' 
 4983:   title='$text'>$text</a>
 4984: </div>
 4985: 
 4986: END_BLOCK
 4987: 
 4988:     return ($blocked, $output);
 4989: }
 4990: 
 4991: ###############################################
 4992: 
 4993: sub check_ip_acc {
 4994:     my ($acc,$clientip)=@_;
 4995:     &Apache::lonxml::debug("acc is $acc");
 4996:     if (!defined($acc) || $acc =~ /^\s*$/ || $acc =~/^\s*no\s*$/i) {
 4997:         return 1;
 4998:     }
 4999:     my $allowed=0;
 5000:     my $ip=$env{'request.host'} || $ENV{'REMOTE_ADDR'} || $clientip;
 5001: 
 5002:     my $name;
 5003:     foreach my $pattern (split(',',$acc)) {
 5004:         $pattern =~ s/^\s*//;
 5005:         $pattern =~ s/\s*$//;
 5006:         if ($pattern =~ /\*$/) {
 5007:             #35.8.*
 5008:             $pattern=~s/\*//;
 5009:             if ($ip =~ /^\Q$pattern\E/) { $allowed=1; }
 5010:         } elsif ($pattern =~ /(\d+\.\d+\.\d+)\.\[(\d+)-(\d+)\]$/) {
 5011:             #35.8.3.[34-56]
 5012:             my $low=$2;
 5013:             my $high=$3;
 5014:             $pattern=$1;
 5015:             if ($ip =~ /^\Q$pattern\E/) {
 5016:                 my $last=(split(/\./,$ip))[3];
 5017:                 if ($last <=$high && $last >=$low) { $allowed=1; }
 5018:             }
 5019:         } elsif ($pattern =~ /^\*/) {
 5020:             #*.msu.edu
 5021:             $pattern=~s/\*//;
 5022:             if (!defined($name)) {
 5023:                 use Socket;
 5024:                 my $netaddr=inet_aton($ip);
 5025:                 ($name)=gethostbyaddr($netaddr,AF_INET);
 5026:             }
 5027:             if ($name =~ /\Q$pattern\E$/i) { $allowed=1; }
 5028:         } elsif ($pattern =~ /\d+\.\d+\.\d+\.\d+/) {
 5029:             #127.0.0.1
 5030:             if ($ip =~ /^\Q$pattern\E/) { $allowed=1; }
 5031:         } else {
 5032:             #some.name.com
 5033:             if (!defined($name)) {
 5034:                 use Socket;
 5035:                 my $netaddr=inet_aton($ip);
 5036:                 ($name)=gethostbyaddr($netaddr,AF_INET);
 5037:             }
 5038:             if ($name =~ /\Q$pattern\E$/i) { $allowed=1; }
 5039:         }
 5040:         if ($allowed) { last; }
 5041:     }
 5042:     return $allowed;
 5043: }
 5044: 
 5045: ###############################################
 5046: 
 5047: =pod
 5048: 
 5049: =head1 Domain Template Functions
 5050: 
 5051: =over 4
 5052: 
 5053: =item * &determinedomain()
 5054: 
 5055: Inputs: $domain (usually will be undef)
 5056: 
 5057: Returns: Determines which domain should be used for designs
 5058: 
 5059: =cut
 5060: 
 5061: ###############################################
 5062: sub determinedomain {
 5063:     my $domain=shift;
 5064:     if (! $domain) {
 5065:         # Determine domain if we have not been given one
 5066:         $domain = &Apache::lonnet::default_login_domain();
 5067:         if ($env{'user.domain'}) { $domain=$env{'user.domain'}; }
 5068:         if ($env{'request.role.domain'}) { 
 5069:             $domain=$env{'request.role.domain'}; 
 5070:         }
 5071:     }
 5072:     return $domain;
 5073: }
 5074: ###############################################
 5075: 
 5076: sub devalidate_domconfig_cache {
 5077:     my ($udom)=@_;
 5078:     &Apache::lonnet::devalidate_cache_new('domainconfig',$udom);
 5079: }
 5080: 
 5081: # ---------------------- Get domain configuration for a domain
 5082: sub get_domainconf {
 5083:     my ($udom) = @_;
 5084:     my $cachetime=1800;
 5085:     my ($result,$cached)=&Apache::lonnet::is_cached_new('domainconfig',$udom);
 5086:     if (defined($cached)) { return %{$result}; }
 5087: 
 5088:     my %domconfig = &Apache::lonnet::get_dom('configuration',
 5089: 					     ['login','rolecolors','autoenroll'],$udom);
 5090:     my (%designhash,%legacy);
 5091:     if (keys(%domconfig) > 0) {
 5092:         if (ref($domconfig{'login'}) eq 'HASH') {
 5093:             if (keys(%{$domconfig{'login'}})) {
 5094:                 foreach my $key (keys(%{$domconfig{'login'}})) {
 5095:                     if (ref($domconfig{'login'}{$key}) eq 'HASH') {
 5096:                         if (($key eq 'loginvia') || ($key eq 'headtag')) {
 5097:                             if (ref($domconfig{'login'}{$key}) eq 'HASH') {
 5098:                                 foreach my $hostname (keys(%{$domconfig{'login'}{$key}})) {
 5099:                                     if (ref($domconfig{'login'}{$key}{$hostname}) eq 'HASH') {
 5100:                                         if ($key eq 'loginvia') {
 5101:                                             if ($domconfig{'login'}{'loginvia'}{$hostname}{'server'}) {
 5102:                                                 my $server = $domconfig{'login'}{'loginvia'}{$hostname}{'server'};
 5103:                                                 $designhash{$udom.'.login.loginvia'} = $server;
 5104:                                                 if ($domconfig{'login'}{'loginvia'}{$hostname}{'serverpath'} eq 'custom') {
 5105: 
 5106:                                                     $designhash{$udom.'.login.loginvia_'.$hostname} = $server.':'.$domconfig{'login'}{'loginvia'}{$hostname}{'custompath'};
 5107:                                                 } else {
 5108:                                                     $designhash{$udom.'.login.loginvia_'.$hostname} = $server.':'.$domconfig{'login'}{'loginvia'}{$hostname}{'serverpath'};
 5109:                                                 }
 5110:                                             }
 5111:                                         } elsif ($key eq 'headtag') {
 5112:                                             if ($domconfig{'login'}{'headtag'}{$hostname}{'url'}) {
 5113:                                                 $designhash{$udom.'.login.headtag_'.$hostname} = $domconfig{'login'}{'headtag'}{$hostname}{'url'};
 5114:                                             }
 5115:                                         }
 5116:                                         if ($domconfig{'login'}{$key}{$hostname}{'exempt'}) {
 5117:                                             $designhash{$udom.'.login.'.$key.'_exempt_'.$hostname} = $domconfig{'login'}{$key}{$hostname}{'exempt'};
 5118:                                         }
 5119:                                     }
 5120:                                 }
 5121:                             }
 5122:                         } else {
 5123:                             foreach my $img (keys(%{$domconfig{'login'}{$key}})) {
 5124:                                 $designhash{$udom.'.login.'.$key.'_'.$img} = 
 5125:                                     $domconfig{'login'}{$key}{$img};
 5126:                             }
 5127:                         }
 5128:                     } else {
 5129:                         $designhash{$udom.'.login.'.$key}=$domconfig{'login'}{$key};
 5130:                     }
 5131:                 }
 5132:             } else {
 5133:                 $legacy{'login'} = 1;
 5134:             }
 5135:         } else {
 5136:             $legacy{'login'} = 1;
 5137:         }
 5138:         if (ref($domconfig{'rolecolors'}) eq 'HASH') {
 5139:             if (keys(%{$domconfig{'rolecolors'}})) {
 5140:                 foreach my $role (keys(%{$domconfig{'rolecolors'}})) {
 5141:                     if (ref($domconfig{'rolecolors'}{$role}) eq 'HASH') {
 5142:                         foreach my $item (keys(%{$domconfig{'rolecolors'}{$role}})) {
 5143:                             $designhash{$udom.'.'.$role.'.'.$item}=$domconfig{'rolecolors'}{$role}{$item};
 5144:                         }
 5145:                     }
 5146:                 }
 5147:             } else {
 5148:                 $legacy{'rolecolors'} = 1;
 5149:             }
 5150:         } else {
 5151:             $legacy{'rolecolors'} = 1;
 5152:         }
 5153:         if (ref($domconfig{'autoenroll'}) eq 'HASH') {
 5154:             if ($domconfig{'autoenroll'}{'co-owners'}) {
 5155:                 $designhash{$udom.'.autoassign.co-owners'}=$domconfig{'autoenroll'}{'co-owners'};
 5156:             }
 5157:         }
 5158:         if (keys(%legacy) > 0) {
 5159:             my %legacyhash = &get_legacy_domconf($udom);
 5160:             foreach my $item (keys(%legacyhash)) {
 5161:                 if ($item =~ /^\Q$udom\E\.login/) {
 5162:                     if ($legacy{'login'}) { 
 5163:                         $designhash{$item} = $legacyhash{$item};
 5164:                     }
 5165:                 } else {
 5166:                     if ($legacy{'rolecolors'}) {
 5167:                         $designhash{$item} = $legacyhash{$item};
 5168:                     }
 5169:                 }
 5170:             }
 5171:         }
 5172:     } else {
 5173:         %designhash = &get_legacy_domconf($udom); 
 5174:     }
 5175:     &Apache::lonnet::do_cache_new('domainconfig',$udom,\%designhash,
 5176: 				  $cachetime);
 5177:     return %designhash;
 5178: }
 5179: 
 5180: sub get_legacy_domconf {
 5181:     my ($udom) = @_;
 5182:     my %legacyhash;
 5183:     my $designdir=$Apache::lonnet::perlvar{'lonTabDir'}.'/lonDomColors';
 5184:     my $designfile =  $designdir.'/'.$udom.'.tab';
 5185:     if (-e $designfile) {
 5186:         if ( open (my $fh,"<$designfile") ) {
 5187:             while (my $line = <$fh>) {
 5188:                 next if ($line =~ /^\#/);
 5189:                 chomp($line);
 5190:                 my ($key,$val)=(split(/\=/,$line));
 5191:                 if ($val) { $legacyhash{$udom.'.'.$key}=$val; }
 5192:             }
 5193:             close($fh);
 5194:         }
 5195:     }
 5196:     if (-e $Apache::lonnet::perlvar{'lonDocRoot'}.'/adm/lonDomLogos/'.$udom.'.gif') {
 5197:         $legacyhash{$udom.'.login.domlogo'} = "/adm/lonDomLogos/$udom.gif";
 5198:     }
 5199:     return %legacyhash;
 5200: }
 5201: 
 5202: =pod
 5203: 
 5204: =item * &domainlogo()
 5205: 
 5206: Inputs: $domain (usually will be undef)
 5207: 
 5208: Returns: A link to a domain logo, if the domain logo exists.
 5209: If the domain logo does not exist, a description of the domain.
 5210: 
 5211: =cut
 5212: 
 5213: ###############################################
 5214: sub domainlogo {
 5215:     my $domain = &determinedomain(shift);
 5216:     my %designhash = &get_domainconf($domain);    
 5217:     # See if there is a logo
 5218:     if ($designhash{$domain.'.login.domlogo'} ne '') {
 5219:         my $imgsrc = $designhash{$domain.'.login.domlogo'};
 5220:         if ($imgsrc =~ m{^/(adm|res)/}) {
 5221: 	    if ($imgsrc =~ m{^/res/}) {
 5222: 		my $local_name = &Apache::lonnet::filelocation('',$imgsrc);
 5223: 		&Apache::lonnet::repcopy($local_name);
 5224: 	    }
 5225: 	   $imgsrc = &lonhttpdurl($imgsrc);
 5226:         } 
 5227:         return '<img src="'.$imgsrc.'" alt="'.$domain.'" />';
 5228:     } elsif (defined(&Apache::lonnet::domain($domain,'description'))) {
 5229:         return &Apache::lonnet::domain($domain,'description');
 5230:     } else {
 5231:         return '';
 5232:     }
 5233: }
 5234: ##############################################
 5235: 
 5236: =pod
 5237: 
 5238: =item * &designparm()
 5239: 
 5240: Inputs: $which parameter; $domain (usually will be undef)
 5241: 
 5242: Returns: value of designparamter $which
 5243: 
 5244: =cut
 5245: 
 5246: 
 5247: ##############################################
 5248: sub designparm {
 5249:     my ($which,$domain)=@_;
 5250:     if (exists($env{'environment.color.'.$which})) {
 5251:         return $env{'environment.color.'.$which};
 5252:     }
 5253:     $domain=&determinedomain($domain);
 5254:     my %domdesign;
 5255:     unless ($domain eq 'public') {
 5256:         %domdesign = &get_domainconf($domain);
 5257:     }
 5258:     my $output;
 5259:     if ($domdesign{$domain.'.'.$which} ne '') {
 5260:         $output = $domdesign{$domain.'.'.$which};
 5261:     } else {
 5262:         $output = $defaultdesign{$which};
 5263:     }
 5264:     if (($which =~ /^(student|coordinator|author|admin)\.img$/) ||
 5265:         ($which =~ /login\.(img|logo|domlogo|login)/)) {
 5266:         if ($output =~ m{^/(adm|res)/}) {
 5267:             if ($output =~ m{^/res/}) {
 5268:                 my $local_name = &Apache::lonnet::filelocation('',$output);
 5269:                 &Apache::lonnet::repcopy($local_name);
 5270:             }
 5271:             $output = &lonhttpdurl($output);
 5272:         }
 5273:     }
 5274:     return $output;
 5275: }
 5276: 
 5277: ##############################################
 5278: =pod
 5279: 
 5280: =item * &authorspace()
 5281: 
 5282: Inputs: $url (usually will be undef).
 5283: 
 5284: Returns: Path to Authoring Space containing the resource or 
 5285:          directory being viewed (or for which action is being taken). 
 5286:          If $url is provided, and begins /priv/<domain>/<uname>
 5287:          the path will be that portion of the $context argument.
 5288:          Otherwise the path will be for the author space of the current
 5289:          user when the current role is author, or for that of the 
 5290:          co-author/assistant co-author space when the current role 
 5291:          is co-author or assistant co-author.
 5292: 
 5293: =cut
 5294: 
 5295: sub authorspace {
 5296:     my ($url) = @_;
 5297:     if ($url ne '') {
 5298:         if ($url =~ m{^(/priv/$match_domain/$match_username/)}) {
 5299:            return $1;
 5300:         }
 5301:     }
 5302:     my $caname = '';
 5303:     my $cadom = '';
 5304:     if ($env{'request.role'} =~ /^(?:ca|aa)/) {
 5305:         ($cadom,$caname) =
 5306:             ($env{'request.role'}=~/($match_domain)\/($match_username)$/);
 5307:     } elsif ($env{'request.role'} =~ m{^au\./($match_domain)/}) {
 5308:         $caname = $env{'user.name'};
 5309:         $cadom = $env{'user.domain'};
 5310:     }
 5311:     if (($caname ne '') && ($cadom ne '')) {
 5312:         return "/priv/$cadom/$caname/";
 5313:     }
 5314:     return;
 5315: }
 5316: 
 5317: ##############################################
 5318: =pod
 5319: 
 5320: =item * &head_subbox()
 5321: 
 5322: Inputs: $content (contains HTML code with page functions, etc.)
 5323: 
 5324: Returns: HTML div with $content
 5325:          To be included in page header
 5326: 
 5327: =cut
 5328: 
 5329: sub head_subbox {
 5330:     my ($content)=@_;
 5331:     my $output =
 5332:         '<div class="LC_head_subbox">'
 5333:        .$content
 5334:        .'</div>'
 5335: }
 5336: 
 5337: ##############################################
 5338: =pod
 5339: 
 5340: =item * &CSTR_pageheader()
 5341: 
 5342: Input: (optional) filename from which breadcrumb trail is built.
 5343:        In most cases no input as needed, as $env{'request.filename'}
 5344:        is appropriate for use in building the breadcrumb trail.
 5345: 
 5346: Returns: HTML div with CSTR path and recent box
 5347:          To be included on Authoring Space pages
 5348: 
 5349: =cut
 5350: 
 5351: sub CSTR_pageheader {
 5352:     my ($trailfile) = @_;
 5353:     if ($trailfile eq '') {
 5354:         $trailfile = $env{'request.filename'};
 5355:     }
 5356: 
 5357: # this is for resources; directories have customtitle, and crumbs
 5358: # and select recent are created in lonpubdir.pm
 5359: 
 5360:     my $londocroot = $Apache::lonnet::perlvar{'lonDocRoot'};
 5361:     my ($udom,$uname,$thisdisfn)=
 5362:         ($trailfile =~ m{^\Q$londocroot\E/priv/([^/]+)/([^/]+)(?:|/(.*))$});
 5363:     my $formaction = "/priv/$udom/$uname/$thisdisfn";
 5364:     $formaction =~ s{/+}{/}g;
 5365: 
 5366:     my $parentpath = '';
 5367:     my $lastitem = '';
 5368:     if ($thisdisfn =~ m-(.+/)([^/]*)$-) {
 5369:         $parentpath = $1;
 5370:         $lastitem = $2;
 5371:     } else {
 5372:         $lastitem = $thisdisfn;
 5373:     }
 5374: 
 5375:     my $output =
 5376:          '<div>'
 5377:         .&Apache::loncommon::help_open_menu('','',3,'Authoring') #FIXME: Broken? Where is it?
 5378:         .'<b>'.&mt('Authoring Space:').'</b> '
 5379:         .'<form name="dirs" method="post" action="'.$formaction
 5380:         .'" target="_top">' #FIXME lonpubdir: target="_parent"
 5381:         .&Apache::lonhtmlcommon::crumbs($uname.'/'.$parentpath,'_top','/priv/'.$udom,undef,undef);
 5382: 
 5383:     if ($lastitem) {
 5384:         $output .=
 5385:              '<span class="LC_filename">'
 5386:             .$lastitem
 5387:             .'</span>';
 5388:     }
 5389:     $output .=
 5390:          '<br />'
 5391:         #FIXME lonpubdir: &Apache::lonhtmlcommon::crumbs($uname.$thisdisfn.'/','_top','/priv','','+1',1)."</b></tt><br />"
 5392:         .&Apache::lonhtmlcommon::select_recent('construct','recent','this.form.action=this.form.recent.value;this.form.submit()')
 5393:         .'</form>'
 5394:         .&Apache::lonmenu::constspaceform()
 5395:         .'</div>';
 5396: 
 5397:     return $output;
 5398: }
 5399: 
 5400: ###############################################
 5401: ###############################################
 5402: 
 5403: =pod
 5404: 
 5405: =back
 5406: 
 5407: =head1 HTML Helpers
 5408: 
 5409: =over 4
 5410: 
 5411: =item * &bodytag()
 5412: 
 5413: Returns a uniform header for LON-CAPA web pages.
 5414: 
 5415: Inputs: 
 5416: 
 5417: =over 4
 5418: 
 5419: =item * $title, A title to be displayed on the page.
 5420: 
 5421: =item * $function, the current role (can be undef).
 5422: 
 5423: =item * $addentries, extra parameters for the <body> tag.
 5424: 
 5425: =item * $bodyonly, if defined, only return the <body> tag.
 5426: 
 5427: =item * $domain, if defined, force a given domain.
 5428: 
 5429: =item * $forcereg, if page should register as content page (relevant for 
 5430:             text interface only)
 5431: 
 5432: =item * $no_nav_bar, if true, keep the 'what is this' info but remove the
 5433:                      navigational links
 5434: 
 5435: =item * $bgcolor, used to override the bgcolor on a webpage to a specific value
 5436: 
 5437: =item * $args, optional argument valid values are
 5438:             no_auto_mt_title -> prevents &mt()ing the title arg
 5439:             inherit_jsmath -> when creating popup window in a page,
 5440:                               should it have jsmath forced on by the
 5441:                               current page
 5442: 
 5443: =item * $advtoolsref, optional argument, ref to an array containing
 5444:             inlineremote items to be added in "Functions" menu below
 5445:             breadcrumbs.
 5446: 
 5447: =back
 5448: 
 5449: Returns: A uniform header for LON-CAPA web pages.  
 5450: If $bodyonly is nonzero, a string containing a <body> tag will be returned.
 5451: If $bodyonly is undef or zero, an html string containing a <body> tag and 
 5452: other decorations will be returned.
 5453: 
 5454: =cut
 5455: 
 5456: sub bodytag {
 5457:     my ($title,$function,$addentries,$bodyonly,$domain,$forcereg,
 5458:         $no_nav_bar,$bgcolor,$args,$advtoolsref)=@_;
 5459: 
 5460:     my $public;
 5461:     if ((($env{'user.name'} eq 'public') && ($env{'user.domain'} eq 'public'))
 5462:         || ($env{'user.name'} eq '') && ($env{'user.domain'} eq '')) {
 5463:         $public = 1;
 5464:     }
 5465:     if (!$args->{'no_auto_mt_title'}) { $title = &mt($title); }
 5466:     my $httphost = $args->{'use_absolute'};
 5467: 
 5468:     $function = &get_users_function() if (!$function);
 5469:     my $img =    &designparm($function.'.img',$domain);
 5470:     my $font =   &designparm($function.'.font',$domain);
 5471:     my $pgbg   = $bgcolor || &designparm($function.'.pgbg',$domain);
 5472: 
 5473:     my %design = ( 'style'   => 'margin-top: 0',
 5474: 		   'bgcolor' => $pgbg,
 5475: 		   'text'    => $font,
 5476:                    'alink'   => &designparm($function.'.alink',$domain),
 5477: 		   'vlink'   => &designparm($function.'.vlink',$domain),
 5478: 		   'link'    => &designparm($function.'.link',$domain),);
 5479:     @design{keys(%$addentries)} = @$addentries{keys(%$addentries)}; 
 5480: 
 5481:  # role and realm
 5482:     my ($role,$realm) = split(m{\./},$env{'request.role'},2);
 5483:     if ($realm) {
 5484:         $realm = '/'.$realm;
 5485:     }
 5486:     if ($role  eq 'ca') {
 5487:         my ($rdom,$rname) = ($realm =~ m{^/($match_domain)/($match_username)$});
 5488:         $realm = &plainname($rname,$rdom);
 5489:     } 
 5490: # realm
 5491:     if ($env{'request.course.id'}) {
 5492:         if ($env{'request.role'} !~ /^cr/) {
 5493:             $role = &Apache::lonnet::plaintext($role,&course_type());
 5494:         }
 5495:         if ($env{'request.course.sec'}) {
 5496:             $role .= ('&nbsp;'x2).'-&nbsp;'.&mt('section:').'&nbsp;'.$env{'request.course.sec'};
 5497:         }   
 5498: 	$realm = $env{'course.'.$env{'request.course.id'}.'.description'};
 5499:     } else {
 5500:         $role = &Apache::lonnet::plaintext($role);
 5501:     }
 5502: 
 5503:     if (!$realm) { $realm='&nbsp;'; }
 5504: 
 5505:     my $extra_body_attr = &make_attr_string($forcereg,\%design);
 5506: 
 5507: # construct main body tag
 5508:     my $bodytag = "<body $extra_body_attr>".
 5509: 	&Apache::lontexconvert::init_math_support($args->{'inherit_jsmath'});
 5510: 
 5511:     &get_unprocessed_cgi($ENV{'QUERY_STRING'}, ['inhibitmenu']);
 5512: 
 5513:     if (($bodyonly) || ($no_nav_bar) || ($env{'form.inhibitmenu'} eq 'yes')) {
 5514:         return $bodytag;
 5515:     }
 5516: 
 5517:     if ($public) {
 5518: 	undef($role);
 5519:     }
 5520:     
 5521:     my $titleinfo = '<h1>'.$title.'</h1>';
 5522:     #
 5523:     # Extra info if you are the DC
 5524:     my $dc_info = '';
 5525:     if ($env{'user.adv'} && exists($env{'user.role.dc./'.
 5526:                         $env{'course.'.$env{'request.course.id'}.
 5527:                                  '.domain'}.'/'})) {
 5528:         my $cid = $env{'request.course.id'};
 5529:         $dc_info = $cid.' '.$env{'course.'.$cid.'.internal.coursecode'};
 5530:         $dc_info =~ s/\s+$//;
 5531:     }
 5532: 
 5533:     $role = '<span class="LC_nobreak">('.$role.')</span>' if $role;
 5534: 
 5535:         if ($env{'request.state'} eq 'construct') { $forcereg=1; }
 5536: 
 5537:         #    if ($env{'request.state'} eq 'construct') {
 5538:         #        $titleinfo = &CSTR_pageheader(); #FIXME: Will be removed once all scripts have their own calls
 5539:         #    }
 5540: 
 5541:         $bodytag .= Apache::lonhtmlcommon::scripttag(
 5542:             Apache::lonmenu::utilityfunctions($httphost), 'start');
 5543: 
 5544:         my ($left,$right) = Apache::lonmenu::primary_menu();
 5545: 
 5546:         if ($env{'request.noversionuri'} =~ m{^/res/adm/pages/}) {
 5547:              if ($dc_info) {
 5548:                  $dc_info = qq|<span class="LC_cusr_subheading">$dc_info</span>|;
 5549:              }
 5550:              $bodytag .= qq|<div id="LC_nav_bar">$left $role<br />
 5551:                 <em>$realm</em> $dc_info</div>|;
 5552:             return $bodytag;
 5553:         }
 5554: 
 5555:         unless ($env{'request.symb'} =~ m/\.page___\d+___/) {
 5556:             $bodytag .= qq|<div id="LC_nav_bar">$left $role</div>|;
 5557:         }
 5558: 
 5559:         $bodytag .= $right;
 5560: 
 5561:         if ($dc_info) {
 5562:             $dc_info = &dc_courseid_toggle($dc_info);
 5563:         }
 5564:         $bodytag .= qq|<div id="LC_realm">$realm $dc_info</div>|;
 5565: 
 5566:         #if directed to not display the secondary menu, don't.  
 5567:         if ($args->{'no_secondary_menu'}) {
 5568:             return $bodytag;
 5569:         }
 5570:         #don't show menus for public users
 5571:         if (!$public){
 5572:             $bodytag .= Apache::lonmenu::secondary_menu($httphost);
 5573:             $bodytag .= Apache::lonmenu::serverform();
 5574:             $bodytag .= Apache::lonhtmlcommon::scripttag('', 'end');
 5575:             if ($env{'request.state'} eq 'construct') {
 5576:                 $bodytag .= &Apache::lonmenu::innerregister($forcereg,
 5577:                                 $args->{'bread_crumbs'});
 5578:             } elsif ($forcereg) {
 5579:                 $bodytag .= &Apache::lonmenu::innerregister($forcereg,undef,
 5580:                                                             $args->{'group'});
 5581:             } else {
 5582:                 $bodytag .= 
 5583:                     &Apache::lonmenu::prepare_functions($env{'request.noversionuri'},
 5584:                                                         $forcereg,$args->{'group'},
 5585:                                                         $args->{'bread_crumbs'},
 5586:                                                         $advtoolsref);
 5587:             }
 5588:         }else{
 5589:             # this is to seperate menu from content when there's no secondary
 5590:             # menu. Especially needed for public accessible ressources.
 5591:             $bodytag .= '<hr style="clear:both" />';
 5592:             $bodytag .= Apache::lonhtmlcommon::scripttag('', 'end'); 
 5593:         }
 5594: 
 5595:         return $bodytag;
 5596: }
 5597: 
 5598: sub dc_courseid_toggle {
 5599:     my ($dc_info) = @_;
 5600:     return ' <span id="dccidtext" class="LC_cusr_subheading LC_nobreak">'.
 5601:            '<a href="javascript:showCourseID();" class="LC_menubuttons_link">'.
 5602:            &mt('(More ...)').'</a></span>'.
 5603:            '<div id="dccid" class="LC_dccid">'.$dc_info.'</div>';
 5604: }
 5605: 
 5606: sub make_attr_string {
 5607:     my ($register,$attr_ref) = @_;
 5608: 
 5609:     if ($attr_ref && !ref($attr_ref)) {
 5610: 	die("addentries Must be a hash ref ".
 5611: 	    join(':',caller(1))." ".
 5612: 	    join(':',caller(0))." ");
 5613:     }
 5614: 
 5615:     if ($register) {
 5616: 	my ($on_load,$on_unload);
 5617: 	foreach my $key (keys(%{$attr_ref})) {
 5618: 	    if      (lc($key) eq 'onload') {
 5619: 		$on_load.=$attr_ref->{$key}.';';
 5620: 		delete($attr_ref->{$key});
 5621: 
 5622: 	    } elsif (lc($key) eq 'onunload') {
 5623: 		$on_unload.=$attr_ref->{$key}.';';
 5624: 		delete($attr_ref->{$key});
 5625: 	    }
 5626: 	}
 5627: 	$attr_ref->{'onload'}  = $on_load;
 5628: 	$attr_ref->{'onunload'}= $on_unload;
 5629:     }
 5630: 
 5631:     my $attr_string;
 5632:     foreach my $attr (sort(keys(%$attr_ref))) {
 5633: 	$attr_string .= " $attr=\"".$attr_ref->{$attr}.'" ';
 5634:     }
 5635:     return $attr_string;
 5636: }
 5637: 
 5638: 
 5639: ###############################################
 5640: ###############################################
 5641: 
 5642: =pod
 5643: 
 5644: =item * &endbodytag()
 5645: 
 5646: Returns a uniform footer for LON-CAPA web pages.
 5647: 
 5648: Inputs: 1 - optional reference to an args hash
 5649: If in the hash, key for noredirectlink has a value which evaluates to true,
 5650: a 'Continue' link is not displayed if the page contains an
 5651: internal redirect in the <head></head> section,
 5652: i.e., $env{'internal.head.redirect'} exists   
 5653: 
 5654: =cut
 5655: 
 5656: sub endbodytag {
 5657:     my ($args) = @_;
 5658:     my $endbodytag;
 5659:     unless ((ref($args) eq 'HASH') && ($args->{'notbody'})) {
 5660:         $endbodytag='</body>';
 5661:     }
 5662:     $endbodytag=&Apache::lontexconvert::jsMath_process()."\n".$endbodytag;
 5663:     if ( exists( $env{'internal.head.redirect'} ) ) {
 5664:         if (!(ref($args) eq 'HASH' && $args->{'noredirectlink'})) {
 5665: 	    $endbodytag=
 5666: 	        "<br /><a href=\"$env{'internal.head.redirect'}\">".
 5667: 	        &mt('Continue').'</a>'.
 5668: 	        $endbodytag;
 5669:         }
 5670:     }
 5671:     return $endbodytag;
 5672: }
 5673: 
 5674: =pod
 5675: 
 5676: =item * &standard_css()
 5677: 
 5678: Returns a style sheet
 5679: 
 5680: Inputs: (all optional)
 5681:             domain         -> force to color decorate a page for a specific
 5682:                                domain
 5683:             function       -> force usage of a specific rolish color scheme
 5684:             bgcolor        -> override the default page bgcolor
 5685: 
 5686: =cut
 5687: 
 5688: sub standard_css {
 5689:     my ($function,$domain,$bgcolor) = @_;
 5690:     $function  = &get_users_function() if (!$function);
 5691:     my $img    = &designparm($function.'.img',   $domain);
 5692:     my $tabbg  = &designparm($function.'.tabbg', $domain);
 5693:     my $font   = &designparm($function.'.font',  $domain);
 5694:     my $fontmenu = &designparm($function.'.fontmenu', $domain);
 5695: #second colour for later usage
 5696:     my $sidebg = &designparm($function.'.sidebg',$domain);
 5697:     my $pgbg_or_bgcolor =
 5698: 	         $bgcolor ||
 5699: 	         &designparm($function.'.pgbg',  $domain);
 5700:     my $pgbg   = &designparm($function.'.pgbg',  $domain);
 5701:     my $alink  = &designparm($function.'.alink', $domain);
 5702:     my $vlink  = &designparm($function.'.vlink', $domain);
 5703:     my $link   = &designparm($function.'.link',  $domain);
 5704: 
 5705:     my $sans                 = 'Verdana,Arial,Helvetica,sans-serif';
 5706:     my $mono                 = 'monospace';
 5707:     my $data_table_head      = $sidebg;
 5708:     my $data_table_light     = '#FAFAFA';
 5709:     my $data_table_dark      = '#E0E0E0';
 5710:     my $data_table_darker    = '#CCCCCC';
 5711:     my $data_table_highlight = '#FFFF00';
 5712:     my $mail_new             = '#FFBB77';
 5713:     my $mail_new_hover       = '#DD9955';
 5714:     my $mail_read            = '#BBBB77';
 5715:     my $mail_read_hover      = '#999944';
 5716:     my $mail_replied         = '#AAAA88';
 5717:     my $mail_replied_hover   = '#888855';
 5718:     my $mail_other           = '#99BBBB';
 5719:     my $mail_other_hover     = '#669999';
 5720:     my $table_header         = '#DDDDDD';
 5721:     my $feedback_link_bg     = '#BBBBBB';
 5722:     my $lg_border_color      = '#C8C8C8';
 5723:     my $button_hover         = '#BF2317';
 5724: 
 5725:     my $border = ($env{'browser.type'} eq 'explorer' ||
 5726:       $env{'browser.type'} eq 'safari'     ) ? '0 2px 0 2px'
 5727:                                              : '0 3px 0 4px';
 5728: 
 5729: 
 5730:     return <<END;
 5731: 
 5732: /* needed for iframe to allow 100% height in FF */
 5733: body, html { 
 5734:     margin: 0;
 5735:     padding: 0 0.5%;
 5736:     height: 99%; /* to avoid scrollbars */
 5737: }
 5738: 
 5739: body {
 5740:   font-family: $sans;
 5741:   line-height:130%;
 5742:   font-size:0.83em;
 5743:   color:$font;
 5744: }
 5745: 
 5746: a:focus,
 5747: a:focus img {
 5748:   color: red;
 5749: }
 5750: 
 5751: form, .inline {
 5752:   display: inline;
 5753: }
 5754: 
 5755: .LC_right {
 5756:   text-align:right;
 5757: }
 5758: 
 5759: .LC_middle {
 5760:   vertical-align:middle;
 5761: }
 5762: 
 5763: .LC_floatleft {
 5764:   float: left;
 5765: }
 5766: 
 5767: .LC_floatright {
 5768:   float: right;
 5769: }
 5770: 
 5771: .LC_400Box {
 5772:   width:400px;
 5773: }
 5774: 
 5775: .LC_iframecontainer {
 5776:     width: 98%;
 5777:     margin: 0;
 5778:     position: fixed;
 5779:     top: 8.5em;
 5780:     bottom: 0;
 5781: }
 5782: 
 5783: .LC_iframecontainer iframe{
 5784:     border: none;
 5785:     width: 100%;
 5786:     height: 100%;
 5787: }
 5788: 
 5789: .LC_filename {
 5790:   font-family: $mono;
 5791:   white-space:pre;
 5792:   font-size: 120%;
 5793: }
 5794: 
 5795: .LC_fileicon {
 5796:   border: none;
 5797:   height: 1.3em;
 5798:   vertical-align: text-bottom;
 5799:   margin-right: 0.3em;
 5800:   text-decoration:none;
 5801: }
 5802: 
 5803: .LC_setting {
 5804:   text-decoration:underline;
 5805: }
 5806: 
 5807: .LC_error {
 5808:   color: red;
 5809: }
 5810: 
 5811: .LC_warning {
 5812:   color: darkorange;
 5813: }
 5814: 
 5815: .LC_diff_removed {
 5816:   color: red;
 5817: }
 5818: 
 5819: .LC_info,
 5820: .LC_success,
 5821: .LC_diff_added {
 5822:   color: green;
 5823: }
 5824: 
 5825: div.LC_confirm_box {
 5826:   background-color: #FAFAFA;
 5827:   border: 1px solid $lg_border_color;
 5828:   margin-right: 0;
 5829:   padding: 5px;
 5830: }
 5831: 
 5832: div.LC_confirm_box .LC_error img,
 5833: div.LC_confirm_box .LC_success img {
 5834:   vertical-align: middle;
 5835: }
 5836: 
 5837: .LC_icon {
 5838:   border: none;
 5839:   vertical-align: middle;
 5840: }
 5841: 
 5842: .LC_docs_spacer {
 5843:   width: 25px;
 5844:   height: 1px;
 5845:   border: none;
 5846: }
 5847: 
 5848: .LC_internal_info {
 5849:   color: #999999;
 5850: }
 5851: 
 5852: .LC_discussion {
 5853:   background: $data_table_dark;
 5854:   border: 1px solid black;
 5855:   margin: 2px;
 5856: }
 5857: 
 5858: .LC_disc_action_left {
 5859:   background: $sidebg;
 5860:   text-align: left;
 5861:   padding: 4px;
 5862:   margin: 2px;
 5863: }
 5864: 
 5865: .LC_disc_action_right {
 5866:   background: $sidebg;
 5867:   text-align: right;
 5868:   padding: 4px;
 5869:   margin: 2px;
 5870: }
 5871: 
 5872: .LC_disc_new_item {
 5873:   background: white;
 5874:   border: 2px solid red;
 5875:   margin: 4px;
 5876:   padding: 4px;
 5877: }
 5878: 
 5879: .LC_disc_old_item {
 5880:   background: white;
 5881:   margin: 4px;
 5882:   padding: 4px;
 5883: }
 5884: 
 5885: table.LC_pastsubmission {
 5886:   border: 1px solid black;
 5887:   margin: 2px;
 5888: }
 5889: 
 5890: table#LC_menubuttons {
 5891:   width: 100%;
 5892:   background: $pgbg;
 5893:   border: 2px;
 5894:   border-collapse: separate;
 5895:   padding: 0;
 5896: }
 5897: 
 5898: table#LC_title_bar a {
 5899:   color: $fontmenu;
 5900: }
 5901: 
 5902: table#LC_title_bar {
 5903:   clear: both;
 5904:   display: none;
 5905: }
 5906: 
 5907: table#LC_title_bar,
 5908: table.LC_breadcrumbs, /* obsolete? */
 5909: table#LC_title_bar.LC_with_remote {
 5910:   width: 100%;
 5911:   border-color: $pgbg;
 5912:   border-style: solid;
 5913:   border-width: $border;
 5914:   background: $pgbg;
 5915:   color: $fontmenu;
 5916:   border-collapse: collapse;
 5917:   padding: 0;
 5918:   margin: 0;
 5919: }
 5920: 
 5921: ul.LC_breadcrumb_tools_outerlist {
 5922:     margin: 0;
 5923:     padding: 0;
 5924:     position: relative;
 5925:     list-style: none;
 5926: }
 5927: ul.LC_breadcrumb_tools_outerlist li {
 5928:     display: inline;
 5929: }
 5930: 
 5931: .LC_breadcrumb_tools_navigation {
 5932:     padding: 0;
 5933:     margin: 0;
 5934:     float: left;
 5935: }
 5936: .LC_breadcrumb_tools_tools {
 5937:     padding: 0;
 5938:     margin: 0;
 5939:     float: right;
 5940: }
 5941: 
 5942: table#LC_title_bar td {
 5943:   background: $tabbg;
 5944: }
 5945: 
 5946: table#LC_menubuttons img {
 5947:   border: none;
 5948: }
 5949: 
 5950: .LC_breadcrumbs_component {
 5951:   float: right;
 5952:   margin: 0 1em;
 5953: }
 5954: .LC_breadcrumbs_component img {
 5955:   vertical-align: middle;
 5956: }
 5957: 
 5958: td.LC_table_cell_checkbox {
 5959:   text-align: center;
 5960: }
 5961: 
 5962: .LC_fontsize_small {
 5963:   font-size: 70%;
 5964: }
 5965: 
 5966: #LC_breadcrumbs {
 5967:   clear:both;
 5968:   background: $sidebg;
 5969:   border-bottom: 1px solid $lg_border_color;
 5970:   line-height: 2.5em;
 5971:   overflow: hidden;
 5972:   margin: 0;
 5973:   padding: 0;
 5974:   text-align: left;
 5975: }
 5976: 
 5977: .LC_head_subbox, .LC_actionbox {
 5978:   clear:both;
 5979:   background: #F8F8F8; /* $sidebg; */
 5980:   border: 1px solid $sidebg;
 5981:   margin: 0 0 10px 0;
 5982:   padding: 3px;
 5983:   text-align: left;
 5984: }
 5985: 
 5986: .LC_fontsize_medium {
 5987:   font-size: 85%;
 5988: }
 5989: 
 5990: .LC_fontsize_large {
 5991:   font-size: 120%;
 5992: }
 5993: 
 5994: .LC_menubuttons_inline_text {
 5995:   color: $font;
 5996:   font-size: 90%;
 5997:   padding-left:3px;
 5998: }
 5999: 
 6000: .LC_menubuttons_inline_text img{
 6001:   vertical-align: middle;
 6002: }
 6003: 
 6004: li.LC_menubuttons_inline_text img {
 6005:   cursor:pointer;
 6006:   text-decoration: none;
 6007: }
 6008: 
 6009: .LC_menubuttons_link {
 6010:   text-decoration: none;
 6011: }
 6012: 
 6013: .LC_menubuttons_category {
 6014:   color: $font;
 6015:   background: $pgbg;
 6016:   font-size: larger;
 6017:   font-weight: bold;
 6018: }
 6019: 
 6020: td.LC_menubuttons_text {
 6021:   color: $font;
 6022: }
 6023: 
 6024: .LC_current_location {
 6025:   background: $tabbg;
 6026: }
 6027: 
 6028: table.LC_data_table {
 6029:   border: 1px solid #000000;
 6030:   border-collapse: separate;
 6031:   border-spacing: 1px;
 6032:   background: $pgbg;
 6033: }
 6034: 
 6035: .LC_data_table_dense {
 6036:   font-size: small;
 6037: }
 6038: 
 6039: table.LC_nested_outer {
 6040:   border: 1px solid #000000;
 6041:   border-collapse: collapse;
 6042:   border-spacing: 0;
 6043:   width: 100%;
 6044: }
 6045: 
 6046: table.LC_innerpickbox,
 6047: table.LC_nested {
 6048:   border: none;
 6049:   border-collapse: collapse;
 6050:   border-spacing: 0;
 6051:   width: 100%;
 6052: }
 6053: 
 6054: table.LC_data_table tr th,
 6055: table.LC_calendar tr th,
 6056: table.LC_prior_tries tr th,
 6057: table.LC_innerpickbox tr th {
 6058:   font-weight: bold;
 6059:   background-color: $data_table_head;
 6060:   color:$fontmenu;
 6061:   font-size:90%;
 6062: }
 6063: 
 6064: table.LC_innerpickbox tr th,
 6065: table.LC_innerpickbox tr td {
 6066:   vertical-align: top;
 6067: }
 6068: 
 6069: table.LC_data_table tr.LC_info_row > td {
 6070:   background-color: #CCCCCC;
 6071:   font-weight: bold;
 6072:   text-align: left;
 6073: }
 6074: 
 6075: table.LC_data_table tr.LC_odd_row > td {
 6076:   background-color: $data_table_light;
 6077:   padding: 2px;
 6078:   vertical-align: top;
 6079: }
 6080: 
 6081: table.LC_pick_box tr > td.LC_odd_row {
 6082:   background-color: $data_table_light;
 6083:   vertical-align: top;
 6084: }
 6085: 
 6086: table.LC_data_table tr.LC_even_row > td {
 6087:   background-color: $data_table_dark;
 6088:   padding: 2px;
 6089:   vertical-align: top;
 6090: }
 6091: 
 6092: table.LC_pick_box tr > td.LC_even_row {
 6093:   background-color: $data_table_dark;
 6094:   vertical-align: top;
 6095: }
 6096: 
 6097: table.LC_data_table tr.LC_data_table_highlight td {
 6098:   background-color: $data_table_darker;
 6099: }
 6100: 
 6101: table.LC_data_table tr td.LC_leftcol_header {
 6102:   background-color: $data_table_head;
 6103:   font-weight: bold;
 6104: }
 6105: 
 6106: table.LC_data_table tr.LC_empty_row td,
 6107: table.LC_nested tr.LC_empty_row td {
 6108:   font-weight: bold;
 6109:   font-style: italic;
 6110:   text-align: center;
 6111:   padding: 8px;
 6112: }
 6113: 
 6114: table.LC_data_table tr.LC_empty_row td,
 6115: table.LC_data_table tr.LC_footer_row td {
 6116:   background-color: $sidebg;
 6117: }
 6118: 
 6119: table.LC_nested tr.LC_empty_row td {
 6120:   background-color: #FFFFFF;
 6121: }
 6122: 
 6123: table.LC_caption {
 6124: }
 6125: 
 6126: table.LC_nested tr.LC_empty_row td {
 6127:   padding: 4ex
 6128: }
 6129: 
 6130: table.LC_nested_outer tr th {
 6131:   font-weight: bold;
 6132:   color:$fontmenu;
 6133:   background-color: $data_table_head;
 6134:   font-size: small;
 6135:   border-bottom: 1px solid #000000;
 6136: }
 6137: 
 6138: table.LC_nested_outer tr td.LC_subheader {
 6139:   background-color: $data_table_head;
 6140:   font-weight: bold;
 6141:   font-size: small;
 6142:   border-bottom: 1px solid #000000;
 6143:   text-align: right;
 6144: }
 6145: 
 6146: table.LC_nested tr.LC_info_row td {
 6147:   background-color: #CCCCCC;
 6148:   font-weight: bold;
 6149:   font-size: small;
 6150:   text-align: center;
 6151: }
 6152: 
 6153: table.LC_nested tr.LC_info_row td.LC_left_item,
 6154: table.LC_nested_outer tr th.LC_left_item {
 6155:   text-align: left;
 6156: }
 6157: 
 6158: table.LC_nested td {
 6159:   background-color: #FFFFFF;
 6160:   font-size: small;
 6161: }
 6162: 
 6163: table.LC_nested_outer tr th.LC_right_item,
 6164: table.LC_nested tr.LC_info_row td.LC_right_item,
 6165: table.LC_nested tr.LC_odd_row td.LC_right_item,
 6166: table.LC_nested tr td.LC_right_item {
 6167:   text-align: right;
 6168: }
 6169: 
 6170: table.LC_nested tr.LC_odd_row td {
 6171:   background-color: #EEEEEE;
 6172: }
 6173: 
 6174: table.LC_createuser {
 6175: }
 6176: 
 6177: table.LC_createuser tr.LC_section_row td {
 6178:   font-size: small;
 6179: }
 6180: 
 6181: table.LC_createuser tr.LC_info_row td  {
 6182:   background-color: #CCCCCC;
 6183:   font-weight: bold;
 6184:   text-align: center;
 6185: }
 6186: 
 6187: table.LC_calendar {
 6188:   border: 1px solid #000000;
 6189:   border-collapse: collapse;
 6190:   width: 98%;
 6191: }
 6192: 
 6193: table.LC_calendar_pickdate {
 6194:   font-size: xx-small;
 6195: }
 6196: 
 6197: table.LC_calendar tr td {
 6198:   border: 1px solid #000000;
 6199:   vertical-align: top;
 6200:   width: 14%;
 6201: }
 6202: 
 6203: table.LC_calendar tr td.LC_calendar_day_empty {
 6204:   background-color: $data_table_dark;
 6205: }
 6206: 
 6207: table.LC_calendar tr td.LC_calendar_day_current {
 6208:   background-color: $data_table_highlight;
 6209: }
 6210: 
 6211: table.LC_data_table tr td.LC_mail_new {
 6212:   background-color: $mail_new;
 6213: }
 6214: 
 6215: table.LC_data_table tr.LC_mail_new:hover {
 6216:   background-color: $mail_new_hover;
 6217: }
 6218: 
 6219: table.LC_data_table tr td.LC_mail_read {
 6220:   background-color: $mail_read;
 6221: }
 6222: 
 6223: /*
 6224: table.LC_data_table tr.LC_mail_read:hover {
 6225:   background-color: $mail_read_hover;
 6226: }
 6227: */
 6228: 
 6229: table.LC_data_table tr td.LC_mail_replied {
 6230:   background-color: $mail_replied;
 6231: }
 6232: 
 6233: /*
 6234: table.LC_data_table tr.LC_mail_replied:hover {
 6235:   background-color: $mail_replied_hover;
 6236: }
 6237: */
 6238: 
 6239: table.LC_data_table tr td.LC_mail_other {
 6240:   background-color: $mail_other;
 6241: }
 6242: 
 6243: /*
 6244: table.LC_data_table tr.LC_mail_other:hover {
 6245:   background-color: $mail_other_hover;
 6246: }
 6247: */
 6248: 
 6249: table.LC_data_table tr > td.LC_browser_file,
 6250: table.LC_data_table tr > td.LC_browser_file_published {
 6251:   background: #AAEE77;
 6252: }
 6253: 
 6254: table.LC_data_table tr > td.LC_browser_file_locked,
 6255: table.LC_data_table tr > td.LC_browser_file_unpublished {
 6256:   background: #FFAA99;
 6257: }
 6258: 
 6259: table.LC_data_table tr > td.LC_browser_file_obsolete {
 6260:   background: #888888;
 6261: }
 6262: 
 6263: table.LC_data_table tr > td.LC_browser_file_modified,
 6264: table.LC_data_table tr > td.LC_browser_file_metamodified {
 6265:   background: #F8F866;
 6266: }
 6267: 
 6268: table.LC_data_table tr.LC_browser_folder > td {
 6269:   background: #E0E8FF;
 6270: }
 6271: 
 6272: table.LC_data_table tr > td.LC_roles_is {
 6273:   /* background: #77FF77; */
 6274: }
 6275: 
 6276: table.LC_data_table tr > td.LC_roles_future {
 6277:   border-right: 8px solid #FFFF77;
 6278: }
 6279: 
 6280: table.LC_data_table tr > td.LC_roles_will {
 6281:   border-right: 8px solid #FFAA77;
 6282: }
 6283: 
 6284: table.LC_data_table tr > td.LC_roles_expired {
 6285:   border-right: 8px solid #FF7777;
 6286: }
 6287: 
 6288: table.LC_data_table tr > td.LC_roles_will_not {
 6289:   border-right: 8px solid #AAFF77;
 6290: }
 6291: 
 6292: table.LC_data_table tr > td.LC_roles_selected {
 6293:   border-right: 8px solid #11CC55;
 6294: }
 6295: 
 6296: span.LC_current_location {
 6297:   font-size:larger;
 6298:   background: $pgbg;
 6299: }
 6300: 
 6301: span.LC_current_nav_location {
 6302:   font-weight:bold;
 6303:   background: $sidebg;
 6304: }
 6305: 
 6306: span.LC_parm_menu_item {
 6307:   font-size: larger;
 6308: }
 6309: 
 6310: span.LC_parm_scope_all {
 6311:   color: red;
 6312: }
 6313: 
 6314: span.LC_parm_scope_folder {
 6315:   color: green;
 6316: }
 6317: 
 6318: span.LC_parm_scope_resource {
 6319:   color: orange;
 6320: }
 6321: 
 6322: span.LC_parm_part {
 6323:   color: blue;
 6324: }
 6325: 
 6326: span.LC_parm_folder,
 6327: span.LC_parm_symb {
 6328:   font-size: x-small;
 6329:   font-family: $mono;
 6330:   color: #AAAAAA;
 6331: }
 6332: 
 6333: ul.LC_parm_parmlist li {
 6334:   display: inline-block;
 6335:   padding: 0.3em 0.8em;
 6336:   vertical-align: top;
 6337:   width: 150px;
 6338:   border-top:1px solid $lg_border_color;
 6339: }
 6340: 
 6341: td.LC_parm_overview_level_menu,
 6342: td.LC_parm_overview_map_menu,
 6343: td.LC_parm_overview_parm_selectors,
 6344: td.LC_parm_overview_restrictions  {
 6345:   border: 1px solid black;
 6346:   border-collapse: collapse;
 6347: }
 6348: 
 6349: table.LC_parm_overview_restrictions td {
 6350:   border-width: 1px 4px 1px 4px;
 6351:   border-style: solid;
 6352:   border-color: $pgbg;
 6353:   text-align: center;
 6354: }
 6355: 
 6356: table.LC_parm_overview_restrictions th {
 6357:   background: $tabbg;
 6358:   border-width: 1px 4px 1px 4px;
 6359:   border-style: solid;
 6360:   border-color: $pgbg;
 6361: }
 6362: 
 6363: table#LC_helpmenu {
 6364:   border: none;
 6365:   height: 55px;
 6366:   border-spacing: 0;
 6367: }
 6368: 
 6369: table#LC_helpmenu fieldset legend {
 6370:   font-size: larger;
 6371: }
 6372: 
 6373: table#LC_helpmenu_links {
 6374:   width: 100%;
 6375:   border: 1px solid black;
 6376:   background: $pgbg;
 6377:   padding: 0;
 6378:   border-spacing: 1px;
 6379: }
 6380: 
 6381: table#LC_helpmenu_links tr td {
 6382:   padding: 1px;
 6383:   background: $tabbg;
 6384:   text-align: center;
 6385:   font-weight: bold;
 6386: }
 6387: 
 6388: table#LC_helpmenu_links a:link,
 6389: table#LC_helpmenu_links a:visited,
 6390: table#LC_helpmenu_links a:active {
 6391:   text-decoration: none;
 6392:   color: $font;
 6393: }
 6394: 
 6395: table#LC_helpmenu_links a:hover {
 6396:   text-decoration: underline;
 6397:   color: $vlink;
 6398: }
 6399: 
 6400: .LC_chrt_popup_exists {
 6401:   border: 1px solid #339933;
 6402:   margin: -1px;
 6403: }
 6404: 
 6405: .LC_chrt_popup_up {
 6406:   border: 1px solid yellow;
 6407:   margin: -1px;
 6408: }
 6409: 
 6410: .LC_chrt_popup {
 6411:   border: 1px solid #8888FF;
 6412:   background: #CCCCFF;
 6413: }
 6414: 
 6415: table.LC_pick_box {
 6416:   border-collapse: separate;
 6417:   background: white;
 6418:   border: 1px solid black;
 6419:   border-spacing: 1px;
 6420: }
 6421: 
 6422: table.LC_pick_box td.LC_pick_box_title {
 6423:   background: $sidebg;
 6424:   font-weight: bold;
 6425:   text-align: left;
 6426:   vertical-align: top;
 6427:   width: 184px;
 6428:   padding: 8px;
 6429: }
 6430: 
 6431: table.LC_pick_box td.LC_pick_box_value {
 6432:   text-align: left;
 6433:   padding: 8px;
 6434: }
 6435: 
 6436: table.LC_pick_box td.LC_pick_box_select {
 6437:   text-align: left;
 6438:   padding: 8px;
 6439: }
 6440: 
 6441: table.LC_pick_box td.LC_pick_box_separator {
 6442:   padding: 0;
 6443:   height: 1px;
 6444:   background: black;
 6445: }
 6446: 
 6447: table.LC_pick_box td.LC_pick_box_submit {
 6448:   text-align: right;
 6449: }
 6450: 
 6451: table.LC_pick_box td.LC_evenrow_value {
 6452:   text-align: left;
 6453:   padding: 8px;
 6454:   background-color: $data_table_light;
 6455: }
 6456: 
 6457: table.LC_pick_box td.LC_oddrow_value {
 6458:   text-align: left;
 6459:   padding: 8px;
 6460:   background-color: $data_table_light;
 6461: }
 6462: 
 6463: span.LC_helpform_receipt_cat {
 6464:   font-weight: bold;
 6465: }
 6466: 
 6467: table.LC_group_priv_box {
 6468:   background: white;
 6469:   border: 1px solid black;
 6470:   border-spacing: 1px;
 6471: }
 6472: 
 6473: table.LC_group_priv_box td.LC_pick_box_title {
 6474:   background: $tabbg;
 6475:   font-weight: bold;
 6476:   text-align: right;
 6477:   width: 184px;
 6478: }
 6479: 
 6480: table.LC_group_priv_box td.LC_groups_fixed {
 6481:   background: $data_table_light;
 6482:   text-align: center;
 6483: }
 6484: 
 6485: table.LC_group_priv_box td.LC_groups_optional {
 6486:   background: $data_table_dark;
 6487:   text-align: center;
 6488: }
 6489: 
 6490: table.LC_group_priv_box td.LC_groups_functionality {
 6491:   background: $data_table_darker;
 6492:   text-align: center;
 6493:   font-weight: bold;
 6494: }
 6495: 
 6496: table.LC_group_priv td {
 6497:   text-align: left;
 6498:   padding: 0;
 6499: }
 6500: 
 6501: .LC_navbuttons {
 6502:   margin: 2ex 0ex 2ex 0ex;
 6503: }
 6504: 
 6505: .LC_topic_bar {
 6506:   font-weight: bold;
 6507:   background: $tabbg;
 6508:   margin: 1em 0em 1em 2em;
 6509:   padding: 3px;
 6510:   font-size: 1.2em;
 6511: }
 6512: 
 6513: .LC_topic_bar span {
 6514:   left: 0.5em;
 6515:   position: absolute;
 6516:   vertical-align: middle;
 6517:   font-size: 1.2em;
 6518: }
 6519: 
 6520: table.LC_course_group_status {
 6521:   margin: 20px;
 6522: }
 6523: 
 6524: table.LC_status_selector td {
 6525:   vertical-align: top;
 6526:   text-align: center;
 6527:   padding: 4px;
 6528: }
 6529: 
 6530: div.LC_feedback_link {
 6531:   clear: both;
 6532:   background: $sidebg;
 6533:   width: 100%;
 6534:   padding-bottom: 10px;
 6535:   border: 1px $tabbg solid;
 6536:   height: 22px;
 6537:   line-height: 22px;
 6538:   padding-top: 5px;
 6539: }
 6540: 
 6541: div.LC_feedback_link img {
 6542:   height: 22px;
 6543:   vertical-align:middle;
 6544: }
 6545: 
 6546: div.LC_feedback_link a {
 6547:   text-decoration: none;
 6548: }
 6549: 
 6550: div.LC_comblock {
 6551:   display:inline;
 6552:   color:$font;
 6553:   font-size:90%;
 6554: }
 6555: 
 6556: div.LC_feedback_link div.LC_comblock {
 6557:   padding-left:5px;
 6558: }
 6559: 
 6560: div.LC_feedback_link div.LC_comblock a {
 6561:   color:$font;
 6562: }
 6563: 
 6564: span.LC_feedback_link {
 6565:   /* background: $feedback_link_bg; */
 6566:   font-size: larger;
 6567: }
 6568: 
 6569: span.LC_message_link {
 6570:   /* background: $feedback_link_bg; */
 6571:   font-size: larger;
 6572:   position: absolute;
 6573:   right: 1em;
 6574: }
 6575: 
 6576: table.LC_prior_tries {
 6577:   border: 1px solid #000000;
 6578:   border-collapse: separate;
 6579:   border-spacing: 1px;
 6580: }
 6581: 
 6582: table.LC_prior_tries td {
 6583:   padding: 2px;
 6584: }
 6585: 
 6586: .LC_answer_correct {
 6587:   background: lightgreen;
 6588:   color: darkgreen;
 6589:   padding: 6px;
 6590: }
 6591: 
 6592: .LC_answer_charged_try {
 6593:   background: #FFAAAA;
 6594:   color: darkred;
 6595:   padding: 6px;
 6596: }
 6597: 
 6598: .LC_answer_not_charged_try,
 6599: .LC_answer_no_grade,
 6600: .LC_answer_late {
 6601:   background: lightyellow;
 6602:   color: black;
 6603:   padding: 6px;
 6604: }
 6605: 
 6606: .LC_answer_previous {
 6607:   background: lightblue;
 6608:   color: darkblue;
 6609:   padding: 6px;
 6610: }
 6611: 
 6612: .LC_answer_no_message {
 6613:   background: #FFFFFF;
 6614:   color: black;
 6615:   padding: 6px;
 6616: }
 6617: 
 6618: .LC_answer_unknown {
 6619:   background: orange;
 6620:   color: black;
 6621:   padding: 6px;
 6622: }
 6623: 
 6624: span.LC_prior_numerical,
 6625: span.LC_prior_string,
 6626: span.LC_prior_custom,
 6627: span.LC_prior_reaction,
 6628: span.LC_prior_math {
 6629:   font-family: $mono;
 6630:   white-space: pre;
 6631: }
 6632: 
 6633: span.LC_prior_string {
 6634:   font-family: $mono;
 6635:   white-space: pre;
 6636: }
 6637: 
 6638: table.LC_prior_option {
 6639:   width: 100%;
 6640:   border-collapse: collapse;
 6641: }
 6642: 
 6643: table.LC_prior_rank,
 6644: table.LC_prior_match {
 6645:   border-collapse: collapse;
 6646: }
 6647: 
 6648: table.LC_prior_option tr td,
 6649: table.LC_prior_rank tr td,
 6650: table.LC_prior_match tr td {
 6651:   border: 1px solid #000000;
 6652: }
 6653: 
 6654: .LC_nobreak {
 6655:   white-space: nowrap;
 6656: }
 6657: 
 6658: span.LC_cusr_emph {
 6659:   font-style: italic;
 6660: }
 6661: 
 6662: span.LC_cusr_subheading {
 6663:   font-weight: normal;
 6664:   font-size: 85%;
 6665: }
 6666: 
 6667: div.LC_docs_entry_move {
 6668:   border: 1px solid #BBBBBB;
 6669:   background: #DDDDDD;
 6670:   width: 22px;
 6671:   padding: 1px;
 6672:   margin: 0;
 6673: }
 6674: 
 6675: table.LC_data_table tr > td.LC_docs_entry_commands,
 6676: table.LC_data_table tr > td.LC_docs_entry_parameter {
 6677:   font-size: x-small;
 6678: }
 6679: 
 6680: .LC_docs_entry_parameter {
 6681:   white-space: nowrap;
 6682: }
 6683: 
 6684: .LC_docs_copy {
 6685:   color: #000099;
 6686: }
 6687: 
 6688: .LC_docs_cut {
 6689:   color: #550044;
 6690: }
 6691: 
 6692: .LC_docs_rename {
 6693:   color: #009900;
 6694: }
 6695: 
 6696: .LC_docs_remove {
 6697:   color: #990000;
 6698: }
 6699: 
 6700: .LC_docs_reinit_warn,
 6701: .LC_docs_ext_edit {
 6702:   font-size: x-small;
 6703: }
 6704: 
 6705: table.LC_docs_adddocs td,
 6706: table.LC_docs_adddocs th {
 6707:   border: 1px solid #BBBBBB;
 6708:   padding: 4px;
 6709:   background: #DDDDDD;
 6710: }
 6711: 
 6712: table.LC_sty_begin {
 6713:   background: #BBFFBB;
 6714: }
 6715: 
 6716: table.LC_sty_end {
 6717:   background: #FFBBBB;
 6718: }
 6719: 
 6720: table.LC_double_column {
 6721:   border-width: 0;
 6722:   border-collapse: collapse;
 6723:   width: 100%;
 6724:   padding: 2px;
 6725: }
 6726: 
 6727: table.LC_double_column tr td.LC_left_col {
 6728:   top: 2px;
 6729:   left: 2px;
 6730:   width: 47%;
 6731:   vertical-align: top;
 6732: }
 6733: 
 6734: table.LC_double_column tr td.LC_right_col {
 6735:   top: 2px;
 6736:   right: 2px;
 6737:   width: 47%;
 6738:   vertical-align: top;
 6739: }
 6740: 
 6741: div.LC_left_float {
 6742:   float: left;
 6743:   padding-right: 5%;
 6744:   padding-bottom: 4px;
 6745: }
 6746: 
 6747: div.LC_clear_float_header {
 6748:   padding-bottom: 2px;
 6749: }
 6750: 
 6751: div.LC_clear_float_footer {
 6752:   padding-top: 10px;
 6753:   clear: both;
 6754: }
 6755: 
 6756: div.LC_grade_show_user {
 6757: /*  border-left: 5px solid $sidebg; */
 6758:   border-top: 5px solid #000000;
 6759:   margin: 50px 0 0 0;
 6760:   padding: 15px 0 5px 10px;
 6761: }
 6762: 
 6763: div.LC_grade_show_user_odd_row {
 6764: /*  border-left: 5px solid #000000; */
 6765: }
 6766: 
 6767: div.LC_grade_show_user div.LC_Box {
 6768:   margin-right: 50px;
 6769: }
 6770: 
 6771: div.LC_grade_submissions,
 6772: div.LC_grade_message_center,
 6773: div.LC_grade_info_links {
 6774:   margin: 5px;
 6775:   width: 99%;
 6776:   background: #FFFFFF;
 6777: }
 6778: 
 6779: div.LC_grade_submissions_header,
 6780: div.LC_grade_message_center_header {
 6781:   font-weight: bold;
 6782:   font-size: large;
 6783: }
 6784: 
 6785: div.LC_grade_submissions_body,
 6786: div.LC_grade_message_center_body {
 6787:   border: 1px solid black;
 6788:   width: 99%;
 6789:   background: #FFFFFF;
 6790: }
 6791: 
 6792: table.LC_scantron_action {
 6793:   width: 100%;
 6794: }
 6795: 
 6796: table.LC_scantron_action tr th {
 6797:   font-weight:bold;
 6798:   font-style:normal;
 6799: }
 6800: 
 6801: .LC_edit_problem_header,
 6802: div.LC_edit_problem_footer {
 6803:   font-weight: normal;
 6804:   font-size:  medium;
 6805:   margin: 2px;
 6806:   background-color: $sidebg;
 6807: }
 6808: 
 6809: div.LC_edit_problem_header,
 6810: div.LC_edit_problem_header div,
 6811: div.LC_edit_problem_footer,
 6812: div.LC_edit_problem_footer div,
 6813: div.LC_edit_problem_editxml_header,
 6814: div.LC_edit_problem_editxml_header div {
 6815:   margin-top: 5px;
 6816:   z-index: 100;
 6817: }
 6818: 
 6819: div.LC_edit_problem_header_title {
 6820:   font-weight: bold;
 6821:   font-size: larger;
 6822:   background: $tabbg;
 6823:   padding: 3px;
 6824:   margin: 0 0 5px 0;
 6825: }
 6826: 
 6827: table.LC_edit_problem_header_title {
 6828:   width: 100%;
 6829:   background: $tabbg;
 6830: }
 6831: 
 6832: div.LC_edit_problem_discards {
 6833:   float: left;
 6834: }
 6835: 
 6836: div.LC_edit_actionbar {
 6837:     margin: -5px 0px 0px 0px !important;
 6838:     background-color: $sidebg;
 6839:     height: 31px;
 6840: }
 6841: 
 6842: div.LC_edit_problem_saves {
 6843:   float: right;
 6844:   padding-bottom: 5px;
 6845: }
 6846: 
 6847: .LC_edit_opt {
 6848:   padding-left: 1em;
 6849:   white-space: nowrap;
 6850: }
 6851: 
 6852: .LC_edit_problem_latexhelper{
 6853:     text-align: right;
 6854: }
 6855: 
 6856: #LC_edit_problem_colorful div{
 6857:     margin-left: 40px;
 6858: }
 6859: 
 6860: #LC_edit_problem_codemirror div{
 6861:     margin-left: 0px;
 6862: }
 6863: 
 6864: img.stift {
 6865:   border-width: 0;
 6866:   vertical-align: middle;
 6867: }
 6868: 
 6869: table td.LC_mainmenu_col_fieldset {
 6870:   vertical-align: top;
 6871: }
 6872: 
 6873: div.LC_createcourse {
 6874:   margin: 10px 10px 10px 10px;
 6875: }
 6876: 
 6877: .LC_dccid {
 6878:   float: right;
 6879:   margin: 0.2em 0 0 0;
 6880:   padding: 0;
 6881:   font-size: 90%;
 6882:   display:none;
 6883: }
 6884: 
 6885: ol.LC_primary_menu a:hover,
 6886: ol#LC_MenuBreadcrumbs a:hover,
 6887: ol#LC_PathBreadcrumbs a:hover,
 6888: ul#LC_secondary_menu a:hover,
 6889: .LC_FormSectionClearButton input:hover
 6890: ul.LC_TabContent   li:hover a {
 6891:   color:$button_hover;
 6892:   text-decoration:none;
 6893: }
 6894: 
 6895: h1 {
 6896:   padding: 0;
 6897:   line-height:130%;
 6898: }
 6899: 
 6900: h2,
 6901: h3,
 6902: h4,
 6903: h5,
 6904: h6 {
 6905:   margin: 5px 0 5px 0;
 6906:   padding: 0;
 6907:   line-height:130%;
 6908: }
 6909: 
 6910: .LC_hcell {
 6911:   padding:3px 15px 3px 15px;
 6912:   margin: 0;
 6913:   background-color:$tabbg;
 6914:   color:$fontmenu;
 6915:   border-bottom:solid 1px $lg_border_color;
 6916: }
 6917: 
 6918: .LC_Box > .LC_hcell {
 6919:   margin: 0 -10px 10px -10px;
 6920: }
 6921: 
 6922: .LC_noBorder {
 6923:   border: 0;
 6924: }
 6925: 
 6926: .LC_FormSectionClearButton input {
 6927:   background-color:transparent;
 6928:   border: none;
 6929:   cursor:pointer;
 6930:   text-decoration:underline;
 6931: }
 6932: 
 6933: .LC_help_open_topic {
 6934:   color: #FFFFFF;
 6935:   background-color: #EEEEFF;
 6936:   margin: 1px;
 6937:   padding: 4px;
 6938:   border: 1px solid #000033;
 6939:   white-space: nowrap;
 6940:   /* vertical-align: middle; */
 6941: }
 6942: 
 6943: dl,
 6944: ul,
 6945: div,
 6946: fieldset {
 6947:   margin: 10px 10px 10px 0;
 6948:   /* overflow: hidden; */
 6949: }
 6950: 
 6951: article.geogebraweb div {
 6952:     margin: 0;
 6953: }
 6954: 
 6955: fieldset > legend {
 6956:   font-weight: bold;
 6957:   padding: 0 5px 0 5px;
 6958: }
 6959: 
 6960: #LC_nav_bar {
 6961:   float: left;
 6962:   background-color: $pgbg_or_bgcolor;
 6963:   margin: 0 0 2px 0;
 6964: }
 6965: 
 6966: #LC_realm {
 6967:   margin: 0.2em 0 0 0;
 6968:   padding: 0;
 6969:   font-weight: bold;
 6970:   text-align: center;
 6971:   background-color: $pgbg_or_bgcolor;
 6972: }
 6973: 
 6974: #LC_nav_bar em {
 6975:   font-weight: bold;
 6976:   font-style: normal;
 6977: }
 6978: 
 6979: ol.LC_primary_menu {
 6980:   margin: 0;
 6981:   padding: 0;
 6982: }
 6983: 
 6984: ol#LC_PathBreadcrumbs {
 6985:   margin: 0;
 6986: }
 6987: 
 6988: ol.LC_primary_menu li {
 6989:   color: RGB(80, 80, 80);
 6990:   vertical-align: middle;
 6991:   text-align: left;
 6992:   list-style: none;
 6993:   position: relative;
 6994:   float: left;
 6995:   z-index: 100; /* will be displayed above codemirror and underneath the help-layer */
 6996:   line-height: 1.5em;
 6997: }
 6998: 
 6999: ol.LC_primary_menu li a,
 7000: ol.LC_primary_menu li p {
 7001:   display: block;
 7002:   margin: 0;
 7003:   padding: 0 5px 0 10px;
 7004:   text-decoration: none;
 7005: }
 7006: 
 7007: ol.LC_primary_menu li p span.LC_primary_menu_innertitle {
 7008:   display: inline-block;
 7009:   width: 95%;
 7010:   text-align: left;
 7011: }
 7012: 
 7013: ol.LC_primary_menu li p span.LC_primary_menu_innerarrow {
 7014:   display: inline-block;	
 7015:   width: 5%;
 7016:   float: right;
 7017:   text-align: right;
 7018:   font-size: 70%;
 7019: }
 7020: 
 7021: ol.LC_primary_menu ul {
 7022:   display: none;
 7023:   width: 15em;
 7024:   background-color: $data_table_light;
 7025:   position: absolute;
 7026:   top: 100%;
 7027: }
 7028: 
 7029: ol.LC_primary_menu ul ul {
 7030:   left: 100%;
 7031:   top: 0;
 7032: }
 7033: 
 7034: ol.LC_primary_menu li:hover > ul, ol.LC_primary_menu li.hover > ul {
 7035:   display: block;
 7036:   position: absolute;
 7037:   margin: 0;
 7038:   padding: 0;
 7039:   z-index: 2;
 7040: }
 7041: 
 7042: ol.LC_primary_menu li:hover li, ol.LC_primary_menu li.hover li {
 7043: /* First Submenu -> size should be smaller than the menu title of the whole menu */
 7044:   font-size: 90%;
 7045:   vertical-align: top;
 7046:   float: none;
 7047:   border-left: 1px solid black;
 7048:   border-right: 1px solid black;
 7049: /* A dark bottom border to visualize different menu options; 
 7050: overwritten in the create_submenu routine for the last border-bottom of the menu */
 7051:   border-bottom: 1px solid $data_table_dark; 
 7052: }
 7053: 
 7054: ol.LC_primary_menu li li p:hover {
 7055:   color:$button_hover;
 7056:   text-decoration:none;
 7057:   background-color:$data_table_dark;
 7058: }
 7059: 
 7060: ol.LC_primary_menu li li a:hover {
 7061:    color:$button_hover;
 7062:    background-color:$data_table_dark;
 7063: }
 7064: 
 7065: /* Font-size equal to the size of the predecessors*/
 7066: ol.LC_primary_menu li:hover li li {
 7067:   font-size: 100%;
 7068: }
 7069: 
 7070: ol.LC_primary_menu li img {
 7071:   vertical-align: bottom;
 7072:   height: 1.1em;
 7073:   margin: 0.2em 0 0 0;
 7074: }
 7075: 
 7076: ol.LC_primary_menu a {
 7077:   color: RGB(80, 80, 80);
 7078:   text-decoration: none;
 7079: }
 7080: 
 7081: ol.LC_primary_menu a.LC_new_message {
 7082:   font-weight:bold;
 7083:   color: darkred;
 7084: }
 7085: 
 7086: ol.LC_docs_parameters {
 7087:   margin-left: 0;
 7088:   padding: 0;
 7089:   list-style: none;
 7090: }
 7091: 
 7092: ol.LC_docs_parameters li {
 7093:   margin: 0;
 7094:   padding-right: 20px;
 7095:   display: inline;
 7096: }
 7097: 
 7098: ol.LC_docs_parameters li:before {
 7099:   content: "\\002022 \\0020";
 7100: }
 7101: 
 7102: li.LC_docs_parameters_title {
 7103:   font-weight: bold;
 7104: }
 7105: 
 7106: ol.LC_docs_parameters li.LC_docs_parameters_title:before {
 7107:   content: "";
 7108: }
 7109: 
 7110: ul#LC_secondary_menu {
 7111:   clear: right;
 7112:   color: $fontmenu;
 7113:   background: $tabbg;
 7114:   list-style: none;
 7115:   padding: 0;
 7116:   margin: 0;
 7117:   width: 100%;
 7118:   text-align: left;
 7119:   float: left;
 7120: }
 7121: 
 7122: ul#LC_secondary_menu li {
 7123:   font-weight: bold;
 7124:   line-height: 1.8em;
 7125:   border-right: 1px solid black;
 7126:   float: left;
 7127: }
 7128: 
 7129: ul#LC_secondary_menu li.LC_hoverable:hover, ul#LC_secondary_menu li.hover {
 7130:   background-color: $data_table_light;
 7131: }
 7132: 
 7133: ul#LC_secondary_menu li a {
 7134:   padding: 0 0.8em;
 7135: }
 7136: 
 7137: ul#LC_secondary_menu li ul {
 7138:   display: none;
 7139: }
 7140: 
 7141: ul#LC_secondary_menu li:hover ul, ul#LC_secondary_menu li.hover ul {
 7142:   display: block;
 7143:   position: absolute;
 7144:   margin: 0;
 7145:   padding: 0;
 7146:   list-style:none;
 7147:   float: none;
 7148:   background-color: $data_table_light;
 7149:   z-index: 2;
 7150:   margin-left: -1px;
 7151: }
 7152: 
 7153: ul#LC_secondary_menu li ul li {
 7154:   font-size: 90%;
 7155:   vertical-align: top;
 7156:   border-left: 1px solid black;
 7157:   border-right: 1px solid black;
 7158:   background-color: $data_table_light;
 7159:   list-style:none;
 7160:   float: none;
 7161: }
 7162: 
 7163: ul#LC_secondary_menu li ul li:hover, ul#LC_secondary_menu li ul li.hover {
 7164:   background-color: $data_table_dark;
 7165: }
 7166: 
 7167: ul.LC_TabContent {
 7168:   display:block;
 7169:   background: $sidebg;
 7170:   border-bottom: solid 1px $lg_border_color;
 7171:   list-style:none;
 7172:   margin: -1px -10px 0 -10px;
 7173:   padding: 0;
 7174: }
 7175: 
 7176: ul.LC_TabContent li,
 7177: ul.LC_TabContentBigger li {
 7178:   float:left;
 7179: }
 7180: 
 7181: ul#LC_secondary_menu li a {
 7182:   color: $fontmenu;
 7183:   text-decoration: none;
 7184: }
 7185: 
 7186: ul.LC_TabContent {
 7187:   min-height:20px;
 7188: }
 7189: 
 7190: ul.LC_TabContent li {
 7191:   vertical-align:middle;
 7192:   padding: 0 16px 0 10px;
 7193:   background-color:$tabbg;
 7194:   border-bottom:solid 1px $lg_border_color;
 7195:   border-left: solid 1px $font;
 7196: }
 7197: 
 7198: ul.LC_TabContent .right {
 7199:   float:right;
 7200: }
 7201: 
 7202: ul.LC_TabContent li a,
 7203: ul.LC_TabContent li {
 7204:   color:rgb(47,47,47);
 7205:   text-decoration:none;
 7206:   font-size:95%;
 7207:   font-weight:bold;
 7208:   min-height:20px;
 7209: }
 7210: 
 7211: ul.LC_TabContent li a:hover,
 7212: ul.LC_TabContent li a:focus {
 7213:   color: $button_hover;
 7214:   background:none;
 7215:   outline:none;
 7216: }
 7217: 
 7218: ul.LC_TabContent li:hover {
 7219:   color: $button_hover;
 7220:   cursor:pointer;
 7221: }
 7222: 
 7223: ul.LC_TabContent li.active {
 7224:   color: $font;
 7225:   background:#FFFFFF url(/adm/lonIcons/open.gif) no-repeat scroll right center;
 7226:   border-bottom:solid 1px #FFFFFF;
 7227:   cursor: default;
 7228: }
 7229: 
 7230: ul.LC_TabContent li.active a {
 7231:   color:$font;
 7232:   background:#FFFFFF;
 7233:   outline: none;
 7234: }
 7235: 
 7236: ul.LC_TabContent li.goback {
 7237:   float: left;
 7238:   border-left: none;
 7239: }
 7240: 
 7241: #maincoursedoc {
 7242:   clear:both;
 7243: }
 7244: 
 7245: ul.LC_TabContentBigger {
 7246:   display:block;
 7247:   list-style:none;
 7248:   padding: 0;
 7249: }
 7250: 
 7251: ul.LC_TabContentBigger li {
 7252:   vertical-align:bottom;
 7253:   height: 30px;
 7254:   font-size:110%;
 7255:   font-weight:bold;
 7256:   color: #737373;
 7257: }
 7258: 
 7259: ul.LC_TabContentBigger li.active {
 7260:   position: relative;
 7261:   top: 1px;
 7262: }
 7263: 
 7264: ul.LC_TabContentBigger li a {
 7265:   background:url('/adm/lonIcons/tabbgleft.gif') left bottom no-repeat;
 7266:   height: 30px;
 7267:   line-height: 30px;
 7268:   text-align: center;
 7269:   display: block;
 7270:   text-decoration: none;
 7271:   outline: none;  
 7272: }
 7273: 
 7274: ul.LC_TabContentBigger li.active a {
 7275:   background:url('/adm/lonIcons/tabbgleft.gif') left top no-repeat;
 7276:   color:$font;
 7277: }
 7278: 
 7279: ul.LC_TabContentBigger li b {
 7280:   background: url('/adm/lonIcons/tabbgright.gif') no-repeat right bottom;
 7281:   display: block;
 7282:   float: left;
 7283:   padding: 0 30px;
 7284:   border-bottom: 1px solid $lg_border_color;
 7285: }
 7286: 
 7287: ul.LC_TabContentBigger li:hover b {
 7288:   color:$button_hover;
 7289: }
 7290: 
 7291: ul.LC_TabContentBigger li.active b {
 7292:   background:url('/adm/lonIcons/tabbgright.gif') right top no-repeat;
 7293:   color:$font;
 7294:   border: 0;
 7295: }
 7296: 
 7297: 
 7298: ul.LC_CourseBreadcrumbs {
 7299:   background: $sidebg;
 7300:   height: 2em;
 7301:   padding-left: 10px;
 7302:   margin: 0;
 7303:   list-style-position: inside;
 7304: }
 7305: 
 7306: ol#LC_MenuBreadcrumbs,
 7307: ol#LC_PathBreadcrumbs {
 7308:   padding-left: 10px;
 7309:   margin: 0;
 7310:   height: 2.5em;  /* equal to #LC_breadcrumbs line-height */
 7311: }
 7312: 
 7313: ol#LC_MenuBreadcrumbs li,
 7314: ol#LC_PathBreadcrumbs li,
 7315: ul.LC_CourseBreadcrumbs li {
 7316:   display: inline;
 7317:   white-space: normal;  
 7318: }
 7319: 
 7320: ol#LC_MenuBreadcrumbs li a,
 7321: ul.LC_CourseBreadcrumbs li a {
 7322:   text-decoration: none;
 7323:   font-size:90%;
 7324: }
 7325: 
 7326: ol#LC_MenuBreadcrumbs h1 {
 7327:   display: inline;
 7328:   font-size: 90%;
 7329:   line-height: 2.5em;
 7330:   margin: 0;
 7331:   padding: 0;
 7332: }
 7333: 
 7334: ol#LC_PathBreadcrumbs li a {
 7335:   text-decoration:none;
 7336:   font-size:100%;
 7337:   font-weight:bold;
 7338: }
 7339: 
 7340: .LC_Box {
 7341:   border: solid 1px $lg_border_color;
 7342:   padding: 0 10px 10px 10px;
 7343: }
 7344: 
 7345: .LC_DocsBox {
 7346:   border: solid 1px $lg_border_color;
 7347:   padding: 0 0 10px 10px;
 7348: }
 7349: 
 7350: .LC_AboutMe_Image {
 7351:   float:left;
 7352:   margin-right:10px;
 7353: }
 7354: 
 7355: .LC_Clear_AboutMe_Image {
 7356:   clear:left;
 7357: }
 7358: 
 7359: dl.LC_ListStyleClean dt {
 7360:   padding-right: 5px;
 7361:   display: table-header-group;
 7362: }
 7363: 
 7364: dl.LC_ListStyleClean dd {
 7365:   display: table-row;
 7366: }
 7367: 
 7368: .LC_ListStyleClean,
 7369: .LC_ListStyleSimple,
 7370: .LC_ListStyleNormal,
 7371: .LC_ListStyleSpecial {
 7372:   /* display:block; */
 7373:   list-style-position: inside;
 7374:   list-style-type: none;
 7375:   overflow: hidden;
 7376:   padding: 0;
 7377: }
 7378: 
 7379: .LC_ListStyleSimple li,
 7380: .LC_ListStyleSimple dd,
 7381: .LC_ListStyleNormal li,
 7382: .LC_ListStyleNormal dd,
 7383: .LC_ListStyleSpecial li,
 7384: .LC_ListStyleSpecial dd {
 7385:   margin: 0;
 7386:   padding: 5px 5px 5px 10px;
 7387:   clear: both;
 7388: }
 7389: 
 7390: .LC_ListStyleClean li,
 7391: .LC_ListStyleClean dd {
 7392:   padding-top: 0;
 7393:   padding-bottom: 0;
 7394: }
 7395: 
 7396: .LC_ListStyleSimple dd,
 7397: .LC_ListStyleSimple li {
 7398:   border-bottom: solid 1px $lg_border_color;
 7399: }
 7400: 
 7401: .LC_ListStyleSpecial li,
 7402: .LC_ListStyleSpecial dd {
 7403:   list-style-type: none;
 7404:   background-color: RGB(220, 220, 220);
 7405:   margin-bottom: 4px;
 7406: }
 7407: 
 7408: table.LC_SimpleTable {
 7409:   margin:5px;
 7410:   border:solid 1px $lg_border_color;
 7411: }
 7412: 
 7413: table.LC_SimpleTable tr {
 7414:   padding: 0;
 7415:   border:solid 1px $lg_border_color;
 7416: }
 7417: 
 7418: table.LC_SimpleTable thead {
 7419:   background:rgb(220,220,220);
 7420: }
 7421: 
 7422: div.LC_columnSection {
 7423:   display: block;
 7424:   clear: both;
 7425:   overflow: hidden;
 7426:   margin: 0;
 7427: }
 7428: 
 7429: div.LC_columnSection>* {
 7430:   float: left;
 7431:   margin: 10px 20px 10px 0;
 7432:   overflow:hidden;
 7433: }
 7434: 
 7435: table em {
 7436:   font-weight: bold;
 7437:   font-style: normal;
 7438: }
 7439: 
 7440: table.LC_tableBrowseRes,
 7441: table.LC_tableOfContent {
 7442:   border:none;
 7443:   border-spacing: 1px;
 7444:   padding: 3px;
 7445:   background-color: #FFFFFF;
 7446:   font-size: 90%;
 7447: }
 7448: 
 7449: table.LC_tableOfContent {
 7450:   border-collapse: collapse;
 7451: }
 7452: 
 7453: table.LC_tableBrowseRes a,
 7454: table.LC_tableOfContent a {
 7455:   background-color: transparent;
 7456:   text-decoration: none;
 7457: }
 7458: 
 7459: table.LC_tableOfContent img {
 7460:   border: none;
 7461:   height: 1.3em;
 7462:   vertical-align: text-bottom;
 7463:   margin-right: 0.3em;
 7464: }
 7465: 
 7466: a#LC_content_toolbar_firsthomework {
 7467:   background-image:url(/res/adm/pages/open-first-problem.gif);
 7468: }
 7469: 
 7470: a#LC_content_toolbar_everything {
 7471:   background-image:url(/res/adm/pages/show-all.gif);
 7472: }
 7473: 
 7474: a#LC_content_toolbar_uncompleted {
 7475:   background-image:url(/res/adm/pages/show-incomplete-problems.gif);
 7476: }
 7477: 
 7478: #LC_content_toolbar_clearbubbles {
 7479:   background-image:url(/res/adm/pages/mark-discussionentries-read.gif);
 7480: }
 7481: 
 7482: a#LC_content_toolbar_changefolder {
 7483:   background : url(/res/adm/pages/close-all-folders.gif) top center ;
 7484: }
 7485: 
 7486: a#LC_content_toolbar_changefolder_toggled {
 7487:   background-image:url(/res/adm/pages/open-all-folders.gif);
 7488: }
 7489: 
 7490: a#LC_content_toolbar_edittoplevel {
 7491:   background-image:url(/res/adm/pages/edittoplevel.gif);
 7492: }
 7493: 
 7494: ul#LC_toolbar li a:hover {
 7495:   background-position: bottom center;
 7496: }
 7497: 
 7498: ul#LC_toolbar {
 7499:   padding: 0;
 7500:   margin: 2px;
 7501:   list-style:none;
 7502:   position:relative;
 7503:   background-color:white;
 7504:   overflow: auto;
 7505: }
 7506: 
 7507: ul#LC_toolbar li {
 7508:   border:1px solid white;
 7509:   padding: 0;
 7510:   margin: 0;
 7511:   float: left;
 7512:   display:inline;
 7513:   vertical-align:middle;
 7514:   white-space: nowrap;
 7515: }
 7516: 
 7517: 
 7518: a.LC_toolbarItem {
 7519:   display:block;
 7520:   padding: 0;
 7521:   margin: 0;
 7522:   height: 32px;
 7523:   width: 32px;
 7524:   color:white;
 7525:   border: none;
 7526:   background-repeat:no-repeat;
 7527:   background-color:transparent;
 7528: }
 7529: 
 7530: ul.LC_funclist {
 7531:     margin: 0;
 7532:     padding: 0.5em 1em 0.5em 0;
 7533: }
 7534: 
 7535: ul.LC_funclist > li:first-child {
 7536:     font-weight:bold; 
 7537:     margin-left:0.8em;
 7538: }
 7539: 
 7540: ul.LC_funclist + ul.LC_funclist {
 7541:     /* 
 7542:        left border as a seperator if we have more than
 7543:        one list 
 7544:     */
 7545:     border-left: 1px solid $sidebg;
 7546:     /* 
 7547:        this hides the left border behind the border of the 
 7548:        outer box if element is wrapped to the next 'line' 
 7549:     */
 7550:     margin-left: -1px;
 7551: }
 7552: 
 7553: ul.LC_funclist li {
 7554:   display: inline;
 7555:   white-space: nowrap;
 7556:   margin: 0 0 0 25px;
 7557:   line-height: 150%;
 7558: }
 7559: 
 7560: .LC_hidden {
 7561:   display: none;
 7562: }
 7563: 
 7564: .LCmodal-overlay {
 7565: 		position:fixed;
 7566: 		top:0;
 7567: 		right:0;
 7568: 		bottom:0;
 7569: 		left:0;
 7570: 		height:100%;
 7571: 		width:100%;
 7572: 		margin:0;
 7573: 		padding:0;
 7574: 		background:#999;
 7575: 		opacity:.75;
 7576: 		filter: alpha(opacity=75);
 7577: 		-moz-opacity: 0.75;
 7578: 		z-index:101;
 7579: }
 7580: 
 7581: * html .LCmodal-overlay {   
 7582: 		position: absolute;
 7583: 		height: expression(document.body.scrollHeight > document.body.offsetHeight ? document.body.scrollHeight : document.body.offsetHeight + 'px');
 7584: }
 7585: 
 7586: .LCmodal-window {
 7587: 		position:fixed;
 7588: 		top:50%;
 7589: 		left:50%;
 7590: 		margin:0;
 7591: 		padding:0;
 7592: 		z-index:102;
 7593: 	}
 7594: 
 7595: * html .LCmodal-window {
 7596: 		position:absolute;
 7597: }
 7598: 
 7599: .LCclose-window {
 7600: 		position:absolute;
 7601: 		width:32px;
 7602: 		height:32px;
 7603: 		right:8px;
 7604: 		top:8px;
 7605: 		background:transparent url('/res/adm/pages/process-stop.png') no-repeat scroll right top;
 7606: 		text-indent:-99999px;
 7607: 		overflow:hidden;
 7608: 		cursor:pointer;
 7609: }
 7610: 
 7611: /*
 7612:   styles used by TTH when "Default set of options to pass to tth/m
 7613:   when converting TeX" in course settings has been set
 7614: 
 7615:   option passed: -t
 7616: 
 7617: */
 7618: 
 7619: td div.comp { margin-top: -0.6ex; margin-bottom: -1ex;}
 7620: td div.comb { margin-top: -0.6ex; margin-bottom: -.6ex;}
 7621: td div.hrcomp { line-height: 0.9; margin-top: -0.8ex; margin-bottom: -1ex;}
 7622: td div.norm {line-height:normal;}
 7623: 
 7624: /*
 7625:   option passed -y3
 7626: */
 7627: 
 7628: span.roman {font-family: serif; font-style: normal; font-weight: normal;}
 7629: span.overacc2 {position: relative;  left: .8em; top: -1.2ex;}
 7630: span.overacc1 {position: relative;  left: .6em; top: -1.2ex;}
 7631: 
 7632: END
 7633: }
 7634: 
 7635: =pod
 7636: 
 7637: =item * &headtag()
 7638: 
 7639: Returns a uniform footer for LON-CAPA web pages.
 7640: 
 7641: Inputs: $title - optional title for the head
 7642:         $head_extra - optional extra HTML to put inside the <head>
 7643:         $args - optional arguments
 7644:             force_register - if is true call registerurl so the remote is 
 7645:                              informed
 7646:             redirect       -> array ref of
 7647:                                    1- seconds before redirect occurs
 7648:                                    2- url to redirect to
 7649:                                    3- whether the side effect should occur
 7650:                            (side effect of setting 
 7651:                                $env{'internal.head.redirect'} to the url 
 7652:                                redirected too)
 7653:             domain         -> force to color decorate a page for a specific
 7654:                                domain
 7655:             function       -> force usage of a specific rolish color scheme
 7656:             bgcolor        -> override the default page bgcolor
 7657:             no_auto_mt_title
 7658:                            -> prevent &mt()ing the title arg
 7659: 
 7660: =cut
 7661: 
 7662: sub headtag {
 7663:     my ($title,$head_extra,$args) = @_;
 7664:     
 7665:     my $function = $args->{'function'} || &get_users_function();
 7666:     my $domain   = $args->{'domain'}   || &determinedomain();
 7667:     my $bgcolor  = $args->{'bgcolor'}  || &designparm($function.'.pgbg',$domain);
 7668:     my $httphost = $args->{'use_absolute'};
 7669:     my $url = join(':',$env{'user.name'},$env{'user.domain'},
 7670: 		   $Apache::lonnet::perlvar{'lonVersion'},
 7671: 		   #time(),
 7672: 		   $env{'environment.color.timestamp'},
 7673: 		   $function,$domain,$bgcolor);
 7674: 
 7675:     $url = '/adm/css/'.&escape($url).'.css';
 7676: 
 7677:     my $result =
 7678: 	'<head>'.
 7679: 	&font_settings($args);
 7680: 
 7681:     my $inhibitprint;
 7682:     if ($args->{'print_suppress'}) {
 7683:         $inhibitprint = &print_suppression();
 7684:     }
 7685: 
 7686:     if (!$args->{'frameset'}) {
 7687: 	$result .= &Apache::lonhtmlcommon::htmlareaheaders();
 7688:     }
 7689:     if ($args->{'force_register'} && $env{'request.noversionuri'} !~ m{^/res/adm/pages/}) {
 7690:         $result .= Apache::lonxml::display_title();
 7691:     }
 7692:     if (!$args->{'no_nav_bar'} 
 7693: 	&& !$args->{'only_body'}
 7694: 	&& !$args->{'frameset'}) {
 7695: 	$result .= &help_menu_js($httphost);
 7696:         $result.=&modal_window();
 7697:         $result.=&togglebox_script();
 7698:         $result.=&wishlist_window();
 7699:         $result.=&LCprogressbarUpdate_script();
 7700:     } else {
 7701:         if ($args->{'add_modal'}) {
 7702:            $result.=&modal_window();
 7703:         }
 7704:         if ($args->{'add_wishlist'}) {
 7705:            $result.=&wishlist_window();
 7706:         }
 7707:         if ($args->{'add_togglebox'}) {
 7708:            $result.=&togglebox_script();
 7709:         }
 7710:         if ($args->{'add_progressbar'}) {
 7711:            $result.=&LCprogressbarUpdate_script();
 7712:         }
 7713:     }
 7714:     if (ref($args->{'redirect'})) {
 7715: 	my ($time,$url,$inhibit_continue) = @{$args->{'redirect'}};
 7716: 	$url = &Apache::lonenc::check_encrypt($url);
 7717: 	if (!$inhibit_continue) {
 7718: 	    $env{'internal.head.redirect'} = $url;
 7719: 	}
 7720: 	$result.=<<ADDMETA
 7721: <meta http-equiv="pragma" content="no-cache" />
 7722: <meta http-equiv="Refresh" content="$time; url=$url" />
 7723: ADDMETA
 7724:     } else {
 7725:         unless (($args->{'frameset'}) || ($args->{'js_ready'}) || ($args->{'only_body'}) || ($args->{'no_nav_bar'})) {
 7726:             my $requrl = $env{'request.uri'};
 7727:             if ($requrl eq '') {
 7728:                 $requrl = $ENV{'REQUEST_URI'};
 7729:                 $requrl =~ s/\?.+$//;
 7730:             }
 7731:             unless (($requrl =~ m{^/adm/(?:switchserver|login|authenticate|logout|groupsort|cleanup|helper|slotrequest|grades)(\?|$)}) ||
 7732:                     (($requrl =~ m{^/res/}) && (($env{'form.submitted'} eq 'scantron') ||
 7733:                      ($env{'form.grade_symb'}) || ($Apache::lonhomework::scantronmode)))) {
 7734:                 my $dom_in_use = $Apache::lonnet::perlvar{'lonDefDomain'};
 7735:                 unless (&Apache::lonnet::allowed('mau',$dom_in_use)) {
 7736:                     my %domdefs = &Apache::lonnet::get_domain_defaults($dom_in_use);
 7737:                     if (ref($domdefs{'offloadnow'}) eq 'HASH') {
 7738:                         my $lonhost = $Apache::lonnet::perlvar{'lonHostID'};
 7739:                         if ($domdefs{'offloadnow'}{$lonhost}) {
 7740:                             my $newserver = &Apache::lonnet::spareserver(30000,undef,1,$dom_in_use);
 7741:                             if (($newserver) && ($newserver ne $lonhost)) {
 7742:                                 my $numsec = 5;
 7743:                                 my $timeout = $numsec * 1000;
 7744:                                 my ($newurl,$locknum,%locks,$msg);
 7745:                                 if ($env{'request.role.adv'}) {
 7746:                                     ($locknum,%locks) = &Apache::lonnet::get_locks();
 7747:                                 }
 7748:                                 my $disable_submit = 0;
 7749:                                 if ($requrl =~ /$LONCAPA::assess_re/) {
 7750:                                     $disable_submit = 1;
 7751:                                 }
 7752:                                 if ($locknum) {
 7753:                                     my @lockinfo = sort(values(%locks));
 7754:                                     $msg = &mt('Once the following tasks are complete: ')."\\n".
 7755:                                            join(", ",sort(values(%locks)))."\\n".
 7756:                                            &mt('your session will be transferred to a different server, after you click "Roles".');
 7757:                                 } else {
 7758:                                     if (($requrl =~ m{^/res/}) && ($env{'form.submitted'} =~ /^part_/)) {
 7759:                                         $msg = &mt('Your LON-CAPA submission has been recorded')."\\n";
 7760:                                     }
 7761:                                     $msg .= &mt('Your current LON-CAPA session will be transferred to a different server in [quant,_1,second].',$numsec);
 7762:                                     $newurl = '/adm/switchserver?otherserver='.$newserver;
 7763:                                     if (($env{'request.role'}) && ($env{'request.role'} ne 'cm')) {
 7764:                                         $newurl .= '&role='.$env{'request.role'};
 7765:                                     }
 7766:                                     if ($env{'request.symb'}) {
 7767:                                         $newurl .= '&symb='.$env{'request.symb'};
 7768:                                     } else {
 7769:                                         $newurl .= '&origurl='.$requrl;
 7770:                                     }
 7771:                                 }
 7772:                                 $result.=<<OFFLOAD
 7773: <meta http-equiv="pragma" content="no-cache" />
 7774: <script type="text/javascript">
 7775: // <![CDATA[
 7776: function LC_Offload_Now() {
 7777:     var dest = "$newurl";
 7778:     if (dest != '') {
 7779:         window.location.href="$newurl";
 7780:     }
 7781: }
 7782: \$(document).ready(function () {
 7783:     window.alert('$msg');
 7784:     if ($disable_submit) {
 7785:         \$(".LC_hwk_submit").prop("disabled", true);
 7786:         \$( ".LC_textline" ).prop( "readonly", "readonly");
 7787:     }
 7788:     setTimeout('LC_Offload_Now()', $timeout);
 7789: });
 7790: // ]]>
 7791: </script>
 7792: OFFLOAD
 7793:                             }
 7794:                         }
 7795:                     }
 7796:                 }
 7797:             }
 7798:         }
 7799:     }
 7800:     if (!defined($title)) {
 7801: 	$title = 'The LearningOnline Network with CAPA';
 7802:     }
 7803:     if (!$args->{'no_auto_mt_title'}) { $title = &mt($title); }
 7804:     $result .= '<title> LON-CAPA '.$title.'</title>'
 7805: 	.'<link rel="stylesheet" type="text/css" href="'.$url.'"';
 7806:     if (!$args->{'frameset'}) {
 7807:         $result .= ' /';
 7808:     }
 7809:     $result .= '>' 
 7810:         .$inhibitprint
 7811: 	.$head_extra;
 7812:     if ($env{'browser.mobile'}) {
 7813:         $result .= '
 7814: <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=0, minimum-scale=1.0, maximum-scale=1.0">
 7815: <meta name="apple-mobile-web-app-capable" content="yes" />';
 7816:     }
 7817:     return $result.'</head>';
 7818: }
 7819: 
 7820: =pod
 7821: 
 7822: =item * &font_settings()
 7823: 
 7824: Returns neccessary <meta> to set the proper encoding
 7825: 
 7826: Inputs: optional reference to HASH -- $args passed to &headtag()
 7827: 
 7828: =cut
 7829: 
 7830: sub font_settings {
 7831:     my ($args) = @_;
 7832:     my $headerstring='';
 7833:     if ((!$env{'browser.mathml'} && $env{'browser.unicode'}) ||
 7834:         ((ref($args) eq 'HASH') && ($args->{'browser.unicode'}))) {
 7835:         $headerstring.=
 7836:             '<meta http-equiv="Content-Type" content="text/html; charset=utf-8"';
 7837:         if (!$args->{'frameset'}) {
 7838: 	    $headerstring.= ' /';
 7839:         }
 7840: 	$headerstring .= '>'."\n";
 7841:     }
 7842:     return $headerstring;
 7843: }
 7844: 
 7845: =pod
 7846: 
 7847: =item * &print_suppression()
 7848: 
 7849: In course context returns css which causes the body to be blank when media="print",
 7850: if printout generation is unavailable for the current resource.
 7851: 
 7852: This could be because:
 7853: 
 7854: (a) printstartdate is in the future
 7855: 
 7856: (b) printenddate is in the past
 7857: 
 7858: (c) there is an active exam block with "printout"
 7859: functionality blocked
 7860: 
 7861: Users with pav, pfo or evb privileges are exempt.
 7862: 
 7863: Inputs: none
 7864: 
 7865: =cut
 7866: 
 7867: 
 7868: sub print_suppression {
 7869:     my $noprint;
 7870:     if ($env{'request.course.id'}) {
 7871:         my $scope = $env{'request.course.id'};
 7872:         if ((&Apache::lonnet::allowed('pav',$scope)) ||
 7873:             (&Apache::lonnet::allowed('pfo',$scope))) {
 7874:             return;
 7875:         }
 7876:         if ($env{'request.course.sec'} ne '') {
 7877:             $scope .= "/$env{'request.course.sec'}";
 7878:             if ((&Apache::lonnet::allowed('pav',$scope)) ||
 7879:                 (&Apache::lonnet::allowed('pfo',$scope))) {
 7880:                 return;
 7881:             }
 7882:         }
 7883:         my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 7884:         my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 7885:         my $blocked = &blocking_status('printout',$cnum,$cdom,undef,1);
 7886:         if ($blocked) {
 7887:             my $checkrole = "cm./$cdom/$cnum";
 7888:             if ($env{'request.course.sec'} ne '') {
 7889:                 $checkrole .= "/$env{'request.course.sec'}";
 7890:             }
 7891:             unless ((&Apache::lonnet::allowed('evb',undef,undef,$checkrole)) &&
 7892:                     ($env{'request.role'} !~ m{^st\./$cdom/$cnum})) {
 7893:                 $noprint = 1;
 7894:             }
 7895:         }
 7896:         unless ($noprint) {
 7897:             my $symb = &Apache::lonnet::symbread();
 7898:             if ($symb ne '') {
 7899:                 my $navmap = Apache::lonnavmaps::navmap->new();
 7900:                 if (ref($navmap)) {
 7901:                     my $res = $navmap->getBySymb($symb);
 7902:                     if (ref($res)) {
 7903:                         if (!$res->resprintable()) {
 7904:                             $noprint = 1;
 7905:                         }
 7906:                     }
 7907:                 }
 7908:             }
 7909:         }
 7910:         if ($noprint) {
 7911:             return <<"ENDSTYLE";
 7912: <style type="text/css" media="print">
 7913:     body { display:none }
 7914: </style>
 7915: ENDSTYLE
 7916:         }
 7917:     }
 7918:     return;
 7919: }
 7920: 
 7921: =pod
 7922: 
 7923: =item * &xml_begin()
 7924: 
 7925: Returns the needed doctype and <html>
 7926: 
 7927: Inputs: none
 7928: 
 7929: =cut
 7930: 
 7931: sub xml_begin {
 7932:     my ($is_frameset) = @_;
 7933:     my $output='';
 7934: 
 7935:     if ($env{'browser.mathml'}) {
 7936: 	$output='<?xml version="1.0"?>'
 7937:             #.'<?xml-stylesheet type="text/css" href="/adm/MathML/mathml.css"?>'."\n"
 7938: #            .'<!DOCTYPE html SYSTEM "/adm/MathML/mathml.dtd" '
 7939:             
 7940: #	    .'<!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">] >'
 7941: 	    .'<!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">'
 7942:             .'<html xmlns:math="http://www.w3.org/1998/Math/MathML" ' 
 7943: 	    .'xmlns="http://www.w3.org/1999/xhtml">';
 7944:     } elsif ($is_frameset) {
 7945:         $output='<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Frameset//EN" "http://www.w3.org/TR/html4/frameset.dtd">'."\n".
 7946:                 '<html>'."\n";
 7947:     } else {
 7948: 	$output='<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">'."\n".
 7949:                 '<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">'."\n";
 7950:     }
 7951:     return $output;
 7952: }
 7953: 
 7954: =pod
 7955: 
 7956: =item * &start_page()
 7957: 
 7958: Returns a complete <html> .. <body> section for LON-CAPA web pages.
 7959: 
 7960: Inputs:
 7961: 
 7962: =over 4
 7963: 
 7964: $title - optional title for the page
 7965: 
 7966: $head_extra - optional extra HTML to incude inside the <head>
 7967: 
 7968: $args - additional optional args supported are:
 7969: 
 7970: =over 8
 7971: 
 7972:              only_body      -> is true will set &bodytag() onlybodytag
 7973:                                     arg on
 7974:              no_nav_bar     -> is true will set &bodytag() no_nav_bar arg on
 7975:              add_entries    -> additional attributes to add to the  <body>
 7976:              domain         -> force to color decorate a page for a 
 7977:                                     specific domain
 7978:              function       -> force usage of a specific rolish color
 7979:                                     scheme
 7980:              redirect       -> see &headtag()
 7981:              bgcolor        -> override the default page bg color
 7982:              js_ready       -> return a string ready for being used in 
 7983:                                     a javascript writeln
 7984:              html_encode    -> return a string ready for being used in 
 7985:                                     a html attribute
 7986:              force_register -> if is true will turn on the &bodytag()
 7987:                                     $forcereg arg
 7988:              frameset       -> if true will start with a <frameset>
 7989:                                     rather than <body>
 7990:              skip_phases    -> hash ref of 
 7991:                                     head -> skip the <html><head> generation
 7992:                                     body -> skip all <body> generation
 7993:              no_auto_mt_title -> prevent &mt()ing the title arg
 7994:              inherit_jsmath -> when creating popup window in a page,
 7995:                                     should it have jsmath forced on by the
 7996:                                     current page
 7997:              bread_crumbs ->             Array containing breadcrumbs
 7998:              bread_crumbs_component ->  if exists show it as headline else show only the breadcrumbs
 7999:              group          -> includes the current group, if page is for a 
 8000:                                specific group  
 8001: 
 8002: =back
 8003: 
 8004: =back
 8005: 
 8006: =cut
 8007: 
 8008: sub start_page {
 8009:     my ($title,$head_extra,$args) = @_;
 8010:     #&Apache::lonnet::logthis("start_page ".join(':',caller(0)));
 8011: 
 8012:     $env{'internal.start_page'}++;
 8013:     my ($result,@advtools);
 8014: 
 8015:     if (! exists($args->{'skip_phases'}{'head'}) ) {
 8016:         $result .= &xml_begin($args->{'frameset'}) . &headtag($title, $head_extra, $args);
 8017:     }
 8018:     
 8019:     if (! exists($args->{'skip_phases'}{'body'}) ) {
 8020: 	if ($args->{'frameset'}) {
 8021: 	    my $attr_string = &make_attr_string($args->{'force_register'},
 8022: 						$args->{'add_entries'});
 8023: 	    $result .= "\n<frameset $attr_string>\n";
 8024:         } else {
 8025:             $result .=
 8026:                 &bodytag($title, 
 8027:                          $args->{'function'},       $args->{'add_entries'},
 8028:                          $args->{'only_body'},      $args->{'domain'},
 8029:                          $args->{'force_register'}, $args->{'no_nav_bar'},
 8030:                          $args->{'bgcolor'},        $args,
 8031:                          \@advtools);
 8032:         }
 8033:     }
 8034: 
 8035:     if ($args->{'js_ready'}) {
 8036: 		$result = &js_ready($result);
 8037:     }
 8038:     if ($args->{'html_encode'}) {
 8039: 		$result = &html_encode($result);
 8040:     }
 8041: 
 8042:     # Preparation for new and consistent functionlist at top of screen
 8043:     # if ($args->{'functionlist'}) {
 8044:     #            $result .= &build_functionlist();
 8045:     #}
 8046: 
 8047:     # Don't add anything more if only_body wanted or in const space
 8048:     return $result if    $args->{'only_body'} 
 8049:                       || $env{'request.state'} eq 'construct';
 8050: 
 8051:     #Breadcrumbs
 8052:     if (exists($args->{'bread_crumbs'}) or exists($args->{'bread_crumbs_component'})) {
 8053: 		&Apache::lonhtmlcommon::clear_breadcrumbs();
 8054: 		#if any br links exists, add them to the breadcrumbs
 8055: 		if (exists($args->{'bread_crumbs'}) and ref($args->{'bread_crumbs'}) eq 'ARRAY') {         
 8056: 			foreach my $crumb (@{$args->{'bread_crumbs'}}){
 8057: 				&Apache::lonhtmlcommon::add_breadcrumb($crumb);
 8058: 			}
 8059: 		}
 8060:                 # if @advtools array contains items add then to the breadcrumbs
 8061:                 if (@advtools > 0) {
 8062:                     &Apache::lonmenu::advtools_crumbs(@advtools);
 8063:                 }
 8064: 
 8065: 		#if bread_crumbs_component exists show it as headline else show only the breadcrumbs
 8066: 		if(exists($args->{'bread_crumbs_component'})){
 8067: 			$result .= &Apache::lonhtmlcommon::breadcrumbs($args->{'bread_crumbs_component'});
 8068: 		}else{
 8069: 			$result .= &Apache::lonhtmlcommon::breadcrumbs();
 8070: 		}
 8071:     }
 8072:     return $result;
 8073: }
 8074: 
 8075: sub end_page {
 8076:     my ($args) = @_;
 8077:     $env{'internal.end_page'}++;
 8078:     my $result;
 8079:     if ($args->{'discussion'}) {
 8080: 	my ($target,$parser);
 8081: 	if (ref($args->{'discussion'})) {
 8082: 	    ($target,$parser) =($args->{'discussion'}{'target'},
 8083: 				$args->{'discussion'}{'parser'});
 8084: 	}
 8085: 	$result .= &Apache::lonxml::xmlend($target,$parser);
 8086:     }
 8087:     if ($args->{'frameset'}) {
 8088: 	$result .= '</frameset>';
 8089:     } else {
 8090: 	$result .= &endbodytag($args);
 8091:     }
 8092:     unless ($args->{'notbody'}) {
 8093:         $result .= "\n</html>";
 8094:     }
 8095: 
 8096:     if ($args->{'js_ready'}) {
 8097: 	$result = &js_ready($result);
 8098:     }
 8099: 
 8100:     if ($args->{'html_encode'}) {
 8101: 	$result = &html_encode($result);
 8102:     }
 8103: 
 8104:     return $result;
 8105: }
 8106: 
 8107: sub wishlist_window {
 8108:     return(<<'ENDWISHLIST');
 8109: <script type="text/javascript">
 8110: // <![CDATA[
 8111: // <!-- BEGIN LON-CAPA Internal
 8112: function set_wishlistlink(title, path) {
 8113:     if (!title) {
 8114:         title = document.title;
 8115:         title = title.replace(/^LON-CAPA /,'');
 8116:     }
 8117:     title = encodeURIComponent(title);
 8118:     title = title.replace("'","\\\'");
 8119:     if (!path) {
 8120:         path = location.pathname;
 8121:     }
 8122:     path = encodeURIComponent(path);
 8123:     path = path.replace("'","\\\'");
 8124:     Win = window.open('/adm/wishlist?mode=newLink&setTitle='+title+'&setPath='+path,
 8125:                       'wishlistNewLink','width=560,height=350,scrollbars=0');
 8126: }
 8127: // END LON-CAPA Internal -->
 8128: // ]]>
 8129: </script>
 8130: ENDWISHLIST
 8131: }
 8132: 
 8133: sub modal_window {
 8134:     return(<<'ENDMODAL');
 8135: <script type="text/javascript">
 8136: // <![CDATA[
 8137: // <!-- BEGIN LON-CAPA Internal
 8138: var modalWindow = {
 8139: 	parent:"body",
 8140: 	windowId:null,
 8141: 	content:null,
 8142: 	width:null,
 8143: 	height:null,
 8144: 	close:function()
 8145: 	{
 8146: 	        $(".LCmodal-window").remove();
 8147: 	        $(".LCmodal-overlay").remove();
 8148: 	},
 8149: 	open:function()
 8150: 	{
 8151: 		var modal = "";
 8152: 		modal += "<div class=\"LCmodal-overlay\"></div>";
 8153: 		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;\">";
 8154: 		modal += this.content;
 8155: 		modal += "</div>";	
 8156: 
 8157: 		$(this.parent).append(modal);
 8158: 
 8159: 		$(".LCmodal-window").append("<a class=\"LCclose-window\"></a>");
 8160: 		$(".LCclose-window").click(function(){modalWindow.close();});
 8161: 		$(".LCmodal-overlay").click(function(){modalWindow.close();});
 8162: 	}
 8163: };
 8164: 	var openMyModal = function(source,width,height,scrolling,transparency,style)
 8165: 	{
 8166:                 source = source.replace("'","&#39;");
 8167: 		modalWindow.windowId = "myModal";
 8168: 		modalWindow.width = width;
 8169: 		modalWindow.height = height;
 8170: 		modalWindow.content = "<iframe width='"+width+"' height='"+height+"' frameborder='0' scrolling='"+scrolling+"' allowtransparency='"+transparency+"' src='" + source + "' style='"+style+"'></iframe>";
 8171: 		modalWindow.open();
 8172: 	};
 8173: // END LON-CAPA Internal -->
 8174: // ]]>
 8175: </script>
 8176: ENDMODAL
 8177: }
 8178: 
 8179: sub modal_link {
 8180:     my ($link,$linktext,$width,$height,$target,$scrolling,$title,$transparency,$style)=@_;
 8181:     unless ($width) { $width=480; }
 8182:     unless ($height) { $height=400; }
 8183:     unless ($scrolling) { $scrolling='yes'; }
 8184:     unless ($transparency) { $transparency='true'; }
 8185: 
 8186:     my $target_attr;
 8187:     if (defined($target)) {
 8188:         $target_attr = 'target="'.$target.'"';
 8189:     }
 8190:     return <<"ENDLINK";
 8191: <a href="$link" $target_attr title="$title" onclick="javascript:openMyModal('$link',$width,$height,'$scrolling','$transparency','$style'); return false;">
 8192:            $linktext</a>
 8193: ENDLINK
 8194: }
 8195: 
 8196: sub modal_adhoc_script {
 8197:     my ($funcname,$width,$height,$content)=@_;
 8198:     return (<<ENDADHOC);
 8199: <script type="text/javascript">
 8200: // <![CDATA[
 8201:         var $funcname = function()
 8202:         {
 8203:                 modalWindow.windowId = "myModal";
 8204:                 modalWindow.width = $width;
 8205:                 modalWindow.height = $height;
 8206:                 modalWindow.content = '$content';
 8207:                 modalWindow.open();
 8208:         };  
 8209: // ]]>
 8210: </script>
 8211: ENDADHOC
 8212: }
 8213: 
 8214: sub modal_adhoc_inner {
 8215:     my ($funcname,$width,$height,$content)=@_;
 8216:     my $innerwidth=$width-20;
 8217:     $content=&js_ready(
 8218:                  &start_page('Dialog',undef,{'only_body'=>1,'bgcolor'=>'#FFFFFF'}).
 8219:                  &start_scrollbox($width.'px',$innerwidth.'px',$height.'px','myModal','#FFFFFF',undef,1).
 8220:                  $content.
 8221:                  &end_scrollbox().
 8222:                  &end_page()
 8223:              );
 8224:     return &modal_adhoc_script($funcname,$width,$height,$content);
 8225: }
 8226: 
 8227: sub modal_adhoc_window {
 8228:     my ($funcname,$width,$height,$content,$linktext)=@_;
 8229:     return &modal_adhoc_inner($funcname,$width,$height,$content).
 8230:            "<a href=\"javascript:$funcname();void(0);\">".$linktext."</a>";
 8231: }
 8232: 
 8233: sub modal_adhoc_launch {
 8234:     my ($funcname,$width,$height,$content)=@_;
 8235:     return &modal_adhoc_inner($funcname,$width,$height,$content).(<<ENDLAUNCH);
 8236: <script type="text/javascript">
 8237: // <![CDATA[
 8238: $funcname();
 8239: // ]]>
 8240: </script>
 8241: ENDLAUNCH
 8242: }
 8243: 
 8244: sub modal_adhoc_close {
 8245:     return (<<ENDCLOSE);
 8246: <script type="text/javascript">
 8247: // <![CDATA[
 8248: modalWindow.close();
 8249: // ]]>
 8250: </script>
 8251: ENDCLOSE
 8252: }
 8253: 
 8254: sub togglebox_script {
 8255:    return(<<ENDTOGGLE);
 8256: <script type="text/javascript"> 
 8257: // <![CDATA[
 8258: function LCtoggleDisplay(id,hidetext,showtext) {
 8259:    link = document.getElementById(id + "link").childNodes[0];
 8260:    with (document.getElementById(id).style) {
 8261:       if (display == "none" ) {
 8262:           display = "inline";
 8263:           link.nodeValue = hidetext;
 8264:         } else {
 8265:           display = "none";
 8266:           link.nodeValue = showtext;
 8267:        }
 8268:    }
 8269: }
 8270: // ]]>
 8271: </script>
 8272: ENDTOGGLE
 8273: }
 8274: 
 8275: sub start_togglebox {
 8276:     my ($id,$heading,$headerbg,$hidetext,$showtext)=@_;
 8277:     unless ($heading) { $heading=''; } else { $heading.=' '; }
 8278:     unless ($showtext) { $showtext=&mt('show'); }
 8279:     unless ($hidetext) { $hidetext=&mt('hide'); }
 8280:     unless ($headerbg) { $headerbg='#FFFFFF'; }
 8281:     return &start_data_table().
 8282:            &start_data_table_header_row().
 8283:            '<td bgcolor="'.$headerbg.'">'.$heading.
 8284:            '[<a id="'.$id.'link" href="javascript:LCtoggleDisplay(\''.$id.'\',\''.$hidetext.'\',\''.
 8285:            $showtext.'\')">'.$showtext.'</a>]</td>'.
 8286:            &end_data_table_header_row().
 8287:            '<tr id="'.$id.'" style="display:none""><td>';
 8288: }
 8289: 
 8290: sub end_togglebox {
 8291:     return '</td></tr>'.&end_data_table();
 8292: }
 8293: 
 8294: sub LCprogressbar_script {
 8295:    my ($id)=@_;
 8296:    return(<<ENDPROGRESS);
 8297: <script type="text/javascript">
 8298: // <![CDATA[
 8299: \$('#progressbar$id').progressbar({
 8300:   value: 0,
 8301:   change: function(event, ui) {
 8302:     var newVal = \$(this).progressbar('option', 'value');
 8303:     \$('.pblabel', this).text(LCprogressTxt);
 8304:   }
 8305: });
 8306: // ]]>
 8307: </script>
 8308: ENDPROGRESS
 8309: }
 8310: 
 8311: sub LCprogressbarUpdate_script {
 8312:    return(<<ENDPROGRESSUPDATE);
 8313: <style type="text/css">
 8314: .ui-progressbar { position:relative; }
 8315: .pblabel { position: absolute; width: 100%; text-align: center; line-height: 1.9em; }
 8316: </style>
 8317: <script type="text/javascript">
 8318: // <![CDATA[
 8319: var LCprogressTxt='---';
 8320: 
 8321: function LCupdateProgress(percent,progresstext,id) {
 8322:    LCprogressTxt=progresstext;
 8323:    \$('#progressbar'+id).progressbar('value',percent);
 8324: }
 8325: // ]]>
 8326: </script>
 8327: ENDPROGRESSUPDATE
 8328: }
 8329: 
 8330: my $LClastpercent;
 8331: my $LCidcnt;
 8332: my $LCcurrentid;
 8333: 
 8334: sub LCprogressbar {
 8335:     my ($r)=(@_);
 8336:     $LClastpercent=0;
 8337:     $LCidcnt++;
 8338:     $LCcurrentid=$$.'_'.$LCidcnt;
 8339:     my $starting=&mt('Starting');
 8340:     my $content=(<<ENDPROGBAR);
 8341:   <div id="progressbar$LCcurrentid">
 8342:     <span class="pblabel">$starting</span>
 8343:   </div>
 8344: ENDPROGBAR
 8345:     &r_print($r,$content.&LCprogressbar_script($LCcurrentid));
 8346: }
 8347: 
 8348: sub LCprogressbarUpdate {
 8349:     my ($r,$val,$text)=@_;
 8350:     unless ($val) { 
 8351:        if ($LClastpercent) {
 8352:            $val=$LClastpercent;
 8353:        } else {
 8354:            $val=0;
 8355:        }
 8356:     }
 8357:     if ($val<0) { $val=0; }
 8358:     if ($val>100) { $val=0; }
 8359:     $LClastpercent=$val;
 8360:     unless ($text) { $text=$val.'%'; }
 8361:     $text=&js_ready($text);
 8362:     &r_print($r,<<ENDUPDATE);
 8363: <script type="text/javascript">
 8364: // <![CDATA[
 8365: LCupdateProgress($val,'$text','$LCcurrentid');
 8366: // ]]>
 8367: </script>
 8368: ENDUPDATE
 8369: }
 8370: 
 8371: sub LCprogressbarClose {
 8372:     my ($r)=@_;
 8373:     $LClastpercent=0;
 8374:     &r_print($r,<<ENDCLOSE);
 8375: <script type="text/javascript">
 8376: // <![CDATA[
 8377: \$("#progressbar$LCcurrentid").hide('slow'); 
 8378: // ]]>
 8379: </script>
 8380: ENDCLOSE
 8381: }
 8382: 
 8383: sub r_print {
 8384:     my ($r,$to_print)=@_;
 8385:     if ($r) {
 8386:       $r->print($to_print);
 8387:       $r->rflush();
 8388:     } else {
 8389:       print($to_print);
 8390:     }
 8391: }
 8392: 
 8393: sub html_encode {
 8394:     my ($result) = @_;
 8395: 
 8396:     $result = &HTML::Entities::encode($result,'<>&"');
 8397:     
 8398:     return $result;
 8399: }
 8400: 
 8401: sub js_ready {
 8402:     my ($result) = @_;
 8403: 
 8404:     $result =~ s/[\n\r]/ /xmsg;
 8405:     $result =~ s/\\/\\\\/xmsg;
 8406:     $result =~ s/'/\\'/xmsg;
 8407:     $result =~ s{</}{<\\/}xmsg;
 8408:     
 8409:     return $result;
 8410: }
 8411: 
 8412: sub validate_page {
 8413:     if (  exists($env{'internal.start_page'})
 8414: 	  &&     $env{'internal.start_page'} > 1) {
 8415: 	&Apache::lonnet::logthis('start_page called multiple times '.
 8416: 				 $env{'internal.start_page'}.' '.
 8417: 				 $ENV{'request.filename'});
 8418:     }
 8419:     if (  exists($env{'internal.end_page'})
 8420: 	  &&     $env{'internal.end_page'} > 1) {
 8421: 	&Apache::lonnet::logthis('end_page called multiple times '.
 8422: 				 $env{'internal.end_page'}.' '.
 8423: 				 $env{'request.filename'});
 8424:     }
 8425:     if (     exists($env{'internal.start_page'})
 8426: 	&& ! exists($env{'internal.end_page'})) {
 8427: 	&Apache::lonnet::logthis('start_page called without end_page '.
 8428: 				 $env{'request.filename'});
 8429:     }
 8430:     if (   ! exists($env{'internal.start_page'})
 8431: 	&&   exists($env{'internal.end_page'})) {
 8432: 	&Apache::lonnet::logthis('end_page called without start_page'.
 8433: 				 $env{'request.filename'});
 8434:     }
 8435: }
 8436: 
 8437: 
 8438: sub start_scrollbox {
 8439:     my ($outerwidth,$width,$height,$id,$bgcolor,$cursor,$needjsready) = @_;
 8440:     unless ($outerwidth) { $outerwidth='520px'; }
 8441:     unless ($width) { $width='500px'; }
 8442:     unless ($height) { $height='200px'; }
 8443:     my ($table_id,$div_id,$tdcol);
 8444:     if ($id ne '') {
 8445:         $table_id = ' id="table_'.$id.'"';
 8446:         $div_id = ' id="div_'.$id.'"';
 8447:     }
 8448:     if ($bgcolor ne '') {
 8449:         $tdcol = "background-color: $bgcolor;";
 8450:     }
 8451:     my $nicescroll_js;
 8452:     if ($env{'browser.mobile'}) {
 8453:         $nicescroll_js = &nicescroll_javascript('div_'.$id,$cursor,$needjsready);
 8454:     }
 8455:     return <<"END";
 8456: $nicescroll_js
 8457: 
 8458: <table style="width: $outerwidth; border: 1px solid none;"$table_id><tr><td style="width: $width;$tdcol">
 8459: <div style="overflow:auto; width:$width; height:$height;"$div_id>
 8460: END
 8461: }
 8462: 
 8463: sub end_scrollbox {
 8464:     return '</div></td></tr></table>';
 8465: }
 8466: 
 8467: sub nicescroll_javascript {
 8468:     my ($id,$cursor,$needjsready,$framecheck,$location) = @_;
 8469:     my %options;
 8470:     if (ref($cursor) eq 'HASH') {
 8471:         %options = %{$cursor};
 8472:     }
 8473:     unless ($options{'railalign'} =~ /^left|right$/) {
 8474:         $options{'railalign'} = 'left';
 8475:     }
 8476:     unless ($options{'cursorcolor'} =~ /^\#\w+$/) {
 8477:         my $function  = &get_users_function();
 8478:         $options{'cursorcolor'} = &designparm($function.'.sidebg',$env{'request.role.domain'});
 8479:         unless ($options{'cursorcolor'} =~ /^\#\w+$/) {
 8480:             $options{'cursorcolor'} = '#00F';
 8481:         }
 8482:     }
 8483:     if ($options{'cursoropacity'} =~ /^[\d.]+$/) {
 8484:         unless ($options{'cursoropacity'} >= 0.0 && $options{'cursoropacity'} <=1.0) {
 8485:             $options{'cursoropacity'}='1.0';
 8486:         }
 8487:     } else {
 8488:         $options{'cursoropacity'}='1.0';
 8489:     }
 8490:     if ($options{'cursorfixedheight'} eq 'none') {
 8491:         delete($options{'cursorfixedheight'});
 8492:     } else {
 8493:         unless ($options{'cursorfixedheight'} =~ /^\d+$/) { $options{'cursorfixedheight'}='50'; }
 8494:     }
 8495:     unless ($options{'railoffset'} =~ /^{[\w\:\d\-,]+}$/) {
 8496:         delete($options{'railoffset'});
 8497:     }
 8498:     my @niceoptions;
 8499:     while (my($key,$value) = each(%options)) {
 8500:         if ($value =~ /^\{.+\}$/) {
 8501:             push(@niceoptions,$key.':'.$value);
 8502:         } else {
 8503:             push(@niceoptions,$key.':"'.$value.'"');
 8504:         }
 8505:     }
 8506:     my $nicescroll_js = '
 8507: $(document).ready(
 8508:       function() {
 8509:           $("#'.$id.'").niceScroll({'.join(',',@niceoptions).'});
 8510:       }
 8511: );
 8512: ';
 8513:     if ($framecheck) {
 8514:         $nicescroll_js .= '
 8515: function expand_div(caller) {
 8516:     if (top === self) {
 8517:         document.getElementById("'.$id.'").style.width = "auto";
 8518:         document.getElementById("'.$id.'").style.height = "auto";
 8519:     } else {
 8520:         try {
 8521:             if (parent.frames) {
 8522:                 if (parent.frames.length > 1) {
 8523:                     var framesrc = parent.frames[1].location.href;
 8524:                     var currsrc = framesrc.replace(/\#.*$/,"");
 8525:                     if ((caller == "search") || (currsrc == "'.$location.'")) {
 8526:                         document.getElementById("'.$id.'").style.width = "auto";
 8527:                         document.getElementById("'.$id.'").style.height = "auto";
 8528:                     }
 8529:                 }
 8530:             }
 8531:         } catch (e) {
 8532:             return;
 8533:         }
 8534:     }
 8535:     return;
 8536: }
 8537: ';
 8538:     }
 8539:     if ($needjsready) {
 8540:         $nicescroll_js = '
 8541: <script type="text/javascript">'."\n".$nicescroll_js."\n</script>\n";
 8542:     } else {
 8543:         $nicescroll_js = &Apache::lonhtmlcommon::scripttag($nicescroll_js);
 8544:     }
 8545:     return $nicescroll_js;
 8546: }
 8547: 
 8548: sub simple_error_page {
 8549:     my ($r,$title,$msg,$args) = @_;
 8550:     if (ref($args) eq 'HASH') {
 8551:         if (!$args->{'no_auto_mt_msg'}) { $msg = &mt($msg); }
 8552:     } else {
 8553:         $msg = &mt($msg);
 8554:     }
 8555: 
 8556:     my $page =
 8557: 	&Apache::loncommon::start_page($title).
 8558: 	'<p class="LC_error">'.$msg.'</p>'.
 8559: 	&Apache::loncommon::end_page();
 8560:     if (ref($r)) {
 8561: 	$r->print($page);
 8562: 	return;
 8563:     }
 8564:     return $page;
 8565: }
 8566: 
 8567: {
 8568:     my @row_count;
 8569: 
 8570:     sub start_data_table_count {
 8571:         unshift(@row_count, 0);
 8572:         return;
 8573:     }
 8574: 
 8575:     sub end_data_table_count {
 8576:         shift(@row_count);
 8577:         return;
 8578:     }
 8579: 
 8580:     sub start_data_table {
 8581: 	my ($add_class,$id) = @_;
 8582: 	my $css_class = (join(' ','LC_data_table',$add_class));
 8583:         my $table_id;
 8584:         if (defined($id)) {
 8585:             $table_id = ' id="'.$id.'"';
 8586:         }
 8587: 	&start_data_table_count();
 8588: 	return '<table class="'.$css_class.'"'.$table_id.'>'."\n";
 8589:     }
 8590: 
 8591:     sub end_data_table {
 8592: 	&end_data_table_count();
 8593: 	return '</table>'."\n";;
 8594:     }
 8595: 
 8596:     sub start_data_table_row {
 8597: 	my ($add_class, $id) = @_;
 8598: 	$row_count[0]++;
 8599: 	my $css_class = ($row_count[0] % 2)?'LC_odd_row':'LC_even_row';
 8600: 	$css_class = (join(' ',$css_class,$add_class)) unless ($add_class eq '');
 8601:         $id = (' id="'.$id.'"') unless ($id eq '');
 8602:         return  '<tr class="'.$css_class.'"'.$id.'>'."\n";
 8603:     }
 8604:     
 8605:     sub continue_data_table_row {
 8606: 	my ($add_class, $id) = @_;
 8607: 	my $css_class = ($row_count[0] % 2)?'LC_odd_row':'LC_even_row';
 8608: 	$css_class = (join(' ',$css_class,$add_class)) unless ($add_class eq '');
 8609:         $id = (' id="'.$id.'"') unless ($id eq '');
 8610:         return  '<tr class="'.$css_class.'"'.$id.'>'."\n";
 8611:     }
 8612: 
 8613:     sub end_data_table_row {
 8614: 	return '</tr>'."\n";;
 8615:     }
 8616: 
 8617:     sub start_data_table_empty_row {
 8618: #	$row_count[0]++;
 8619: 	return  '<tr class="LC_empty_row" >'."\n";;
 8620:     }
 8621: 
 8622:     sub end_data_table_empty_row {
 8623: 	return '</tr>'."\n";;
 8624:     }
 8625: 
 8626:     sub start_data_table_header_row {
 8627: 	return  '<tr class="LC_header_row">'."\n";;
 8628:     }
 8629: 
 8630:     sub end_data_table_header_row {
 8631: 	return '</tr>'."\n";;
 8632:     }
 8633: 
 8634:     sub data_table_caption {
 8635:         my $caption = shift;
 8636:         return "<caption class=\"LC_caption\">$caption</caption>";
 8637:     }
 8638: }
 8639: 
 8640: =pod
 8641: 
 8642: =item * &inhibit_menu_check($arg)
 8643: 
 8644: Checks for a inhibitmenu state and generates output to preserve it
 8645: 
 8646: Inputs:         $arg - can be any of
 8647:                      - undef - in which case the return value is a string 
 8648:                                to add  into arguments list of a uri
 8649:                      - 'input' - in which case the return value is a HTML
 8650:                                  <form> <input> field of type hidden to
 8651:                                  preserve the value
 8652:                      - a url - in which case the return value is the url with
 8653:                                the neccesary cgi args added to preserve the
 8654:                                inhibitmenu state
 8655:                      - a ref to a url - no return value, but the string is
 8656:                                         updated to include the neccessary cgi
 8657:                                         args to preserve the inhibitmenu state
 8658: 
 8659: =cut
 8660: 
 8661: sub inhibit_menu_check {
 8662:     my ($arg) = @_;
 8663:     &get_unprocessed_cgi($ENV{'QUERY_STRING'}, ['inhibitmenu']);
 8664:     if ($arg eq 'input') {
 8665: 	if ($env{'form.inhibitmenu'}) {
 8666: 	    return '<input type="hidden" name="inhibitmenu" value="'.$env{'form.inhibitmenu'}.'" />';
 8667: 	} else {
 8668: 	    return
 8669: 	}
 8670:     }
 8671:     if ($env{'form.inhibitmenu'}) {
 8672: 	if (ref($arg)) {
 8673: 	    $$arg .= '?inhibitmenu='.$env{'form.inhibitmenu'};
 8674: 	} elsif ($arg eq '') {
 8675: 	    $arg .= 'inhibitmenu='.$env{'form.inhibitmenu'};
 8676: 	} else {
 8677: 	    $arg .= '?inhibitmenu='.$env{'form.inhibitmenu'};
 8678: 	}
 8679:     }
 8680:     if (!ref($arg)) {
 8681: 	return $arg;
 8682:     }
 8683: }
 8684: 
 8685: ###############################################
 8686: 
 8687: =pod
 8688: 
 8689: =back
 8690: 
 8691: =head1 User Information Routines
 8692: 
 8693: =over 4
 8694: 
 8695: =item * &get_users_function()
 8696: 
 8697: Used by &bodytag to determine the current users primary role.
 8698: Returns either 'student','coordinator','admin', or 'author'.
 8699: 
 8700: =cut
 8701: 
 8702: ###############################################
 8703: sub get_users_function {
 8704:     my $function = 'norole';
 8705:     if ($env{'request.role'}=~/^(st)/) {
 8706:         $function='student';
 8707:     }
 8708:     if ($env{'request.role'}=~/^(cc|co|in|ta|ep)/) {
 8709:         $function='coordinator';
 8710:     }
 8711:     if ($env{'request.role'}=~/^(su|dc|ad|li)/) {
 8712:         $function='admin';
 8713:     }
 8714:     if (($env{'request.role'}=~/^(au|ca|aa)/) ||
 8715:         ($ENV{'REQUEST_URI'}=~ m{/^(/priv)})) {
 8716:         $function='author';
 8717:     }
 8718:     return $function;
 8719: }
 8720: 
 8721: ###############################################
 8722: 
 8723: =pod
 8724: 
 8725: =item * &show_course()
 8726: 
 8727: Used by lonmenu.pm and lonroles.pm to determine whether to use the word
 8728: 'Courses' or 'Roles' in inline navigation and on screen displaying user's roles.
 8729: 
 8730: Inputs:
 8731: None
 8732: 
 8733: Outputs:
 8734: Scalar: 1 if 'Course' to be used, 0 otherwise.
 8735: 
 8736: =cut
 8737: 
 8738: ###############################################
 8739: sub show_course {
 8740:     my $course = !$env{'user.adv'};
 8741:     if (!$env{'user.adv'}) {
 8742:         foreach my $env (keys(%env)) {
 8743:             next if ($env !~ m/^user\.priv\./);
 8744:             if ($env !~ m/^user\.priv\.(?:st|cm)/) {
 8745:                 $course = 0;
 8746:                 last;
 8747:             }
 8748:         }
 8749:     }
 8750:     return $course;
 8751: }
 8752: 
 8753: ###############################################
 8754: 
 8755: =pod
 8756: 
 8757: =item * &check_user_status()
 8758: 
 8759: Determines current status of supplied role for a
 8760: specific user. Roles can be active, previous or future.
 8761: 
 8762: Inputs: 
 8763: user's domain, user's username, course's domain,
 8764: course's number, optional section ID.
 8765: 
 8766: Outputs:
 8767: role status: active, previous or future. 
 8768: 
 8769: =cut
 8770: 
 8771: sub check_user_status {
 8772:     my ($udom,$uname,$cdom,$crs,$role,$sec) = @_;
 8773:     my %userinfo = &Apache::lonnet::dump('roles',$udom,$uname);
 8774:     my @uroles = keys(%userinfo);
 8775:     my $srchstr;
 8776:     my $active_chk = 'none';
 8777:     my $now = time;
 8778:     if (@uroles > 0) {
 8779:         if (($role eq 'cc') || ($role eq 'co') || ($sec eq '') || (!defined($sec))) {
 8780:             $srchstr = '/'.$cdom.'/'.$crs.'_'.$role;
 8781:         } else {
 8782:             $srchstr = '/'.$cdom.'/'.$crs.'/'.$sec.'_'.$role;
 8783:         }
 8784:         if (grep/^\Q$srchstr\E$/,@uroles) {
 8785:             my $role_end = 0;
 8786:             my $role_start = 0;
 8787:             $active_chk = 'active';
 8788:             if ($userinfo{$srchstr} =~ m/^\Q$role\E_(\d+)/) {
 8789:                 $role_end = $1;
 8790:                 if ($userinfo{$srchstr} =~ m/^\Q$role\E_\Q$role_end\E_(\d+)$/) {
 8791:                     $role_start = $1;
 8792:                 }
 8793:             }
 8794:             if ($role_start > 0) {
 8795:                 if ($now < $role_start) {
 8796:                     $active_chk = 'future';
 8797:                 }
 8798:             }
 8799:             if ($role_end > 0) {
 8800:                 if ($now > $role_end) {
 8801:                     $active_chk = 'previous';
 8802:                 }
 8803:             }
 8804:         }
 8805:     }
 8806:     return $active_chk;
 8807: }
 8808: 
 8809: ###############################################
 8810: 
 8811: =pod
 8812: 
 8813: =item * &get_sections()
 8814: 
 8815: Determines all the sections for a course including
 8816: sections with students and sections containing other roles.
 8817: Incoming parameters: 
 8818: 
 8819: 1. domain
 8820: 2. course number 
 8821: 3. reference to array containing roles for which sections should 
 8822: be gathered (optional).
 8823: 4. reference to array containing status types for which sections 
 8824: should be gathered (optional).
 8825: 
 8826: If the third argument is undefined, sections are gathered for any role. 
 8827: If the fourth argument is undefined, sections are gathered for any status.
 8828: Permissible values are 'active' or 'future' or 'previous'.
 8829:  
 8830: Returns section hash (keys are section IDs, values are
 8831: number of users in each section), subject to the
 8832: optional roles filter, optional status filter 
 8833: 
 8834: =cut
 8835: 
 8836: ###############################################
 8837: sub get_sections {
 8838:     my ($cdom,$cnum,$possible_roles,$possible_status) = @_;
 8839:     if (!defined($cdom) || !defined($cnum)) {
 8840:         my $cid =  $env{'request.course.id'};
 8841: 
 8842: 	return if (!defined($cid));
 8843: 
 8844:         $cdom = $env{'course.'.$cid.'.domain'};
 8845:         $cnum = $env{'course.'.$cid.'.num'};
 8846:     }
 8847: 
 8848:     my %sectioncount;
 8849:     my $now = time;
 8850: 
 8851:     my $check_students = 1;
 8852:     my $only_students = 0;
 8853:     if (ref($possible_roles) eq 'ARRAY') {
 8854:         if (grep(/^st$/,@{$possible_roles})) {
 8855:             if (@{$possible_roles} == 1) {
 8856:                 $only_students = 1;
 8857:             }
 8858:         } else {
 8859:             $check_students = 0;
 8860:         }
 8861:     }
 8862: 
 8863:     if ($check_students) { 
 8864: 	my ($classlist) = &Apache::loncoursedata::get_classlist($cdom,$cnum);
 8865: 	my $sec_index = &Apache::loncoursedata::CL_SECTION();
 8866: 	my $status_index = &Apache::loncoursedata::CL_STATUS();
 8867:         my $start_index = &Apache::loncoursedata::CL_START();
 8868:         my $end_index = &Apache::loncoursedata::CL_END();
 8869:         my $status;
 8870: 	while (my ($student,$data) = each(%$classlist)) {
 8871: 	    my ($section,$stu_status,$start,$end) = ($data->[$sec_index],
 8872: 				                     $data->[$status_index],
 8873:                                                      $data->[$start_index],
 8874:                                                      $data->[$end_index]);
 8875:             if ($stu_status eq 'Active') {
 8876:                 $status = 'active';
 8877:             } elsif ($end < $now) {
 8878:                 $status = 'previous';
 8879:             } elsif ($start > $now) {
 8880:                 $status = 'future';
 8881:             } 
 8882: 	    if ($section ne '-1' && $section !~ /^\s*$/) {
 8883:                 if ((!defined($possible_status)) || (($status ne '') && 
 8884:                     (grep/^\Q$status\E$/,@{$possible_status}))) { 
 8885: 		    $sectioncount{$section}++;
 8886:                 }
 8887: 	    }
 8888: 	}
 8889:     }
 8890:     if ($only_students) {
 8891:         return %sectioncount;
 8892:     }
 8893:     my %courseroles = &Apache::lonnet::dump('nohist_userroles',$cdom,$cnum);
 8894:     foreach my $user (sort(keys(%courseroles))) {
 8895: 	if ($user !~ /^(\w{2})/) { next; }
 8896: 	my ($role) = ($user =~ /^(\w{2})/);
 8897: 	if ($possible_roles && !(grep(/^$role$/,@$possible_roles))) { next; }
 8898: 	my ($section,$status);
 8899: 	if ($role eq 'cr' &&
 8900: 	    $user =~ m-^$role/[^/]*/[^/]*/[^/]*:[^:]*:[^:]*:(\w+)-) {
 8901: 	    $section=$1;
 8902: 	}
 8903: 	if ($user =~ /^$role:[^:]*:[^:]*:(\w+)/) { $section=$1; }
 8904: 	if (!defined($section) || $section eq '-1') { next; }
 8905:         my ($end,$start) = ($courseroles{$user} =~ /^([^:]*):([^:]*)$/);
 8906:         if ($end == -1 && $start == -1) {
 8907:             next; #deleted role
 8908:         }
 8909:         if (!defined($possible_status)) { 
 8910:             $sectioncount{$section}++;
 8911:         } else {
 8912:             if ((!$end || $end >= $now) && (!$start || $start <= $now)) {
 8913:                 $status = 'active';
 8914:             } elsif ($end < $now) {
 8915:                 $status = 'future';
 8916:             } elsif ($start > $now) {
 8917:                 $status = 'previous';
 8918:             }
 8919:             if (($status ne '') && (grep/^\Q$status\E$/,@{$possible_status})) {
 8920:                 $sectioncount{$section}++;
 8921:             }
 8922:         }
 8923:     }
 8924:     return %sectioncount;
 8925: }
 8926: 
 8927: ###############################################
 8928: 
 8929: =pod
 8930: 
 8931: =item * &get_course_users()
 8932: 
 8933: Retrieves usernames:domains for users in the specified course
 8934: with specific role(s), and access status. 
 8935: 
 8936: Incoming parameters:
 8937: 1. course domain
 8938: 2. course number
 8939: 3. access status: users must have - either active, 
 8940: previous, future, or all.
 8941: 4. reference to array of permissible roles
 8942: 5. reference to array of section restrictions (optional)
 8943: 6. reference to results object (hash of hashes).
 8944: 7. reference to optional userdata hash
 8945: 8. reference to optional statushash
 8946: 9. flag if privileged users (except those set to unhide in
 8947:    course settings) should be excluded    
 8948: Keys of top level results hash are roles.
 8949: Keys of inner hashes are username:domain, with 
 8950: values set to access type.
 8951: Optional userdata hash returns an array with arguments in the 
 8952: same order as loncoursedata::get_classlist() for student data.
 8953: 
 8954: Optional statushash returns
 8955: 
 8956: Entries for end, start, section and status are blank because
 8957: of the possibility of multiple values for non-student roles.
 8958: 
 8959: =cut
 8960: 
 8961: ###############################################
 8962: 
 8963: sub get_course_users {
 8964:     my ($cdom,$cnum,$types,$roles,$sections,$users,$userdata,$statushash,$hidepriv) = @_;
 8965:     my %idx = ();
 8966:     my %seclists;
 8967: 
 8968:     $idx{udom} = &Apache::loncoursedata::CL_SDOM();
 8969:     $idx{uname} =  &Apache::loncoursedata::CL_SNAME();
 8970:     $idx{end} = &Apache::loncoursedata::CL_END();
 8971:     $idx{start} = &Apache::loncoursedata::CL_START();
 8972:     $idx{id} = &Apache::loncoursedata::CL_ID();
 8973:     $idx{section} = &Apache::loncoursedata::CL_SECTION();
 8974:     $idx{fullname} = &Apache::loncoursedata::CL_FULLNAME();
 8975:     $idx{status} = &Apache::loncoursedata::CL_STATUS();
 8976: 
 8977:     if (grep(/^st$/,@{$roles})) {
 8978:         my ($classlist,$keylist)=&Apache::loncoursedata::get_classlist($cdom,$cnum);
 8979:         my $now = time;
 8980:         foreach my $student (keys(%{$classlist})) {
 8981:             my $match = 0;
 8982:             my $secmatch = 0;
 8983:             my $section = $$classlist{$student}[$idx{section}];
 8984:             my $status = $$classlist{$student}[$idx{status}];
 8985:             if ($section eq '') {
 8986:                 $section = 'none';
 8987:             }
 8988:             if ((ref($sections) eq 'ARRAY') && (@{$sections} > 0)) {
 8989:                 if (grep(/^all$/,@{$sections})) {
 8990:                     $secmatch = 1;
 8991:                 } elsif ($$classlist{$student}[$idx{section}] eq '') {
 8992:                     if (grep(/^none$/,@{$sections})) {
 8993:                         $secmatch = 1;
 8994:                     }
 8995:                 } else {  
 8996: 		    if (grep(/^\Q$section\E$/,@{$sections})) {
 8997: 		        $secmatch = 1;
 8998:                     }
 8999: 		}
 9000:                 if (!$secmatch) {
 9001:                     next;
 9002:                 }
 9003:             }
 9004:             if (defined($$types{'active'})) {
 9005:                 if ($$classlist{$student}[$idx{status}] eq 'Active') {
 9006:                     push(@{$$users{st}{$student}},'active');
 9007:                     $match = 1;
 9008:                 }
 9009:             }
 9010:             if (defined($$types{'previous'})) {
 9011:                 if ($$classlist{$student}[$idx{status}] eq 'Expired') {
 9012:                     push(@{$$users{st}{$student}},'previous');
 9013:                     $match = 1;
 9014:                 }
 9015:             }
 9016:             if (defined($$types{'future'})) {
 9017:                 if ($$classlist{$student}[$idx{status}] eq 'Future') {
 9018:                     push(@{$$users{st}{$student}},'future');
 9019:                     $match = 1;
 9020:                 }
 9021:             }
 9022:             if ($match) {
 9023:                 push(@{$seclists{$student}},$section);
 9024:                 if (ref($userdata) eq 'HASH') {
 9025:                     $$userdata{$student} = $$classlist{$student};
 9026:                 }
 9027:                 if (ref($statushash) eq 'HASH') {
 9028:                     $statushash->{$student}{'st'}{$section} = $status;
 9029:                 }
 9030:             }
 9031:         }
 9032:     }
 9033:     if ((@{$roles} > 1) || ((@{$roles} == 1) && ($$roles[0] ne "st"))) {
 9034:         my %coursepersonnel = &Apache::lonnet::dump('nohist_userroles',$cdom,$cnum);
 9035:         my $now = time;
 9036:         my %displaystatus = ( previous => 'Expired',
 9037:                               active   => 'Active',
 9038:                               future   => 'Future',
 9039:                             );
 9040:         my (%nothide,@possdoms);
 9041:         if ($hidepriv) {
 9042:             my %coursehash=&Apache::lonnet::coursedescription($cdom.'_'.$cnum);
 9043:             foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
 9044:                 if ($user !~ /:/) {
 9045:                     $nothide{join(':',split(/[\@]/,$user))}=1;
 9046:                 } else {
 9047:                     $nothide{$user} = 1;
 9048:                 }
 9049:             }
 9050:             my @possdoms = ($cdom);
 9051:             if ($coursehash{'checkforpriv'}) {
 9052:                 push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
 9053:             }
 9054:         }
 9055:         foreach my $person (sort(keys(%coursepersonnel))) {
 9056:             my $match = 0;
 9057:             my $secmatch = 0;
 9058:             my $status;
 9059:             my ($role,$user,$usec) = ($person =~ /^([^:]*):([^:]+:[^:]+):([^:]*)/);
 9060:             $user =~ s/:$//;
 9061:             my ($end,$start) = split(/:/,$coursepersonnel{$person});
 9062:             if ($end == -1 || $start == -1) {
 9063:                 next;
 9064:             }
 9065:             if (($role) && ((grep(/^\Q$role\E$/,@{$roles})) ||
 9066:                 (grep(/^cr$/,@{$roles}) && $role =~ /^cr\//))) {
 9067:                 my ($uname,$udom) = split(/:/,$user);
 9068:                 if ((ref($sections) eq 'ARRAY') && (@{$sections} > 0)) {
 9069:                     if (grep(/^all$/,@{$sections})) {
 9070:                         $secmatch = 1;
 9071:                     } elsif ($usec eq '') {
 9072:                         if (grep(/^none$/,@{$sections})) {
 9073:                             $secmatch = 1;
 9074:                         }
 9075:                     } else {
 9076:                         if (grep(/^\Q$usec\E$/,@{$sections})) {
 9077:                             $secmatch = 1;
 9078:                         }
 9079:                     }
 9080:                     if (!$secmatch) {
 9081:                         next;
 9082:                     }
 9083:                 }
 9084:                 if ($usec eq '') {
 9085:                     $usec = 'none';
 9086:                 }
 9087:                 if ($uname ne '' && $udom ne '') {
 9088:                     if ($hidepriv) {
 9089:                         if ((&Apache::lonnet::privileged($uname,$udom,\@possdoms)) &&
 9090:                             (!$nothide{$uname.':'.$udom})) {
 9091:                             next;
 9092:                         }
 9093:                     }
 9094:                     if ($end > 0 && $end < $now) {
 9095:                         $status = 'previous';
 9096:                     } elsif ($start > $now) {
 9097:                         $status = 'future';
 9098:                     } else {
 9099:                         $status = 'active';
 9100:                     }
 9101:                     foreach my $type (keys(%{$types})) { 
 9102:                         if ($status eq $type) {
 9103:                             if (!grep(/^\Q$type\E$/,@{$$users{$role}{$user}})) {
 9104:                                 push(@{$$users{$role}{$user}},$type);
 9105:                             }
 9106:                             $match = 1;
 9107:                         }
 9108:                     }
 9109:                     if (($match) && (ref($userdata) eq 'HASH')) {
 9110:                         if (!exists($$userdata{$uname.':'.$udom})) {
 9111: 			    &get_user_info($udom,$uname,\%idx,$userdata);
 9112:                         }
 9113:                         if (!grep(/^\Q$usec\E$/,@{$seclists{$uname.':'.$udom}})) {
 9114:                             push(@{$seclists{$uname.':'.$udom}},$usec);
 9115:                         }
 9116:                         if (ref($statushash) eq 'HASH') {
 9117:                             $statushash->{$uname.':'.$udom}{$role}{$usec} = $displaystatus{$status};
 9118:                         }
 9119:                     }
 9120:                 }
 9121:             }
 9122:         }
 9123:         if (grep(/^ow$/,@{$roles})) {
 9124:             if ((defined($cdom)) && (defined($cnum))) {
 9125:                 my %csettings = &Apache::lonnet::get('environment',['internal.courseowner'],$cdom,$cnum);
 9126:                 if ( defined($csettings{'internal.courseowner'}) ) {
 9127:                     my $owner = $csettings{'internal.courseowner'};
 9128:                     next if ($owner eq '');
 9129:                     my ($ownername,$ownerdom);
 9130:                     if ($owner =~ /^([^:]+):([^:]+)$/) {
 9131:                         $ownername = $1;
 9132:                         $ownerdom = $2;
 9133:                     } else {
 9134:                         $ownername = $owner;
 9135:                         $ownerdom = $cdom;
 9136:                         $owner = $ownername.':'.$ownerdom;
 9137:                     }
 9138:                     @{$$users{'ow'}{$owner}} = 'any';
 9139:                     if (defined($userdata) && 
 9140: 			!exists($$userdata{$owner})) {
 9141: 			&get_user_info($ownerdom,$ownername,\%idx,$userdata);
 9142:                         if (!grep(/^none$/,@{$seclists{$owner}})) {
 9143:                             push(@{$seclists{$owner}},'none');
 9144:                         }
 9145:                         if (ref($statushash) eq 'HASH') {
 9146:                             $statushash->{$owner}{'ow'}{'none'} = 'Any';
 9147:                         }
 9148: 		    }
 9149:                 }
 9150:             }
 9151:         }
 9152:         foreach my $user (keys(%seclists)) {
 9153:             @{$seclists{$user}} = (sort {$a <=> $b} @{$seclists{$user}});
 9154:             $$userdata{$user}[$idx{section}] = join(',',@{$seclists{$user}});
 9155:         }
 9156:     }
 9157:     return;
 9158: }
 9159: 
 9160: sub get_user_info {
 9161:     my ($udom,$uname,$idx,$userdata) = @_;
 9162:     $$userdata{$uname.':'.$udom}[$$idx{fullname}] = 
 9163: 	&plainname($uname,$udom,'lastname');
 9164:     $$userdata{$uname.':'.$udom}[$$idx{uname}] = $uname;
 9165:     $$userdata{$uname.':'.$udom}[$$idx{udom}] = $udom;
 9166:     my %idhash =  &Apache::lonnet::idrget($udom,($uname));
 9167:     $$userdata{$uname.':'.$udom}[$$idx{id}] = $idhash{$uname}; 
 9168:     return;
 9169: }
 9170: 
 9171: ###############################################
 9172: 
 9173: =pod
 9174: 
 9175: =item * &get_user_quota()
 9176: 
 9177: Retrieves quota assigned for storage of user files.
 9178: Default is to report quota for portfolio files.
 9179: 
 9180: Incoming parameters:
 9181: 1. user's username
 9182: 2. user's domain
 9183: 3. quota name - portfolio, author, or course
 9184:    (if no quota name provided, defaults to portfolio).
 9185: 4. crstype - official, unofficial, textbook or community, if quota name is
 9186:    course
 9187: 
 9188: Returns:
 9189: 1. Disk quota (in MB) assigned to student.
 9190: 2. (Optional) Type of setting: custom or default
 9191:    (individually assigned or default for user's 
 9192:    institutional status).
 9193: 3. (Optional) - User's institutional status (e.g., faculty, staff
 9194:    or student - types as defined in localenroll::inst_usertypes 
 9195:    for user's domain, which determines default quota for user.
 9196: 4. (Optional) - Default quota which would apply to the user.
 9197: 
 9198: If a value has been stored in the user's environment, 
 9199: it will return that, otherwise it returns the maximal default
 9200: defined for the user's institutional status(es) in the domain.
 9201: 
 9202: =cut
 9203: 
 9204: ###############################################
 9205: 
 9206: 
 9207: sub get_user_quota {
 9208:     my ($uname,$udom,$quotaname,$crstype) = @_;
 9209:     my ($quota,$quotatype,$settingstatus,$defquota);
 9210:     if (!defined($udom)) {
 9211:         $udom = $env{'user.domain'};
 9212:     }
 9213:     if (!defined($uname)) {
 9214:         $uname = $env{'user.name'};
 9215:     }
 9216:     if (($udom eq '' || $uname eq '') ||
 9217:         ($udom eq 'public') && ($uname eq 'public')) {
 9218:         $quota = 0;
 9219:         $quotatype = 'default';
 9220:         $defquota = 0; 
 9221:     } else {
 9222:         my $inststatus;
 9223:         if ($quotaname eq 'course') {
 9224:             if (($env{'course.'.$udom.'_'.$uname.'.num'} eq $uname) &&
 9225:                 ($env{'course.'.$udom.'_'.$uname.'.domain'} eq $udom)) {
 9226:                 $quota = $env{'course.'.$udom.'_'.$uname.'.internal.uploadquota'};
 9227:             } else {
 9228:                 my %cenv = &Apache::lonnet::coursedescription("$udom/$uname");
 9229:                 $quota = $cenv{'internal.uploadquota'};
 9230:             }
 9231:         } else {
 9232:             if ($udom eq $env{'user.domain'} && $uname eq $env{'user.name'}) {
 9233:                 if ($quotaname eq 'author') {
 9234:                     $quota = $env{'environment.authorquota'};
 9235:                 } else {
 9236:                     $quota = $env{'environment.portfolioquota'};
 9237:                 }
 9238:                 $inststatus = $env{'environment.inststatus'};
 9239:             } else {
 9240:                 my %userenv = 
 9241:                     &Apache::lonnet::get('environment',['portfolioquota',
 9242:                                          'authorquota','inststatus'],$udom,$uname);
 9243:                 my ($tmp) = keys(%userenv);
 9244:                 if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
 9245:                     if ($quotaname eq 'author') {
 9246:                         $quota = $userenv{'authorquota'};
 9247:                     } else {
 9248:                         $quota = $userenv{'portfolioquota'};
 9249:                     }
 9250:                     $inststatus = $userenv{'inststatus'};
 9251:                 } else {
 9252:                     undef(%userenv);
 9253:                 }
 9254:             }
 9255:         }
 9256:         if ($quota eq '' || wantarray) {
 9257:             if ($quotaname eq 'course') {
 9258:                 my %domdefs = &Apache::lonnet::get_domain_defaults($udom);
 9259:                 if (($crstype eq 'official') || ($crstype eq 'unofficial') || 
 9260:                     ($crstype eq 'community') || ($crstype eq 'textbook')) { 
 9261:                     $defquota = $domdefs{$crstype.'quota'};
 9262:                 }
 9263:                 if ($defquota eq '') {
 9264:                     $defquota = 500;
 9265:                 }
 9266:             } else {
 9267:                 ($defquota,$settingstatus) = &default_quota($udom,$inststatus,$quotaname);
 9268:             }
 9269:             if ($quota eq '') {
 9270:                 $quota = $defquota;
 9271:                 $quotatype = 'default';
 9272:             } else {
 9273:                 $quotatype = 'custom';
 9274:             }
 9275:         }
 9276:     }
 9277:     if (wantarray) {
 9278:         return ($quota,$quotatype,$settingstatus,$defquota);
 9279:     } else {
 9280:         return $quota;
 9281:     }
 9282: }
 9283: 
 9284: ###############################################
 9285: 
 9286: =pod
 9287: 
 9288: =item * &default_quota()
 9289: 
 9290: Retrieves default quota assigned for storage of user portfolio files,
 9291: given an (optional) user's institutional status.
 9292: 
 9293: Incoming parameters:
 9294: 
 9295: 1. domain
 9296: 2. (Optional) institutional status(es).  This is a : separated list of 
 9297:    status types (e.g., faculty, staff, student etc.)
 9298:    which apply to the user for whom the default is being retrieved.
 9299:    If the institutional status string in undefined, the domain
 9300:    default quota will be returned.
 9301: 3.  quota name - portfolio, author, or course
 9302:    (if no quota name provided, defaults to portfolio).
 9303: 
 9304: Returns:
 9305: 
 9306: 1. Default disk quota (in MB) for user portfolios in the domain.
 9307: 2. (Optional) institutional type which determined the value of the
 9308:    default quota.
 9309: 
 9310: If a value has been stored in the domain's configuration db,
 9311: it will return that, otherwise it returns 20 (for backwards 
 9312: compatibility with domains which have not set up a configuration
 9313: db file; the original statically defined portfolio quota was 20 MB). 
 9314: 
 9315: If the user's status includes multiple types (e.g., staff and student),
 9316: the largest default quota which applies to the user determines the
 9317: default quota returned.
 9318: 
 9319: =cut
 9320: 
 9321: ###############################################
 9322: 
 9323: 
 9324: sub default_quota {
 9325:     my ($udom,$inststatus,$quotaname) = @_;
 9326:     my ($defquota,$settingstatus);
 9327:     my %quotahash = &Apache::lonnet::get_dom('configuration',
 9328:                                             ['quotas'],$udom);
 9329:     my $key = 'defaultquota';
 9330:     if ($quotaname eq 'author') {
 9331:         $key = 'authorquota';
 9332:     }
 9333:     if (ref($quotahash{'quotas'}) eq 'HASH') {
 9334:         if ($inststatus ne '') {
 9335:             my @statuses = map { &unescape($_); } split(/:/,$inststatus);
 9336:             foreach my $item (@statuses) {
 9337:                 if (ref($quotahash{'quotas'}{$key}) eq 'HASH') {
 9338:                     if ($quotahash{'quotas'}{$key}{$item} ne '') {
 9339:                         if ($defquota eq '') {
 9340:                             $defquota = $quotahash{'quotas'}{$key}{$item};
 9341:                             $settingstatus = $item;
 9342:                         } elsif ($quotahash{'quotas'}{$key}{$item} > $defquota) {
 9343:                             $defquota = $quotahash{'quotas'}{$key}{$item};
 9344:                             $settingstatus = $item;
 9345:                         }
 9346:                     }
 9347:                 } elsif ($key eq 'defaultquota') {
 9348:                     if ($quotahash{'quotas'}{$item} ne '') {
 9349:                         if ($defquota eq '') {
 9350:                             $defquota = $quotahash{'quotas'}{$item};
 9351:                             $settingstatus = $item;
 9352:                         } elsif ($quotahash{'quotas'}{$item} > $defquota) {
 9353:                             $defquota = $quotahash{'quotas'}{$item};
 9354:                             $settingstatus = $item;
 9355:                         }
 9356:                     }
 9357:                 }
 9358:             }
 9359:         }
 9360:         if ($defquota eq '') {
 9361:             if (ref($quotahash{'quotas'}{$key}) eq 'HASH') {
 9362:                 $defquota = $quotahash{'quotas'}{$key}{'default'};
 9363:             } elsif ($key eq 'defaultquota') {
 9364:                 $defquota = $quotahash{'quotas'}{'default'};
 9365:             }
 9366:             $settingstatus = 'default';
 9367:             if ($defquota eq '') {
 9368:                 if ($quotaname eq 'author') {
 9369:                     $defquota = 500;
 9370:                 }
 9371:             }
 9372:         }
 9373:     } else {
 9374:         $settingstatus = 'default';
 9375:         if ($quotaname eq 'author') {
 9376:             $defquota = 500;
 9377:         } else {
 9378:             $defquota = 20;
 9379:         }
 9380:     }
 9381:     if (wantarray) {
 9382:         return ($defquota,$settingstatus);
 9383:     } else {
 9384:         return $defquota;
 9385:     }
 9386: }
 9387: 
 9388: ###############################################
 9389: 
 9390: =pod
 9391: 
 9392: =item * &excess_filesize_warning()
 9393: 
 9394: Returns warning message if upload of file to authoring space, or copying
 9395: of existing file within authoring space will cause quota for the authoring
 9396: space to be exceeded.
 9397: 
 9398: Same, if upload of a file directly to a course/community via Course Editor
 9399: will cause quota for uploaded content for the course to be exceeded.
 9400: 
 9401: Inputs: 7 
 9402: 1. username or coursenum
 9403: 2. domain
 9404: 3. context ('author' or 'course')
 9405: 4. filename of file for which action is being requested
 9406: 5. filesize (kB) of file
 9407: 6. action being taken: copy or upload.
 9408: 7. quotatype (in course context -- official, unofficial, community or textbook).
 9409: 
 9410: Returns: 1 scalar: HTML to display containing warning if quota would be exceeded,
 9411:          otherwise return null.
 9412: 
 9413: =back
 9414: 
 9415: =cut
 9416: 
 9417: sub excess_filesize_warning {
 9418:     my ($uname,$udom,$context,$filename,$filesize,$action,$quotatype) = @_;
 9419:     my $current_disk_usage = 0;
 9420:     my $disk_quota = &get_user_quota($uname,$udom,$context,$quotatype); #expressed in MB
 9421:     if ($context eq 'author') {
 9422:         my $authorspace = $Apache::lonnet::perlvar{'lonDocRoot'}."/priv/$udom/$uname";
 9423:         $current_disk_usage = &Apache::lonnet::diskusage($udom,$uname,$authorspace);
 9424:     } else {
 9425:         foreach my $subdir ('docs','supplemental') {
 9426:             $current_disk_usage += &Apache::lonnet::diskusage($udom,$uname,"userfiles/$subdir",1);
 9427:         }
 9428:     }
 9429:     $disk_quota = int($disk_quota * 1000);
 9430:     if (($current_disk_usage + $filesize) > $disk_quota) {
 9431:         return '<p class="LC_warning">'.
 9432:                 &mt("Unable to $action [_1]. (size = [_2] kilobytes). Disk quota will be exceeded.",
 9433:                     '<span class="LC_filename">'.$filename.'</span>',$filesize).'</p>'.
 9434:                '<p>'.&mt('Disk quota is [_1] kilobytes. Your current disk usage is [_2] kilobytes.',
 9435:                             $disk_quota,$current_disk_usage).
 9436:                '</p>';
 9437:     }
 9438:     return;
 9439: }
 9440: 
 9441: ###############################################
 9442: 
 9443: 
 9444: 
 9445: 
 9446: sub get_secgrprole_info {
 9447:     my ($cdom,$cnum,$needroles,$type)  = @_;
 9448:     my %sections_count = &get_sections($cdom,$cnum);
 9449:     my @sections =  (sort {$a <=> $b} keys(%sections_count));
 9450:     my %curr_groups = &Apache::longroup::coursegroups($cdom,$cnum);
 9451:     my @groups = sort(keys(%curr_groups));
 9452:     my $allroles = [];
 9453:     my $rolehash;
 9454:     my $accesshash = {
 9455:                      active => 'Currently has access',
 9456:                      future => 'Will have future access',
 9457:                      previous => 'Previously had access',
 9458:                   };
 9459:     if ($needroles) {
 9460:         $rolehash = {'all' => 'all'};
 9461:         my %user_roles = &Apache::lonnet::dump('nohist_userroles',$cdom,$cnum);
 9462: 	if (&Apache::lonnet::error(%user_roles)) {
 9463: 	    undef(%user_roles);
 9464: 	}
 9465:         foreach my $item (keys(%user_roles)) {
 9466:             my ($role)=split(/\:/,$item,2);
 9467:             if ($role eq 'cr') { next; }
 9468:             if ($role =~ /^cr/) {
 9469:                 $$rolehash{$role} = (split('/',$role))[3];
 9470:             } else {
 9471:                 $$rolehash{$role} = &Apache::lonnet::plaintext($role,$type);
 9472:             }
 9473:         }
 9474:         foreach my $key (sort(keys(%{$rolehash}))) {
 9475:             push(@{$allroles},$key);
 9476:         }
 9477:         push (@{$allroles},'st');
 9478:         $$rolehash{'st'} = &Apache::lonnet::plaintext('st',$type);
 9479:     }
 9480:     return (\@sections,\@groups,$allroles,$rolehash,$accesshash);
 9481: }
 9482: 
 9483: sub user_picker {
 9484:     my ($dom,$srch,$forcenewuser,$caller,$cancreate,$usertype,$context) = @_;
 9485:     my $currdom = $dom;
 9486:     my %curr_selected = (
 9487:                         srchin => 'dom',
 9488:                         srchby => 'lastname',
 9489:                       );
 9490:     my $srchterm;
 9491:     if ((ref($srch) eq 'HASH') && ($env{'form.origform'} ne 'crtusername')) {
 9492:         if ($srch->{'srchby'} ne '') {
 9493:             $curr_selected{'srchby'} = $srch->{'srchby'};
 9494:         }
 9495:         if ($srch->{'srchin'} ne '') {
 9496:             $curr_selected{'srchin'} = $srch->{'srchin'};
 9497:         }
 9498:         if ($srch->{'srchtype'} ne '') {
 9499:             $curr_selected{'srchtype'} = $srch->{'srchtype'};
 9500:         }
 9501:         if ($srch->{'srchdomain'} ne '') {
 9502:             $currdom = $srch->{'srchdomain'};
 9503:         }
 9504:         $srchterm = $srch->{'srchterm'};
 9505:     }
 9506:     my %lt=&Apache::lonlocal::texthash(
 9507:                     'usr'       => 'Search criteria',
 9508:                     'doma'      => 'Domain/institution to search',
 9509:                     'uname'     => 'username',
 9510:                     'lastname'  => 'last name',
 9511:                     'lastfirst' => 'last name, first name',
 9512:                     'crs'       => 'in this course',
 9513:                     'dom'       => 'in selected LON-CAPA domain', 
 9514:                     'alc'       => 'all LON-CAPA',
 9515:                     'instd'     => 'in institutional directory for selected domain',
 9516:                     'exact'     => 'is',
 9517:                     'contains'  => 'contains',
 9518:                     'begins'    => 'begins with',
 9519:                     'youm'      => "You must include some text to search for.",
 9520:                     'thte'      => "The text you are searching for must contain at least two characters when using a 'begins' type search.",
 9521:                     'thet'      => "The text you are searching for must contain at least three characters when using a 'contains' type search.",
 9522:                     'yomc'      => "You must choose a domain when using an institutional directory search.",
 9523:                     'ymcd'      => "You must choose a domain when using a domain search.",
 9524:                     'whus'      => "When using searching by last,first you must include a comma as separator between last name and first name.",
 9525:                     'whse'      => "When searching by last,first you must include at least one character in the first name.",
 9526:                      'thfo'     => "The following need to be corrected before the search can be run:",
 9527:                                        );
 9528:     my $domform = &select_dom_form($currdom,'srchdomain',1,1);
 9529:     my $srchinsel = ' <select name="srchin">';
 9530: 
 9531:     my @srchins = ('crs','dom','alc','instd');
 9532: 
 9533:     foreach my $option (@srchins) {
 9534:         # FIXME 'alc' option unavailable until 
 9535:         #       loncreateuser::print_user_query_page()
 9536:         #       has been completed.
 9537:         next if ($option eq 'alc');
 9538:         next if (($option eq 'crs') && ($env{'form.form'} eq 'requestcrs'));  
 9539:         next if ($option eq 'crs' && !$env{'request.course.id'});
 9540:         if ($curr_selected{'srchin'} eq $option) {
 9541:             $srchinsel .= ' 
 9542:    <option value="'.$option.'" selected="selected">'.$lt{$option}.'</option>';
 9543:         } else {
 9544:             $srchinsel .= '
 9545:    <option value="'.$option.'">'.$lt{$option}.'</option>';
 9546:         }
 9547:     }
 9548:     $srchinsel .= "\n  </select>\n";
 9549: 
 9550:     my $srchbysel =  ' <select name="srchby">';
 9551:     foreach my $option ('lastname','lastfirst','uname') {
 9552:         if ($curr_selected{'srchby'} eq $option) {
 9553:             $srchbysel .= '
 9554:    <option value="'.$option.'" selected="selected">'.$lt{$option}.'</option>';
 9555:         } else {
 9556:             $srchbysel .= '
 9557:    <option value="'.$option.'">'.$lt{$option}.'</option>';
 9558:          }
 9559:     }
 9560:     $srchbysel .= "\n  </select>\n";
 9561: 
 9562:     my $srchtypesel = ' <select name="srchtype">';
 9563:     foreach my $option ('begins','contains','exact') {
 9564:         if ($curr_selected{'srchtype'} eq $option) {
 9565:             $srchtypesel .= '
 9566:    <option value="'.$option.'" selected="selected">'.$lt{$option}.'</option>';
 9567:         } else {
 9568:             $srchtypesel .= '
 9569:    <option value="'.$option.'">'.$lt{$option}.'</option>';
 9570:         }
 9571:     }
 9572:     $srchtypesel .= "\n  </select>\n";
 9573: 
 9574:     my ($newuserscript,$new_user_create);
 9575:     my $context_dom = $env{'request.role.domain'};
 9576:     if ($context eq 'requestcrs') {
 9577:         if ($env{'form.coursedom'} ne '') { 
 9578:             $context_dom = $env{'form.coursedom'};
 9579:         }
 9580:     }
 9581:     if ($forcenewuser) {
 9582:         if (ref($srch) eq 'HASH') {
 9583:             if ($srch->{'srchby'} eq 'uname' && $srch->{'srchtype'} eq 'exact' && $srch->{'srchin'} eq 'dom' && $srch->{'srchdomain'} eq $context_dom) {
 9584:                 if ($cancreate) {
 9585:                     $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>';
 9586:                 } else {
 9587:                     my $helplink = 'javascript:helpMenu('."'display'".')';
 9588:                     my %usertypetext = (
 9589:                         official   => 'institutional',
 9590:                         unofficial => 'non-institutional',
 9591:                     );
 9592:                     $new_user_create = '<p class="LC_warning">'
 9593:                                       .&mt("You are not authorized to create new $usertypetext{$usertype} users in this domain.")
 9594:                                       .' '
 9595:                                       .&mt('Please contact the [_1]helpdesk[_2] for assistance.'
 9596:                                           ,'<a href="'.$helplink.'">','</a>')
 9597:                                       .'</p><br />';
 9598:                 }
 9599:             }
 9600:         }
 9601: 
 9602:         $newuserscript = <<"ENDSCRIPT";
 9603: 
 9604: function setSearch(createnew,callingForm) {
 9605:     if (createnew == 1) {
 9606:         for (var i=0; i<callingForm.srchby.length; i++) {
 9607:             if (callingForm.srchby.options[i].value == 'uname') {
 9608:                 callingForm.srchby.selectedIndex = i;
 9609:             }
 9610:         }
 9611:         for (var i=0; i<callingForm.srchin.length; i++) {
 9612:             if ( callingForm.srchin.options[i].value == 'dom') {
 9613: 		callingForm.srchin.selectedIndex = i;
 9614:             }
 9615:         }
 9616:         for (var i=0; i<callingForm.srchtype.length; i++) {
 9617:             if (callingForm.srchtype.options[i].value == 'exact') {
 9618:                 callingForm.srchtype.selectedIndex = i;
 9619:             }
 9620:         }
 9621:         for (var i=0; i<callingForm.srchdomain.length; i++) {
 9622:             if (callingForm.srchdomain.options[i].value == '$context_dom') {
 9623:                 callingForm.srchdomain.selectedIndex = i;
 9624:             }
 9625:         }
 9626:     }
 9627: }
 9628: ENDSCRIPT
 9629: 
 9630:     }
 9631: 
 9632:     my $output = <<"END_BLOCK";
 9633: <script type="text/javascript">
 9634: // <![CDATA[
 9635: function validateEntry(callingForm) {
 9636: 
 9637:     var checkok = 1;
 9638:     var srchin;
 9639:     for (var i=0; i<callingForm.srchin.length; i++) {
 9640: 	if ( callingForm.srchin[i].checked ) {
 9641: 	    srchin = callingForm.srchin[i].value;
 9642: 	}
 9643:     }
 9644: 
 9645:     var srchtype = callingForm.srchtype.options[callingForm.srchtype.selectedIndex].value;
 9646:     var srchby = callingForm.srchby.options[callingForm.srchby.selectedIndex].value;
 9647:     var srchdomain = callingForm.srchdomain.options[callingForm.srchdomain.selectedIndex].value;
 9648:     var srchterm =  callingForm.srchterm.value;
 9649:     var srchin = callingForm.srchin.options[callingForm.srchin.selectedIndex].value;
 9650:     var msg = "";
 9651: 
 9652:     if (srchterm == "") {
 9653:         checkok = 0;
 9654:         msg += "$lt{'youm'}\\n";
 9655:     }
 9656: 
 9657:     if (srchtype== 'begins') {
 9658:         if (srchterm.length < 2) {
 9659:             checkok = 0;
 9660:             msg += "$lt{'thte'}\\n";
 9661:         }
 9662:     }
 9663: 
 9664:     if (srchtype== 'contains') {
 9665:         if (srchterm.length < 3) {
 9666:             checkok = 0;
 9667:             msg += "$lt{'thet'}\\n";
 9668:         }
 9669:     }
 9670:     if (srchin == 'instd') {
 9671:         if (srchdomain == '') {
 9672:             checkok = 0;
 9673:             msg += "$lt{'yomc'}\\n";
 9674:         }
 9675:     }
 9676:     if (srchin == 'dom') {
 9677:         if (srchdomain == '') {
 9678:             checkok = 0;
 9679:             msg += "$lt{'ymcd'}\\n";
 9680:         }
 9681:     }
 9682:     if (srchby == 'lastfirst') {
 9683:         if (srchterm.indexOf(",") == -1) {
 9684:             checkok = 0;
 9685:             msg += "$lt{'whus'}\\n";
 9686:         }
 9687:         if (srchterm.indexOf(",") == srchterm.length -1) {
 9688:             checkok = 0;
 9689:             msg += "$lt{'whse'}\\n";
 9690:         }
 9691:     }
 9692:     if (checkok == 0) {
 9693:         alert("$lt{'thfo'}\\n"+msg);
 9694:         return;
 9695:     }
 9696:     if (checkok == 1) {
 9697:         callingForm.submit();
 9698:     }
 9699: }
 9700: 
 9701: $newuserscript
 9702: 
 9703: // ]]>
 9704: </script>
 9705: 
 9706: $new_user_create
 9707: 
 9708: END_BLOCK
 9709: 
 9710:     $output .= &Apache::lonhtmlcommon::start_pick_box().
 9711:                &Apache::lonhtmlcommon::row_title($lt{'doma'}).
 9712:                $domform.
 9713:                &Apache::lonhtmlcommon::row_closure().
 9714:                &Apache::lonhtmlcommon::row_title($lt{'usr'}).
 9715:                $srchbysel.
 9716:                $srchtypesel. 
 9717:                '<input type="text" size="15" name="srchterm" value="'.$srchterm.'" />'.
 9718:                $srchinsel.
 9719:                &Apache::lonhtmlcommon::row_closure(1). 
 9720:                &Apache::lonhtmlcommon::end_pick_box().
 9721:                '<br />';
 9722:     return $output;
 9723: }
 9724: 
 9725: sub user_rule_check {
 9726:     my ($usershash,$checks,$alerts,$rulematch,$inst_results,$curr_rules,$got_rules) = @_;
 9727:     my $response;
 9728:     if (ref($usershash) eq 'HASH') {
 9729:         foreach my $user (keys(%{$usershash})) {
 9730:             my ($uname,$udom) = split(/:/,$user);
 9731:             next if ($udom eq '' || $uname eq '');
 9732:             my ($id,$newuser);
 9733:             if (ref($usershash->{$user}) eq 'HASH') {
 9734:                 $newuser = $usershash->{$user}->{'newuser'};
 9735:                 $id = $usershash->{$user}->{'id'};
 9736:             }
 9737:             my $inst_response;
 9738:             if (ref($checks) eq 'HASH') {
 9739:                 if (defined($checks->{'username'})) {
 9740:                     ($inst_response,%{$inst_results->{$user}}) = 
 9741:                         &Apache::lonnet::get_instuser($udom,$uname);
 9742:                 } elsif (defined($checks->{'id'})) {
 9743:                     ($inst_response,%{$inst_results->{$user}}) =
 9744:                         &Apache::lonnet::get_instuser($udom,undef,$id);
 9745:                 }
 9746:             } else {
 9747:                 ($inst_response,%{$inst_results->{$user}}) =
 9748:                     &Apache::lonnet::get_instuser($udom,$uname);
 9749:                 return;
 9750:             }
 9751:             if (!$got_rules->{$udom}) {
 9752:                 my %domconfig = &Apache::lonnet::get_dom('configuration',
 9753:                                                   ['usercreation'],$udom);
 9754:                 if (ref($domconfig{'usercreation'}) eq 'HASH') {
 9755:                     foreach my $item ('username','id') {
 9756:                         if (ref($domconfig{'usercreation'}{$item.'_rule'}) eq 'ARRAY') {
 9757:                             $$curr_rules{$udom}{$item} = 
 9758:                                 $domconfig{'usercreation'}{$item.'_rule'};
 9759:                         }
 9760:                     }
 9761:                 }
 9762:                 $got_rules->{$udom} = 1;  
 9763:             }
 9764:             foreach my $item (keys(%{$checks})) {
 9765:                 if (ref($$curr_rules{$udom}) eq 'HASH') {
 9766:                     if (ref($$curr_rules{$udom}{$item}) eq 'ARRAY') {
 9767:                         if (@{$$curr_rules{$udom}{$item}} > 0) {
 9768:                             my %rule_check = &Apache::lonnet::inst_rulecheck($udom,$uname,$id,$item,$$curr_rules{$udom}{$item});
 9769:                             foreach my $rule (@{$$curr_rules{$udom}{$item}}) {
 9770:                                 if ($rule_check{$rule}) {
 9771:                                     $$rulematch{$user}{$item} = $rule;
 9772:                                     if ($inst_response eq 'ok') {
 9773:                                         if (ref($inst_results) eq 'HASH') {
 9774:                                             if (ref($inst_results->{$user}) eq 'HASH') {
 9775:                                                 if (keys(%{$inst_results->{$user}}) == 0) {
 9776:                                                     $$alerts{$item}{$udom}{$uname} = 1;
 9777:                                                 }
 9778:                                             }
 9779:                                         }
 9780:                                     }
 9781:                                     last;
 9782:                                 }
 9783:                             }
 9784:                         }
 9785:                     }
 9786:                 }
 9787:             }
 9788:         }
 9789:     }
 9790:     return;
 9791: }
 9792: 
 9793: sub user_rule_formats {
 9794:     my ($domain,$domdesc,$curr_rules,$check) = @_;
 9795:     my %text = ( 
 9796:                  'username' => 'Usernames',
 9797:                  'id'       => 'IDs',
 9798:                );
 9799:     my $output;
 9800:     my ($rules,$ruleorder) = &Apache::lonnet::inst_userrules($domain,$check);
 9801:     if ((ref($rules) eq 'HASH') && (ref($ruleorder) eq 'ARRAY')) {
 9802:         if (@{$ruleorder} > 0) {
 9803:             $output = '<br />'.
 9804:                       &mt($text{$check}.' with the following format(s) may [_1]only[_2] be used for verified users at [_3]:',
 9805:                           '<span class="LC_cusr_emph">','</span>',$domdesc).
 9806:                       ' <ul>';
 9807:             foreach my $rule (@{$ruleorder}) {
 9808:                 if (ref($curr_rules) eq 'ARRAY') {
 9809:                     if (grep(/^\Q$rule\E$/,@{$curr_rules})) {
 9810:                         if (ref($rules->{$rule}) eq 'HASH') {
 9811:                             $output .= '<li>'.$rules->{$rule}{'name'}.': '.
 9812:                                         $rules->{$rule}{'desc'}.'</li>';
 9813:                         }
 9814:                     }
 9815:                 }
 9816:             }
 9817:             $output .= '</ul>';
 9818:         }
 9819:     }
 9820:     return $output;
 9821: }
 9822: 
 9823: sub instrule_disallow_msg {
 9824:     my ($checkitem,$domdesc,$count,$mode) = @_;
 9825:     my $response;
 9826:     my %text = (
 9827:                   item   => 'username',
 9828:                   items  => 'usernames',
 9829:                   match  => 'matches',
 9830:                   do     => 'does',
 9831:                   action => 'a username',
 9832:                   one    => 'one',
 9833:                );
 9834:     if ($count > 1) {
 9835:         $text{'item'} = 'usernames';
 9836:         $text{'match'} ='match';
 9837:         $text{'do'} = 'do';
 9838:         $text{'action'} = 'usernames',
 9839:         $text{'one'} = 'ones';
 9840:     }
 9841:     if ($checkitem eq 'id') {
 9842:         $text{'items'} = 'IDs';
 9843:         $text{'item'} = 'ID';
 9844:         $text{'action'} = 'an ID';
 9845:         if ($count > 1) {
 9846:             $text{'item'} = 'IDs';
 9847:             $text{'action'} = 'IDs';
 9848:         }
 9849:     }
 9850:     $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 />';
 9851:     if ($mode eq 'upload') {
 9852:         if ($checkitem eq 'username') {
 9853:             $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'}.");
 9854:         } elsif ($checkitem eq 'id') {
 9855:             $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.");
 9856:         }
 9857:     } elsif ($mode eq 'selfcreate') {
 9858:         if ($checkitem eq 'id') {
 9859:             $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.");
 9860:         }
 9861:     } else {
 9862:         if ($checkitem eq 'username') {
 9863:             $response .= &mt("You must choose $text{'action'} with a different format --  $text{'one'} that will not conflict with 'official' institutional $text{'items'}.");
 9864:         } elsif ($checkitem eq 'id') {
 9865:             $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.");
 9866:         }
 9867:     }
 9868:     return $response;
 9869: }
 9870: 
 9871: sub personal_data_fieldtitles {
 9872:     my %fieldtitles = &Apache::lonlocal::texthash (
 9873:                         id => 'Student/Employee ID',
 9874:                         permanentemail => 'E-mail address',
 9875:                         lastname => 'Last Name',
 9876:                         firstname => 'First Name',
 9877:                         middlename => 'Middle Name',
 9878:                         generation => 'Generation',
 9879:                         gen => 'Generation',
 9880:                         inststatus => 'Affiliation',
 9881:                    );
 9882:     return %fieldtitles;
 9883: }
 9884: 
 9885: sub sorted_inst_types {
 9886:     my ($dom) = @_;
 9887:     my ($usertypes,$order);
 9888:     my %domdefaults = &Apache::lonnet::get_domain_defaults($dom);
 9889:     if (ref($domdefaults{'inststatus'}) eq 'HASH') {
 9890:         $usertypes = $domdefaults{'inststatus'}{'inststatustypes'};
 9891:         $order = $domdefaults{'inststatus'}{'inststatusorder'};
 9892:     } else {
 9893:         ($usertypes,$order) = &Apache::lonnet::retrieve_inst_usertypes($dom);
 9894:     }
 9895:     my $othertitle = &mt('All users');
 9896:     if ($env{'request.course.id'}) {
 9897:         $othertitle  = &mt('Any users');
 9898:     }
 9899:     my @types;
 9900:     if (ref($order) eq 'ARRAY') {
 9901:         @types = @{$order};
 9902:     }
 9903:     if (@types == 0) {
 9904:         if (ref($usertypes) eq 'HASH') {
 9905:             @types = sort(keys(%{$usertypes}));
 9906:         }
 9907:     }
 9908:     if (keys(%{$usertypes}) > 0) {
 9909:         $othertitle = &mt('Other users');
 9910:     }
 9911:     return ($othertitle,$usertypes,\@types);
 9912: }
 9913: 
 9914: sub get_institutional_codes {
 9915:     my ($settings,$allcourses,$LC_code) = @_;
 9916: # Get complete list of course sections to update
 9917:     my @currsections = ();
 9918:     my @currxlists = ();
 9919:     my $coursecode = $$settings{'internal.coursecode'};
 9920: 
 9921:     if ($$settings{'internal.sectionnums'} ne '') {
 9922:         @currsections = split(/,/,$$settings{'internal.sectionnums'});
 9923:     }
 9924: 
 9925:     if ($$settings{'internal.crosslistings'} ne '') {
 9926:         @currxlists = split(/,/,$$settings{'internal.crosslistings'});
 9927:     }
 9928: 
 9929:     if (@currxlists > 0) {
 9930:         foreach (@currxlists) {
 9931:             if (m/^([^:]+):(\w*)$/) {
 9932:                 unless (grep/^$1$/,@{$allcourses}) {
 9933:                     push @{$allcourses},$1;
 9934:                     $$LC_code{$1} = $2;
 9935:                 }
 9936:             }
 9937:         }
 9938:     }
 9939:  
 9940:     if (@currsections > 0) {
 9941:         foreach (@currsections) {
 9942:             if (m/^(\w+):(\w*)$/) {
 9943:                 my $sec = $coursecode.$1;
 9944:                 my $lc_sec = $2;
 9945:                 unless (grep/^$sec$/,@{$allcourses}) {
 9946:                     push @{$allcourses},$sec;
 9947:                     $$LC_code{$sec} = $lc_sec;
 9948:                 }
 9949:             }
 9950:         }
 9951:     }
 9952:     return;
 9953: }
 9954: 
 9955: sub get_standard_codeitems {
 9956:     return ('Year','Semester','Department','Number','Section');
 9957: }
 9958: 
 9959: =pod
 9960: 
 9961: =head1 Slot Helpers
 9962: 
 9963: =over 4
 9964: 
 9965: =item * sorted_slots()
 9966: 
 9967: Sorts an array of slot names in order of an optional sort key,
 9968: default sort is by slot start time (earliest first). 
 9969: 
 9970: Inputs:
 9971: 
 9972: =over 4
 9973: 
 9974: slotsarr  - Reference to array of unsorted slot names.
 9975: 
 9976: slots     - Reference to hash of hash, where outer hash keys are slot names.
 9977: 
 9978: sortkey   - Name of key in inner hash to be sorted on (e.g., starttime).
 9979: 
 9980: =back
 9981: 
 9982: Returns:
 9983: 
 9984: =over 4
 9985: 
 9986: sorted   - An array of slot names sorted by a specified sort key 
 9987:            (default sort key is start time of the slot).
 9988: 
 9989: =back
 9990: 
 9991: =cut
 9992: 
 9993: 
 9994: sub sorted_slots {
 9995:     my ($slotsarr,$slots,$sortkey) = @_;
 9996:     if ($sortkey eq '') {
 9997:         $sortkey = 'starttime';
 9998:     }
 9999:     my @sorted;
10000:     if ((ref($slotsarr) eq 'ARRAY') && (ref($slots) eq 'HASH')) {
10001:         @sorted =
10002:             sort {
10003:                      if (ref($slots->{$a}) && ref($slots->{$b})) {
10004:                          return $slots->{$a}{$sortkey} <=> $slots->{$b}{$sortkey}
10005:                      }
10006:                      if (ref($slots->{$a})) { return -1;}
10007:                      if (ref($slots->{$b})) { return 1;}
10008:                      return 0;
10009:                  } @{$slotsarr};
10010:     }
10011:     return @sorted;
10012: }
10013: 
10014: =pod
10015: 
10016: =item * get_future_slots()
10017: 
10018: Inputs:
10019: 
10020: =over 4
10021: 
10022: cnum - course number
10023: 
10024: cdom - course domain
10025: 
10026: now - current UNIX time
10027: 
10028: symb - optional symb
10029: 
10030: =back
10031: 
10032: Returns:
10033: 
10034: =over 4
10035: 
10036: sorted_reservable - ref to array of student_schedulable slots currently 
10037:                     reservable, ordered by end date of reservation period.
10038: 
10039: reservable_now - ref to hash of student_schedulable slots currently
10040:                  reservable.
10041: 
10042:     Keys in inner hash are:
10043:     (a) symb: either blank or symb to which slot use is restricted.
10044:     (b) endreserve: end date of reservation period. 
10045: 
10046: sorted_future - ref to array of student_schedulable slots reservable in
10047:                 the future, ordered by start date of reservation period.
10048: 
10049: future_reservable - ref to hash of student_schedulable slots reservable
10050:                     in the future.
10051: 
10052:     Keys in inner hash are:
10053:     (a) symb: either blank or symb to which slot use is restricted.
10054:     (b) startreserve:  start date of reservation period.
10055: 
10056: =back
10057: 
10058: =cut
10059: 
10060: sub get_future_slots {
10061:     my ($cnum,$cdom,$now,$symb) = @_;
10062:     my (%reservable_now,%future_reservable,@sorted_reservable,@sorted_future);
10063:     my %slots = &Apache::lonnet::get_course_slots($cnum,$cdom);
10064:     foreach my $slot (keys(%slots)) {
10065:         next unless($slots{$slot}->{'type'} eq 'schedulable_student');
10066:         if ($symb) {
10067:             next if (($slots{$slot}->{'symb'} ne '') && 
10068:                      ($slots{$slot}->{'symb'} ne $symb));
10069:         }
10070:         if (($slots{$slot}->{'starttime'} > $now) &&
10071:             ($slots{$slot}->{'endtime'} > $now)) {
10072:             if (($slots{$slot}->{'allowedsections'}) || ($slots{$slot}->{'allowedusers'})) {
10073:                 my $userallowed = 0;
10074:                 if ($slots{$slot}->{'allowedsections'}) {
10075:                     my @allowed_sec = split(',',$slots{$slot}->{'allowedsections'});
10076:                     if (!defined($env{'request.role.sec'})
10077:                         && grep(/^No section assigned$/,@allowed_sec)) {
10078:                         $userallowed=1;
10079:                     } else {
10080:                         if (grep(/^\Q$env{'request.role.sec'}\E$/,@allowed_sec)) {
10081:                             $userallowed=1;
10082:                         }
10083:                     }
10084:                     unless ($userallowed) {
10085:                         if (defined($env{'request.course.groups'})) {
10086:                             my @groups = split(/:/,$env{'request.course.groups'});
10087:                             foreach my $group (@groups) {
10088:                                 if (grep(/^\Q$group\E$/,@allowed_sec)) {
10089:                                     $userallowed=1;
10090:                                     last;
10091:                                 }
10092:                             }
10093:                         }
10094:                     }
10095:                 }
10096:                 if ($slots{$slot}->{'allowedusers'}) {
10097:                     my @allowed_users = split(',',$slots{$slot}->{'allowedusers'});
10098:                     my $user = $env{'user.name'}.':'.$env{'user.domain'};
10099:                     if (grep(/^\Q$user\E$/,@allowed_users)) {
10100:                         $userallowed = 1;
10101:                     }
10102:                 }
10103:                 next unless($userallowed);
10104:             }
10105:             my $startreserve = $slots{$slot}->{'startreserve'};
10106:             my $endreserve = $slots{$slot}->{'endreserve'};
10107:             my $symb = $slots{$slot}->{'symb'};
10108:             if (($startreserve < $now) &&
10109:                 (!$endreserve || $endreserve > $now)) {
10110:                 my $lastres = $endreserve;
10111:                 if (!$lastres) {
10112:                     $lastres = $slots{$slot}->{'starttime'};
10113:                 }
10114:                 $reservable_now{$slot} = {
10115:                                            symb       => $symb,
10116:                                            endreserve => $lastres
10117:                                          };
10118:             } elsif (($startreserve > $now) &&
10119:                      (!$endreserve || $endreserve > $startreserve)) {
10120:                 $future_reservable{$slot} = {
10121:                                               symb         => $symb,
10122:                                               startreserve => $startreserve
10123:                                             };
10124:             }
10125:         }
10126:     }
10127:     my @unsorted_reservable = keys(%reservable_now);
10128:     if (@unsorted_reservable > 0) {
10129:         @sorted_reservable = 
10130:             &sorted_slots(\@unsorted_reservable,\%reservable_now,'endreserve');
10131:     }
10132:     my @unsorted_future = keys(%future_reservable);
10133:     if (@unsorted_future > 0) {
10134:         @sorted_future =
10135:             &sorted_slots(\@unsorted_future,\%future_reservable,'startreserve');
10136:     }
10137:     return (\@sorted_reservable,\%reservable_now,\@sorted_future,\%future_reservable);
10138: }
10139: 
10140: =pod
10141: 
10142: =back
10143: 
10144: =head1 HTTP Helpers
10145: 
10146: =over 4
10147: 
10148: =item * &get_unprocessed_cgi($query,$possible_names)
10149: 
10150: Modify the %env hash to contain unprocessed CGI form parameters held in
10151: $query.  The parameters listed in $possible_names (an array reference),
10152: will be set in $env{'form.name'} if they do not already exist.
10153: 
10154: Typically called with $ENV{'QUERY_STRING'} as the first parameter.  
10155: $possible_names is an ref to an array of form element names.  As an example:
10156: get_unprocessed_cgi($ENV{'QUERY_STRING'},['uname','udom']);
10157: will result in $env{'form.uname'} and $env{'form.udom'} being set.
10158: 
10159: =cut
10160: 
10161: sub get_unprocessed_cgi {
10162:   my ($query,$possible_names)= @_;
10163:   # $Apache::lonxml::debug=1;
10164:   foreach my $pair (split(/&/,$query)) {
10165:     my ($name, $value) = split(/=/,$pair);
10166:     $name = &unescape($name);
10167:     if (!defined($possible_names) || (grep {$_ eq $name} @$possible_names)) {
10168:       $value =~ tr/+/ /;
10169:       $value =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack("C",hex($1))/eg;
10170:       unless (defined($env{'form.'.$name})) { &add_to_env('form.'.$name,$value) };
10171:     }
10172:   }
10173: }
10174: 
10175: =pod
10176: 
10177: =item * &cacheheader() 
10178: 
10179: returns cache-controlling header code
10180: 
10181: =cut
10182: 
10183: sub cacheheader {
10184:     unless ($env{'request.method'} eq 'GET') { return ''; }
10185:     my $date=strftime("%a, %d %b %Y %H:%M:%S GMT",gmtime);
10186:     my $output .='<meta HTTP-EQUIV="Expires" CONTENT="'.$date.'" />
10187:                 <meta HTTP-EQUIV="Cache-control" CONTENT="no-cache" />
10188:                 <meta HTTP-EQUIV="Pragma" CONTENT="no-cache" />';
10189:     return $output;
10190: }
10191: 
10192: =pod
10193: 
10194: =item * &no_cache($r) 
10195: 
10196: specifies header code to not have cache
10197: 
10198: =cut
10199: 
10200: sub no_cache {
10201:     my ($r) = @_;
10202:     if ($ENV{'REQUEST_METHOD'} ne 'GET' &&
10203: 	$env{'request.method'} ne 'GET') { return ''; }
10204:     my $date=strftime("%a, %d %b %Y %H:%M:%S GMT",gmtime(time));
10205:     $r->no_cache(1);
10206:     $r->header_out("Expires" => $date);
10207:     $r->header_out("Pragma" => "no-cache");
10208: }
10209: 
10210: sub content_type {
10211:     my ($r,$type,$charset) = @_;
10212:     if ($r) {
10213: 	#  Note that printout.pl calls this with undef for $r.
10214: 	&no_cache($r);
10215:     }
10216:     if ($env{'browser.mathml'} && $type eq 'text/html') { $type='text/xml'; }
10217:     unless ($charset) {
10218: 	$charset=&Apache::lonlocal::current_encoding;
10219:     }
10220:     if ($charset) { $type.='; charset='.$charset; }
10221:     if ($r) {
10222: 	$r->content_type($type);
10223:     } else {
10224: 	print("Content-type: $type\n\n");
10225:     }
10226: }
10227: 
10228: =pod
10229: 
10230: =item * &add_to_env($name,$value) 
10231: 
10232: adds $name to the %env hash with value
10233: $value, if $name already exists, the entry is converted to an array
10234: reference and $value is added to the array.
10235: 
10236: =cut
10237: 
10238: sub add_to_env {
10239:   my ($name,$value)=@_;
10240:   if (defined($env{$name})) {
10241:     if (ref($env{$name})) {
10242:       #already have multiple values
10243:       push(@{ $env{$name} },$value);
10244:     } else {
10245:       #first time seeing multiple values, convert hash entry to an arrayref
10246:       my $first=$env{$name};
10247:       undef($env{$name});
10248:       push(@{ $env{$name} },$first,$value);
10249:     }
10250:   } else {
10251:     $env{$name}=$value;
10252:   }
10253: }
10254: 
10255: =pod
10256: 
10257: =item * &get_env_multiple($name) 
10258: 
10259: gets $name from the %env hash, it seemlessly handles the cases where multiple
10260: values may be defined and end up as an array ref.
10261: 
10262: returns an array of values
10263: 
10264: =cut
10265: 
10266: sub get_env_multiple {
10267:     my ($name) = @_;
10268:     my @values;
10269:     if (defined($env{$name})) {
10270:         # exists is it an array
10271:         if (ref($env{$name})) {
10272:             @values=@{ $env{$name} };
10273:         } else {
10274:             $values[0]=$env{$name};
10275:         }
10276:     }
10277:     return(@values);
10278: }
10279: 
10280: sub ask_for_embedded_content {
10281:     my ($actionurl,$state,$allfiles,$codebase,$args)=@_;
10282:     my (%subdependencies,%dependencies,%mapping,%existing,%newfiles,%pathchanges,
10283:         %currsubfile,%unused,$rem);
10284:     my $counter = 0;
10285:     my $numnew = 0;
10286:     my $numremref = 0;
10287:     my $numinvalid = 0;
10288:     my $numpathchg = 0;
10289:     my $numexisting = 0;
10290:     my $numunused = 0;
10291:     my ($output,$upload_output,$toplevel,$url,$udom,$uname,$getpropath,$cdom,$cnum,
10292:         $fileloc,$filename,$delete_output,$modify_output,$title,$symb,$path,$navmap);
10293:     my $heading = &mt('Upload embedded files');
10294:     my $buttontext = &mt('Upload');
10295: 
10296:     if ($env{'request.course.id'}) {
10297:         if ($actionurl eq '/adm/dependencies') {
10298:             $navmap = Apache::lonnavmaps::navmap->new();
10299:         }
10300:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
10301:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
10302:     }
10303:     if (($actionurl eq '/adm/portfolio') || 
10304:         ($actionurl eq '/adm/coursegrp_portfolio')) {
10305:         my $current_path='/';
10306:         if ($env{'form.currentpath'}) {
10307:             $current_path = $env{'form.currentpath'};
10308:         }
10309:         if ($actionurl eq '/adm/coursegrp_portfolio') {
10310:             $udom = $cdom;
10311:             $uname = $cnum;
10312:             $url = '/userfiles/groups/'.$env{'form.group'}.'/portfolio';
10313:         } else {
10314:             $udom = $env{'user.domain'};
10315:             $uname = $env{'user.name'};
10316:             $url = '/userfiles/portfolio';
10317:         }
10318:         $toplevel = $url.'/';
10319:         $url .= $current_path;
10320:         $getpropath = 1;
10321:     } elsif (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank') ||
10322:              ($actionurl eq '/adm/imsimport')) { 
10323:         my ($udom,$uname,$rest) = ($args->{'current_path'} =~ m{/priv/($match_domain)/($match_username)/?(.*)$});
10324:         $url = $Apache::lonnet::perlvar{'lonDocRoot'}."/priv/$udom/$uname/";
10325:         $toplevel = $url;
10326:         if ($rest ne '') {
10327:             $url .= $rest;
10328:         }
10329:     } elsif ($actionurl eq '/adm/coursedocs') {
10330:         if (ref($args) eq 'HASH') {
10331:             $url = $args->{'docs_url'};
10332:             $toplevel = $url;
10333:             if ($args->{'context'} eq 'paste') {
10334:                 ($cdom,$cnum) = ($url =~ m{^\Q/uploaded/\E($match_domain)/($match_courseid)/});
10335:                 ($path) = 
10336:                     ($toplevel =~ m{^(\Q/uploaded/$cdom/$cnum/\E(?:docs|supplemental)/(?:default|\d+)/\d+)/});
10337:                 $fileloc = &Apache::lonnet::filelocation('',$toplevel);
10338:                 $fileloc =~ s{^/}{};
10339:             }
10340:         }
10341:     } elsif ($actionurl eq '/adm/dependencies')  {
10342:         if ($env{'request.course.id'} ne '') {
10343:             if (ref($args) eq 'HASH') {
10344:                 $url = $args->{'docs_url'};
10345:                 $title = $args->{'docs_title'};
10346:                 $toplevel = $url; 
10347:                 unless ($toplevel =~ m{^/}) {
10348:                     $toplevel = "/$url";
10349:                 }
10350:                 ($rem) = ($toplevel =~ m{^(.+/)[^/]+$});
10351:                 if ($toplevel =~ m{^(\Q/uploaded/$cdom/$cnum/portfolio/syllabus\E)}) {
10352:                     $path = $1;
10353:                 } else {
10354:                     ($path) =
10355:                         ($toplevel =~ m{^(\Q/uploaded/$cdom/$cnum/\E(?:docs|supplemental)/(?:default|\d+)/\d+)/});
10356:                 }
10357:                 if ($toplevel=~/^\/*(uploaded|editupload)/) {
10358:                     $fileloc = $toplevel;
10359:                     $fileloc=~ s/^\s*(\S+)\s*$/$1/;
10360:                     my ($udom,$uname,$fname) =
10361:                         ($fileloc=~ m{^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$});
10362:                     $fileloc = propath($udom,$uname).'/userfiles/'.$fname;
10363:                 } else {
10364:                     $fileloc = &Apache::lonnet::filelocation('',$toplevel);
10365:                 }
10366:                 $fileloc =~ s{^/}{};
10367:                 ($filename) = ($fileloc =~ m{.+/([^/]+)$});
10368:                 $heading = &mt('Status of dependencies in [_1]',"$title ($filename)");
10369:             }
10370:         }
10371:     } elsif ($actionurl eq "/public/$cdom/$cnum/syllabus") {
10372:         $udom = $cdom;
10373:         $uname = $cnum;
10374:         $url = "/uploaded/$cdom/$cnum/portfolio/syllabus";
10375:         $toplevel = $url;
10376:         $path = $url;
10377:         $fileloc = &Apache::lonnet::filelocation('',$toplevel).'/';
10378:         $fileloc =~ s{^/}{};
10379:     }
10380:     foreach my $file (keys(%{$allfiles})) {
10381:         my $embed_file;
10382:         if (($path eq "/uploaded/$cdom/$cnum/portfolio/syllabus") && ($file =~ m{^\Q$path/\E(.+)$})) {
10383:             $embed_file = $1;
10384:         } else {
10385:             $embed_file = $file;
10386:         }
10387:         my ($absolutepath,$cleaned_file);
10388:         if ($embed_file =~ m{^\w+://}) {
10389:             $cleaned_file = $embed_file;
10390:             $newfiles{$cleaned_file} = 1;
10391:             $mapping{$cleaned_file} = $embed_file;
10392:         } else {
10393:             $cleaned_file = &clean_path($embed_file);
10394:             if ($embed_file =~ m{^/}) {
10395:                 $absolutepath = $embed_file;
10396:             }
10397:             if ($cleaned_file =~ m{/}) {
10398:                 my ($path,$fname) = ($cleaned_file =~ m{^(.+)/([^/]*)$});
10399:                 $path = &check_for_traversal($path,$url,$toplevel);
10400:                 my $item = $fname;
10401:                 if ($path ne '') {
10402:                     $item = $path.'/'.$fname;
10403:                     $subdependencies{$path}{$fname} = 1;
10404:                 } else {
10405:                     $dependencies{$item} = 1;
10406:                 }
10407:                 if ($absolutepath) {
10408:                     $mapping{$item} = $absolutepath;
10409:                 } else {
10410:                     $mapping{$item} = $embed_file;
10411:                 }
10412:             } else {
10413:                 $dependencies{$embed_file} = 1;
10414:                 if ($absolutepath) {
10415:                     $mapping{$cleaned_file} = $absolutepath;
10416:                 } else {
10417:                     $mapping{$cleaned_file} = $embed_file;
10418:                 }
10419:             }
10420:         }
10421:     }
10422:     my $dirptr = 16384;
10423:     foreach my $path (keys(%subdependencies)) {
10424:         $currsubfile{$path} = {};
10425:         if (($actionurl eq '/adm/portfolio') || 
10426:             ($actionurl eq '/adm/coursegrp_portfolio')) {
10427:             my ($sublistref,$listerror) =
10428:                 &Apache::lonnet::dirlist($url.$path,$udom,$uname,$getpropath);
10429:             if (ref($sublistref) eq 'ARRAY') {
10430:                 foreach my $line (@{$sublistref}) {
10431:                     my ($file_name,$rest) = split(/\&/,$line,2);
10432:                     $currsubfile{$path}{$file_name} = 1;
10433:                 }
10434:             }
10435:         } elsif (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank')) {
10436:             if (opendir(my $dir,$url.'/'.$path)) {
10437:                 my @subdir_list = grep(!/^\./,readdir($dir));
10438:                 map {$currsubfile{$path}{$_} = 1;} @subdir_list;
10439:             }
10440:         } elsif (($actionurl eq '/adm/dependencies') ||
10441:                  (($actionurl eq '/adm/coursedocs') && (ref($args) eq 'HASH') &&
10442:                   ($args->{'context'} eq 'paste')) ||
10443:                  ($actionurl eq "/public/$cdom/$cnum/syllabus")) {
10444:             if ($env{'request.course.id'} ne '') {
10445:                 my $dir;
10446:                 if ($actionurl eq "/public/$cdom/$cnum/syllabus") {
10447:                     $dir = $fileloc;
10448:                 } else {
10449:                     ($dir) = ($fileloc =~ m{^(.+/)[^/]+$});
10450:                 }
10451:                 if ($dir ne '') {
10452:                     my ($sublistref,$listerror) =
10453:                         &Apache::lonnet::dirlist($dir.$path,$cdom,$cnum,$getpropath,undef,'/');
10454:                     if (ref($sublistref) eq 'ARRAY') {
10455:                         foreach my $line (@{$sublistref}) {
10456:                             my ($file_name,$dom,undef,$testdir,undef,undef,undef,undef,$size,
10457:                                 undef,$mtime)=split(/\&/,$line,12);
10458:                             unless (($testdir&$dirptr) ||
10459:                                     ($file_name =~ /^\.\.?$/)) {
10460:                                 $currsubfile{$path}{$file_name} = [$size,$mtime];
10461:                             }
10462:                         }
10463:                     }
10464:                 }
10465:             }
10466:         }
10467:         foreach my $file (keys(%{$subdependencies{$path}})) {
10468:             if (exists($currsubfile{$path}{$file})) {
10469:                 my $item = $path.'/'.$file;
10470:                 unless ($mapping{$item} eq $item) {
10471:                     $pathchanges{$item} = 1;
10472:                 }
10473:                 $existing{$item} = 1;
10474:                 $numexisting ++;
10475:             } else {
10476:                 $newfiles{$path.'/'.$file} = 1;
10477:             }
10478:         }
10479:         if ($actionurl eq '/adm/dependencies') {
10480:             foreach my $path (keys(%currsubfile)) {
10481:                 if (ref($currsubfile{$path}) eq 'HASH') {
10482:                     foreach my $file (keys(%{$currsubfile{$path}})) {
10483:                          unless ($subdependencies{$path}{$file}) {
10484:                              next if (($rem ne '') &&
10485:                                       (($env{"httpref.$rem"."$path/$file"} ne '') ||
10486:                                        (ref($navmap) &&
10487:                                        (($navmap->getResourceByUrl($rem."$path/$file") ne '') ||
10488:                                         (($file =~ /^(.*\.s?html?)\.bak$/i) &&
10489:                                          ($navmap->getResourceByUrl($rem."$path/$1")))))));
10490:                              $unused{$path.'/'.$file} = 1; 
10491:                          }
10492:                     }
10493:                 }
10494:             }
10495:         }
10496:     }
10497:     my %currfile;
10498:     if (($actionurl eq '/adm/portfolio') ||
10499:         ($actionurl eq '/adm/coursegrp_portfolio')) {
10500:         my ($dirlistref,$listerror) =
10501:             &Apache::lonnet::dirlist($url,$udom,$uname,$getpropath);
10502:         if (ref($dirlistref) eq 'ARRAY') {
10503:             foreach my $line (@{$dirlistref}) {
10504:                 my ($file_name,$rest) = split(/\&/,$line,2);
10505:                 $currfile{$file_name} = 1;
10506:             }
10507:         }
10508:     } elsif (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank')) {
10509:         if (opendir(my $dir,$url)) {
10510:             my @dir_list = grep(!/^\./,readdir($dir));
10511:             map {$currfile{$_} = 1;} @dir_list;
10512:         }
10513:     } elsif (($actionurl eq '/adm/dependencies') ||
10514:              (($actionurl eq '/adm/coursedocs') && (ref($args) eq 'HASH') &&
10515:               ($args->{'context'} eq 'paste')) ||
10516:              ($actionurl eq "/public/$cdom/$cnum/syllabus")) {
10517:         if ($env{'request.course.id'} ne '') {
10518:             my ($dir) = ($fileloc =~ m{^(.+/)[^/]+$});
10519:             if ($dir ne '') {
10520:                 my ($dirlistref,$listerror) =
10521:                     &Apache::lonnet::dirlist($dir,$cdom,$cnum,$getpropath,undef,'/');
10522:                 if (ref($dirlistref) eq 'ARRAY') {
10523:                     foreach my $line (@{$dirlistref}) {
10524:                         my ($file_name,$dom,undef,$testdir,undef,undef,undef,undef,
10525:                             $size,undef,$mtime)=split(/\&/,$line,12);
10526:                         unless (($testdir&$dirptr) ||
10527:                                 ($file_name =~ /^\.\.?$/)) {
10528:                             $currfile{$file_name} = [$size,$mtime];
10529:                         }
10530:                     }
10531:                 }
10532:             }
10533:         }
10534:     }
10535:     foreach my $file (keys(%dependencies)) {
10536:         if (exists($currfile{$file})) {
10537:             unless ($mapping{$file} eq $file) {
10538:                 $pathchanges{$file} = 1;
10539:             }
10540:             $existing{$file} = 1;
10541:             $numexisting ++;
10542:         } else {
10543:             $newfiles{$file} = 1;
10544:         }
10545:     }
10546:     foreach my $file (keys(%currfile)) {
10547:         unless (($file eq $filename) ||
10548:                 ($file eq $filename.'.bak') ||
10549:                 ($dependencies{$file})) {
10550:             if ($actionurl eq '/adm/dependencies') {
10551:                 unless ($toplevel =~ m{^\Q/uploaded/$cdom/$cnum/portfolio/syllabus\E}) {
10552:                     next if (($rem ne '') &&
10553:                              (($env{"httpref.$rem".$file} ne '') ||
10554:                               (ref($navmap) &&
10555:                               (($navmap->getResourceByUrl($rem.$file) ne '') ||
10556:                                (($file =~ /^(.*\.s?html?)\.bak$/i) &&
10557:                                 ($navmap->getResourceByUrl($rem.$1)))))));
10558:                 }
10559:             }
10560:             $unused{$file} = 1;
10561:         }
10562:     }
10563:     if (($actionurl eq '/adm/coursedocs') && (ref($args) eq 'HASH') &&
10564:         ($args->{'context'} eq 'paste')) {
10565:         $counter = scalar(keys(%existing));
10566:         $numpathchg = scalar(keys(%pathchanges));
10567:         return ($output,$counter,$numpathchg,\%existing);
10568:     } elsif (($actionurl eq "/public/$cdom/$cnum/syllabus") && 
10569:              (ref($args) eq 'HASH') && ($args->{'context'} eq 'rewrites')) {
10570:         $counter = scalar(keys(%existing));
10571:         $numpathchg = scalar(keys(%pathchanges));
10572:         return ($output,$counter,$numpathchg,\%existing,\%mapping);
10573:     }
10574:     foreach my $embed_file (sort {lc($a) cmp lc($b)} keys(%newfiles)) {
10575:         if ($actionurl eq '/adm/dependencies') {
10576:             next if ($embed_file =~ m{^\w+://});
10577:         }
10578:         $upload_output .= &start_data_table_row().
10579:                           '<td valign="top"><img src="'.&icon($embed_file).'" />&nbsp;'.
10580:                           '<span class="LC_filename">'.$embed_file.'</span>';
10581:         unless ($mapping{$embed_file} eq $embed_file) {
10582:             $upload_output .= '<br /><span class="LC_info" style="font-size:smaller;">'.
10583:                               &mt('changed from: [_1]',$mapping{$embed_file}).'</span>';
10584:         }
10585:         $upload_output .= '</td>';
10586:         if ($args->{'ignore_remote_references'} && $embed_file =~ m{^\w+://}) { 
10587:             $upload_output.='<td align="right">'.
10588:                             '<span class="LC_info LC_fontsize_medium">'.
10589:                             &mt("URL points to web address").'</span>';
10590:             $numremref++;
10591:         } elsif ($args->{'error_on_invalid_names'}
10592:             && $embed_file ne &Apache::lonnet::clean_filename($embed_file,{'keep_path' => 1,})) {
10593:             $upload_output.='<td align="right"><span class="LC_warning">'.
10594:                             &mt('Invalid characters').'</span>';
10595:             $numinvalid++;
10596:         } else {
10597:             $upload_output .= '<td>'.
10598:                               &embedded_file_element('upload_embedded',$counter,
10599:                                                      $embed_file,\%mapping,
10600:                                                      $allfiles,$codebase,'upload');
10601:             $counter ++;
10602:             $numnew ++;
10603:         }
10604:         $upload_output .= '</td>'.&Apache::loncommon::end_data_table_row()."\n";
10605:     }
10606:     foreach my $embed_file (sort {lc($a) cmp lc($b)} keys(%existing)) {
10607:         if ($actionurl eq '/adm/dependencies') {
10608:             my ($size,$mtime) = &get_dependency_details(\%currfile,\%currsubfile,$embed_file);
10609:             $modify_output .= &start_data_table_row().
10610:                               '<td><a href="'.$path.'/'.$embed_file.'" style="text-decoration:none;">'.
10611:                               '<img src="'.&icon($embed_file).'" border="0" />'.
10612:                               '&nbsp;<span class="LC_filename">'.$embed_file.'</span></a></td>'.
10613:                               '<td>'.$size.'</td>'.
10614:                               '<td>'.$mtime.'</td>'.
10615:                               '<td><label><input type="checkbox" name="mod_upload_dep" '.
10616:                               'onclick="toggleBrowse('."'$counter'".')" id="mod_upload_dep_'.
10617:                               $counter.'" value="'.$counter.'" />'.&mt('Yes').'</label>'.
10618:                               '<div id="moduploaddep_'.$counter.'" style="display:none;">'.
10619:                               &embedded_file_element('upload_embedded',$counter,
10620:                                                      $embed_file,\%mapping,
10621:                                                      $allfiles,$codebase,'modify').
10622:                               '</div></td>'.
10623:                               &end_data_table_row()."\n";
10624:             $counter ++;
10625:         } else {
10626:             $upload_output .= &start_data_table_row().
10627:                               '<td valign="top"><img src="'.&icon($embed_file).'" />&nbsp;'.
10628:                               '<span class="LC_filename">'.$embed_file.'</span></td>'.
10629:                               '<td align="right"><span class="LC_info LC_fontsize_medium">'.&mt('Already exists').'</span></td>'.
10630:                               &Apache::loncommon::end_data_table_row()."\n";
10631:         }
10632:     }
10633:     my $delidx = $counter;
10634:     foreach my $oldfile (sort {lc($a) cmp lc($b)} keys(%unused)) {
10635:         my ($size,$mtime) = &get_dependency_details(\%currfile,\%currsubfile,$oldfile);
10636:         $delete_output .= &start_data_table_row().
10637:                           '<td><img src="'.&icon($oldfile).'" />'.
10638:                           '&nbsp;<span class="LC_filename">'.$oldfile.'</span></td>'.
10639:                           '<td>'.$size.'</td>'.
10640:                           '<td>'.$mtime.'</td>'.
10641:                           '<td><label><input type="checkbox" name="del_upload_dep" '.
10642:                           ' value="'.$delidx.'" />'.&mt('Yes').'</label>'.
10643:                           &embedded_file_element('upload_embedded',$delidx,
10644:                                                  $oldfile,\%mapping,$allfiles,
10645:                                                  $codebase,'delete').'</td>'.
10646:                           &end_data_table_row()."\n"; 
10647:         $numunused ++;
10648:         $delidx ++;
10649:     }
10650:     if ($upload_output) {
10651:         $upload_output = &start_data_table().
10652:                          $upload_output.
10653:                          &end_data_table()."\n";
10654:     }
10655:     if ($modify_output) {
10656:         $modify_output = &start_data_table().
10657:                          &start_data_table_header_row().
10658:                          '<th>'.&mt('File').'</th>'.
10659:                          '<th>'.&mt('Size (KB)').'</th>'.
10660:                          '<th>'.&mt('Modified').'</th>'.
10661:                          '<th>'.&mt('Upload replacement?').'</th>'.
10662:                          &end_data_table_header_row().
10663:                          $modify_output.
10664:                          &end_data_table()."\n";
10665:     }
10666:     if ($delete_output) {
10667:         $delete_output = &start_data_table().
10668:                          &start_data_table_header_row().
10669:                          '<th>'.&mt('File').'</th>'.
10670:                          '<th>'.&mt('Size (KB)').'</th>'.
10671:                          '<th>'.&mt('Modified').'</th>'.
10672:                          '<th>'.&mt('Delete?').'</th>'.
10673:                          &end_data_table_header_row().
10674:                          $delete_output.
10675:                          &end_data_table()."\n";
10676:     }
10677:     my $applies = 0;
10678:     if ($numremref) {
10679:         $applies ++;
10680:     }
10681:     if ($numinvalid) {
10682:         $applies ++;
10683:     }
10684:     if ($numexisting) {
10685:         $applies ++;
10686:     }
10687:     if ($counter || $numunused) {
10688:         $output = '<form name="upload_embedded" action="'.$actionurl.'"'.
10689:                   ' method="post" enctype="multipart/form-data">'."\n".
10690:                   $state.'<h3>'.$heading.'</h3>'; 
10691:         if ($actionurl eq '/adm/dependencies') {
10692:             if ($numnew) {
10693:                 $output .= '<h4>'.&mt('Missing dependencies').'</h4>'.
10694:                            '<p>'.&mt('The following files need to be uploaded.').'</p>'."\n".
10695:                            $upload_output.'<br />'."\n";
10696:             }
10697:             if ($numexisting) {
10698:                 $output .= '<h4>'.&mt('Uploaded dependencies (in use)').'</h4>'.
10699:                            '<p>'.&mt('Upload a new file to replace the one currently in use.').'</p>'."\n".
10700:                            $modify_output.'<br />'."\n";
10701:                            $buttontext = &mt('Save changes');
10702:             }
10703:             if ($numunused) {
10704:                 $output .= '<h4>'.&mt('Unused files').'</h4>'.
10705:                            '<p>'.&mt('The following uploaded files are no longer used.').'</p>'."\n".
10706:                            $delete_output.'<br />'."\n";
10707:                            $buttontext = &mt('Save changes');
10708:             }
10709:         } else {
10710:             $output .= $upload_output.'<br />'."\n";
10711:         }
10712:         $output .= '<input type ="hidden" name="number_embedded_items" value="'.
10713:                    $counter.'" />'."\n";
10714:         if ($actionurl eq '/adm/dependencies') { 
10715:             $output .= '<input type ="hidden" name="number_newemb_items" value="'.
10716:                        $numnew.'" />'."\n";
10717:         } elsif ($actionurl eq '') {
10718:             $output .=  '<input type="hidden" name="phase" value="three" />';
10719:         }
10720:     } elsif ($applies) {
10721:         $output = '<b>'.&mt('Referenced files').'</b>:<br />';
10722:         if ($applies > 1) {
10723:             $output .=  
10724:                 &mt('No dependencies need to be uploaded, as one of the following applies to each reference:').'<ul>';
10725:             if ($numremref) {
10726:                 $output .= '<li>'.&mt('reference is to a URL which points to another server').'</li>'."\n";
10727:             }
10728:             if ($numinvalid) {
10729:                 $output .= '<li>'.&mt('reference is to file with a name containing invalid characters').'</li>'."\n";
10730:             }
10731:             if ($numexisting) {
10732:                 $output .= '<li>'.&mt('reference is to an existing file at the specified location').'</li>'."\n";
10733:             }
10734:             $output .= '</ul><br />';
10735:         } elsif ($numremref) {
10736:             $output .= '<p>'.&mt('None to upload, as all references are to URLs pointing to another server.').'</p>';
10737:         } elsif ($numinvalid) {
10738:             $output .= '<p>'.&mt('None to upload, as all references are to files with names containing invalid characters.').'</p>';
10739:         } elsif ($numexisting) {
10740:             $output .= '<p>'.&mt('None to upload, as all references are to existing files.').'</p>';
10741:         }
10742:         $output .= $upload_output.'<br />';
10743:     }
10744:     my ($pathchange_output,$chgcount);
10745:     $chgcount = $counter;
10746:     if (keys(%pathchanges) > 0) {
10747:         foreach my $embed_file (sort {lc($a) cmp lc($b)} keys(%pathchanges)) {
10748:             if ($counter) {
10749:                 $output .= &embedded_file_element('pathchange',$chgcount,
10750:                                                   $embed_file,\%mapping,
10751:                                                   $allfiles,$codebase,'change');
10752:             } else {
10753:                 $pathchange_output .= 
10754:                     &start_data_table_row().
10755:                     '<td><input type ="checkbox" name="namechange" value="'.
10756:                     $chgcount.'" checked="checked" /></td>'.
10757:                     '<td>'.$mapping{$embed_file}.'</td>'.
10758:                     '<td>'.$embed_file.
10759:                     &embedded_file_element('pathchange',$numpathchg,$embed_file,
10760:                                            \%mapping,$allfiles,$codebase,'change').
10761:                     '</td>'.&end_data_table_row();
10762:             }
10763:             $numpathchg ++;
10764:             $chgcount ++;
10765:         }
10766:     }
10767:     if (($counter) || ($numunused)) {
10768:         if ($numpathchg) {
10769:             $output .= '<input type ="hidden" name="number_pathchange_items" value="'.
10770:                        $numpathchg.'" />'."\n";
10771:         }
10772:         if (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank') || 
10773:             ($actionurl eq '/adm/imsimport')) {
10774:             $output .= '<input type="hidden" name="phase" value="three" />'."\n";
10775:         } elsif ($actionurl eq '/adm/portfolio' || $actionurl eq '/adm/coursegrp_portfolio') {
10776:             $output .= '<input type="hidden" name="action" value="upload_embedded" />';
10777:         } elsif ($actionurl eq '/adm/dependencies') {
10778:             $output .= '<input type="hidden" name="action" value="process_changes" />';
10779:         }
10780:         $output .= '<input type ="submit" value="'.$buttontext.'" />'."\n".'</form>'."\n";
10781:     } elsif ($numpathchg) {
10782:         my %pathchange = ();
10783:         $output .= &modify_html_form('pathchange',$actionurl,$state,\%pathchange,$pathchange_output);
10784:         if (($actionurl eq '/adm/portfolio') || ($actionurl eq '/adm/coursegrp_portfolio')) {
10785:             $output .= '<p>'.&mt('or').'</p>'; 
10786:         }
10787:     }
10788:     return ($output,$counter,$numpathchg);
10789: }
10790: 
10791: =pod
10792: 
10793: =item * clean_path($name)
10794: 
10795: Performs clean-up of directories, subdirectories and filename in an
10796: embedded object, referenced in an HTML file which is being uploaded
10797: to a course or portfolio, where 
10798: "Upload embedded images/multimedia files if HTML file" checkbox was
10799: checked.
10800: 
10801: Clean-up is similar to replacements in lonnet::clean_filename()
10802: except each / between sub-directory and next level is preserved.
10803: 
10804: =cut
10805: 
10806: sub clean_path {
10807:     my ($embed_file) = @_;
10808:     $embed_file =~s{^/+}{};
10809:     my @contents;
10810:     if ($embed_file =~ m{/}) {
10811:         @contents = split(/\//,$embed_file);
10812:     } else {
10813:         @contents = ($embed_file);
10814:     }
10815:     my $lastidx = scalar(@contents)-1;
10816:     for (my $i=0; $i<=$lastidx; $i++) { 
10817:         $contents[$i]=~s{\\}{/}g;
10818:         $contents[$i]=~s/\s+/\_/g;
10819:         $contents[$i]=~s{[^/\w\.\-]}{}g;
10820:         if ($i == $lastidx) {
10821:             $contents[$i]=~s/\.(\d+)(?=\.)/_$1/g;
10822:         }
10823:     }
10824:     if ($lastidx > 0) {
10825:         return join('/',@contents);
10826:     } else {
10827:         return $contents[0];
10828:     }
10829: }
10830: 
10831: sub embedded_file_element {
10832:     my ($context,$num,$embed_file,$mapping,$allfiles,$codebase,$type) = @_;
10833:     return unless ((ref($mapping) eq 'HASH') && (ref($allfiles) eq 'HASH') &&
10834:                    (ref($codebase) eq 'HASH'));
10835:     my $output;
10836:     if (($context eq 'upload_embedded') && ($type ne 'delete')) {
10837:        $output = '<input name="embedded_item_'.$num.'" type="file" value="" />'."\n";
10838:     }
10839:     $output .= '<input name="embedded_orig_'.$num.'" type="hidden" value="'.
10840:                &escape($embed_file).'" />';
10841:     unless (($context eq 'upload_embedded') && 
10842:             ($mapping->{$embed_file} eq $embed_file)) {
10843:         $output .='
10844:         <input name="embedded_ref_'.$num.'" type="hidden" value="'.&escape($mapping->{$embed_file}).'" />';
10845:     }
10846:     my $attrib;
10847:     if (ref($allfiles->{$mapping->{$embed_file}}) eq 'ARRAY') {
10848:         $attrib = &escape(join(':',@{$allfiles->{$mapping->{$embed_file}}}));
10849:     }
10850:     $output .=
10851:         "\n\t\t".
10852:         '<input name="embedded_attrib_'.$num.'" type="hidden" value="'.
10853:         $attrib.'" />';
10854:     if (exists($codebase->{$mapping->{$embed_file}})) {
10855:         $output .=
10856:             "\n\t\t".
10857:             '<input name="codebase_'.$num.'" type="hidden" value="'.
10858:             &escape($codebase->{$mapping->{$embed_file}}).'" />';
10859:     }
10860:     return $output;
10861: }
10862: 
10863: sub get_dependency_details {
10864:     my ($currfile,$currsubfile,$embed_file) = @_;
10865:     my ($size,$mtime,$showsize,$showmtime);
10866:     if ((ref($currfile) eq 'HASH') && (ref($currsubfile))) {
10867:         if ($embed_file =~ m{/}) {
10868:             my ($path,$fname) = split(/\//,$embed_file);
10869:             if (ref($currsubfile->{$path}{$fname}) eq 'ARRAY') {
10870:                 ($size,$mtime) = @{$currsubfile->{$path}{$fname}};
10871:             }
10872:         } else {
10873:             if (ref($currfile->{$embed_file}) eq 'ARRAY') {
10874:                 ($size,$mtime) = @{$currfile->{$embed_file}};
10875:             }
10876:         }
10877:         $showsize = $size/1024.0;
10878:         $showsize = sprintf("%.1f",$showsize);
10879:         if ($mtime > 0) {
10880:             $showmtime = &Apache::lonlocal::locallocaltime($mtime);
10881:         }
10882:     }
10883:     return ($showsize,$showmtime);
10884: }
10885: 
10886: sub ask_embedded_js {
10887:     return <<"END";
10888: <script type="text/javascript"">
10889: // <![CDATA[
10890: function toggleBrowse(counter) {
10891:     var chkboxid = document.getElementById('mod_upload_dep_'+counter);
10892:     var fileid = document.getElementById('embedded_item_'+counter);
10893:     var uploaddivid = document.getElementById('moduploaddep_'+counter);
10894:     if (chkboxid.checked == true) {
10895:         uploaddivid.style.display='block';
10896:     } else {
10897:         uploaddivid.style.display='none';
10898:         fileid.value = '';
10899:     }
10900: }
10901: // ]]>
10902: </script>
10903: 
10904: END
10905: }
10906: 
10907: sub upload_embedded {
10908:     my ($context,$dirpath,$uname,$udom,$dir_root,$url_root,$group,$disk_quota,
10909:         $current_disk_usage,$hiddenstate,$actionurl) = @_;
10910:     my (%pathchange,$output,$modifyform,$footer,$returnflag);
10911:     for (my $i=0; $i<$env{'form.number_embedded_items'}; $i++) {
10912:         next if (!exists($env{'form.embedded_item_'.$i.'.filename'}));
10913:         my $orig_uploaded_filename =
10914:             $env{'form.embedded_item_'.$i.'.filename'};
10915:         foreach my $type ('orig','ref','attrib','codebase') {
10916:             if ($env{'form.embedded_'.$type.'_'.$i} ne '') {
10917:                 $env{'form.embedded_'.$type.'_'.$i} =
10918:                     &unescape($env{'form.embedded_'.$type.'_'.$i});
10919:             }
10920:         }
10921:         my ($path,$fname) =
10922:             ($env{'form.embedded_orig_'.$i} =~ m{(.*/)([^/]*)});
10923:         # no path, whole string is fname
10924:         if (!$fname) { $fname = $env{'form.embedded_orig_'.$i} };
10925:         $fname = &Apache::lonnet::clean_filename($fname);
10926:         # See if there is anything left
10927:         next if ($fname eq '');
10928: 
10929:         # Check if file already exists as a file or directory.
10930:         my ($state,$msg);
10931:         if ($context eq 'portfolio') {
10932:             my $port_path = $dirpath;
10933:             if ($group ne '') {
10934:                 $port_path = "groups/$group/$port_path";
10935:             }
10936:             ($state,$msg) = &check_for_upload($env{'form.currentpath'}.$path,
10937:                                               $fname,$group,'embedded_item_'.$i,
10938:                                               $dir_root,$port_path,$disk_quota,
10939:                                               $current_disk_usage,$uname,$udom);
10940:             if ($state eq 'will_exceed_quota'
10941:                 || $state eq 'file_locked') {
10942:                 $output .= $msg;
10943:                 next;
10944:             }
10945:         } elsif (($context eq 'author') || ($context eq 'testbank')) {
10946:             ($state,$msg) = &check_for_existing($path,$fname,'embedded_item_'.$i);
10947:             if ($state eq 'exists') {
10948:                 $output .= $msg;
10949:                 next;
10950:             }
10951:         }
10952:         # Check if extension is valid
10953:         if (($fname =~ /\.(\w+)$/) &&
10954:             (&Apache::loncommon::fileembstyle($1) eq 'hdn')) {
10955:             $output .= &mt('Invalid file extension ([_1]) - reserved for internal use.',$1)
10956:                       .' '.&mt('Rename the file with a different extension and re-upload.').'<br />';
10957:             next;
10958:         } elsif (($fname =~ /\.(\w+)$/) &&
10959:                  (!defined(&Apache::loncommon::fileembstyle($1)))) {
10960:             $output .= &mt('Unrecognized file extension ([_1]) - rename the file with a proper extension and re-upload.',$1).'<br />';
10961:             next;
10962:         } elsif ($fname=~/\.(\d+)\.(\w+)$/) {
10963:             $output .= &mt('Filename not allowed - rename the file to remove the number immediately before the file extension([_1]) and re-upload.',$2).'<br />';
10964:             next;
10965:         }
10966:         $env{'form.embedded_item_'.$i.'.filename'}=$fname;
10967:         my $subdir = $path;
10968:         $subdir =~ s{/+$}{};
10969:         if ($context eq 'portfolio') {
10970:             my $result;
10971:             if ($state eq 'existingfile') {
10972:                 $result=
10973:                     &Apache::lonnet::userfileupload('embedded_item_'.$i,'existingfile',
10974:                                                     $dirpath.$env{'form.currentpath'}.$subdir);
10975:             } else {
10976:                 $result=
10977:                     &Apache::lonnet::userfileupload('embedded_item_'.$i,'',
10978:                                                     $dirpath.
10979:                                                     $env{'form.currentpath'}.$subdir);
10980:                 if ($result !~ m|^/uploaded/|) {
10981:                     $output .= '<span class="LC_error">'
10982:                                .&mt('An error occurred ([_1]) while trying to upload [_2] for embedded element [_3].'
10983:                                ,$result,$orig_uploaded_filename,$env{'form.embedded_orig_'.$i})
10984:                                .'</span><br />';
10985:                     next;
10986:                 } else {
10987:                     $output .= &mt('Uploaded [_1]','<span class="LC_filename">'.
10988:                                $path.$fname.'</span>').'<br />';     
10989:                 }
10990:             }
10991:         } elsif (($context eq 'coursedoc') || ($context eq 'syllabus')) {
10992:             my $extendedsubdir = $dirpath.'/'.$subdir;
10993:             $extendedsubdir =~ s{/+$}{};
10994:             my $result =
10995:                 &Apache::lonnet::userfileupload('embedded_item_'.$i,$context,$extendedsubdir);
10996:             if ($result !~ m|^/uploaded/|) {
10997:                 $output .= '<span class="LC_error">'
10998:                            .&mt('An error occurred ([_1]) while trying to upload [_2] for embedded element [_3].'
10999:                            ,$result,$orig_uploaded_filename,$env{'form.embedded_orig_'.$i})
11000:                            .'</span><br />';
11001:                     next;
11002:             } else {
11003:                 $output .= &mt('Uploaded [_1]','<span class="LC_filename">'.
11004:                            $path.$fname.'</span>').'<br />';
11005:                 if ($context eq 'syllabus') {
11006:                     &Apache::lonnet::make_public_indefinitely($result);
11007:                 }
11008:             }
11009:         } else {
11010: # Save the file
11011:             my $target = $env{'form.embedded_item_'.$i};
11012:             my $fullpath = $dir_root.$dirpath.'/'.$path;
11013:             my $dest = $fullpath.$fname;
11014:             my $url = $url_root.$dirpath.'/'.$path.$fname;
11015:             my @parts=split(/\//,"$dirpath/$path");
11016:             my $count;
11017:             my $filepath = $dir_root;
11018:             foreach my $subdir (@parts) {
11019:                 $filepath .= "/$subdir";
11020:                 if (!-e $filepath) {
11021:                     mkdir($filepath,0770);
11022:                 }
11023:             }
11024:             my $fh;
11025:             if (!open($fh,'>'.$dest)) {
11026:                 &Apache::lonnet::logthis('Failed to create '.$dest);
11027:                 $output .= '<span class="LC_error">'.
11028:                            &mt('An error occurred while trying to upload [_1] for embedded element [_2].',
11029:                                $orig_uploaded_filename,$env{'form.embedded_orig_'.$i}).
11030:                            '</span><br />';
11031:             } else {
11032:                 if (!print $fh $env{'form.embedded_item_'.$i}) {
11033:                     &Apache::lonnet::logthis('Failed to write to '.$dest);
11034:                     $output .= '<span class="LC_error">'.
11035:                               &mt('An error occurred while writing the file [_1] for embedded element [_2].',
11036:                                   $orig_uploaded_filename,$env{'form.embedded_orig_'.$i}).
11037:                               '</span><br />';
11038:                 } else {
11039:                     $output .= &mt('Uploaded [_1]','<span class="LC_filename">'.
11040:                                $url.'</span>').'<br />';
11041:                     unless ($context eq 'testbank') {
11042:                         $footer .= &mt('View embedded file: [_1]',
11043:                                        '<a href="'.$url.'">'.$fname.'</a>').'<br />';
11044:                     }
11045:                 }
11046:                 close($fh);
11047:             }
11048:         }
11049:         if ($env{'form.embedded_ref_'.$i}) {
11050:             $pathchange{$i} = 1;
11051:         }
11052:     }
11053:     if ($output) {
11054:         $output = '<p>'.$output.'</p>';
11055:     }
11056:     $output .= &modify_html_form('upload_embedded',$actionurl,$hiddenstate,\%pathchange);
11057:     $returnflag = 'ok';
11058:     my $numpathchgs = scalar(keys(%pathchange));
11059:     if ($numpathchgs > 0) {
11060:         if ($context eq 'portfolio') {
11061:             $output .= '<p>'.&mt('or').'</p>';
11062:         } elsif ($context eq 'testbank') {
11063:             $output .=  '<p>'.&mt('Or [_1]continue[_2] the testbank import without modifying the reference(s).',
11064:                                   '<a href="javascript:document.testbankForm.submit();">','</a>').'</p>';
11065:             $returnflag = 'modify_orightml';
11066:         }
11067:     }
11068:     return ($output.$footer,$returnflag,$numpathchgs);
11069: }
11070: 
11071: sub modify_html_form {
11072:     my ($context,$actionurl,$hiddenstate,$pathchange,$pathchgtable) = @_;
11073:     my $end = 0;
11074:     my $modifyform;
11075:     if ($context eq 'upload_embedded') {
11076:         return unless (ref($pathchange) eq 'HASH');
11077:         if ($env{'form.number_embedded_items'}) {
11078:             $end += $env{'form.number_embedded_items'};
11079:         }
11080:         if ($env{'form.number_pathchange_items'}) {
11081:             $end += $env{'form.number_pathchange_items'};
11082:         }
11083:         if ($end) {
11084:             for (my $i=0; $i<$end; $i++) {
11085:                 if ($i < $env{'form.number_embedded_items'}) {
11086:                     next unless($pathchange->{$i});
11087:                 }
11088:                 $modifyform .=
11089:                     &start_data_table_row().
11090:                     '<td><input type ="checkbox" name="namechange" value="'.$i.'" '.
11091:                     'checked="checked" /></td>'.
11092:                     '<td>'.$env{'form.embedded_ref_'.$i}.
11093:                     '<input type="hidden" name="embedded_ref_'.$i.'" value="'.
11094:                     &escape($env{'form.embedded_ref_'.$i}).'" />'.
11095:                     '<input type="hidden" name="embedded_codebase_'.$i.'" value="'.
11096:                     &escape($env{'form.embedded_codebase_'.$i}).'" />'.
11097:                     '<input type="hidden" name="embedded_attrib_'.$i.'" value="'.
11098:                     &escape($env{'form.embedded_attrib_'.$i}).'" /></td>'.
11099:                     '<td>'.$env{'form.embedded_orig_'.$i}.
11100:                     '<input type="hidden" name="embedded_orig_'.$i.'" value="'.
11101:                     &escape($env{'form.embedded_orig_'.$i}).'" /></td>'.
11102:                     &end_data_table_row();
11103:             }
11104:         }
11105:     } else {
11106:         $modifyform = $pathchgtable;
11107:         if (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank')) {
11108:             $hiddenstate .= '<input type="hidden" name="phase" value="four" />';
11109:         } elsif (($actionurl eq '/adm/portfolio') || ($actionurl eq '/adm/coursegrp_portfolio')) {
11110:             $hiddenstate .= '<input type="hidden" name="action" value="modify_orightml" />';
11111:         }
11112:     }
11113:     if ($modifyform) {
11114:         if ($actionurl eq '/adm/dependencies') {
11115:             $hiddenstate .= '<input type="hidden" name="action" value="modifyhrefs" />';
11116:         }
11117:         return '<h3>'.&mt('Changes in content of HTML file required').'</h3>'."\n".
11118:                '<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".
11119:                '<li>'.&mt('For consistency between the reference(s) and the location of the corresponding stored file within LON-CAPA.').'</li>'."\n".
11120:                '<li>'.&mt('To change absolute paths to relative paths, or replace directory traversal via "../" within the original reference.').'</li>'."\n".
11121:                '</ol></p>'."\n".'<p>'.
11122:                &mt('LON-CAPA can make the required changes to your HTML file.').'</p>'."\n".
11123:                '<form method="post" name="refchanger" action="'.$actionurl.'">'.
11124:                &start_data_table()."\n".
11125:                &start_data_table_header_row().
11126:                '<th>'.&mt('Change?').'</th>'.
11127:                '<th>'.&mt('Current reference').'</th>'.
11128:                '<th>'.&mt('Required reference').'</th>'.
11129:                &end_data_table_header_row()."\n".
11130:                $modifyform.
11131:                &end_data_table().'<br />'."\n".$hiddenstate.
11132:                '<input type="submit" name="pathchanges" value="'.&mt('Modify HTML file').'" />'.
11133:                '</form>'."\n";
11134:     }
11135:     return;
11136: }
11137: 
11138: sub modify_html_refs {
11139:     my ($context,$dirpath,$uname,$udom,$dir_root,$url) = @_;
11140:     my $container;
11141:     if ($context eq 'portfolio') {
11142:         $container = $env{'form.container'};
11143:     } elsif ($context eq 'coursedoc') {
11144:         $container = $env{'form.primaryurl'};
11145:     } elsif ($context eq 'manage_dependencies') {
11146:         (undef,undef,$container) = &Apache::lonnet::decode_symb($env{'form.symb'});
11147:         $container = "/$container";
11148:     } elsif ($context eq 'syllabus') {
11149:         $container = $url;
11150:     } else {
11151:         $container = $Apache::lonnet::perlvar{'lonDocRoot'}.$env{'form.filename'};
11152:     }
11153:     my (%allfiles,%codebase,$output,$content);
11154:     my @changes = &get_env_multiple('form.namechange');
11155:     unless ((@changes > 0) || ($context eq 'syllabus')) {
11156:         if (wantarray) {
11157:             return ('',0,0); 
11158:         } else {
11159:             return;
11160:         }
11161:     }
11162:     if (($context eq 'portfolio') || ($context eq 'coursedoc') || 
11163:         ($context eq 'manage_dependencies') || ($context eq 'syllabus')) {
11164:         unless ($container =~ m{^/uploaded/\Q$udom\E/\Q$uname\E/}) {
11165:             if (wantarray) {
11166:                 return ('',0,0);
11167:             } else {
11168:                 return;
11169:             }
11170:         } 
11171:         $content = &Apache::lonnet::getfile($container);
11172:         if ($content eq '-1') {
11173:             if (wantarray) {
11174:                 return ('',0,0);
11175:             } else {
11176:                 return;
11177:             }
11178:         }
11179:     } else {
11180:         unless ($container =~ /^\Q$dir_root\E/) {
11181:             if (wantarray) {
11182:                 return ('',0,0);
11183:             } else {
11184:                 return;
11185:             }
11186:         } 
11187:         if (open(my $fh,"<$container")) {
11188:             $content = join('', <$fh>);
11189:             close($fh);
11190:         } else {
11191:             if (wantarray) {
11192:                 return ('',0,0);
11193:             } else {
11194:                 return;
11195:             }
11196:         }
11197:     }
11198:     my ($count,$codebasecount) = (0,0);
11199:     my $mm = new File::MMagic;
11200:     my $mime_type = $mm->checktype_contents($content);
11201:     if ($mime_type eq 'text/html') {
11202:         my $parse_result = 
11203:             &Apache::lonnet::extract_embedded_items($container,\%allfiles,
11204:                                                     \%codebase,\$content);
11205:         if ($parse_result eq 'ok') {
11206:             foreach my $i (@changes) {
11207:                 my $orig = &unescape($env{'form.embedded_orig_'.$i});
11208:                 my $ref = &unescape($env{'form.embedded_ref_'.$i});
11209:                 if ($allfiles{$ref}) {
11210:                     my $newname =  $orig;
11211:                     my ($attrib_regexp,$codebase);
11212:                     $attrib_regexp = &unescape($env{'form.embedded_attrib_'.$i});
11213:                     if ($attrib_regexp =~ /:/) {
11214:                         $attrib_regexp =~ s/\:/|/g;
11215:                     }
11216:                     if ($content =~ m{($attrib_regexp\s*=\s*['"]?)\Q$ref\E(['"]?)}) {
11217:                         my $numchg = ($content =~ s{($attrib_regexp\s*=\s*['"]?)\Q$ref\E(['"]?)}{$1$newname$2}gi);
11218:                         $count += $numchg;
11219:                         $allfiles{$newname} = $allfiles{$ref};
11220:                         delete($allfiles{$ref});
11221:                     }
11222:                     if ($env{'form.embedded_codebase_'.$i} ne '') {
11223:                         $codebase = &unescape($env{'form.embedded_codebase_'.$i});
11224:                         my $numchg = ($content =~ s/(codebase\s*=\s*["']?)\Q$codebase\E(["']?)/$1.$2/i); #' stupid emacs
11225:                         $codebasecount ++;
11226:                     }
11227:                 }
11228:             }
11229:             my $skiprewrites;
11230:             if ($count || $codebasecount) {
11231:                 my $saveresult;
11232:                 if (($context eq 'portfolio') || ($context eq 'coursedoc') || 
11233:                     ($context eq 'manage_dependencies') || ($context eq 'syllabus')) {
11234:                     my $url = &Apache::lonnet::store_edited_file($container,$content,$udom,$uname,\$saveresult);
11235:                     if ($url eq $container) {
11236:                         my ($fname) = ($container =~ m{/([^/]+)$});
11237:                         $output = '<p>'.&mt('Updated [quant,_1,reference] in [_2].',
11238:                                             $count,'<span class="LC_filename">'.
11239:                                             $fname.'</span>').'</p>';
11240:                     } else {
11241:                          $output = '<p class="LC_error">'.
11242:                                    &mt('Error: update failed for: [_1].',
11243:                                    '<span class="LC_filename">'.
11244:                                    $container.'</span>').'</p>';
11245:                     }
11246:                     if ($context eq 'syllabus') {
11247:                         unless ($saveresult eq 'ok') {
11248:                             $skiprewrites = 1;
11249:                         }
11250:                     }
11251:                 } else {
11252:                     if (open(my $fh,">$container")) {
11253:                         print $fh $content;
11254:                         close($fh);
11255:                         $output = '<p>'.&mt('Updated [quant,_1,reference] in [_2].',
11256:                                   $count,'<span class="LC_filename">'.
11257:                                   $container.'</span>').'</p>';
11258:                     } else {
11259:                          $output = '<p class="LC_error">'.
11260:                                    &mt('Error: could not update [_1].',
11261:                                    '<span class="LC_filename">'.
11262:                                    $container.'</span>').'</p>';
11263:                     }
11264:                 }
11265:             }
11266:             if (($context eq 'syllabus') && (!$skiprewrites)) {
11267:                 my ($actionurl,$state);
11268:                 $actionurl = "/public/$udom/$uname/syllabus";
11269:                 my ($ignore,$num,$numpathchanges,$existing,$mapping) =
11270:                     &ask_for_embedded_content($actionurl,$state,\%allfiles,
11271:                                               \%codebase,
11272:                                               {'context' => 'rewrites',
11273:                                                'ignore_remote_references' => 1,});
11274:                 if (ref($mapping) eq 'HASH') {
11275:                     my $rewrites = 0;
11276:                     foreach my $key (keys(%{$mapping})) {
11277:                         next if ($key =~ m{^https?://});
11278:                         my $ref = $mapping->{$key};
11279:                         my $newname = "/uploaded/$udom/$uname/portfolio/syllabus/$key";
11280:                         my $attrib;
11281:                         if (ref($allfiles{$mapping->{$key}}) eq 'ARRAY') {
11282:                             $attrib = join('|',@{$allfiles{$mapping->{$key}}});
11283:                         }
11284:                         if ($content =~ m{($attrib\s*=\s*['"]?)\Q$ref\E(['"]?)}) {
11285:                             my $numchg = ($content =~ s{($attrib\s*=\s*['"]?)\Q$ref\E(['"]?)}{$1$newname$2}gi);
11286:                             $rewrites += $numchg;
11287:                         }
11288:                     }
11289:                     if ($rewrites) {
11290:                         my $saveresult; 
11291:                         my $url = &Apache::lonnet::store_edited_file($container,$content,$udom,$uname,\$saveresult);
11292:                         if ($url eq $container) {
11293:                             my ($fname) = ($container =~ m{/([^/]+)$});
11294:                             $output .= '<p>'.&mt('Rewrote [quant,_1,link] as [quant,_1,absolute link] in [_2].',
11295:                                             $count,'<span class="LC_filename">'.
11296:                                             $fname.'</span>').'</p>';
11297:                         } else {
11298:                             $output .= '<p class="LC_error">'.
11299:                                        &mt('Error: could not update links in [_1].',
11300:                                        '<span class="LC_filename">'.
11301:                                        $container.'</span>').'</p>';
11302: 
11303:                         }
11304:                     }
11305:                 }
11306:             }
11307:         } else {
11308:             &logthis('Failed to parse '.$container.
11309:                      ' to modify references: '.$parse_result);
11310:         }
11311:     }
11312:     if (wantarray) {
11313:         return ($output,$count,$codebasecount);
11314:     } else {
11315:         return $output;
11316:     }
11317: }
11318: 
11319: sub check_for_existing {
11320:     my ($path,$fname,$element) = @_;
11321:     my ($state,$msg);
11322:     if (-d $path.'/'.$fname) {
11323:         $state = 'exists';
11324:         $msg = &mt('Unable to upload [_1]. A directory by that name was found in [_2].','<span class="LC_filename">'.$fname.'</span>',$path);
11325:     } elsif (-e $path.'/'.$fname) {
11326:         $state = 'exists';
11327:         $msg = &mt('Unable to upload [_1]. A file by that name was found in [_2].','<span class="LC_filename">'.$fname.'</span>',$path);
11328:     }
11329:     if ($state eq 'exists') {
11330:         $msg = '<span class="LC_error">'.$msg.'</span><br />';
11331:     }
11332:     return ($state,$msg);
11333: }
11334: 
11335: sub check_for_upload {
11336:     my ($path,$fname,$group,$element,$portfolio_root,$port_path,
11337:         $disk_quota,$current_disk_usage,$uname,$udom) = @_;
11338:     my $filesize = length($env{'form.'.$element});
11339:     if (!$filesize) {
11340:         my $msg = '<span class="LC_error">'.
11341:                   &mt('Unable to upload [_1]. (size = [_2] bytes)', 
11342:                       '<span class="LC_filename">'.$fname.'</span>',
11343:                       $filesize).'<br />'.
11344:                   &mt('Either the file you attempted to upload was empty, or your web browser was unable to read its contents.').'<br />'.
11345:                   '</span>';
11346:         return ('zero_bytes',$msg);
11347:     }
11348:     $filesize =  $filesize/1000; #express in k (1024?)
11349:     my $getpropath = 1;
11350:     my ($dirlistref,$listerror) =
11351:          &Apache::lonnet::dirlist($portfolio_root.$path,$udom,$uname,$getpropath);
11352:     my $found_file = 0;
11353:     my $locked_file = 0;
11354:     my @lockers;
11355:     my $navmap;
11356:     if ($env{'request.course.id'}) {
11357:         $navmap = Apache::lonnavmaps::navmap->new();
11358:     }
11359:     if (ref($dirlistref) eq 'ARRAY') {
11360:         foreach my $line (@{$dirlistref}) {
11361:             my ($file_name,$rest)=split(/\&/,$line,2);
11362:             if ($file_name eq $fname){
11363:                 $file_name = $path.$file_name;
11364:                 if ($group ne '') {
11365:                     $file_name = $group.$file_name;
11366:                 }
11367:                 $found_file = 1;
11368:                 if (&Apache::lonnet::is_locked($file_name,$udom,$uname,\@lockers) eq 'true') {
11369:                     foreach my $lock (@lockers) {
11370:                         if (ref($lock) eq 'ARRAY') {
11371:                             my ($symb,$crsid) = @{$lock};
11372:                             if ($crsid eq $env{'request.course.id'}) {
11373:                                 if (ref($navmap)) {
11374:                                     my $res = $navmap->getBySymb($symb);
11375:                                     foreach my $part (@{$res->parts()}) { 
11376:                                         my ($slot_status,$slot_time,$slot_name)=$res->check_for_slot($part);
11377:                                         unless (($slot_status == $res->RESERVED) ||
11378:                                                 ($slot_status == $res->RESERVED_LOCATION)) {
11379:                                             $locked_file = 1;
11380:                                         }
11381:                                     }
11382:                                 } else {
11383:                                     $locked_file = 1;
11384:                                 }
11385:                             } else {
11386:                                 $locked_file = 1;
11387:                             }
11388:                         }
11389:                    }
11390:                 } else {
11391:                     my @info = split(/\&/,$rest);
11392:                     my $currsize = $info[6]/1000;
11393:                     if ($currsize < $filesize) {
11394:                         my $extra = $filesize - $currsize;
11395:                         if (($current_disk_usage + $extra) > $disk_quota) {
11396:                             my $msg = '<p class="LC_warning">'.
11397:                                       &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.',
11398:                                           '<span class="LC_filename">'.$fname.'</span>',$filesize,$currsize).'</p>'.
11399:                                       '<p>'.&mt('Disk quota is [_1] kilobytes. Your current disk usage is [_2] kilobytes.',
11400:                                                    $disk_quota,$current_disk_usage).'</p>';
11401:                             return ('will_exceed_quota',$msg);
11402:                         }
11403:                     }
11404:                 }
11405:             }
11406:         }
11407:     }
11408:     if (($current_disk_usage + $filesize) > $disk_quota){
11409:         my $msg = '<p class="LC_warning">'.
11410:                 &mt('Unable to upload [_1]. (size = [_2] kilobytes). Disk quota will be exceeded.','<span class="LC_filename">'.$fname.'</span>',$filesize).'</p>'.
11411:                   '<p>'.&mt('Disk quota is [_1] kilobytes. Your current disk usage is [_2] kilobytes.',$disk_quota,$current_disk_usage).'</p>';
11412:         return ('will_exceed_quota',$msg);
11413:     } elsif ($found_file) {
11414:         if ($locked_file) {
11415:             my $msg = '<p class="LC_warning">';
11416:             $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>');
11417:             $msg .= '</p>';
11418:             $msg .= &mt('You will be able to rename or delete existing [_1] after a grade has been assigned.','<span class="LC_filename">'.$fname.'</span>');
11419:             return ('file_locked',$msg);
11420:         } else {
11421:             my $msg = '<p class="LC_error">';
11422:             $msg .= &mt(' A file by that name: [_1] was found in [_2].','<span class="LC_filename">'.$fname.'</span>',$port_path.$env{'form.currentpath'});
11423:             $msg .= '</p>';
11424:             return ('existingfile',$msg);
11425:         }
11426:     }
11427: }
11428: 
11429: sub check_for_traversal {
11430:     my ($path,$url,$toplevel) = @_;
11431:     my @parts=split(/\//,$path);
11432:     my $cleanpath;
11433:     my $fullpath = $url;
11434:     for (my $i=0;$i<@parts;$i++) {
11435:         next if ($parts[$i] eq '.');
11436:         if ($parts[$i] eq '..') {
11437:             $fullpath =~ s{([^/]+/)$}{};
11438:         } else {
11439:             $fullpath .= $parts[$i].'/';
11440:         }
11441:     }
11442:     if ($fullpath =~ /^\Q$url\E(.*)$/) {
11443:         $cleanpath = $1;
11444:     } elsif ($fullpath =~ /^\Q$toplevel\E(.*)$/) {
11445:         my $curr_toprel = $1;
11446:         my @parts = split(/\//,$curr_toprel);
11447:         my ($url_toprel) = ($url =~ /^\Q$toplevel\E(.*)$/);
11448:         my @urlparts = split(/\//,$url_toprel);
11449:         my $doubledots;
11450:         my $startdiff = -1;
11451:         for (my $i=0; $i<@urlparts; $i++) {
11452:             if ($startdiff == -1) {
11453:                 unless ($urlparts[$i] eq $parts[$i]) {
11454:                     $startdiff = $i;
11455:                     $doubledots .= '../';
11456:                 }
11457:             } else {
11458:                 $doubledots .= '../';
11459:             }
11460:         }
11461:         if ($startdiff > -1) {
11462:             $cleanpath = $doubledots;
11463:             for (my $i=$startdiff; $i<@parts; $i++) {
11464:                 $cleanpath .= $parts[$i].'/';
11465:             }
11466:         }
11467:     }
11468:     $cleanpath =~ s{(/)$}{};
11469:     return $cleanpath;
11470: }
11471: 
11472: sub is_archive_file {
11473:     my ($mimetype) = @_;
11474:     if (($mimetype eq 'application/octet-stream') ||
11475:         ($mimetype eq 'application/x-stuffit') ||
11476:         ($mimetype =~ m{^application/(x\-)?(compressed|tar|zip|tgz|gz|gtar|gzip|gunzip|bz|bz2|bzip2)})) {
11477:         return 1;
11478:     }
11479:     return;
11480: }
11481: 
11482: sub decompress_form {
11483:     my ($mimetype,$archiveurl,$action,$noextract,$hiddenelements,$dirlist) = @_;
11484:     my %lt = &Apache::lonlocal::texthash (
11485:         this => 'This file is an archive file.',
11486:         camt => 'This file is a Camtasia archive file.',
11487:         itsc => 'Its contents are as follows:',
11488:         youm => 'You may wish to extract its contents.',
11489:         extr => 'Extract contents',
11490:         auto => 'LON-CAPA can process the files automatically, or you can decide how each should be handled.',
11491:         proa => 'Process automatically?',
11492:         yes  => 'Yes',
11493:         no   => 'No',
11494:         fold => 'Title for folder containing movie',
11495:         movi => 'Title for page containing embedded movie', 
11496:     );
11497:     my $fileloc = &Apache::lonnet::filelocation(undef,$archiveurl);
11498:     my ($is_camtasia,$topdir,%toplevel,@paths);
11499:     my $info = &list_archive_contents($fileloc,\@paths);
11500:     if (@paths) {
11501:         foreach my $path (@paths) {
11502:             $path =~ s{^/}{};
11503:             if ($path =~ m{^([^/]+)/$}) {
11504:                 $topdir = $1;
11505:             }
11506:             if ($path =~ m{^([^/]+)/}) {
11507:                 $toplevel{$1} = $path;
11508:             } else {
11509:                 $toplevel{$path} = $path;
11510:             }
11511:         }
11512:     }
11513:     if ($mimetype =~ m{^application/(x\-)?(compressed|zip)}) {
11514:         my @camtasia6 = ("$topdir/","$topdir/index.html",
11515:                         "$topdir/media/",
11516:                         "$topdir/media/$topdir.mp4",
11517:                         "$topdir/media/FirstFrame.png",
11518:                         "$topdir/media/player.swf",
11519:                         "$topdir/media/swfobject.js",
11520:                         "$topdir/media/expressInstall.swf");
11521:         my @camtasia8_1 = ("$topdir/","$topdir/$topdir.html",
11522:                          "$topdir/$topdir.mp4",
11523:                          "$topdir/$topdir\_config.xml",
11524:                          "$topdir/$topdir\_controller.swf",
11525:                          "$topdir/$topdir\_embed.css",
11526:                          "$topdir/$topdir\_First_Frame.png",
11527:                          "$topdir/$topdir\_player.html",
11528:                          "$topdir/$topdir\_Thumbnails.png",
11529:                          "$topdir/playerProductInstall.swf",
11530:                          "$topdir/scripts/",
11531:                          "$topdir/scripts/config_xml.js",
11532:                          "$topdir/scripts/handlebars.js",
11533:                          "$topdir/scripts/jquery-1.7.1.min.js",
11534:                          "$topdir/scripts/jquery-ui-1.8.15.custom.min.js",
11535:                          "$topdir/scripts/modernizr.js",
11536:                          "$topdir/scripts/player-min.js",
11537:                          "$topdir/scripts/swfobject.js",
11538:                          "$topdir/skins/",
11539:                          "$topdir/skins/configuration_express.xml",
11540:                          "$topdir/skins/express_show/",
11541:                          "$topdir/skins/express_show/player-min.css",
11542:                          "$topdir/skins/express_show/spritesheet.png");
11543:         my @camtasia8_4 = ("$topdir/","$topdir/$topdir.html",
11544:                          "$topdir/$topdir.mp4",
11545:                          "$topdir/$topdir\_config.xml",
11546:                          "$topdir/$topdir\_controller.swf",
11547:                          "$topdir/$topdir\_embed.css",
11548:                          "$topdir/$topdir\_First_Frame.png",
11549:                          "$topdir/$topdir\_player.html",
11550:                          "$topdir/$topdir\_Thumbnails.png",
11551:                          "$topdir/playerProductInstall.swf",
11552:                          "$topdir/scripts/",
11553:                          "$topdir/scripts/config_xml.js",
11554:                          "$topdir/scripts/techsmith-smart-player.min.js",
11555:                          "$topdir/skins/",
11556:                          "$topdir/skins/configuration_express.xml",
11557:                          "$topdir/skins/express_show/",
11558:                          "$topdir/skins/express_show/spritesheet.min.css",
11559:                          "$topdir/skins/express_show/spritesheet.png",
11560:                          "$topdir/skins/express_show/techsmith-smart-player.min.css");
11561:         my @diffs = &compare_arrays(\@paths,\@camtasia6);
11562:         if (@diffs == 0) {
11563:             $is_camtasia = 6;
11564:         } else {
11565:             @diffs = &compare_arrays(\@paths,\@camtasia8_1);
11566:             if (@diffs == 0) {
11567:                 $is_camtasia = 8;
11568:             } else {
11569:                 @diffs = &compare_arrays(\@paths,\@camtasia8_4);
11570:                 if (@diffs == 0) {
11571:                     $is_camtasia = 8;
11572:                 }
11573:             }
11574:         }
11575:     }
11576:     my $output;
11577:     if ($is_camtasia) {
11578:         $output = <<"ENDCAM";
11579: <script type="text/javascript" language="Javascript">
11580: // <![CDATA[
11581: 
11582: function camtasiaToggle() {
11583:     for (var i=0; i<document.uploaded_decompress.autoextract_camtasia.length; i++) {
11584:         if (document.uploaded_decompress.autoextract_camtasia[i].checked) {
11585:             if (document.uploaded_decompress.autoextract_camtasia[i].value == $is_camtasia) {
11586:                 document.getElementById('camtasia_titles').style.display='block';
11587:             } else {
11588:                 document.getElementById('camtasia_titles').style.display='none';
11589:             }
11590:         }
11591:     }
11592:     return;
11593: }
11594: 
11595: // ]]>
11596: </script>
11597: <p>$lt{'camt'}</p>
11598: ENDCAM
11599:     } else {
11600:         $output = '<p>'.$lt{'this'};
11601:         if ($info eq '') {
11602:             $output .= ' '.$lt{'youm'}.'</p>'."\n";
11603:         } else {
11604:             $output .= ' '.$lt{'itsc'}.'</p>'."\n".
11605:                        '<div><pre>'.$info.'</pre></div>';
11606:         }
11607:     }
11608:     $output .= '<form name="uploaded_decompress" action="'.$action.'" method="post">'."\n";
11609:     my $duplicates;
11610:     my $num = 0;
11611:     if (ref($dirlist) eq 'ARRAY') {
11612:         foreach my $item (@{$dirlist}) {
11613:             if (ref($item) eq 'ARRAY') {
11614:                 if (exists($toplevel{$item->[0]})) {
11615:                     $duplicates .= 
11616:                         &start_data_table_row().
11617:                         '<td><label><input type="radio" name="archive_overwrite_'.$num.'" '.
11618:                         'value="0" checked="checked" />'.&mt('No').'</label>'.
11619:                         '&nbsp;<label><input type="radio" name="archive_overwrite_'.$num.'" '.
11620:                         'value="1" />'.&mt('Yes').'</label>'.
11621:                         '<input type="hidden" name="archive_overwrite_name_'.$num.'" value="'.$item->[0].'" /></td>'."\n".
11622:                         '<td>'.$item->[0].'</td>';
11623:                     if ($item->[2]) {
11624:                         $duplicates .= '<td>'.&mt('Directory').'</td>';
11625:                     } else {
11626:                         $duplicates .= '<td>'.&mt('File').'</td>';
11627:                     }
11628:                     $duplicates .= '<td>'.$item->[3].'</td>'.
11629:                                    '<td>'.
11630:                                    &Apache::lonlocal::locallocaltime($item->[4]).
11631:                                    '</td>'.
11632:                                    &end_data_table_row();
11633:                     $num ++;
11634:                 }
11635:             }
11636:         }
11637:     }
11638:     my $itemcount;
11639:     if (@paths > 0) {
11640:         $itemcount = scalar(@paths);
11641:     } else {
11642:         $itemcount = 1;
11643:     }
11644:     if ($is_camtasia) {
11645:         $output .= $lt{'auto'}.'<br />'.
11646:                    '<span class="LC_nobreak">'.$lt{'proa'}.'<label>'.
11647:                    '<input type="radio" name="autoextract_camtasia" value="'.$is_camtasia.'" onclick="javascript:camtasiaToggle();" checked="checked" />'.
11648:                    $lt{'yes'}.'</label>&nbsp;<label>'.
11649:                    '<input type="radio" name="autoextract_camtasia" value="0" onclick="javascript:camtasiaToggle();" />'.
11650:                    $lt{'no'}.'</label></span><br />'.
11651:                    '<div id="camtasia_titles" style="display:block">'.
11652:                    &Apache::lonhtmlcommon::start_pick_box().
11653:                    &Apache::lonhtmlcommon::row_title($lt{'fold'}).
11654:                    '<input type="textbox" name="camtasia_foldername" value="'.$env{'form.comment'}.'" />'."\n".
11655:                    &Apache::lonhtmlcommon::row_closure().
11656:                    &Apache::lonhtmlcommon::row_title($lt{'movi'}).
11657:                    '<input type="textbox" name="camtasia_moviename" value="" />'."\n".
11658:                    &Apache::lonhtmlcommon::row_closure(1).
11659:                    &Apache::lonhtmlcommon::end_pick_box().
11660:                    '</div>';
11661:     }
11662:     $output .= 
11663:         '<input type="hidden" name="archive_overwrite_total" value="'.$num.'" />'.
11664:         '<input type="hidden" name="archive_itemcount" value="'.$itemcount.'" />'.
11665:         "\n";
11666:     if ($duplicates ne '') {
11667:         $output .= '<p><span class="LC_warning">'.
11668:                    &mt('Warning: decompression of the archive will overwrite the following items which already exist:').'</span><br />'.  
11669:                    &start_data_table().
11670:                    &start_data_table_header_row().
11671:                    '<th>'.&mt('Overwrite?').'</th>'.
11672:                    '<th>'.&mt('Name').'</th>'.
11673:                    '<th>'.&mt('Type').'</th>'.
11674:                    '<th>'.&mt('Size').'</th>'.
11675:                    '<th>'.&mt('Last modified').'</th>'.
11676:                    &end_data_table_header_row().
11677:                    $duplicates.
11678:                    &end_data_table().
11679:                    '</p>';
11680:     }
11681:     $output .= '<input type="hidden" name="archiveurl" value="'.$archiveurl.'" />'."\n";
11682:     if (ref($hiddenelements) eq 'HASH') {
11683:         foreach my $hidden (sort(keys(%{$hiddenelements}))) {
11684:             $output .= '<input type="hidden" name="'.$hidden.'" value="'.$hiddenelements->{$hidden}.'" />'."\n";
11685:         }
11686:     }
11687:     $output .= <<"END";
11688: <br />
11689: <input type="submit" name="decompress" value="$lt{'extr'}" />
11690: </form>
11691: $noextract
11692: END
11693:     return $output;
11694: }
11695: 
11696: sub decompression_utility {
11697:     my ($program) = @_;
11698:     my @utilities = ('tar','gunzip','bunzip2','unzip'); 
11699:     my $location;
11700:     if (grep(/^\Q$program\E$/,@utilities)) { 
11701:         foreach my $dir ('/bin/','/usr/bin/','/usr/local/bin/','/sbin/',
11702:                          '/usr/sbin/') {
11703:             if (-x $dir.$program) {
11704:                 $location = $dir.$program;
11705:                 last;
11706:             }
11707:         }
11708:     }
11709:     return $location;
11710: }
11711: 
11712: sub list_archive_contents {
11713:     my ($file,$pathsref) = @_;
11714:     my (@cmd,$output);
11715:     my $needsregexp;
11716:     if ($file =~ /\.zip$/) {
11717:         @cmd = (&decompression_utility('unzip'),"-l");
11718:         $needsregexp = 1;
11719:     } elsif (($file =~ m/\.tar\.gz$/) ||
11720:              ($file =~ /\.tgz$/)) {
11721:         @cmd = (&decompression_utility('tar'),"-ztf");
11722:     } elsif ($file =~ /\.tar\.bz2$/) {
11723:         @cmd = (&decompression_utility('tar'),"-jtf");
11724:     } elsif ($file =~ m|\.tar$|) {
11725:         @cmd = (&decompression_utility('tar'),"-tf");
11726:     }
11727:     if (@cmd) {
11728:         undef($!);
11729:         undef($@);
11730:         if (open(my $fh,"-|", @cmd, $file)) {
11731:             while (my $line = <$fh>) {
11732:                 $output .= $line;
11733:                 chomp($line);
11734:                 my $item;
11735:                 if ($needsregexp) {
11736:                     ($item) = ($line =~ /^\s*\d+\s+[\d\-]+\s+[\d:]+\s*(.+)$/); 
11737:                 } else {
11738:                     $item = $line;
11739:                 }
11740:                 if ($item ne '') {
11741:                     unless (grep(/^\Q$item\E$/,@{$pathsref})) {
11742:                         push(@{$pathsref},$item);
11743:                     } 
11744:                 }
11745:             }
11746:             close($fh);
11747:         }
11748:     }
11749:     return $output;
11750: }
11751: 
11752: sub decompress_uploaded_file {
11753:     my ($file,$dir) = @_;
11754:     &Apache::lonnet::appenv({'cgi.file' => $file});
11755:     &Apache::lonnet::appenv({'cgi.dir' => $dir});
11756:     my $result = &Apache::lonnet::ssi_body('/cgi-bin/decompress.pl');
11757:     my ($handle) = ($env{'user.environment'} =~m{/([^/]+)\.id$});
11758:     my $lonidsdir = $Apache::lonnet::perlvar{'lonIDsDir'};
11759:     &Apache::lonnet::transfer_profile_to_env($lonidsdir,$handle,1);
11760:     my $decompressed = $env{'cgi.decompressed'};
11761:     &Apache::lonnet::delenv('cgi.file');
11762:     &Apache::lonnet::delenv('cgi.dir');
11763:     &Apache::lonnet::delenv('cgi.decompressed');
11764:     return ($decompressed,$result);
11765: }
11766: 
11767: sub process_decompression {
11768:     my ($docudom,$docuname,$file,$destination,$dir_root,$hiddenelem) = @_;
11769:     my ($dir,$error,$warning,$output);
11770:     if ($file !~ /\.(zip|tar|bz2|gz|tar.gz|tar.bz2|tgz)$/i) {
11771:         $error = &mt('Filename not a supported archive file type.').
11772:                  '<br />'.&mt('Filename should end with one of: [_1].',
11773:                               '.zip, .tar, .bz2, .gz, .tar.gz, .tar.bz2, .tgz');
11774:     } else {
11775:         my $docuhome = &Apache::lonnet::homeserver($docuname,$docudom);
11776:         if ($docuhome eq 'no_host') {
11777:             $error = &mt('Could not determine home server for course.');
11778:         } else {
11779:             my @ids=&Apache::lonnet::current_machine_ids();
11780:             my $currdir = "$dir_root/$destination";
11781:             if (grep(/^\Q$docuhome\E$/,@ids)) {
11782:                 $dir = &LONCAPA::propath($docudom,$docuname).
11783:                        "$dir_root/$destination";
11784:             } else {
11785:                 $dir = $Apache::lonnet::perlvar{'lonDocRoot'}.
11786:                        "$dir_root/$docudom/$docuname/$destination";
11787:                 unless (&Apache::lonnet::repcopy_userfile("$dir/$file") eq 'ok') {
11788:                     $error = &mt('Archive file not found.');
11789:                 }
11790:             }
11791:             my (@to_overwrite,@to_skip);
11792:             if ($env{'form.archive_overwrite_total'} > 0) {
11793:                 my $total = $env{'form.archive_overwrite_total'};
11794:                 for (my $i=0; $i<$total; $i++) {
11795:                     if ($env{'form.archive_overwrite_'.$i} == 1) {
11796:                         push(@to_overwrite,$env{'form.archive_overwrite_name_'.$i});
11797:                     } elsif ($env{'form.archive_overwrite_'.$i} == 0) {
11798:                         push(@to_skip,$env{'form.archive_overwrite_name_'.$i});
11799:                     }
11800:                 }
11801:             }
11802:             my $numskip = scalar(@to_skip);
11803:             if (($numskip > 0) && 
11804:                 ($numskip == $env{'form.archive_itemcount'})) {
11805:                 $warning = &mt('All items in the archive file already exist, and no overwriting of existing files has been requested.');         
11806:             } elsif ($dir eq '') {
11807:                 $error = &mt('Directory containing archive file unavailable.');
11808:             } elsif (!$error) {
11809:                 my ($decompressed,$display);
11810:                 if ($numskip > 0) {
11811:                     my $tempdir = time.'_'.$$.int(rand(10000));
11812:                     mkdir("$dir/$tempdir",0755);
11813:                     system("mv $dir/$file $dir/$tempdir/$file");
11814:                     ($decompressed,$display) = 
11815:                         &decompress_uploaded_file($file,"$dir/$tempdir");
11816:                     foreach my $item (@to_skip) {
11817:                         if (($item ne '') && ($item !~ /\.\./)) {
11818:                             if (-f "$dir/$tempdir/$item") { 
11819:                                 unlink("$dir/$tempdir/$item");
11820:                             } elsif (-d "$dir/$tempdir/$item") {
11821:                                 system("rm -rf $dir/$tempdir/$item");
11822:                             }
11823:                         }
11824:                     }
11825:                     system("mv $dir/$tempdir/* $dir");
11826:                     rmdir("$dir/$tempdir");   
11827:                 } else {
11828:                     ($decompressed,$display) = 
11829:                         &decompress_uploaded_file($file,$dir);
11830:                 }
11831:                 if ($decompressed eq 'ok') {
11832:                     $output = '<p class="LC_info">'.
11833:                               &mt('Files extracted successfully from archive.').
11834:                               '</p>'."\n";
11835:                     my ($warning,$result,@contents);
11836:                     my ($newdirlistref,$newlisterror) =
11837:                         &Apache::lonnet::dirlist($currdir,$docudom,
11838:                                                  $docuname,1);
11839:                     my (%is_dir,%changes,@newitems);
11840:                     my $dirptr = 16384;
11841:                     if (ref($newdirlistref) eq 'ARRAY') {
11842:                         foreach my $dir_line (@{$newdirlistref}) {
11843:                             my ($item,undef,undef,$testdir)=split(/\&/,$dir_line,5);
11844:                             unless (($item =~ /^\.+$/) || ($item eq $file) || 
11845:                                     ((@to_skip > 0) && (grep(/^\Q$item\E$/,@to_skip)))) {
11846:                                 push(@newitems,$item);
11847:                                 if ($dirptr&$testdir) {
11848:                                     $is_dir{$item} = 1;
11849:                                 }
11850:                                 $changes{$item} = 1;
11851:                             }
11852:                         }
11853:                     }
11854:                     if (keys(%changes) > 0) {
11855:                         foreach my $item (sort(@newitems)) {
11856:                             if ($changes{$item}) {
11857:                                 push(@contents,$item);
11858:                             }
11859:                         }
11860:                     }
11861:                     if (@contents > 0) {
11862:                         my $wantform;
11863:                         unless ($env{'form.autoextract_camtasia'}) {
11864:                             $wantform = 1;
11865:                         }
11866:                         my (%children,%parent,%dirorder,%titles);
11867:                         my ($count,$datatable) = &get_extracted($docudom,$docuname,
11868:                                                                 $currdir,\%is_dir,
11869:                                                                 \%children,\%parent,
11870:                                                                 \@contents,\%dirorder,
11871:                                                                 \%titles,$wantform);
11872:                         if ($datatable ne '') {
11873:                             $output .= &archive_options_form('decompressed',$datatable,
11874:                                                              $count,$hiddenelem);
11875:                             my $startcount = 6;
11876:                             $output .= &archive_javascript($startcount,$count,
11877:                                                            \%titles,\%children);
11878:                         }
11879:                         if ($env{'form.autoextract_camtasia'}) {
11880:                             my $version = $env{'form.autoextract_camtasia'};
11881:                             my %displayed;
11882:                             my $total = 1;
11883:                             $env{'form.archive_directory'} = [];
11884:                             foreach my $i (sort { $a <=> $b } keys(%dirorder)) {
11885:                                 my $path = join('/',map { $titles{$_}; } @{$dirorder{$i}});
11886:                                 $path =~ s{/$}{};
11887:                                 my $item;
11888:                                 if ($path ne '') {
11889:                                     $item = "$path/$titles{$i}";
11890:                                 } else {
11891:                                     $item = $titles{$i};
11892:                                 }
11893:                                 $env{'form.archive_content_'.$i} = "$dir_root/$destination/$item";
11894:                                 if ($item eq $contents[0]) {
11895:                                     push(@{$env{'form.archive_directory'}},$i);
11896:                                     $env{'form.archive_'.$i} = 'display';
11897:                                     $env{'form.archive_title_'.$i} = $env{'form.camtasia_foldername'};
11898:                                     $displayed{'folder'} = $i;
11899:                                 } elsif ((($item eq "$contents[0]/index.html") && ($version == 6)) ||
11900:                                          (($item eq "$contents[0]/$contents[0]".'.html') && ($version == 8))) { 
11901:                                     $env{'form.archive_'.$i} = 'display';
11902:                                     $env{'form.archive_title_'.$i} = $env{'form.camtasia_moviename'};
11903:                                     $displayed{'web'} = $i;
11904:                                 } else {
11905:                                     if ((($item eq "$contents[0]/media") && ($version == 6)) ||
11906:                                         ((($item eq "$contents[0]/scripts") || ($item eq "$contents[0]/skins") ||
11907:                                              ($item eq "$contents[0]/skins/express_show")) && ($version == 8))) {
11908:                                         push(@{$env{'form.archive_directory'}},$i);
11909:                                     }
11910:                                     $env{'form.archive_'.$i} = 'dependency';
11911:                                 }
11912:                                 $total ++;
11913:                             }
11914:                             for (my $i=1; $i<$total; $i++) {
11915:                                 next if ($i == $displayed{'web'});
11916:                                 next if ($i == $displayed{'folder'});
11917:                                 $env{'form.archive_dependent_on_'.$i} = $displayed{'web'};
11918:                             }
11919:                             $env{'form.phase'} = 'decompress_cleanup';
11920:                             $env{'form.archivedelete'} = 1;
11921:                             $env{'form.archive_count'} = $total-1;
11922:                             $output .=
11923:                                 &process_extracted_files('coursedocs',$docudom,
11924:                                                          $docuname,$destination,
11925:                                                          $dir_root,$hiddenelem);
11926:                         }
11927:                     } else {
11928:                         $warning = &mt('No new items extracted from archive file.');
11929:                     }
11930:                 } else {
11931:                     $output = $display;
11932:                     $error = &mt('An error occurred during extraction from the archive file.');
11933:                 }
11934:             }
11935:         }
11936:     }
11937:     if ($error) {
11938:         $output .= '<p class="LC_error">'.&mt('Not extracted.').'<br />'.
11939:                    $error.'</p>'."\n";
11940:     }
11941:     if ($warning) {
11942:         $output .= '<p class="LC_warning">'.$warning.'</p>'."\n";
11943:     }
11944:     return $output;
11945: }
11946: 
11947: sub get_extracted {
11948:     my ($docudom,$docuname,$currdir,$is_dir,$children,$parent,$contents,$dirorder,
11949:         $titles,$wantform) = @_;
11950:     my $count = 0;
11951:     my $depth = 0;
11952:     my $datatable;
11953:     my @hierarchy;
11954:     return unless ((ref($is_dir) eq 'HASH') && (ref($children) eq 'HASH') &&
11955:                    (ref($parent) eq 'HASH') && (ref($contents) eq 'ARRAY') &&
11956:                    (ref($dirorder) eq 'HASH') && (ref($titles) eq 'HASH'));
11957:     foreach my $item (@{$contents}) {
11958:         $count ++;
11959:         @{$dirorder->{$count}} = @hierarchy;
11960:         $titles->{$count} = $item;
11961:         &archive_hierarchy($depth,$count,$parent,$children);
11962:         if ($wantform) {
11963:             $datatable .= &archive_row($is_dir->{$item},$item,
11964:                                        $currdir,$depth,$count);
11965:         }
11966:         if ($is_dir->{$item}) {
11967:             $depth ++;
11968:             push(@hierarchy,$count);
11969:             $parent->{$depth} = $count;
11970:             $datatable .=
11971:                 &recurse_extracted_archive("$currdir/$item",$docudom,$docuname,
11972:                                            \$depth,\$count,\@hierarchy,$dirorder,
11973:                                            $children,$parent,$titles,$wantform);
11974:             $depth --;
11975:             pop(@hierarchy);
11976:         }
11977:     }
11978:     return ($count,$datatable);
11979: }
11980: 
11981: sub recurse_extracted_archive {
11982:     my ($currdir,$docudom,$docuname,$depth,$count,$hierarchy,$dirorder,
11983:         $children,$parent,$titles,$wantform) = @_;
11984:     my $result='';
11985:     unless ((ref($depth)) && (ref($count)) && (ref($hierarchy) eq 'ARRAY') &&
11986:             (ref($children) eq 'HASH') && (ref($parent) eq 'HASH') &&
11987:             (ref($dirorder) eq 'HASH')) {
11988:         return $result;
11989:     }
11990:     my $dirptr = 16384;
11991:     my ($newdirlistref,$newlisterror) =
11992:         &Apache::lonnet::dirlist($currdir,$docudom,$docuname,1);
11993:     if (ref($newdirlistref) eq 'ARRAY') {
11994:         foreach my $dir_line (@{$newdirlistref}) {
11995:             my ($item,undef,undef,$testdir)=split(/\&/,$dir_line,5);
11996:             unless ($item =~ /^\.+$/) {
11997:                 $$count ++;
11998:                 @{$dirorder->{$$count}} = @{$hierarchy};
11999:                 $titles->{$$count} = $item;
12000:                 &archive_hierarchy($$depth,$$count,$parent,$children);
12001: 
12002:                 my $is_dir;
12003:                 if ($dirptr&$testdir) {
12004:                     $is_dir = 1;
12005:                 }
12006:                 if ($wantform) {
12007:                     $result .= &archive_row($is_dir,$item,$currdir,$$depth,$$count);
12008:                 }
12009:                 if ($is_dir) {
12010:                     $$depth ++;
12011:                     push(@{$hierarchy},$$count);
12012:                     $parent->{$$depth} = $$count;
12013:                     $result .=
12014:                         &recurse_extracted_archive("$currdir/$item",$docudom,
12015:                                                    $docuname,$depth,$count,
12016:                                                    $hierarchy,$dirorder,$children,
12017:                                                    $parent,$titles,$wantform);
12018:                     $$depth --;
12019:                     pop(@{$hierarchy});
12020:                 }
12021:             }
12022:         }
12023:     }
12024:     return $result;
12025: }
12026: 
12027: sub archive_hierarchy {
12028:     my ($depth,$count,$parent,$children) =@_;
12029:     if ((ref($parent) eq 'HASH') && (ref($children) eq 'HASH')) {
12030:         if (exists($parent->{$depth})) {
12031:              $children->{$parent->{$depth}} .= $count.':';
12032:         }
12033:     }
12034:     return;
12035: }
12036: 
12037: sub archive_row {
12038:     my ($is_dir,$item,$currdir,$depth,$count) = @_;
12039:     my ($name) = ($item =~ m{([^/]+)$});
12040:     my %choices = &Apache::lonlocal::texthash (
12041:                                        'display'    => 'Add as file',
12042:                                        'dependency' => 'Include as dependency',
12043:                                        'discard'    => 'Discard',
12044:                                       );
12045:     if ($is_dir) {
12046:         $choices{'display'} = &mt('Add as folder'); 
12047:     }
12048:     my $output = &start_data_table_row().'<td align="right">'.$count.'</td>'."\n";
12049:     my $offset = 0;
12050:     foreach my $action ('display','dependency','discard') {
12051:         $offset ++;
12052:         if ($action ne 'display') {
12053:             $offset ++;
12054:         }  
12055:         $output .= '<td><span class="LC_nobreak">'.
12056:                    '<label><input type="radio" name="archive_'.$count.
12057:                    '" id="archive_'.$action.'_'.$count.'" value="'.$action.'"';
12058:         my $text = $choices{$action};
12059:         if ($is_dir) {
12060:             $output .= ' onclick="javascript:propagateCheck(this.form,'."'$count'".');"';
12061:             if ($action eq 'display') {
12062:                 $text = &mt('Add as folder');
12063:             }
12064:         } else {
12065:             $output .= ' onclick="javascript:dependencyCheck(this.form,'."$count,$offset".');"';
12066: 
12067:         }
12068:         $output .= ' />&nbsp;'.$choices{$action}.'</label></span>';
12069:         if ($action eq 'dependency') {
12070:             $output .= '<div id="arc_depon_'.$count.'" style="display:none;">'."\n".
12071:                        &mt('Used by:').'&nbsp;<select name="archive_dependent_on_'.$count.'" '.
12072:                        'onchange="propagateSelect(this.form,'."$count,$offset".')">'."\n".
12073:                        '<option value=""></option>'."\n".
12074:                        '</select>'."\n".
12075:                        '</div>';
12076:         } elsif ($action eq 'display') {
12077:             $output .= '<div id="arc_title_'.$count.'" style="display:none;">'."\n".
12078:                        &mt('Title:').'&nbsp;<input type="text" name="archive_title_'.$count.'" id="archive_title_'.$count.'" />'."\n".
12079:                        '</div>';
12080:         }
12081:         $output .= '</td>';
12082:     }
12083:     $output .= '<td><input type="hidden" name="archive_content_'.$count.'" value="'.
12084:                &HTML::Entities::encode("$currdir/$item",'"<>&').'" />'.('&nbsp;' x 2);
12085:     for (my $i=0; $i<$depth; $i++) {
12086:         $output .= ('<img src="/adm/lonIcons/whitespace1.gif" class="LC_docs_spacer" alt="" />' x2)."\n";
12087:     }
12088:     if ($is_dir) {
12089:         $output .= '<img src="/adm/lonIcons/navmap.folder.open.gif" alt="" />&nbsp;'."\n".
12090:                    '<input type="hidden" name="archive_directory" value="'.$count.'" />'."\n";
12091:     } else {
12092:         $output .= '<input type="hidden" name="archive_file" value="'.$count.'" />'."\n";
12093:     }
12094:     $output .= '&nbsp;'.$name.'</td>'."\n".
12095:                &end_data_table_row();
12096:     return $output;
12097: }
12098: 
12099: sub archive_options_form {
12100:     my ($form,$display,$count,$hiddenelem) = @_;
12101:     my %lt = &Apache::lonlocal::texthash(
12102:                perm => 'Permanently remove archive file?',
12103:                hows => 'How should each extracted item be incorporated in the course?',
12104:                cont => 'Content actions for all',
12105:                addf => 'Add as folder/file',
12106:                incd => 'Include as dependency for a displayed file',
12107:                disc => 'Discard',
12108:                no   => 'No',
12109:                yes  => 'Yes',
12110:                save => 'Save',
12111:     );
12112:     my $output = <<"END";
12113: <form name="$form" method="post" action="">
12114: <p><span class="LC_nobreak">$lt{'perm'}&nbsp;
12115: <label>
12116:   <input type="radio" name="archivedelete" value="0" checked="checked" />$lt{'no'}
12117: </label>
12118: &nbsp;
12119: <label>
12120:   <input type="radio" name="archivedelete" value="1" />$lt{'yes'}</label>
12121: </span>
12122: </p>
12123: <input type="hidden" name="phase" value="decompress_cleanup" />
12124: <br />$lt{'hows'}
12125: <div class="LC_columnSection">
12126:   <fieldset>
12127:     <legend>$lt{'cont'}</legend>
12128:     <input type="button" value="$lt{'addf'}" onclick="javascript:checkAll(document.$form,'display');" /> 
12129:     &nbsp;&nbsp;<input type="button" value="$lt{'incd'}" onclick="javascript:checkAll(document.$form,'dependency');" />
12130:     &nbsp;&nbsp;<input type="button" value="$lt{'disc'}" onclick="javascript:checkAll(document.$form,'discard');" />
12131:   </fieldset>
12132: </div>
12133: END
12134:     return $output.
12135:            &start_data_table()."\n".
12136:            $display."\n".
12137:            &end_data_table()."\n".
12138:            '<input type="hidden" name="archive_count" value="'.$count.'" />'.
12139:            $hiddenelem.
12140:            '<br /><input type="submit" name="archive_submit" value="'.$lt{'save'}.'" />'.
12141:            '</form>';
12142: }
12143: 
12144: sub archive_javascript {
12145:     my ($startcount,$numitems,$titles,$children) = @_;
12146:     return unless ((ref($titles) eq 'HASH') && (ref($children) eq 'HASH'));
12147:     my $maintitle = $env{'form.comment'};
12148:     my $scripttag = <<START;
12149: <script type="text/javascript">
12150: // <![CDATA[
12151: 
12152: function checkAll(form,prefix) {
12153:     var idstr =  new RegExp("^archive_"+prefix+"_\\\\d+\$");
12154:     for (var i=0; i < form.elements.length; i++) {
12155:         var id = form.elements[i].id;
12156:         if ((id != '') && (id != undefined)) {
12157:             if (idstr.test(id)) {
12158:                 if (form.elements[i].type == 'radio') {
12159:                     form.elements[i].checked = true;
12160:                     var nostart = i-$startcount;
12161:                     var offset = nostart%7;
12162:                     var count = (nostart-offset)/7;    
12163:                     dependencyCheck(form,count,offset);
12164:                 }
12165:             }
12166:         }
12167:     }
12168: }
12169: 
12170: function propagateCheck(form,count) {
12171:     if (count > 0) {
12172:         var startelement = $startcount + ((count-1) * 7);
12173:         for (var j=1; j<6; j++) {
12174:             if ((j != 2) && (j != 4)) {
12175:                 var item = startelement + j; 
12176:                 if (form.elements[item].type == 'radio') {
12177:                     if (form.elements[item].checked) {
12178:                         containerCheck(form,count,j);
12179:                         break;
12180:                     }
12181:                 }
12182:             }
12183:         }
12184:     }
12185: }
12186: 
12187: numitems = $numitems
12188: var titles = new Array(numitems);
12189: var parents = new Array(numitems);
12190: for (var i=0; i<numitems; i++) {
12191:     parents[i] = new Array;
12192: }
12193: var maintitle = '$maintitle';
12194: 
12195: START
12196: 
12197:     foreach my $container (sort { $a <=> $b } (keys(%{$children}))) {
12198:         my @contents = split(/:/,$children->{$container});
12199:         for (my $i=0; $i<@contents; $i ++) {
12200:             $scripttag .= 'parents['.$container.']['.$i.'] = '.$contents[$i]."\n";
12201:         }
12202:     }
12203: 
12204:     foreach my $key (sort { $a <=> $b } (keys(%{$titles}))) {
12205:         $scripttag .= "titles[$key] = '".$titles->{$key}."';\n";
12206:     }
12207: 
12208:     $scripttag .= <<END;
12209: 
12210: function containerCheck(form,count,offset) {
12211:     if (count > 0) {
12212:         dependencyCheck(form,count,offset);
12213:         var item = (offset+$startcount)+7*(count-1);
12214:         form.elements[item].checked = true;
12215:         if(Object.prototype.toString.call(parents[count]) === '[object Array]') {
12216:             if (parents[count].length > 0) {
12217:                 for (var j=0; j<parents[count].length; j++) {
12218:                     containerCheck(form,parents[count][j],offset);
12219:                 }
12220:             }
12221:         }
12222:     }
12223: }
12224: 
12225: function dependencyCheck(form,count,offset) {
12226:     if (count > 0) {
12227:         var chosen = (offset+$startcount)+7*(count-1);
12228:         var depitem = $startcount + ((count-1) * 7) + 4;
12229:         var currtype = form.elements[depitem].type;
12230:         if (form.elements[chosen].value == 'dependency') {
12231:             document.getElementById('arc_depon_'+count).style.display='block'; 
12232:             form.elements[depitem].options.length = 0;
12233:             form.elements[depitem].options[0] = new Option('Select','',true,true);
12234:             for (var i=1; i<=numitems; i++) {
12235:                 if (i == count) {
12236:                     continue;
12237:                 }
12238:                 var startelement = $startcount + (i-1) * 7;
12239:                 for (var j=1; j<6; j++) {
12240:                     if ((j != 2) && (j!= 4)) {
12241:                         var item = startelement + j;
12242:                         if (form.elements[item].type == 'radio') {
12243:                             if (form.elements[item].checked) {
12244:                                 if (form.elements[item].value == 'display') {
12245:                                     var n = form.elements[depitem].options.length;
12246:                                     form.elements[depitem].options[n] = new Option(titles[i],i,false,false);
12247:                                 }
12248:                             }
12249:                         }
12250:                     }
12251:                 }
12252:             }
12253:         } else {
12254:             document.getElementById('arc_depon_'+count).style.display='none';
12255:             form.elements[depitem].options.length = 0;
12256:             form.elements[depitem].options[0] = new Option('Select','',true,true);
12257:         }
12258:         titleCheck(form,count,offset);
12259:     }
12260: }
12261: 
12262: function propagateSelect(form,count,offset) {
12263:     if (count > 0) {
12264:         var item = (1+offset+$startcount)+7*(count-1);
12265:         var picked = form.elements[item].options[form.elements[item].selectedIndex].value; 
12266:         if (Object.prototype.toString.call(parents[count]) === '[object Array]') {
12267:             if (parents[count].length > 0) {
12268:                 for (var j=0; j<parents[count].length; j++) {
12269:                     containerSelect(form,parents[count][j],offset,picked);
12270:                 }
12271:             }
12272:         }
12273:     }
12274: }
12275: 
12276: function containerSelect(form,count,offset,picked) {
12277:     if (count > 0) {
12278:         var item = (offset+$startcount)+7*(count-1);
12279:         if (form.elements[item].type == 'radio') {
12280:             if (form.elements[item].value == 'dependency') {
12281:                 if (form.elements[item+1].type == 'select-one') {
12282:                     for (var i=0; i<form.elements[item+1].options.length; i++) {
12283:                         if (form.elements[item+1].options[i].value == picked) {
12284:                             form.elements[item+1].selectedIndex = i;
12285:                             break;
12286:                         }
12287:                     }
12288:                 }
12289:                 if (Object.prototype.toString.call(parents[count]) === '[object Array]') {
12290:                     if (parents[count].length > 0) {
12291:                         for (var j=0; j<parents[count].length; j++) {
12292:                             containerSelect(form,parents[count][j],offset,picked);
12293:                         }
12294:                     }
12295:                 }
12296:             }
12297:         }
12298:     }
12299: }
12300: 
12301: function titleCheck(form,count,offset) {
12302:     if (count > 0) {
12303:         var chosen = (offset+$startcount)+7*(count-1);
12304:         var depitem = $startcount + ((count-1) * 7) + 2;
12305:         var currtype = form.elements[depitem].type;
12306:         if (form.elements[chosen].value == 'display') {
12307:             document.getElementById('arc_title_'+count).style.display='block';
12308:             if ((count==1) && ((parents[count].length > 0) || (numitems == 1))) {
12309:                 document.getElementById('archive_title_'+count).value=maintitle;
12310:             }
12311:         } else {
12312:             document.getElementById('arc_title_'+count).style.display='none';
12313:             if (currtype == 'text') { 
12314:                 document.getElementById('archive_title_'+count).value='';
12315:             }
12316:         }
12317:     }
12318:     return;
12319: }
12320: 
12321: // ]]>
12322: </script>
12323: END
12324:     return $scripttag;
12325: }
12326: 
12327: sub process_extracted_files {
12328:     my ($context,$docudom,$docuname,$destination,$dir_root,$hiddenelem) = @_;
12329:     my $numitems = $env{'form.archive_count'};
12330:     return unless ($numitems);
12331:     my @ids=&Apache::lonnet::current_machine_ids();
12332:     my ($prefix,$pathtocheck,$dir,$ishome,$error,$warning,%toplevelitems,%is_dir,
12333:         %folders,%containers,%mapinner,%prompttofetch);
12334:     my $docuhome = &Apache::lonnet::homeserver($docuname,$docudom);
12335:     if (grep(/^\Q$docuhome\E$/,@ids)) {
12336:         $prefix = &LONCAPA::propath($docudom,$docuname);
12337:         $pathtocheck = "$dir_root/$destination";
12338:         $dir = $dir_root;
12339:         $ishome = 1;
12340:     } else {
12341:         $prefix = $Apache::lonnet::perlvar{'lonDocRoot'};
12342:         $pathtocheck = "$dir_root/$docudom/$docuname/$destination";
12343:         $dir = "$dir_root/$docudom/$docuname";    
12344:     }
12345:     my $currdir = "$dir_root/$destination";
12346:     (my $docstype,$mapinner{'0'}) = ($destination =~ m{^(docs|supplemental)/(\w+)/});
12347:     if ($env{'form.folderpath'}) {
12348:         my @items = split('&',$env{'form.folderpath'});
12349:         $folders{'0'} = $items[-2];
12350:         if ($env{'form.folderpath'} =~ /\:1$/) {
12351:             $containers{'0'}='page';
12352:         } else {  
12353:             $containers{'0'}='sequence';
12354:         }
12355:     }
12356:     my @archdirs = &get_env_multiple('form.archive_directory');
12357:     if ($numitems) {
12358:         for (my $i=1; $i<=$numitems; $i++) {
12359:             my $path = $env{'form.archive_content_'.$i};
12360:             if ($path =~ m{^\Q$pathtocheck\E/([^/]+)$}) {
12361:                 my $item = $1;
12362:                 $toplevelitems{$item} = $i;
12363:                 if (grep(/^\Q$i\E$/,@archdirs)) {
12364:                     $is_dir{$item} = 1;
12365:                 }
12366:             }
12367:         }
12368:     }
12369:     my ($output,%children,%parent,%titles,%dirorder,$result);
12370:     if (keys(%toplevelitems) > 0) {
12371:         my @contents = sort(keys(%toplevelitems));
12372:         (my $count,undef) = &get_extracted($docudom,$docuname,$currdir,\%is_dir,\%children,
12373:                                            \%parent,\@contents,\%dirorder,\%titles);
12374:     }
12375:     my (%referrer,%orphaned,%todelete,%todeletedir,%newdest,%newseqid);
12376:     if ($numitems) {
12377:         for (my $i=1; $i<=$numitems; $i++) {
12378:             next if ($env{'form.archive_'.$i} eq 'dependency');
12379:             my $path = $env{'form.archive_content_'.$i};
12380:             if ($path =~ /^\Q$pathtocheck\E/) {
12381:                 if ($env{'form.archive_'.$i} eq 'discard') {
12382:                     if ($prefix ne '' && $path ne '') {
12383:                         if (-e $prefix.$path) {
12384:                             if ((@archdirs > 0) && 
12385:                                 (grep(/^\Q$i\E$/,@archdirs))) {
12386:                                 $todeletedir{$prefix.$path} = 1;
12387:                             } else {
12388:                                 $todelete{$prefix.$path} = 1;
12389:                             }
12390:                         }
12391:                     }
12392:                 } elsif ($env{'form.archive_'.$i} eq 'display') {
12393:                     my ($docstitle,$title,$url,$outer);
12394:                     ($title) = ($path =~ m{/([^/]+)$});
12395:                     $docstitle = $env{'form.archive_title_'.$i};
12396:                     if ($docstitle eq '') {
12397:                         $docstitle = $title;
12398:                     }
12399:                     $outer = 0;
12400:                     if (ref($dirorder{$i}) eq 'ARRAY') {
12401:                         if (@{$dirorder{$i}} > 0) {
12402:                             foreach my $item (reverse(@{$dirorder{$i}})) {
12403:                                 if ($env{'form.archive_'.$item} eq 'display') {
12404:                                     $outer = $item;
12405:                                     last;
12406:                                 }
12407:                             }
12408:                         }
12409:                     }
12410:                     my ($errtext,$fatal) = 
12411:                         &LONCAPA::map::mapread('/uploaded/'.$docudom.'/'.$docuname.
12412:                                                '/'.$folders{$outer}.'.'.
12413:                                                $containers{$outer});
12414:                     next if ($fatal);
12415:                     if ((@archdirs > 0) && (grep(/^\Q$i\E$/,@archdirs))) {
12416:                         if ($context eq 'coursedocs') {
12417:                             $mapinner{$i} = time;
12418:                             $folders{$i} = 'default_'.$mapinner{$i};
12419:                             $containers{$i} = 'sequence';
12420:                             my $url = '/uploaded/'.$docudom.'/'.$docuname.'/'.
12421:                                       $folders{$i}.'.'.$containers{$i};
12422:                             my $newidx = &LONCAPA::map::getresidx();
12423:                             $LONCAPA::map::resources[$newidx]=
12424:                                 $docstitle.':'.$url.':false:normal:res';
12425:                             push(@LONCAPA::map::order,$newidx);
12426:                             my ($outtext,$errtext) =
12427:                                 &LONCAPA::map::storemap('/uploaded/'.$docudom.'/'.
12428:                                                         $docuname.'/'.$folders{$outer}.
12429:                                                         '.'.$containers{$outer},1,1);
12430:                             $newseqid{$i} = $newidx;
12431:                             unless ($errtext) {
12432:                                 $result .=  '<li>'.&mt('Folder: [_1] added to course',$docstitle).'</li>'."\n";
12433:                             }
12434:                         }
12435:                     } else {
12436:                         if ($context eq 'coursedocs') {
12437:                             my $newidx=&LONCAPA::map::getresidx();
12438:                             my $url = '/uploaded/'.$docudom.'/'.$docuname.'/'.
12439:                                       $docstype.'/'.$mapinner{$outer}.'/'.$newidx.'/'.
12440:                                       $title;
12441:                             if (!-e "$prefix$dir/$docstype/$mapinner{$outer}") {
12442:                                 mkdir("$prefix$dir/$docstype/$mapinner{$outer}",0755);
12443:                             }
12444:                             if (!-e "$prefix$dir/$docstype/$mapinner{$outer}/$newidx") {
12445:                                 mkdir("$prefix$dir/$docstype/$mapinner{$outer}/$newidx");
12446:                             }
12447:                             if (-e "$prefix$dir/$docstype/$mapinner{$outer}/$newidx") {
12448:                                 system("mv $prefix$path $prefix$dir/$docstype/$mapinner{$outer}/$newidx/$title");
12449:                                 $newdest{$i} = "$prefix$dir/$docstype/$mapinner{$outer}/$newidx";
12450:                                 unless ($ishome) {
12451:                                     my $fetch = "$newdest{$i}/$title";
12452:                                     $fetch =~ s/^\Q$prefix$dir\E//;
12453:                                     $prompttofetch{$fetch} = 1;
12454:                                 }
12455:                             }
12456:                             $LONCAPA::map::resources[$newidx]=
12457:                                 $docstitle.':'.$url.':false:normal:res';
12458:                             push(@LONCAPA::map::order, $newidx);
12459:                             my ($outtext,$errtext)=
12460:                                 &LONCAPA::map::storemap('/uploaded/'.$docudom.'/'.
12461:                                                         $docuname.'/'.$folders{$outer}.
12462:                                                         '.'.$containers{$outer},1,1);
12463:                             unless ($errtext) {
12464:                                 if (-e "$prefix$dir/$docstype/$mapinner{$outer}/$newidx/$title") {
12465:                                     $result .= '<li>'.&mt('File: [_1] added to course',$docstitle).'</li>'."\n";
12466:                                 }
12467:                             }
12468:                         }
12469:                     }
12470:                 }
12471:             } else {
12472:                 $warning .= &mt('Item extracted from archive: [_1] has unexpected path.',$path).'<br />'; 
12473:             }
12474:         }
12475:         for (my $i=1; $i<=$numitems; $i++) {
12476:             next unless ($env{'form.archive_'.$i} eq 'dependency');
12477:             my $path = $env{'form.archive_content_'.$i};
12478:             if ($path =~ /^\Q$pathtocheck\E/) {
12479:                 my ($title) = ($path =~ m{/([^/]+)$});
12480:                 $referrer{$i} = $env{'form.archive_dependent_on_'.$i};
12481:                 if ($env{'form.archive_'.$referrer{$i}} eq 'display') {
12482:                     if (ref($dirorder{$i}) eq 'ARRAY') {
12483:                         my ($itemidx,$fullpath,$relpath);
12484:                         if (ref($dirorder{$referrer{$i}}) eq 'ARRAY') {
12485:                             my $container = $dirorder{$referrer{$i}}->[-1];
12486:                             for (my $j=0; $j<@{$dirorder{$i}}; $j++) {
12487:                                 if ($dirorder{$i}->[$j] eq $container) {
12488:                                     $itemidx = $j;
12489:                                 }
12490:                             }
12491:                         }
12492:                         if ($itemidx eq '') {
12493:                             $itemidx =  0;
12494:                         } 
12495:                         if (grep(/^\Q$referrer{$i}\E$/,@archdirs)) {
12496:                             if ($mapinner{$referrer{$i}}) {
12497:                                 $fullpath = "$prefix$dir/$docstype/$mapinner{$referrer{$i}}";
12498:                                 for (my $j=$itemidx; $j<@{$dirorder{$i}}; $j++) {
12499:                                     if (grep(/^\Q$dirorder{$i}->[$j]\E$/,@archdirs)) {
12500:                                         unless (defined($newseqid{$dirorder{$i}->[$j]})) {
12501:                                             $fullpath .= '/'.$titles{$dirorder{$i}->[$j]};
12502:                                             $relpath .= '/'.$titles{$dirorder{$i}->[$j]};
12503:                                             if (!-e $fullpath) {
12504:                                                 mkdir($fullpath,0755);
12505:                                             }
12506:                                         }
12507:                                     } else {
12508:                                         last;
12509:                                     }
12510:                                 }
12511:                             }
12512:                         } elsif ($newdest{$referrer{$i}}) {
12513:                             $fullpath = $newdest{$referrer{$i}};
12514:                             for (my $j=$itemidx; $j<@{$dirorder{$i}}; $j++) {
12515:                                 if ($env{'form.archive_'.$dirorder{$i}->[$j]} eq 'discard') {
12516:                                     $orphaned{$i} = $env{'form.archive_'.$dirorder{$i}->[$j]};
12517:                                     last;
12518:                                 } elsif (grep(/^\Q$dirorder{$i}->[$j]\E$/,@archdirs)) {
12519:                                     unless (defined($newseqid{$dirorder{$i}->[$j]})) {
12520:                                         $fullpath .= '/'.$titles{$dirorder{$i}->[$j]};
12521:                                         $relpath .= '/'.$titles{$dirorder{$i}->[$j]};
12522:                                         if (!-e $fullpath) {
12523:                                             mkdir($fullpath,0755);
12524:                                         }
12525:                                     }
12526:                                 } else {
12527:                                     last;
12528:                                 }
12529:                             }
12530:                         }
12531:                         if ($fullpath ne '') {
12532:                             if (-e "$prefix$path") {
12533:                                 system("mv $prefix$path $fullpath/$title");
12534:                             }
12535:                             if (-e "$fullpath/$title") {
12536:                                 my $showpath;
12537:                                 if ($relpath ne '') {
12538:                                     $showpath = "$relpath/$title";
12539:                                 } else {
12540:                                     $showpath = "/$title";
12541:                                 } 
12542:                                 $result .= '<li>'.&mt('[_1] included as a dependency',$showpath).'</li>'."\n";
12543:                             } 
12544:                             unless ($ishome) {
12545:                                 my $fetch = "$fullpath/$title";
12546:                                 $fetch =~ s/^\Q$prefix$dir\E//; 
12547:                                 $prompttofetch{$fetch} = 1;
12548:                             }
12549:                         }
12550:                     }
12551:                 } elsif ($env{'form.archive_'.$referrer{$i}} eq 'discard') {
12552:                     $warning .= &mt('[_1] is a dependency of [_2], which was discarded.',
12553:                                     $path,$env{'form.archive_content_'.$referrer{$i}}).'<br />';
12554:                 }
12555:             } else {
12556:                 $warning .= &mt('Item extracted from archive: [_1] has unexpected path.',$path).'<br />'; 
12557:             }
12558:         }
12559:         if (keys(%todelete)) {
12560:             foreach my $key (keys(%todelete)) {
12561:                 unlink($key);
12562:             }
12563:         }
12564:         if (keys(%todeletedir)) {
12565:             foreach my $key (keys(%todeletedir)) {
12566:                 rmdir($key);
12567:             }
12568:         }
12569:         foreach my $dir (sort(keys(%is_dir))) {
12570:             if (($pathtocheck ne '') && ($dir ne ''))  {
12571:                 &cleanup_empty_dirs($prefix."$pathtocheck/$dir");
12572:             }
12573:         }
12574:         if ($result ne '') {
12575:             $output .= '<ul>'."\n".
12576:                        $result."\n".
12577:                        '</ul>';
12578:         }
12579:         unless ($ishome) {
12580:             my $replicationfail;
12581:             foreach my $item (keys(%prompttofetch)) {
12582:                 my $fetchresult= &Apache::lonnet::reply('fetchuserfile:'.$item,$docuhome);
12583:                 unless ($fetchresult eq 'ok') {
12584:                     $replicationfail .= '<li>'.$item.'</li>'."\n";
12585:                 }
12586:             }
12587:             if ($replicationfail) {
12588:                 $output .= '<p class="LC_error">'.
12589:                            &mt('Course home server failed to retrieve:').'<ul>'.
12590:                            $replicationfail.
12591:                            '</ul></p>';
12592:             }
12593:         }
12594:     } else {
12595:         $warning = &mt('No items found in archive.');
12596:     }
12597:     if ($error) {
12598:         $output .= '<p class="LC_error">'.&mt('Not extracted.').'<br />'.
12599:                    $error.'</p>'."\n";
12600:     }
12601:     if ($warning) {
12602:         $output .= '<p class="LC_warning">'.$warning.'</p>'."\n";
12603:     }
12604:     return $output;
12605: }
12606: 
12607: sub cleanup_empty_dirs {
12608:     my ($path) = @_;
12609:     if (($path ne '') && (-d $path)) {
12610:         if (opendir(my $dirh,$path)) {
12611:             my @dircontents = grep(!/^\./,readdir($dirh));
12612:             my $numitems = 0;
12613:             foreach my $item (@dircontents) {
12614:                 if (-d "$path/$item") {
12615:                     &cleanup_empty_dirs("$path/$item");
12616:                     if (-e "$path/$item") {
12617:                         $numitems ++;
12618:                     }
12619:                 } else {
12620:                     $numitems ++;
12621:                 }
12622:             }
12623:             if ($numitems == 0) {
12624:                 rmdir($path);
12625:             }
12626:             closedir($dirh);
12627:         }
12628:     }
12629:     return;
12630: }
12631: 
12632: =pod
12633: 
12634: =item * &get_folder_hierarchy()
12635: 
12636: Provides hierarchy of names of folders/sub-folders containing the current
12637: item,
12638: 
12639: Inputs: 3
12640:      - $navmap - navmaps object
12641: 
12642:      - $map - url for map (either the trigger itself, or map containing
12643:                            the resource, which is the trigger).
12644: 
12645:      - $showitem - 1 => show title for map itself; 0 => do not show.
12646: 
12647: Outputs: 1 @pathitems - array of folder/subfolder names.
12648: 
12649: =cut
12650: 
12651: sub get_folder_hierarchy {
12652:     my ($navmap,$map,$showitem) = @_;
12653:     my @pathitems;
12654:     if (ref($navmap)) {
12655:         my $mapres = $navmap->getResourceByUrl($map);
12656:         if (ref($mapres)) {
12657:             my $pcslist = $mapres->map_hierarchy();
12658:             if ($pcslist ne '') {
12659:                 my @pcs = split(/,/,$pcslist);
12660:                 foreach my $pc (@pcs) {
12661:                     if ($pc == 1) {
12662:                         push(@pathitems,&mt('Main Content'));
12663:                     } else {
12664:                         my $res = $navmap->getByMapPc($pc);
12665:                         if (ref($res)) {
12666:                             my $title = $res->compTitle();
12667:                             $title =~ s/\W+/_/g;
12668:                             if ($title ne '') {
12669:                                 push(@pathitems,$title);
12670:                             }
12671:                         }
12672:                     }
12673:                 }
12674:             }
12675:             if ($showitem) {
12676:                 if ($mapres->{ID} eq '0.0') {
12677:                     push(@pathitems,&mt('Main Content'));
12678:                 } else {
12679:                     my $maptitle = $mapres->compTitle();
12680:                     $maptitle =~ s/\W+/_/g;
12681:                     if ($maptitle ne '') {
12682:                         push(@pathitems,$maptitle);
12683:                     }
12684:                 }
12685:             }
12686:         }
12687:     }
12688:     return @pathitems;
12689: }
12690: 
12691: =pod
12692: 
12693: =item * &get_turnedin_filepath()
12694: 
12695: Determines path in a user's portfolio file for storage of files uploaded
12696: to a specific essayresponse or dropbox item.
12697: 
12698: Inputs: 3 required + 1 optional.
12699: $symb is symb for resource, $uname and $udom are for current user (required).
12700: $caller is optional (can be "submission", if routine is called when storing
12701: an upoaded file when "Submit Answer" button was pressed).
12702: 
12703: Returns array containing $path and $multiresp. 
12704: $path is path in portfolio.  $multiresp is 1 if this resource contains more
12705: than one file upload item.  Callers of routine should append partid as a 
12706: subdirectory to $path in cases where $multiresp is 1.
12707: 
12708: Called by: homework/essayresponse.pm and homework/structuretags.pm
12709: 
12710: =cut
12711: 
12712: sub get_turnedin_filepath {
12713:     my ($symb,$uname,$udom,$caller) = @_;
12714:     my ($map,$resid,$resurl)=&Apache::lonnet::decode_symb($symb);
12715:     my $turnindir;
12716:     my %userhash = &Apache::lonnet::userenvironment($udom,$uname,'turnindir');
12717:     $turnindir = $userhash{'turnindir'};
12718:     my ($path,$multiresp);
12719:     if ($turnindir eq '') {
12720:         if ($caller eq 'submission') {
12721:             $turnindir = &mt('turned in');
12722:             $turnindir =~ s/\W+/_/g;
12723:             my %newhash = (
12724:                             'turnindir' => $turnindir,
12725:                           );
12726:             &Apache::lonnet::put('environment',\%newhash,$udom,$uname);
12727:         }
12728:     }
12729:     if ($turnindir ne '') {
12730:         $path = '/'.$turnindir.'/';
12731:         my ($multipart,$turnin,@pathitems);
12732:         my $navmap = Apache::lonnavmaps::navmap->new();
12733:         if (defined($navmap)) {
12734:             my $mapres = $navmap->getResourceByUrl($map);
12735:             if (ref($mapres)) {
12736:                 my $pcslist = $mapres->map_hierarchy();
12737:                 if ($pcslist ne '') {
12738:                     foreach my $pc (split(/,/,$pcslist)) {
12739:                         my $res = $navmap->getByMapPc($pc);
12740:                         if (ref($res)) {
12741:                             my $title = $res->compTitle();
12742:                             $title =~ s/\W+/_/g;
12743:                             if ($title ne '') {
12744:                                 if (($pc > 1) && (length($title) > 12)) {
12745:                                     $title = substr($title,0,12);
12746:                                 }
12747:                                 push(@pathitems,$title);
12748:                             }
12749:                         }
12750:                     }
12751:                 }
12752:                 my $maptitle = $mapres->compTitle();
12753:                 $maptitle =~ s/\W+/_/g;
12754:                 if ($maptitle ne '') {
12755:                     if (length($maptitle) > 12) {
12756:                         $maptitle = substr($maptitle,0,12);
12757:                     }
12758:                     push(@pathitems,$maptitle);
12759:                 }
12760:                 unless ($env{'request.state'} eq 'construct') {
12761:                     my $res = $navmap->getBySymb($symb);
12762:                     if (ref($res)) {
12763:                         my $partlist = $res->parts();
12764:                         my $totaluploads = 0;
12765:                         if (ref($partlist) eq 'ARRAY') {
12766:                             foreach my $part (@{$partlist}) {
12767:                                 my @types = $res->responseType($part);
12768:                                 my @ids = $res->responseIds($part);
12769:                                 for (my $i=0; $i < scalar(@ids); $i++) {
12770:                                     if ($types[$i] eq 'essay') {
12771:                                         my $partid = $part.'_'.$ids[$i];
12772:                                         if (&Apache::lonnet::EXT("resource.$partid.uploadedfiletypes") ne '') {
12773:                                             $totaluploads ++;
12774:                                         }
12775:                                     }
12776:                                 }
12777:                             }
12778:                             if ($totaluploads > 1) {
12779:                                 $multiresp = 1;
12780:                             }
12781:                         }
12782:                     }
12783:                 }
12784:             } else {
12785:                 return;
12786:             }
12787:         } else {
12788:             return;
12789:         }
12790:         my $restitle=&Apache::lonnet::gettitle($symb);
12791:         $restitle =~ s/\W+/_/g;
12792:         if ($restitle eq '') {
12793:             $restitle = ($resurl =~ m{/[^/]+$});
12794:             if ($restitle eq '') {
12795:                 $restitle = time;
12796:             }
12797:         }
12798:         if (length($restitle) > 12) {
12799:             $restitle = substr($restitle,0,12);
12800:         }
12801:         push(@pathitems,$restitle);
12802:         $path .= join('/',@pathitems);
12803:     }
12804:     return ($path,$multiresp);
12805: }
12806: 
12807: =pod
12808: 
12809: =back
12810: 
12811: =head1 CSV Upload/Handling functions
12812: 
12813: =over 4
12814: 
12815: =item * &upfile_store($r)
12816: 
12817: Store uploaded file, $r should be the HTTP Request object,
12818: needs $env{'form.upfile'}
12819: returns $datatoken to be put into hidden field
12820: 
12821: =cut
12822: 
12823: sub upfile_store {
12824:     my $r=shift;
12825:     $env{'form.upfile'}=~s/\r/\n/gs;
12826:     $env{'form.upfile'}=~s/\f/\n/gs;
12827:     $env{'form.upfile'}=~s/\n+/\n/gs;
12828:     $env{'form.upfile'}=~s/\n+$//gs;
12829: 
12830:     my $datatoken=$env{'user.name'}.'_'.$env{'user.domain'}.
12831: 	'_enroll_'.$env{'request.course.id'}.'_'.time.'_'.$$;
12832:     {
12833:         my $datafile = $r->dir_config('lonDaemons').
12834:                            '/tmp/'.$datatoken.'.tmp';
12835:         if ( open(my $fh,">$datafile") ) {
12836:             print $fh $env{'form.upfile'};
12837:             close($fh);
12838:         }
12839:     }
12840:     return $datatoken;
12841: }
12842: 
12843: =pod
12844: 
12845: =item * &load_tmp_file($r)
12846: 
12847: Load uploaded file from tmp, $r should be the HTTP Request object,
12848: needs $env{'form.datatoken'},
12849: sets $env{'form.upfile'} to the contents of the file
12850: 
12851: =cut
12852: 
12853: sub load_tmp_file {
12854:     my $r=shift;
12855:     my @studentdata=();
12856:     {
12857:         my $studentfile = $r->dir_config('lonDaemons').
12858:                               '/tmp/'.$env{'form.datatoken'}.'.tmp';
12859:         if ( open(my $fh,"<$studentfile") ) {
12860:             @studentdata=<$fh>;
12861:             close($fh);
12862:         }
12863:     }
12864:     $env{'form.upfile'}=join('',@studentdata);
12865: }
12866: 
12867: =pod
12868: 
12869: =item * &upfile_record_sep()
12870: 
12871: Separate uploaded file into records
12872: returns array of records,
12873: needs $env{'form.upfile'} and $env{'form.upfiletype'}
12874: 
12875: =cut
12876: 
12877: sub upfile_record_sep {
12878:     if ($env{'form.upfiletype'} eq 'xml') {
12879:     } else {
12880: 	my @records;
12881: 	foreach my $line (split(/\n/,$env{'form.upfile'})) {
12882: 	    if ($line=~/^\s*$/) { next; }
12883: 	    push(@records,$line);
12884: 	}
12885: 	return @records;
12886:     }
12887: }
12888: 
12889: =pod
12890: 
12891: =item * &record_sep($record)
12892: 
12893: Separate a record into fields $record should be an item from the upfile_record_sep(), needs $env{'form.upfiletype'}
12894: 
12895: =cut
12896: 
12897: sub takeleft {
12898:     my $index=shift;
12899:     return substr('0000'.$index,-4,4);
12900: }
12901: 
12902: sub record_sep {
12903:     my $record=shift;
12904:     my %components=();
12905:     if ($env{'form.upfiletype'} eq 'xml') {
12906:     } elsif ($env{'form.upfiletype'} eq 'space') {
12907:         my $i=0;
12908:         foreach my $field (split(/\s+/,$record)) {
12909:             $field=~s/^(\"|\')//;
12910:             $field=~s/(\"|\')$//;
12911:             $components{&takeleft($i)}=$field;
12912:             $i++;
12913:         }
12914:     } elsif ($env{'form.upfiletype'} eq 'tab') {
12915:         my $i=0;
12916:         foreach my $field (split(/\t/,$record)) {
12917:             $field=~s/^(\"|\')//;
12918:             $field=~s/(\"|\')$//;
12919:             $components{&takeleft($i)}=$field;
12920:             $i++;
12921:         }
12922:     } else {
12923:         my $separator=',';
12924:         if ($env{'form.upfiletype'} eq 'semisv') {
12925:             $separator=';';
12926:         }
12927:         my $i=0;
12928: # the character we are looking for to indicate the end of a quote or a record 
12929:         my $looking_for=$separator;
12930: # do not add the characters to the fields
12931:         my $ignore=0;
12932: # we just encountered a separator (or the beginning of the record)
12933:         my $just_found_separator=1;
12934: # store the field we are working on here
12935:         my $field='';
12936: # work our way through all characters in record
12937:         foreach my $character ($record=~/(.)/g) {
12938:             if ($character eq $looking_for) {
12939:                if ($character ne $separator) {
12940: # Found the end of a quote, again looking for separator
12941:                   $looking_for=$separator;
12942:                   $ignore=1;
12943:                } else {
12944: # Found a separator, store away what we got
12945:                   $components{&takeleft($i)}=$field;
12946: 	          $i++;
12947:                   $just_found_separator=1;
12948:                   $ignore=0;
12949:                   $field='';
12950:                }
12951:                next;
12952:             }
12953: # single or double quotation marks after a separator indicate beginning of a quote
12954: # we are now looking for the end of the quote and need to ignore separators
12955:             if ((($character eq '"') || ($character eq "'")) && ($just_found_separator))  {
12956:                $looking_for=$character;
12957:                next;
12958:             }
12959: # ignore would be true after we reached the end of a quote
12960:             if ($ignore) { next; }
12961:             if (($just_found_separator) && ($character=~/\s/)) { next; }
12962:             $field.=$character;
12963:             $just_found_separator=0; 
12964:         }
12965: # catch the very last entry, since we never encountered the separator
12966:         $components{&takeleft($i)}=$field;
12967:     }
12968:     return %components;
12969: }
12970: 
12971: ######################################################
12972: ######################################################
12973: 
12974: =pod
12975: 
12976: =item * &upfile_select_html()
12977: 
12978: Return HTML code to select a file from the users machine and specify 
12979: the file type.
12980: 
12981: =cut
12982: 
12983: ######################################################
12984: ######################################################
12985: sub upfile_select_html {
12986:     my %Types = (
12987:                  csv   => &mt('CSV (comma separated values, spreadsheet)'),
12988:                  semisv => &mt('Semicolon separated values'),
12989:                  space => &mt('Space separated'),
12990:                  tab   => &mt('Tabulator separated'),
12991: #                 xml   => &mt('HTML/XML'),
12992:                  );
12993:     my $Str = '<input type="file" name="upfile" size="50" />'.
12994:         '<br />'.&mt('Type').': <select name="upfiletype">';
12995:     foreach my $type (sort(keys(%Types))) {
12996:         $Str .= '<option value="'.$type.'" >'.$Types{$type}."</option>\n";
12997:     }
12998:     $Str .= "</select>\n";
12999:     return $Str;
13000: }
13001: 
13002: sub get_samples {
13003:     my ($records,$toget) = @_;
13004:     my @samples=({});
13005:     my $got=0;
13006:     foreach my $rec (@$records) {
13007: 	my %temp = &record_sep($rec);
13008: 	if (! grep(/\S/, values(%temp))) { next; }
13009: 	if (%temp) {
13010: 	    $samples[$got]=\%temp;
13011: 	    $got++;
13012: 	    if ($got == $toget) { last; }
13013: 	}
13014:     }
13015:     return \@samples;
13016: }
13017: 
13018: ######################################################
13019: ######################################################
13020: 
13021: =pod
13022: 
13023: =item * &csv_print_samples($r,$records)
13024: 
13025: Prints a table of sample values from each column uploaded $r is an
13026: Apache Request ref, $records is an arrayref from
13027: &Apache::loncommon::upfile_record_sep
13028: 
13029: =cut
13030: 
13031: ######################################################
13032: ######################################################
13033: sub csv_print_samples {
13034:     my ($r,$records) = @_;
13035:     my $samples = &get_samples($records,5);
13036: 
13037:     $r->print(&mt('Samples').'<br />'.&start_data_table().
13038:               &start_data_table_header_row());
13039:     foreach my $sample (sort({$a <=> $b} keys(%{ $samples->[0] }))) { 
13040:         $r->print('<th>'.&mt('Column [_1]',($sample+1)).'</th>'); }
13041:     $r->print(&end_data_table_header_row());
13042:     foreach my $hash (@$samples) {
13043: 	$r->print(&start_data_table_row());
13044: 	foreach my $sample (sort({$a <=> $b} keys(%{ $samples->[0] }))) {
13045: 	    $r->print('<td>');
13046: 	    if (defined($$hash{$sample})) { $r->print($$hash{$sample}); }
13047: 	    $r->print('</td>');
13048: 	}
13049: 	$r->print(&end_data_table_row());
13050:     }
13051:     $r->print(&end_data_table().'<br />'."\n");
13052: }
13053: 
13054: ######################################################
13055: ######################################################
13056: 
13057: =pod
13058: 
13059: =item * &csv_print_select_table($r,$records,$d)
13060: 
13061: Prints a table to create associations between values and table columns.
13062: 
13063: $r is an Apache Request ref,
13064: $records is an arrayref from &Apache::loncommon::upfile_record_sep,
13065: $d is an array of 2 element arrays (internal name, displayed name,defaultcol)
13066: 
13067: =cut
13068: 
13069: ######################################################
13070: ######################################################
13071: sub csv_print_select_table {
13072:     my ($r,$records,$d) = @_;
13073:     my $i=0;
13074:     my $samples = &get_samples($records,1);
13075:     $r->print(&mt('Associate columns with student attributes.')."\n".
13076: 	      &start_data_table().&start_data_table_header_row().
13077:               '<th>'.&mt('Attribute').'</th>'.
13078:               '<th>'.&mt('Column').'</th>'.
13079:               &end_data_table_header_row()."\n");
13080:     foreach my $array_ref (@$d) {
13081: 	my ($value,$display,$defaultcol)=@{ $array_ref };
13082: 	$r->print(&start_data_table_row().'<td>'.$display.'</td>');
13083: 
13084: 	$r->print('<td><select name="f'.$i.'"'.
13085: 		  ' onchange="javascript:flip(this.form,'.$i.');">');
13086: 	$r->print('<option value="none"></option>');
13087: 	foreach my $sample (sort({$a <=> $b} keys(%{ $samples->[0] }))) {
13088: 	    $r->print('<option value="'.$sample.'"'.
13089:                       ($sample eq $defaultcol ? ' selected="selected" ' : '').
13090:                       '>'.&mt('Column [_1]',($sample+1)).'</option>');
13091: 	}
13092: 	$r->print('</select></td>'.&end_data_table_row()."\n");
13093: 	$i++;
13094:     }
13095:     $r->print(&end_data_table());
13096:     $i--;
13097:     return $i;
13098: }
13099: 
13100: ######################################################
13101: ######################################################
13102: 
13103: =pod
13104: 
13105: =item * &csv_samples_select_table($r,$records,$d)
13106: 
13107: Prints a table of sample values from the upload and can make associate samples to internal names.
13108: 
13109: $r is an Apache Request ref,
13110: $records is an arrayref from &Apache::loncommon::upfile_record_sep,
13111: $d is an array of 2 element arrays (internal name, displayed name)
13112: 
13113: =cut
13114: 
13115: ######################################################
13116: ######################################################
13117: sub csv_samples_select_table {
13118:     my ($r,$records,$d) = @_;
13119:     my $i=0;
13120:     #
13121:     my $max_samples = 5;
13122:     my $samples = &get_samples($records,$max_samples);
13123:     $r->print(&start_data_table().
13124:               &start_data_table_header_row().'<th>'.
13125:               &mt('Field').'</th><th>'.&mt('Samples').'</th>'.
13126:               &end_data_table_header_row());
13127: 
13128:     foreach my $key (sort(keys(%{ $samples->[0] }))) {
13129: 	$r->print(&start_data_table_row().'<td><select name="f'.$i.'"'.
13130: 		  ' onchange="javascript:flip(this.form,'.$i.');">');
13131: 	foreach my $option (@$d) {
13132: 	    my ($value,$display,$defaultcol)=@{ $option };
13133: 	    $r->print('<option value="'.$value.'"'.
13134:                       ($i eq $defaultcol ? ' selected="selected" ':'').'>'.
13135:                       $display.'</option>');
13136: 	}
13137: 	$r->print('</select></td><td>');
13138: 	foreach my $line (0..($max_samples-1)) {
13139: 	    if (defined($samples->[$line]{$key})) { 
13140: 		$r->print($samples->[$line]{$key}."<br />\n"); 
13141: 	    }
13142: 	}
13143: 	$r->print('</td>'.&end_data_table_row());
13144: 	$i++;
13145:     }
13146:     $r->print(&end_data_table());
13147:     $i--;
13148:     return($i);
13149: }
13150: 
13151: ######################################################
13152: ######################################################
13153: 
13154: =pod
13155: 
13156: =item * &clean_excel_name($name)
13157: 
13158: Returns a replacement for $name which does not contain any illegal characters.
13159: 
13160: =cut
13161: 
13162: ######################################################
13163: ######################################################
13164: sub clean_excel_name {
13165:     my ($name) = @_;
13166:     $name =~ s/[:\*\?\/\\]//g;
13167:     if (length($name) > 31) {
13168:         $name = substr($name,0,31);
13169:     }
13170:     return $name;
13171: }
13172: 
13173: =pod
13174: 
13175: =item * &check_if_partid_hidden($id,$symb,$udom,$uname)
13176: 
13177: Returns either 1 or undef
13178: 
13179: 1 if the part is to be hidden, undef if it is to be shown
13180: 
13181: Arguments are:
13182: 
13183: $id the id of the part to be checked
13184: $symb, optional the symb of the resource to check
13185: $udom, optional the domain of the user to check for
13186: $uname, optional the username of the user to check for
13187: 
13188: =cut
13189: 
13190: sub check_if_partid_hidden {
13191:     my ($id,$symb,$udom,$uname) = @_;
13192:     my $hiddenparts=&Apache::lonnet::EXT('resource.0.hiddenparts',
13193: 					 $symb,$udom,$uname);
13194:     my $truth=1;
13195:     #if the string starts with !, then the list is the list to show not hide
13196:     if ($hiddenparts=~s/^\s*!//) { $truth=undef; }
13197:     my @hiddenlist=split(/,/,$hiddenparts);
13198:     foreach my $checkid (@hiddenlist) {
13199: 	if ($checkid =~ /^\s*\Q$id\E\s*$/) { return $truth; }
13200:     }
13201:     return !$truth;
13202: }
13203: 
13204: 
13205: ############################################################
13206: ############################################################
13207: 
13208: =pod
13209: 
13210: =back 
13211: 
13212: =head1 cgi-bin script and graphing routines
13213: 
13214: =over 4
13215: 
13216: =item * &get_cgi_id()
13217: 
13218: Inputs: none
13219: 
13220: Returns an id which can be used to pass environment variables
13221: to various cgi-bin scripts.  These environment variables will
13222: be removed from the users environment after a given time by
13223: the routine &Apache::lonnet::transfer_profile_to_env.
13224: 
13225: =cut
13226: 
13227: ############################################################
13228: ############################################################
13229: my $uniq=0;
13230: sub get_cgi_id {
13231:     $uniq=($uniq+1)%100000;
13232:     return (time.'_'.$$.'_'.$uniq);
13233: }
13234: 
13235: ############################################################
13236: ############################################################
13237: 
13238: =pod
13239: 
13240: =item * &DrawBarGraph()
13241: 
13242: Facilitates the plotting of data in a (stacked) bar graph.
13243: Puts plot definition data into the users environment in order for 
13244: graph.png to plot it.  Returns an <img> tag for the plot.
13245: The bars on the plot are labeled '1','2',...,'n'.
13246: 
13247: Inputs:
13248: 
13249: =over 4
13250: 
13251: =item $Title: string, the title of the plot
13252: 
13253: =item $xlabel: string, text describing the X-axis of the plot
13254: 
13255: =item $ylabel: string, text describing the Y-axis of the plot
13256: 
13257: =item $Max: scalar, the maximum Y value to use in the plot
13258: If $Max is < any data point, the graph will not be rendered.
13259: 
13260: =item $colors: array ref holding the colors to be used for the data sets when
13261: they are plotted.  If undefined, default values will be used.
13262: 
13263: =item $labels: array ref holding the labels to use on the x-axis for the bars.
13264: 
13265: =item @Values: An array of array references.  Each array reference holds data
13266: to be plotted in a stacked bar chart.
13267: 
13268: =item If the final element of @Values is a hash reference the key/value
13269: pairs will be added to the graph definition.
13270: 
13271: =back
13272: 
13273: Returns:
13274: 
13275: An <img> tag which references graph.png and the appropriate identifying
13276: information for the plot.
13277: 
13278: =cut
13279: 
13280: ############################################################
13281: ############################################################
13282: sub DrawBarGraph {
13283:     my ($Title,$xlabel,$ylabel,$Max,$colors,$labels,@Values)=@_;
13284:     #
13285:     if (! defined($colors)) {
13286:         $colors = ['#33ff00', 
13287:                   '#0033cc', '#990000', '#aaaa66', '#663399', '#ff9933',
13288:                   '#66ccff', '#ff9999', '#cccc33', '#660000', '#33cc66',
13289:                   ]; 
13290:     }
13291:     my $extra_settings = {};
13292:     if (ref($Values[-1]) eq 'HASH') {
13293:         $extra_settings = pop(@Values);
13294:     }
13295:     #
13296:     my $identifier = &get_cgi_id();
13297:     my $id = 'cgi.'.$identifier;        
13298:     if (! @Values || ref($Values[0]) ne 'ARRAY') {
13299:         return '';
13300:     }
13301:     #
13302:     my @Labels;
13303:     if (defined($labels)) {
13304:         @Labels = @$labels;
13305:     } else {
13306:         for (my $i=0;$i<@{$Values[0]};$i++) {
13307:             push (@Labels,$i+1);
13308:         }
13309:     }
13310:     #
13311:     my $NumBars = scalar(@{$Values[0]});
13312:     if ($NumBars < scalar(@Labels)) { $NumBars = scalar(@Labels); }
13313:     my %ValuesHash;
13314:     my $NumSets=1;
13315:     foreach my $array (@Values) {
13316:         next if (! ref($array));
13317:         $ValuesHash{$id.'.data.'.$NumSets++} = 
13318:             join(',',@$array);
13319:     }
13320:     #
13321:     my ($height,$width,$xskip,$bar_width) = (200,120,1,15);
13322:     if ($NumBars < 3) {
13323:         $width = 120+$NumBars*32;
13324:         $xskip = 1;
13325:         $bar_width = 30;
13326:     } elsif ($NumBars < 5) {
13327:         $width = 120+$NumBars*20;
13328:         $xskip = 1;
13329:         $bar_width = 20;
13330:     } elsif ($NumBars < 10) {
13331:         $width = 120+$NumBars*15;
13332:         $xskip = 1;
13333:         $bar_width = 15;
13334:     } elsif ($NumBars <= 25) {
13335:         $width = 120+$NumBars*11;
13336:         $xskip = 5;
13337:         $bar_width = 8;
13338:     } elsif ($NumBars <= 50) {
13339:         $width = 120+$NumBars*8;
13340:         $xskip = 5;
13341:         $bar_width = 4;
13342:     } else {
13343:         $width = 120+$NumBars*8;
13344:         $xskip = 5;
13345:         $bar_width = 4;
13346:     }
13347:     #
13348:     $Max = 1 if ($Max < 1);
13349:     if ( int($Max) < $Max ) {
13350:         $Max++;
13351:         $Max = int($Max);
13352:     }
13353:     $Title  = '' if (! defined($Title));
13354:     $xlabel = '' if (! defined($xlabel));
13355:     $ylabel = '' if (! defined($ylabel));
13356:     $ValuesHash{$id.'.title'}    = &escape($Title);
13357:     $ValuesHash{$id.'.xlabel'}   = &escape($xlabel);
13358:     $ValuesHash{$id.'.ylabel'}   = &escape($ylabel);
13359:     $ValuesHash{$id.'.y_max_value'} = $Max;
13360:     $ValuesHash{$id.'.NumBars'}  = $NumBars;
13361:     $ValuesHash{$id.'.NumSets'}  = $NumSets;
13362:     $ValuesHash{$id.'.PlotType'} = 'bar';
13363:     $ValuesHash{$id.'.Colors'}   = join(',',@{$colors});
13364:     $ValuesHash{$id.'.height'}   = $height;
13365:     $ValuesHash{$id.'.width'}    = $width;
13366:     $ValuesHash{$id.'.xskip'}    = $xskip;
13367:     $ValuesHash{$id.'.bar_width'} = $bar_width;
13368:     $ValuesHash{$id.'.labels'} = join(',',@Labels);
13369:     #
13370:     # Deal with other parameters
13371:     while (my ($key,$value) = each(%$extra_settings)) {
13372:         $ValuesHash{$id.'.'.$key} = $value;
13373:     }
13374:     #
13375:     &Apache::lonnet::appenv(\%ValuesHash);
13376:     return '<img src="/cgi-bin/graph.png?'.$identifier.'" border="1" />';
13377: }
13378: 
13379: ############################################################
13380: ############################################################
13381: 
13382: =pod
13383: 
13384: =item * &DrawXYGraph()
13385: 
13386: Facilitates the plotting of data in an XY graph.
13387: Puts plot definition data into the users environment in order for 
13388: graph.png to plot it.  Returns an <img> tag for the plot.
13389: 
13390: Inputs:
13391: 
13392: =over 4
13393: 
13394: =item $Title: string, the title of the plot
13395: 
13396: =item $xlabel: string, text describing the X-axis of the plot
13397: 
13398: =item $ylabel: string, text describing the Y-axis of the plot
13399: 
13400: =item $Max: scalar, the maximum Y value to use in the plot
13401: If $Max is < any data point, the graph will not be rendered.
13402: 
13403: =item $colors: Array ref containing the hex color codes for the data to be 
13404: plotted in.  If undefined, default values will be used.
13405: 
13406: =item $Xlabels: Array ref containing the labels to be used for the X-axis.
13407: 
13408: =item $Ydata: Array ref containing Array refs.  
13409: Each of the contained arrays will be plotted as a separate curve.
13410: 
13411: =item %Values: hash indicating or overriding any default values which are 
13412: passed to graph.png.  
13413: Possible values are: width, xskip, x_ticks, x_tick_offset, among others.
13414: 
13415: =back
13416: 
13417: Returns:
13418: 
13419: An <img> tag which references graph.png and the appropriate identifying
13420: information for the plot.
13421: 
13422: =cut
13423: 
13424: ############################################################
13425: ############################################################
13426: sub DrawXYGraph {
13427:     my ($Title,$xlabel,$ylabel,$Max,$colors,$Xlabels,$Ydata,%Values)=@_;
13428:     #
13429:     # Create the identifier for the graph
13430:     my $identifier = &get_cgi_id();
13431:     my $id = 'cgi.'.$identifier;
13432:     #
13433:     $Title  = '' if (! defined($Title));
13434:     $xlabel = '' if (! defined($xlabel));
13435:     $ylabel = '' if (! defined($ylabel));
13436:     my %ValuesHash = 
13437:         (
13438:          $id.'.title'  => &escape($Title),
13439:          $id.'.xlabel' => &escape($xlabel),
13440:          $id.'.ylabel' => &escape($ylabel),
13441:          $id.'.y_max_value'=> $Max,
13442:          $id.'.labels'     => join(',',@$Xlabels),
13443:          $id.'.PlotType'   => 'XY',
13444:          );
13445:     #
13446:     if (defined($colors) && ref($colors) eq 'ARRAY') {
13447:         $ValuesHash{$id.'.Colors'}   = join(',',@{$colors});
13448:     }
13449:     #
13450:     if (! ref($Ydata) || ref($Ydata) ne 'ARRAY') {
13451:         return '';
13452:     }
13453:     my $NumSets=1;
13454:     foreach my $array (@{$Ydata}){
13455:         next if (! ref($array));
13456:         $ValuesHash{$id.'.data.'.$NumSets++} = join(',',@$array);
13457:     }
13458:     $ValuesHash{$id.'.NumSets'} = $NumSets-1;
13459:     #
13460:     # Deal with other parameters
13461:     while (my ($key,$value) = each(%Values)) {
13462:         $ValuesHash{$id.'.'.$key} = $value;
13463:     }
13464:     #
13465:     &Apache::lonnet::appenv(\%ValuesHash);
13466:     return '<img src="/cgi-bin/graph.png?'.$identifier.'" border="1" />';
13467: }
13468: 
13469: ############################################################
13470: ############################################################
13471: 
13472: =pod
13473: 
13474: =item * &DrawXYYGraph()
13475: 
13476: Facilitates the plotting of data in an XY graph with two Y axes.
13477: Puts plot definition data into the users environment in order for 
13478: graph.png to plot it.  Returns an <img> tag for the plot.
13479: 
13480: Inputs:
13481: 
13482: =over 4
13483: 
13484: =item $Title: string, the title of the plot
13485: 
13486: =item $xlabel: string, text describing the X-axis of the plot
13487: 
13488: =item $ylabel: string, text describing the Y-axis of the plot
13489: 
13490: =item $colors: Array ref containing the hex color codes for the data to be 
13491: plotted in.  If undefined, default values will be used.
13492: 
13493: =item $Xlabels: Array ref containing the labels to be used for the X-axis.
13494: 
13495: =item $Ydata1: The first data set
13496: 
13497: =item $Min1: The minimum value of the left Y-axis
13498: 
13499: =item $Max1: The maximum value of the left Y-axis
13500: 
13501: =item $Ydata2: The second data set
13502: 
13503: =item $Min2: The minimum value of the right Y-axis
13504: 
13505: =item $Max2: The maximum value of the left Y-axis
13506: 
13507: =item %Values: hash indicating or overriding any default values which are 
13508: passed to graph.png.  
13509: Possible values are: width, xskip, x_ticks, x_tick_offset, among others.
13510: 
13511: =back
13512: 
13513: Returns:
13514: 
13515: An <img> tag which references graph.png and the appropriate identifying
13516: information for the plot.
13517: 
13518: =cut
13519: 
13520: ############################################################
13521: ############################################################
13522: sub DrawXYYGraph {
13523:     my ($Title,$xlabel,$ylabel,$colors,$Xlabels,$Ydata1,$Min1,$Max1,
13524:                                         $Ydata2,$Min2,$Max2,%Values)=@_;
13525:     #
13526:     # Create the identifier for the graph
13527:     my $identifier = &get_cgi_id();
13528:     my $id = 'cgi.'.$identifier;
13529:     #
13530:     $Title  = '' if (! defined($Title));
13531:     $xlabel = '' if (! defined($xlabel));
13532:     $ylabel = '' if (! defined($ylabel));
13533:     my %ValuesHash = 
13534:         (
13535:          $id.'.title'  => &escape($Title),
13536:          $id.'.xlabel' => &escape($xlabel),
13537:          $id.'.ylabel' => &escape($ylabel),
13538:          $id.'.labels' => join(',',@$Xlabels),
13539:          $id.'.PlotType' => 'XY',
13540:          $id.'.NumSets' => 2,
13541:          $id.'.two_axes' => 1,
13542:          $id.'.y1_max_value' => $Max1,
13543:          $id.'.y1_min_value' => $Min1,
13544:          $id.'.y2_max_value' => $Max2,
13545:          $id.'.y2_min_value' => $Min2,
13546:          );
13547:     #
13548:     if (defined($colors) && ref($colors) eq 'ARRAY') {
13549:         $ValuesHash{$id.'.Colors'}   = join(',',@{$colors});
13550:     }
13551:     #
13552:     if (! ref($Ydata1) || ref($Ydata1) ne 'ARRAY' ||
13553:         ! ref($Ydata2) || ref($Ydata2) ne 'ARRAY'){
13554:         return '';
13555:     }
13556:     my $NumSets=1;
13557:     foreach my $array ($Ydata1,$Ydata2){
13558:         next if (! ref($array));
13559:         $ValuesHash{$id.'.data.'.$NumSets++} = join(',',@$array);
13560:     }
13561:     #
13562:     # Deal with other parameters
13563:     while (my ($key,$value) = each(%Values)) {
13564:         $ValuesHash{$id.'.'.$key} = $value;
13565:     }
13566:     #
13567:     &Apache::lonnet::appenv(\%ValuesHash);
13568:     return '<img src="/cgi-bin/graph.png?'.$identifier.'" border="1" />';
13569: }
13570: 
13571: ############################################################
13572: ############################################################
13573: 
13574: =pod
13575: 
13576: =back 
13577: 
13578: =head1 Statistics helper routines?  
13579: 
13580: Bad place for them but what the hell.
13581: 
13582: =over 4
13583: 
13584: =item * &chartlink()
13585: 
13586: Returns a link to the chart for a specific student.  
13587: 
13588: Inputs:
13589: 
13590: =over 4
13591: 
13592: =item $linktext: The text of the link
13593: 
13594: =item $sname: The students username
13595: 
13596: =item $sdomain: The students domain
13597: 
13598: =back
13599: 
13600: =back
13601: 
13602: =cut
13603: 
13604: ############################################################
13605: ############################################################
13606: sub chartlink {
13607:     my ($linktext, $sname, $sdomain) = @_;
13608:     my $link = '<a href="/adm/statistics?reportSelected=student_assessment'.
13609:         '&amp;SelectedStudent='.&escape($sname.':'.$sdomain).
13610:         '&amp;chartoutputmode='.HTML::Entities::encode('html, with all links').
13611:        '">'.$linktext.'</a>';
13612: }
13613: 
13614: #######################################################
13615: #######################################################
13616: 
13617: =pod
13618: 
13619: =head1 Course Environment Routines
13620: 
13621: =over 4
13622: 
13623: =item * &restore_course_settings()
13624: 
13625: =item * &store_course_settings()
13626: 
13627: Restores/Store indicated form parameters from the course environment.
13628: Will not overwrite existing values of the form parameters.
13629: 
13630: Inputs: 
13631: a scalar describing the data (e.g. 'chart', 'problem_analysis')
13632: 
13633: a hash ref describing the data to be stored.  For example:
13634:    
13635: %Save_Parameters = ('Status' => 'scalar',
13636:     'chartoutputmode' => 'scalar',
13637:     'chartoutputdata' => 'scalar',
13638:     'Section' => 'array',
13639:     'Group' => 'array',
13640:     'StudentData' => 'array',
13641:     'Maps' => 'array');
13642: 
13643: Returns: both routines return nothing
13644: 
13645: =back
13646: 
13647: =cut
13648: 
13649: #######################################################
13650: #######################################################
13651: sub store_course_settings {
13652:     return &store_settings($env{'request.course.id'},@_);
13653: }
13654: 
13655: sub store_settings {
13656:     # save to the environment
13657:     # appenv the same items, just to be safe
13658:     my $udom  = $env{'user.domain'};
13659:     my $uname = $env{'user.name'};
13660:     my ($context,$prefix,$Settings) = @_;
13661:     my %SaveHash;
13662:     my %AppHash;
13663:     while (my ($setting,$type) = each(%$Settings)) {
13664:         my $basename = join('.','internal',$context,$prefix,$setting);
13665:         my $envname = 'environment.'.$basename;
13666:         if (exists($env{'form.'.$setting})) {
13667:             # Save this value away
13668:             if ($type eq 'scalar' &&
13669:                 (! exists($env{$envname}) || 
13670:                  $env{$envname} ne $env{'form.'.$setting})) {
13671:                 $SaveHash{$basename} = $env{'form.'.$setting};
13672:                 $AppHash{$envname}   = $env{'form.'.$setting};
13673:             } elsif ($type eq 'array') {
13674:                 my $stored_form;
13675:                 if (ref($env{'form.'.$setting})) {
13676:                     $stored_form = join(',',
13677:                                         map {
13678:                                             &escape($_);
13679:                                         } sort(@{$env{'form.'.$setting}}));
13680:                 } else {
13681:                     $stored_form = 
13682:                         &escape($env{'form.'.$setting});
13683:                 }
13684:                 # Determine if the array contents are the same.
13685:                 if ($stored_form ne $env{$envname}) {
13686:                     $SaveHash{$basename} = $stored_form;
13687:                     $AppHash{$envname}   = $stored_form;
13688:                 }
13689:             }
13690:         }
13691:     }
13692:     my $put_result = &Apache::lonnet::put('environment',\%SaveHash,
13693:                                           $udom,$uname);
13694:     if ($put_result !~ /^(ok|delayed)/) {
13695:         &Apache::lonnet::logthis('unable to save form parameters, '.
13696:                                  'got error:'.$put_result);
13697:     }
13698:     # Make sure these settings stick around in this session, too
13699:     &Apache::lonnet::appenv(\%AppHash);
13700:     return;
13701: }
13702: 
13703: sub restore_course_settings {
13704:     return &restore_settings($env{'request.course.id'},@_);
13705: }
13706: 
13707: sub restore_settings {
13708:     my ($context,$prefix,$Settings) = @_;
13709:     while (my ($setting,$type) = each(%$Settings)) {
13710:         next if (exists($env{'form.'.$setting}));
13711:         my $envname = 'environment.internal.'.$context.'.'.$prefix.
13712:             '.'.$setting;
13713:         if (exists($env{$envname})) {
13714:             if ($type eq 'scalar') {
13715:                 $env{'form.'.$setting} = $env{$envname};
13716:             } elsif ($type eq 'array') {
13717:                 $env{'form.'.$setting} = [ 
13718:                                            map { 
13719:                                                &unescape($_); 
13720:                                            } split(',',$env{$envname})
13721:                                            ];
13722:             }
13723:         }
13724:     }
13725: }
13726: 
13727: #######################################################
13728: #######################################################
13729: 
13730: =pod
13731: 
13732: =head1 Domain E-mail Routines  
13733: 
13734: =over 4
13735: 
13736: =item * &build_recipient_list()
13737: 
13738: Build recipient lists for following types of e-mail:
13739: (a) Error Reports, (b) Package Updates, (c) lonstatus warnings/errors
13740: (d) Help requests, (e) Course requests needing approval, (f) loncapa
13741: module change checking, student/employee ID conflict checks, as
13742: generated by lonerrorhandler.pm, CHECKRPMS, loncron,
13743: lonsupportreq.pm, loncoursequeueadmin.pm, searchcat.pl respectively.
13744: 
13745: Inputs:
13746: defmail (scalar - email address of default recipient), 
13747: mailing type (scalar: errormail, packagesmail, helpdeskmail,
13748: requestsmail, updatesmail, or idconflictsmail).
13749: 
13750: defdom (domain for which to retrieve configuration settings),
13751: 
13752: origmail (scalar - email address of recipient from loncapa.conf, 
13753: i.e., predates configuration by DC via domainprefs.pm 
13754: 
13755: Returns: comma separated list of addresses to which to send e-mail.
13756: 
13757: =back
13758: 
13759: =cut
13760: 
13761: ############################################################
13762: ############################################################
13763: sub build_recipient_list {
13764:     my ($defmail,$mailing,$defdom,$origmail) = @_;
13765:     my @recipients;
13766:     my $otheremails;
13767:     my %domconfig =
13768:          &Apache::lonnet::get_dom('configuration',['contacts'],$defdom);
13769:     if (ref($domconfig{'contacts'}) eq 'HASH') {
13770:         if (exists($domconfig{'contacts'}{$mailing})) {
13771:             if (ref($domconfig{'contacts'}{$mailing}) eq 'HASH') {
13772:                 my @contacts = ('adminemail','supportemail');
13773:                 foreach my $item (@contacts) {
13774:                     if ($domconfig{'contacts'}{$mailing}{$item}) {
13775:                         my $addr = $domconfig{'contacts'}{$item}; 
13776:                         if (!grep(/^\Q$addr\E$/,@recipients)) {
13777:                             push(@recipients,$addr);
13778:                         }
13779:                     }
13780:                     $otheremails = $domconfig{'contacts'}{$mailing}{'others'};
13781:                 }
13782:             }
13783:         } elsif ($origmail ne '') {
13784:             push(@recipients,$origmail);
13785:         }
13786:     } elsif ($origmail ne '') {
13787:         push(@recipients,$origmail);
13788:     }
13789:     if (defined($defmail)) {
13790:         if ($defmail ne '') {
13791:             push(@recipients,$defmail);
13792:         }
13793:     }
13794:     if ($otheremails) {
13795:         my @others;
13796:         if ($otheremails =~ /,/) {
13797:             @others = split(/,/,$otheremails);
13798:         } else {
13799:             push(@others,$otheremails);
13800:         }
13801:         foreach my $addr (@others) {
13802:             if (!grep(/^\Q$addr\E$/,@recipients)) {
13803:                 push(@recipients,$addr);
13804:             }
13805:         }
13806:     }
13807:     my $recipientlist = join(',',@recipients); 
13808:     return $recipientlist;
13809: }
13810: 
13811: ############################################################
13812: ############################################################
13813: 
13814: =pod
13815: 
13816: =head1 Course Catalog Routines
13817: 
13818: =over 4
13819: 
13820: =item * &gather_categories()
13821: 
13822: Converts category definitions - keys of categories hash stored in  
13823: coursecategories in configuration.db on the primary library server in a 
13824: domain - to an array.  Also generates javascript and idx hash used to 
13825: generate Domain Coordinator interface for editing Course Categories.
13826: 
13827: Inputs:
13828: 
13829: categories (reference to hash of category definitions).
13830: 
13831: cats (reference to array of arrays/hashes which encapsulates hierarchy of
13832:       categories and subcategories).
13833: 
13834: idx (reference to hash of counters used in Domain Coordinator interface for 
13835:       editing Course Categories).
13836: 
13837: jsarray (reference to array of categories used to create Javascript arrays for
13838:          Domain Coordinator interface for editing Course Categories).
13839: 
13840: Returns: nothing
13841: 
13842: Side effects: populates cats, idx and jsarray. 
13843: 
13844: =cut
13845: 
13846: sub gather_categories {
13847:     my ($categories,$cats,$idx,$jsarray) = @_;
13848:     my %counters;
13849:     my $num = 0;
13850:     foreach my $item (keys(%{$categories})) {
13851:         my ($cat,$container,$depth) = map { &unescape($_); } split(/:/,$item);
13852:         if ($container eq '' && $depth == 0) {
13853:             $cats->[$depth][$categories->{$item}] = $cat;
13854:         } else {
13855:             $cats->[$depth]{$container}[$categories->{$item}] = $cat;
13856:         }
13857:         my ($escitem,$tail) = split(/:/,$item,2);
13858:         if ($counters{$tail} eq '') {
13859:             $counters{$tail} = $num;
13860:             $num ++;
13861:         }
13862:         if (ref($idx) eq 'HASH') {
13863:             $idx->{$item} = $counters{$tail};
13864:         }
13865:         if (ref($jsarray) eq 'ARRAY') {
13866:             push(@{$jsarray->[$counters{$tail}]},$item);
13867:         }
13868:     }
13869:     return;
13870: }
13871: 
13872: =pod
13873: 
13874: =item * &extract_categories()
13875: 
13876: Used to generate breadcrumb trails for course categories.
13877: 
13878: Inputs:
13879: 
13880: categories (reference to hash of category definitions).
13881: 
13882: cats (reference to array of arrays/hashes which encapsulates hierarchy of
13883:       categories and subcategories).
13884: 
13885: trails (reference to array of breacrumb trails for each category).
13886: 
13887: allitems (reference to hash - key is category key 
13888:          (format: escaped(name):escaped(parent category):depth in hierarchy).
13889: 
13890: idx (reference to hash of counters used in Domain Coordinator interface for
13891:       editing Course Categories).
13892: 
13893: jsarray (reference to array of categories used to create Javascript arrays for
13894:          Domain Coordinator interface for editing Course Categories).
13895: 
13896: subcats (reference to hash of arrays containing all subcategories within each 
13897:          category, -recursive)
13898: 
13899: Returns: nothing
13900: 
13901: Side effects: populates trails and allitems hash references.
13902: 
13903: =cut
13904: 
13905: sub extract_categories {
13906:     my ($categories,$cats,$trails,$allitems,$idx,$jsarray,$subcats) = @_;
13907:     if (ref($categories) eq 'HASH') {
13908:         &gather_categories($categories,$cats,$idx,$jsarray);
13909:         if (ref($cats->[0]) eq 'ARRAY') {
13910:             for (my $i=0; $i<@{$cats->[0]}; $i++) {
13911:                 my $name = $cats->[0][$i];
13912:                 my $item = &escape($name).'::0';
13913:                 my $trailstr;
13914:                 if ($name eq 'instcode') {
13915:                     $trailstr = &mt('Official courses (with institutional codes)');
13916:                 } elsif ($name eq 'communities') {
13917:                     $trailstr = &mt('Communities');
13918:                 } else {
13919:                     $trailstr = $name;
13920:                 }
13921:                 if ($allitems->{$item} eq '') {
13922:                     push(@{$trails},$trailstr);
13923:                     $allitems->{$item} = scalar(@{$trails})-1;
13924:                 }
13925:                 my @parents = ($name);
13926:                 if (ref($cats->[1]{$name}) eq 'ARRAY') {
13927:                     for (my $j=0; $j<@{$cats->[1]{$name}}; $j++) {
13928:                         my $category = $cats->[1]{$name}[$j];
13929:                         if (ref($subcats) eq 'HASH') {
13930:                             push(@{$subcats->{$item}},&escape($category).':'.&escape($name).':1');
13931:                         }
13932:                         &recurse_categories($cats,2,$category,$trails,$allitems,\@parents,$subcats);
13933:                     }
13934:                 } else {
13935:                     if (ref($subcats) eq 'HASH') {
13936:                         $subcats->{$item} = [];
13937:                     }
13938:                 }
13939:             }
13940:         }
13941:     }
13942:     return;
13943: }
13944: 
13945: =pod
13946: 
13947: =item * &recurse_categories()
13948: 
13949: Recursively used to generate breadcrumb trails for course categories.
13950: 
13951: Inputs:
13952: 
13953: cats (reference to array of arrays/hashes which encapsulates hierarchy of
13954:       categories and subcategories).
13955: 
13956: depth (current depth in hierarchy of categories and sub-categories - 0 indexed).
13957: 
13958: category (current course category, for which breadcrumb trail is being generated).
13959: 
13960: trails (reference to array of breadcrumb trails for each category).
13961: 
13962: allitems (reference to hash - key is category key
13963:          (format: escaped(name):escaped(parent category):depth in hierarchy).
13964: 
13965: parents (array containing containers directories for current category, 
13966:          back to top level). 
13967: 
13968: Returns: nothing
13969: 
13970: Side effects: populates trails and allitems hash references
13971: 
13972: =cut
13973: 
13974: sub recurse_categories {
13975:     my ($cats,$depth,$category,$trails,$allitems,$parents,$subcats) = @_;
13976:     my $shallower = $depth - 1;
13977:     if (ref($cats->[$depth]{$category}) eq 'ARRAY') {
13978:         for (my $k=0; $k<@{$cats->[$depth]{$category}}; $k++) {
13979:             my $name = $cats->[$depth]{$category}[$k];
13980:             my $item = &escape($category).':'.&escape($parents->[-1]).':'.$shallower;
13981:             my $trailstr = join(' -&gt; ',(@{$parents},$category));
13982:             if ($allitems->{$item} eq '') {
13983:                 push(@{$trails},$trailstr);
13984:                 $allitems->{$item} = scalar(@{$trails})-1;
13985:             }
13986:             my $deeper = $depth+1;
13987:             push(@{$parents},$category);
13988:             if (ref($subcats) eq 'HASH') {
13989:                 my $subcat = &escape($name).':'.$category.':'.$depth;
13990:                 for (my $j=@{$parents}; $j>=0; $j--) {
13991:                     my $higher;
13992:                     if ($j > 0) {
13993:                         $higher = &escape($parents->[$j]).':'.
13994:                                   &escape($parents->[$j-1]).':'.$j;
13995:                     } else {
13996:                         $higher = &escape($parents->[$j]).'::'.$j;
13997:                     }
13998:                     push(@{$subcats->{$higher}},$subcat);
13999:                 }
14000:             }
14001:             &recurse_categories($cats,$deeper,$name,$trails,$allitems,$parents,
14002:                                 $subcats);
14003:             pop(@{$parents});
14004:         }
14005:     } else {
14006:         my $item = &escape($category).':'.&escape($parents->[-1]).':'.$shallower;
14007:         my $trailstr = join(' -&gt; ',(@{$parents},$category));
14008:         if ($allitems->{$item} eq '') {
14009:             push(@{$trails},$trailstr);
14010:             $allitems->{$item} = scalar(@{$trails})-1;
14011:         }
14012:     }
14013:     return;
14014: }
14015: 
14016: =pod
14017: 
14018: =item * &assign_categories_table()
14019: 
14020: Create a datatable for display of hierarchical categories in a domain,
14021: with checkboxes to allow a course to be categorized. 
14022: 
14023: Inputs:
14024: 
14025: cathash - reference to hash of categories defined for the domain (from
14026:           configuration.db)
14027: 
14028: currcat - scalar with an & separated list of categories assigned to a course. 
14029: 
14030: type    - scalar contains course type (Course or Community).
14031: 
14032: Returns: $output (markup to be displayed) 
14033: 
14034: =cut
14035: 
14036: sub assign_categories_table {
14037:     my ($cathash,$currcat,$type) = @_;
14038:     my $output;
14039:     if (ref($cathash) eq 'HASH') {
14040:         my (@cats,@trails,%allitems,%idx,@jsarray,@path,$maxdepth);
14041:         &extract_categories($cathash,\@cats,\@trails,\%allitems,\%idx,\@jsarray);
14042:         $maxdepth = scalar(@cats);
14043:         if (@cats > 0) {
14044:             my $itemcount = 0;
14045:             if (ref($cats[0]) eq 'ARRAY') {
14046:                 my @currcategories;
14047:                 if ($currcat ne '') {
14048:                     @currcategories = split('&',$currcat);
14049:                 }
14050:                 my $table;
14051:                 for (my $i=0; $i<@{$cats[0]}; $i++) {
14052:                     my $parent = $cats[0][$i];
14053:                     next if ($parent eq 'instcode');
14054:                     if ($type eq 'Community') {
14055:                         next unless ($parent eq 'communities');
14056:                     } else {
14057:                         next if ($parent eq 'communities');
14058:                     }
14059:                     my $css_class = $itemcount%2?' class="LC_odd_row"':'';
14060:                     my $item = &escape($parent).'::0';
14061:                     my $checked = '';
14062:                     if (@currcategories > 0) {
14063:                         if (grep(/^\Q$item\E$/,@currcategories)) {
14064:                             $checked = ' checked="checked"';
14065:                         }
14066:                     }
14067:                     my $parent_title = $parent;
14068:                     if ($parent eq 'communities') {
14069:                         $parent_title = &mt('Communities');
14070:                     }
14071:                     $table .= '<tr '.$css_class.'><td><span class="LC_nobreak">'.
14072:                               '<input type="checkbox" name="usecategory" value="'.
14073:                               $item.'"'.$checked.' />'.$parent_title.'</span>'.
14074:                               '<input type="hidden" name="catname" value="'.$parent.'" /></td>';
14075:                     my $depth = 1;
14076:                     push(@path,$parent);
14077:                     $table .= &assign_category_rows($itemcount,\@cats,$depth,$parent,\@path,\@currcategories);
14078:                     pop(@path);
14079:                     $table .= '</tr><tr><td colspan="'.$maxdepth.'" class="LC_row_separator"></td></tr>';
14080:                     $itemcount ++;
14081:                 }
14082:                 if ($itemcount) {
14083:                     $output = &Apache::loncommon::start_data_table().
14084:                               $table.
14085:                               &Apache::loncommon::end_data_table();
14086:                 }
14087:             }
14088:         }
14089:     }
14090:     return $output;
14091: }
14092: 
14093: =pod
14094: 
14095: =item * &assign_category_rows()
14096: 
14097: Create a datatable row for display of nested categories in a domain,
14098: with checkboxes to allow a course to be categorized,called recursively.
14099: 
14100: Inputs:
14101: 
14102: itemcount - track row number for alternating colors
14103: 
14104: cats - reference to array of arrays/hashes which encapsulates hierarchy of
14105:       categories and subcategories.
14106: 
14107: depth - current depth in hierarchy of categories and sub-categories - 0 indexed.
14108: 
14109: parent - parent of current category item
14110: 
14111: path - Array containing all categories back up through the hierarchy from the
14112:        current category to the top level.
14113: 
14114: currcategories - reference to array of current categories assigned to the course
14115: 
14116: Returns: $output (markup to be displayed).
14117: 
14118: =cut
14119: 
14120: sub assign_category_rows {
14121:     my ($itemcount,$cats,$depth,$parent,$path,$currcategories) = @_;
14122:     my ($text,$name,$item,$chgstr);
14123:     if (ref($cats) eq 'ARRAY') {
14124:         my $maxdepth = scalar(@{$cats});
14125:         if (ref($cats->[$depth]) eq 'HASH') {
14126:             if (ref($cats->[$depth]{$parent}) eq 'ARRAY') {
14127:                 my $numchildren = @{$cats->[$depth]{$parent}};
14128:                 my $css_class = $itemcount%2?' class="LC_odd_row"':'';
14129:                 $text .= '<td><table class="LC_data_table">';
14130:                 for (my $j=0; $j<$numchildren; $j++) {
14131:                     $name = $cats->[$depth]{$parent}[$j];
14132:                     $item = &escape($name).':'.&escape($parent).':'.$depth;
14133:                     my $deeper = $depth+1;
14134:                     my $checked = '';
14135:                     if (ref($currcategories) eq 'ARRAY') {
14136:                         if (@{$currcategories} > 0) {
14137:                             if (grep(/^\Q$item\E$/,@{$currcategories})) {
14138:                                 $checked = ' checked="checked"';
14139:                             }
14140:                         }
14141:                     }
14142:                     $text .= '<tr><td><span class="LC_nobreak"><label>'.
14143:                              '<input type="checkbox" name="usecategory" value="'.
14144:                              $item.'"'.$checked.' />'.$name.'</label></span>'.
14145:                              '<input type="hidden" name="catname" value="'.$name.'" />'.
14146:                              '</td><td>';
14147:                     if (ref($path) eq 'ARRAY') {
14148:                         push(@{$path},$name);
14149:                         $text .= &assign_category_rows($itemcount,$cats,$deeper,$name,$path,$currcategories);
14150:                         pop(@{$path});
14151:                     }
14152:                     $text .= '</td></tr>';
14153:                 }
14154:                 $text .= '</table></td>';
14155:             }
14156:         }
14157:     }
14158:     return $text;
14159: }
14160: 
14161: =pod
14162: 
14163: =back
14164: 
14165: =cut
14166: 
14167: ############################################################
14168: ############################################################
14169: 
14170: 
14171: sub commit_customrole {
14172:     my ($udom,$uname,$url,$three,$four,$five,$start,$end,$context) = @_;
14173:     my $output = &mt('Assigning custom role').' "'.$five.'" by '.$four.':'.$three.' in '.$url.
14174:                          ($start?', '.&mt('starting').' '.localtime($start):'').
14175:                          ($end?', ending '.localtime($end):'').': <b>'.
14176:               &Apache::lonnet::assigncustomrole(
14177:                  $udom,$uname,$url,$three,$four,$five,$end,$start,undef,undef,$context).
14178:                  '</b><br />';
14179:     return $output;
14180: }
14181: 
14182: sub commit_standardrole {
14183:     my ($udom,$uname,$url,$three,$start,$end,$one,$two,$sec,$context,$credits) = @_;
14184:     my ($output,$logmsg,$linefeed);
14185:     if ($context eq 'auto') {
14186:         $linefeed = "\n";
14187:     } else {
14188:         $linefeed = "<br />\n";
14189:     }  
14190:     if ($three eq 'st') {
14191:         my $result = &commit_studentrole(\$logmsg,$udom,$uname,$url,$three,$start,$end,
14192:                                          $one,$two,$sec,$context,$credits);
14193:         if (($result =~ /^error/) || ($result eq 'not_in_class') || 
14194:             ($result eq 'unknown_course') || ($result eq 'refused')) {
14195:             $output = $logmsg.' '.&mt('Error: ').$result."\n"; 
14196:         } else {
14197:             $output = $logmsg.$linefeed.&mt('Assigning').' '.$three.' in '.$url.
14198:                ($start?', '.&mt('starting').' '.localtime($start):'').
14199:                ($end?', '.&mt('ending').' '.localtime($end):'').': ';
14200:             if ($context eq 'auto') {
14201:                 $output .= $result.$linefeed.&mt('Add to classlist').': ok';
14202:             } else {
14203:                $output .= '<b>'.$result.'</b>'.$linefeed.
14204:                &mt('Add to classlist').': <b>ok</b>';
14205:             }
14206:             $output .= $linefeed;
14207:         }
14208:     } else {
14209:         $output = &mt('Assigning').' '.$three.' in '.$url.
14210:                ($start?', '.&mt('starting').' '.localtime($start):'').
14211:                ($end?', '.&mt('ending').' '.localtime($end):'').': ';
14212:         my $result = &Apache::lonnet::assignrole($udom,$uname,$url,$three,$end,$start,'','',$context);
14213:         if ($context eq 'auto') {
14214:             $output .= $result.$linefeed;
14215:         } else {
14216:             $output .= '<b>'.$result.'</b>'.$linefeed;
14217:         }
14218:     }
14219:     return $output;
14220: }
14221: 
14222: sub commit_studentrole {
14223:     my ($logmsg,$udom,$uname,$url,$three,$start,$end,$one,$two,$sec,$context,
14224:         $credits) = @_;
14225:     my ($result,$linefeed,$oldsecurl,$newsecurl);
14226:     if ($context eq 'auto') {
14227:         $linefeed = "\n";
14228:     } else {
14229:         $linefeed = '<br />'."\n";
14230:     }
14231:     if (defined($one) && defined($two)) {
14232:         my $cid=$one.'_'.$two;
14233:         my $oldsec=&Apache::lonnet::getsection($udom,$uname,$cid);
14234:         my $secchange = 0;
14235:         my $expire_role_result;
14236:         my $modify_section_result;
14237:         if ($oldsec ne '-1') { 
14238:             if ($oldsec ne $sec) {
14239:                 $secchange = 1;
14240:                 my $now = time;
14241:                 my $uurl='/'.$cid;
14242:                 $uurl=~s/\_/\//g;
14243:                 if ($oldsec) {
14244:                     $uurl.='/'.$oldsec;
14245:                 }
14246:                 $oldsecurl = $uurl;
14247:                 $expire_role_result = 
14248:                     &Apache::lonnet::assignrole($udom,$uname,$uurl,'st',$now,'','',$context);
14249:                 if ($env{'request.course.sec'} ne '') { 
14250:                     if ($expire_role_result eq 'refused') {
14251:                         my @roles = ('st');
14252:                         my @statuses = ('previous');
14253:                         my @roledoms = ($one);
14254:                         my $withsec = 1;
14255:                         my %roleshash = 
14256:                             &Apache::lonnet::get_my_roles($uname,$udom,'userroles',
14257:                                               \@statuses,\@roles,\@roledoms,$withsec);
14258:                         if (defined ($roleshash{$two.':'.$one.':st:'.$oldsec})) {
14259:                             my ($oldstart,$oldend) = 
14260:                                 split(':',$roleshash{$two.':'.$one.':st:'.$oldsec});
14261:                             if ($oldend > 0 && $oldend <= $now) {
14262:                                 $expire_role_result = 'ok';
14263:                             }
14264:                         }
14265:                     }
14266:                 }
14267:                 $result = $expire_role_result;
14268:             }
14269:         }
14270:         if (($expire_role_result eq 'ok') || ($secchange == 0)) {
14271:             $modify_section_result = 
14272:                 &Apache::lonnet::modify_student_enrollment($udom,$uname,undef,undef,
14273:                                                            undef,undef,undef,$sec,
14274:                                                            $end,$start,'','',$cid,
14275:                                                            '',$context,$credits);
14276:             if ($modify_section_result =~ /^ok/) {
14277:                 if ($secchange == 1) {
14278:                     if ($sec eq '') {
14279:                         $$logmsg .= &mt('Section for [_1] switched from (possibly expired) old section: [_2] to student role without a section.',$uname,$oldsec).$linefeed;
14280:                     } else {
14281:                         $$logmsg .= &mt('Section for [_1] switched from (possibly expired) old section: [_2] to new section: [_3].',$uname,$oldsec,$sec).$linefeed;
14282:                     }
14283:                 } elsif ($oldsec eq '-1') {
14284:                     if ($sec eq '') {
14285:                         $$logmsg .= &mt('New student role without a section for [_1] in course [_2].',$uname,$cid).$linefeed;
14286:                     } else {
14287:                         $$logmsg .= &mt('New student role for [_1] in section [_2] in course [_3].',$uname,$sec,$cid).$linefeed;
14288:                     }
14289:                 } else {
14290:                     if ($sec eq '') {
14291:                         $$logmsg .= &mt('Student [_1] assigned to course [_2] without a section.',$uname,$cid).$linefeed;
14292:                     } else {
14293:                         $$logmsg .= &mt('Student [_1] assigned to section [_2] in course [_3].',$uname,$sec,$cid).$linefeed;
14294:                     }
14295:                 }
14296:             } else {
14297:                 if ($secchange) { 
14298:                     $$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;
14299:                 } else {
14300:                     $$logmsg .= &mt('Error when attempting to modify role for [_1] for section: "[_2]" in course [_3] -error:',$uname,$sec,$cid).' '.$modify_section_result.$linefeed;
14301:                 }
14302:             }
14303:             $result = $modify_section_result;
14304:         } elsif ($secchange == 1) {
14305:             if ($oldsec eq '') {
14306:                 $$logmsg .= &mt('Error when attempting to expire existing role without a section for [_1] in course [_2] -error: ',$uname,$cid).' '.$expire_role_result.$linefeed;
14307:             } else {
14308:                 $$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;
14309:             }
14310:             if ($expire_role_result eq 'refused') {
14311:                 my $newsecurl = '/'.$cid;
14312:                 $newsecurl =~ s/\_/\//g;
14313:                 if ($sec ne '') {
14314:                     $newsecurl.='/'.$sec;
14315:                 }
14316:                 if (&Apache::lonnet::allowed('cst',$newsecurl) && !(&Apache::lonnet::allowed('cst',$oldsecurl))) {
14317:                     if ($sec eq '') {
14318:                         $$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;
14319:                     } else {
14320:                         $$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;
14321:                     }
14322:                 }
14323:             }
14324:         }
14325:     } else {
14326:         $$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;
14327:         $result = "error: incomplete course id\n";
14328:     }
14329:     return $result;
14330: }
14331: 
14332: sub show_role_extent {
14333:     my ($scope,$context,$role) = @_;
14334:     $scope =~ s{^/}{};
14335:     my @courseroles = &Apache::lonuserutils::roles_by_context('course',1);
14336:     push(@courseroles,'co');
14337:     my @authorroles = &Apache::lonuserutils::roles_by_context('author');
14338:     if (($context eq 'course') || (grep(/^\Q$role\E/,@courseroles))) {
14339:         $scope =~ s{/}{_};
14340:         return '<span class="LC_cusr_emph">'.$env{'course.'.$scope.'.description'}.'</span>';
14341:     } elsif (($context eq 'author') || (grep(/^\Q$role\E/,@authorroles))) {
14342:         my ($audom,$auname) = split(/\//,$scope);
14343:         return &mt('[_1] Author Space','<span class="LC_cusr_emph">'.
14344:                    &Apache::loncommon::plainname($auname,$audom).'</span>');
14345:     } else {
14346:         $scope =~ s{/$}{};
14347:         return &mt('Domain: [_1]','<span class="LC_cusr_emph">'.
14348:                    &Apache::lonnet::domain($scope,'description').'</span>');
14349:     }
14350: }
14351: 
14352: ############################################################
14353: ############################################################
14354: 
14355: sub check_clone {
14356:     my ($args,$linefeed) = @_;
14357:     my $cloneid='/'.$args->{'clonedomain'}.'/'.$args->{'clonecourse'};
14358:     my ($clonecrsudom,$clonecrsunum)= &LONCAPA::split_courseid($cloneid);
14359:     my $clonehome=&Apache::lonnet::homeserver($clonecrsunum,$clonecrsudom);
14360:     my $clonemsg;
14361:     my $can_clone = 0;
14362:     my $lctype = lc($args->{'crstype'});
14363:     if ($lctype ne 'community') {
14364:         $lctype = 'course';
14365:     }
14366:     if ($clonehome eq 'no_host') {
14367:         if ($args->{'crstype'} eq 'Community') {
14368:             $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'});
14369:         } else {
14370:             $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'});
14371:         }     
14372:     } else {
14373: 	my %clonedesc = &Apache::lonnet::coursedescription($cloneid,{'one_time' => 1});
14374:         if ($args->{'crstype'} eq 'Community') {
14375:             if ($clonedesc{'type'} ne 'Community') {
14376:                  $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'});
14377:                 return ($can_clone, $clonemsg, $cloneid, $clonehome);
14378:             }
14379:         }
14380: 	if (($env{'request.role.domain'} eq $args->{'clonedomain'}) && 
14381:             (&Apache::lonnet::allowed('ccc',$env{'request.role.domain'}))) {
14382: 	    $can_clone = 1;
14383: 	} else {
14384: 	    my %clonehash = &Apache::lonnet::get('environment',['cloners'],
14385: 						 $args->{'clonedomain'},$args->{'clonecourse'});
14386: 	    my @cloners = split(/,/,$clonehash{'cloners'});
14387:             if (grep(/^\*$/,@cloners)) {
14388:                 $can_clone = 1;
14389:             } elsif (grep(/^\*\:\Q$args->{'ccdomain'}\E$/,@cloners)) {
14390:                 $can_clone = 1;
14391:             } else {
14392:                 my $ccrole = 'cc';
14393:                 if ($args->{'crstype'} eq 'Community') {
14394:                     $ccrole = 'co';
14395:                 }
14396: 	        my %roleshash =
14397: 		    &Apache::lonnet::get_my_roles($args->{'ccuname'},
14398: 					 $args->{'ccdomain'},
14399:                                          'userroles',['active'],[$ccrole],
14400: 					 [$args->{'clonedomain'}]);
14401: 	        if (($roleshash{$args->{'clonecourse'}.':'.$args->{'clonedomain'}.':'.$ccrole}) || (grep(/^\Q$args->{'ccuname'}\E:\Q$args->{'ccdomain'}\E$/,@cloners))) {
14402:                     $can_clone = 1;
14403:                 } elsif (&Apache::lonnet::is_course_owner($args->{'clonedomain'},$args->{'clonecourse'},$args->{'ccuname'},$args->{'ccdomain'})) {
14404:                     $can_clone = 1;
14405:                 } else {
14406:                     if ($args->{'crstype'} eq 'Community') {
14407:                         $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'});
14408:                     } else {
14409:                         $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'});
14410:                     }
14411: 	        }
14412: 	    }
14413:         }
14414:     }
14415:     return ($can_clone, $clonemsg, $cloneid, $clonehome);
14416: }
14417: 
14418: sub construct_course {
14419:     my ($args,$logmsg,$courseid,$crsudom,$crsunum,$udom,$uname,$context,$cnum,$category,$coderef) = @_;
14420:     my $outcome;
14421:     my $linefeed =  '<br />'."\n";
14422:     if ($context eq 'auto') {
14423:         $linefeed = "\n";
14424:     }
14425: 
14426: #
14427: # Are we cloning?
14428: #
14429:     my ($can_clone, $clonemsg, $cloneid, $clonehome);
14430:     if (($args->{'clonecourse'}) && ($args->{'clonedomain'})) {
14431: 	($can_clone, $clonemsg, $cloneid, $clonehome) = &check_clone($args,$linefeed);
14432: 	if ($context ne 'auto') {
14433:             if ($clonemsg ne '') {
14434: 	        $clonemsg = '<span class="LC_error">'.$clonemsg.'</span>';
14435:             }
14436: 	}
14437: 	$outcome .= $clonemsg.$linefeed;
14438: 
14439:         if (!$can_clone) {
14440: 	    return (0,$outcome);
14441: 	}
14442:     }
14443: 
14444: #
14445: # Open course
14446: #
14447:     my $crstype = lc($args->{'crstype'});
14448:     my %cenv=();
14449:     $$courseid=&Apache::lonnet::createcourse($args->{'course_domain'},
14450:                                              $args->{'cdescr'},
14451:                                              $args->{'curl'},
14452:                                              $args->{'course_home'},
14453:                                              $args->{'nonstandard'},
14454:                                              $args->{'crscode'},
14455:                                              $args->{'ccuname'}.':'.
14456:                                              $args->{'ccdomain'},
14457:                                              $args->{'crstype'},
14458:                                              $cnum,$context,$category);
14459: 
14460:     # Note: The testing routines depend on this being output; see 
14461:     # Utils::Course. This needs to at least be output as a comment
14462:     # if anyone ever decides to not show this, and Utils::Course::new
14463:     # will need to be suitably modified.
14464:     $outcome .= &mt('New LON-CAPA [_1] ID: [_2]',$crstype,$$courseid).$linefeed;
14465:     if ($$courseid =~ /^error:/) {
14466:         return (0,$outcome);
14467:     }
14468: 
14469: #
14470: # Check if created correctly
14471: #
14472:     ($$crsudom,$$crsunum)= &LONCAPA::split_courseid($$courseid);
14473:     my $crsuhome=&Apache::lonnet::homeserver($$crsunum,$$crsudom);
14474:     if ($crsuhome eq 'no_host') {
14475:         $outcome .= &mt('Course creation failed, unrecognized course home server.').$linefeed;
14476:         return (0,$outcome);
14477:     }
14478:     $outcome .= &mt('Created on').': '.$crsuhome.$linefeed;
14479: 
14480: #
14481: # Do the cloning
14482: #   
14483:     if ($can_clone && $cloneid) {
14484: 	$clonemsg = &mt('Cloning [_1] from [_2]',$crstype,$clonehome);
14485: 	if ($context ne 'auto') {
14486: 	    $clonemsg = '<span class="LC_success">'.$clonemsg.'</span>';
14487: 	}
14488: 	$outcome .= $clonemsg.$linefeed;
14489: 	my %oldcenv=&Apache::lonnet::dump('environment',$$crsudom,$$crsunum);
14490: # Copy all files
14491: 	&Apache::lonclonecourse::copycoursefiles($cloneid,$$courseid,$args->{'datemode'},$args->{'dateshift'});
14492: # Restore URL
14493: 	$cenv{'url'}=$oldcenv{'url'};
14494: # Restore title
14495: 	$cenv{'description'}=$oldcenv{'description'};
14496: # Restore creation date, creator and creation context.
14497:         $cenv{'internal.created'}=$oldcenv{'internal.created'};
14498:         $cenv{'internal.creator'}=$oldcenv{'internal.creator'};
14499:         $cenv{'internal.creationcontext'}=$oldcenv{'internal.creationcontext'};
14500: # Mark as cloned
14501: 	$cenv{'clonedfrom'}=$cloneid;
14502: # Need to clone grading mode
14503:         my %newenv=&Apache::lonnet::get('environment',['grading'],$$crsudom,$$crsunum);
14504:         $cenv{'grading'}=$newenv{'grading'};
14505: # Do not clone these environment entries
14506:         &Apache::lonnet::del('environment',
14507:                   ['default_enrollment_start_date',
14508:                    'default_enrollment_end_date',
14509:                    'question.email',
14510:                    'policy.email',
14511:                    'comment.email',
14512:                    'pch.users.denied',
14513:                    'plc.users.denied',
14514:                    'hidefromcat',
14515:                    'checkforpriv',
14516:                    'categories',
14517:                    'internal.uniquecode'],
14518:                    $$crsudom,$$crsunum);
14519:         if ($args->{'textbook'}) {
14520:             $cenv{'internal.textbook'} = $args->{'textbook'};
14521:         }
14522:     }
14523: 
14524: #
14525: # Set environment (will override cloned, if existing)
14526: #
14527:     my @sections = ();
14528:     my @xlists = ();
14529:     if ($args->{'crstype'}) {
14530:         $cenv{'type'}=$args->{'crstype'};
14531:     }
14532:     if ($args->{'crsid'}) {
14533:         $cenv{'courseid'}=$args->{'crsid'};
14534:     }
14535:     if ($args->{'crscode'}) {
14536:         $cenv{'internal.coursecode'}=$args->{'crscode'};
14537:     }
14538:     if ($args->{'crsquota'} ne '') {
14539:         $cenv{'internal.coursequota'}=$args->{'crsquota'};
14540:     } else {
14541:         $cenv{'internal.coursequota'}=$args->{'crsquota'} = 20;
14542:     }
14543:     if ($args->{'ccuname'}) {
14544:         $cenv{'internal.courseowner'} = $args->{'ccuname'}.
14545:                                         ':'.$args->{'ccdomain'};
14546:     } else {
14547:         $cenv{'internal.courseowner'} = $args->{'curruser'};
14548:     }
14549:     if ($args->{'defaultcredits'}) {
14550:         $cenv{'internal.defaultcredits'} = $args->{'defaultcredits'};
14551:     }
14552:     my @badclasses = (); # Used to accumulate sections/crosslistings that did not pass classlist access check for course owner.
14553:     if ($args->{'crssections'}) {
14554:         $cenv{'internal.sectionnums'} = '';
14555:         if ($args->{'crssections'} =~ m/,/) {
14556:             @sections = split/,/,$args->{'crssections'};
14557:         } else {
14558:             $sections[0] = $args->{'crssections'};
14559:         }
14560:         if (@sections > 0) {
14561:             foreach my $item (@sections) {
14562:                 my ($sec,$gp) = split/:/,$item;
14563:                 my $class = $args->{'crscode'}.$sec;
14564:                 my $addcheck = &Apache::lonnet::auto_new_course($$crsunum,$$crsudom,$class,$cenv{'internal.courseowner'});
14565:                 $cenv{'internal.sectionnums'} .= $item.',';
14566:                 unless ($addcheck eq 'ok') {
14567:                     push @badclasses, $class;
14568:                 }
14569:             }
14570:             $cenv{'internal.sectionnums'} =~ s/,$//;
14571:         }
14572:     }
14573: # do not hide course coordinator from staff listing, 
14574: # even if privileged
14575:     $cenv{'nothideprivileged'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
14576: # add course coordinator's domain to domains to check for privileged users
14577: # if different to course domain
14578:     if ($$crsudom ne $args->{'ccdomain'}) {
14579:         $cenv{'checkforpriv'} = $args->{'ccdomain'};
14580:     }
14581: # add crosslistings
14582:     if ($args->{'crsxlist'}) {
14583:         $cenv{'internal.crosslistings'}='';
14584:         if ($args->{'crsxlist'} =~ m/,/) {
14585:             @xlists = split/,/,$args->{'crsxlist'};
14586:         } else {
14587:             $xlists[0] = $args->{'crsxlist'};
14588:         }
14589:         if (@xlists > 0) {
14590:             foreach my $item (@xlists) {
14591:                 my ($xl,$gp) = split/:/,$item;
14592:                 my $addcheck =  &Apache::lonnet::auto_new_course($$crsunum,$$crsudom,$xl,$cenv{'internal.courseowner'});
14593:                 $cenv{'internal.crosslistings'} .= $item.',';
14594:                 unless ($addcheck eq 'ok') {
14595:                     push @badclasses, $xl;
14596:                 }
14597:             }
14598:             $cenv{'internal.crosslistings'} =~ s/,$//;
14599:         }
14600:     }
14601:     if ($args->{'autoadds'}) {
14602:         $cenv{'internal.autoadds'}=$args->{'autoadds'};
14603:     }
14604:     if ($args->{'autodrops'}) {
14605:         $cenv{'internal.autodrops'}=$args->{'autodrops'};
14606:     }
14607: # check for notification of enrollment changes
14608:     my @notified = ();
14609:     if ($args->{'notify_owner'}) {
14610:         if ($args->{'ccuname'} ne '') {
14611:             push(@notified,$args->{'ccuname'}.':'.$args->{'ccdomain'});
14612:         }
14613:     }
14614:     if ($args->{'notify_dc'}) {
14615:         if ($uname ne '') { 
14616:             push(@notified,$uname.':'.$udom);
14617:         }
14618:     }
14619:     if (@notified > 0) {
14620:         my $notifylist;
14621:         if (@notified > 1) {
14622:             $notifylist = join(',',@notified);
14623:         } else {
14624:             $notifylist = $notified[0];
14625:         }
14626:         $cenv{'internal.notifylist'} = $notifylist;
14627:     }
14628:     if (@badclasses > 0) {
14629:         my %lt=&Apache::lonlocal::texthash(
14630:                 'tclb' => 'The courses listed below were included as sections or crosslistings affiliated with your new LON-CAPA course.  However, if automated course roster updates are enabled for this class, these particular sections/crosslistings will not contribute towards enrollment, because the user identified as the course owner for this LON-CAPA course',
14631:                 'dnhr' => 'does not have rights to access enrollment in these classes',
14632:                 'adby' => 'as determined by the policies of your institution on access to official classlists'
14633:         );
14634:         my $badclass_msg = $cenv{'internal.courseowner'}.') - '.$lt{'dnhr'}.
14635:                            ' ('.$lt{'adby'}.')';
14636:         if ($context eq 'auto') {
14637:             $outcome .= $badclass_msg.$linefeed;
14638:             $outcome .= '<div class="LC_warning">'.$badclass_msg.$linefeed.'<ul>'."\n";
14639:             foreach my $item (@badclasses) {
14640:                 if ($context eq 'auto') {
14641:                     $outcome .= " - $item\n";
14642:                 } else {
14643:                     $outcome .= "<li>$item</li>\n";
14644:                 }
14645:             }
14646:             if ($context eq 'auto') {
14647:                 $outcome .= $linefeed;
14648:             } else {
14649:                 $outcome .= "</ul><br /><br /></div>\n";
14650:             }
14651:         } 
14652:     }
14653:     if ($args->{'no_end_date'}) {
14654:         $args->{'endaccess'} = 0;
14655:     }
14656:     $cenv{'internal.autostart'}=$args->{'enrollstart'};
14657:     $cenv{'internal.autoend'}=$args->{'enrollend'};
14658:     $cenv{'default_enrollment_start_date'}=$args->{'startaccess'};
14659:     $cenv{'default_enrollment_end_date'}=$args->{'endaccess'};
14660:     if ($args->{'showphotos'}) {
14661:       $cenv{'internal.showphotos'}=$args->{'showphotos'};
14662:     }
14663:     $cenv{'internal.authtype'} = $args->{'authtype'};
14664:     $cenv{'internal.autharg'} = $args->{'autharg'}; 
14665:     if ( ($cenv{'internal.authtype'} =~ /^krb/) && ($cenv{'internal.autoadds'} == 1)) {
14666:         if (! defined($cenv{'internal.autharg'}) || $cenv{'internal.autharg'}  eq '') {
14667:             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'); 
14668:             if ($context eq 'auto') {
14669:                 $outcome .= $krb_msg;
14670:             } else {
14671:                 $outcome .= '<span class="LC_error">'.$krb_msg.'</span>';
14672:             }
14673:             $outcome .= $linefeed;
14674:         }
14675:     }
14676:     if (($args->{'ccdomain'}) && ($args->{'ccuname'})) {
14677:        if ($args->{'setpolicy'}) {
14678:            $cenv{'policy.email'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
14679:        }
14680:        if ($args->{'setcontent'}) {
14681:            $cenv{'question.email'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
14682:        }
14683:     }
14684:     if ($args->{'reshome'}) {
14685: 	$cenv{'reshome'}=$args->{'reshome'}.'/';
14686: 	$cenv{'reshome'}=~s/\/+$/\//;
14687:     }
14688: #
14689: # course has keyed access
14690: #
14691:     if ($args->{'setkeys'}) {
14692:        $cenv{'keyaccess'}='yes';
14693:     }
14694: # if specified, key authority is not course, but user
14695: # only active if keyaccess is yes
14696:     if ($args->{'keyauth'}) {
14697: 	my ($user,$domain) = split(':',$args->{'keyauth'});
14698: 	$user = &LONCAPA::clean_username($user);
14699: 	$domain = &LONCAPA::clean_username($domain);
14700: 	if ($user ne '' && $domain ne '') {
14701: 	    $cenv{'keyauth'}=$user.':'.$domain;
14702: 	}
14703:     }
14704: 
14705: #
14706: #  generate and store uniquecode (available to course requester), if course should have one.
14707: #
14708:     if ($args->{'uniquecode'}) {
14709:         my ($code,$error) = &make_unique_code($$crsudom,$$crsunum);
14710:         if ($code) {
14711:             $cenv{'internal.uniquecode'} = $code;
14712:             my %crsinfo =
14713:                 &Apache::lonnet::courseiddump($$crsudom,'.',1,'.','.',$$crsunum,undef,undef,'.');
14714:             if (ref($crsinfo{$$crsudom.'_'.$$crsunum}) eq 'HASH') {
14715:                 $crsinfo{$$crsudom.'_'.$$crsunum}{'uniquecode'} = $code;
14716:                 my $putres = &Apache::lonnet::courseidput($$crsudom,\%crsinfo,$crsuhome,'notime');
14717:             } 
14718:             if (ref($coderef)) {
14719:                 $$coderef = $code;
14720:             }
14721:         }
14722:     }
14723: 
14724:     if ($args->{'disresdis'}) {
14725:         $cenv{'pch.roles.denied'}='st';
14726:     }
14727:     if ($args->{'disablechat'}) {
14728:         $cenv{'plc.roles.denied'}='st';
14729:     }
14730: 
14731:     # Record we've not yet viewed the Course Initialization Helper for this 
14732:     # course
14733:     $cenv{'course.helper.not.run'} = 1;
14734:     #
14735:     # Use new Randomseed
14736:     #
14737:     $cenv{'rndseed'}=&Apache::lonnet::latest_rnd_algorithm_id();;
14738:     $cenv{'receiptalg'}=&Apache::lonnet::latest_receipt_algorithm_id();;
14739:     #
14740:     # The encryption code and receipt prefix for this course
14741:     #
14742:     $cenv{'internal.encseed'}=$Apache::lonnet::perlvar{'lonReceipt'}.$$.time.int(rand(9999));
14743:     $cenv{'internal.encpref'}=100+int(9*rand(99));
14744:     #
14745:     # By default, use standard grading
14746:     if (!defined($cenv{'grading'})) { $cenv{'grading'} = 'standard'; }
14747: 
14748:     $outcome .= $linefeed.&mt('Setting environment').': '.                 
14749:           &Apache::lonnet::put('environment',\%cenv,$$crsudom,$$crsunum).$linefeed;
14750: #
14751: # Open all assignments
14752: #
14753:     if ($args->{'openall'}) {
14754:        my $storeunder=$$crsudom.'_'.$$crsunum.'.0.opendate';
14755:        my %storecontent = ($storeunder         => time,
14756:                            $storeunder.'.type' => 'date_start');
14757:        
14758:        $outcome .= &mt('Opening all assignments').': '.&Apache::lonnet::cput
14759:                  ('resourcedata',\%storecontent,$$crsudom,$$crsunum).$linefeed;
14760:    }
14761: #
14762: # Set first page
14763: #
14764:     unless (($args->{'nonstandard'}) || ($args->{'firstres'} eq 'blank')
14765: 	    || ($cloneid)) {
14766: 	use LONCAPA::map;
14767: 	$outcome .= &mt('Setting first resource').': ';
14768: 
14769: 	my $map = '/uploaded/'.$$crsudom.'/'.$$crsunum.'/default.sequence';
14770:         my ($errtext,$fatal)=&LONCAPA::map::mapread($map);
14771: 
14772:         $outcome .= ($fatal?$errtext:'read ok').' - ';
14773:         my $title; my $url;
14774:         if ($args->{'firstres'} eq 'syl') {
14775: 	    $title=&mt('Syllabus');
14776:             $url='/public/'.$$crsudom.'/'.$$crsunum.'/syllabus';
14777:         } else {
14778:             $title=&mt('Table of Contents');
14779:             $url='/adm/navmaps';
14780:         }
14781: 
14782:         $LONCAPA::map::resources[1]=$title.':'.$url.':false:start:res';
14783: 	(my $outtext,$errtext) = &LONCAPA::map::storemap($map,1);
14784: 
14785: 	if ($errtext) { $fatal=2; }
14786:         $outcome .= ($fatal?$errtext:'write ok').$linefeed;
14787:     }
14788: 
14789:     return (1,$outcome);
14790: }
14791: 
14792: sub make_unique_code {
14793:     my ($cdom,$cnum) = @_;
14794:     # get lock on uniquecodes db
14795:     my $lockhash = {
14796:                       $cnum."\0".'uniquecodes' => $env{'user.name'}.
14797:                                                   ':'.$env{'user.domain'},
14798:                    };
14799:     my $tries = 0;
14800:     my $gotlock = &Apache::lonnet::newput_dom('uniquecodes',$lockhash,$cdom);
14801:     my ($code,$error);
14802:   
14803:     while (($gotlock ne 'ok') && ($tries<3)) {
14804:         $tries ++;
14805:         sleep 1;
14806:         $gotlock = &Apache::lonnet::newput_dom('uniquecodes',$lockhash,$cdom);
14807:     }
14808:     if ($gotlock eq 'ok') {
14809:         my %currcodes = &Apache::lonnet::dump_dom('uniquecodes',$cdom);
14810:         my $gotcode;
14811:         my $attempts = 0;
14812:         while ((!$gotcode) && ($attempts < 100)) {
14813:             $code = &generate_code();
14814:             if (!exists($currcodes{$code})) {
14815:                 $gotcode = 1;
14816:                 unless (&Apache::lonnet::newput_dom('uniquecodes',{ $code => $cnum },$cdom) eq 'ok') {
14817:                     $error = 'nostore';
14818:                 }
14819:             }
14820:             $attempts ++;
14821:         }
14822:         my @del_lock = ($cnum."\0".'uniquecodes');
14823:         my $dellockoutcome = &Apache::lonnet::del_dom('uniquecodes',\@del_lock,$cdom);
14824:     } else {
14825:         $error = 'nolock';
14826:     }
14827:     return ($code,$error);
14828: }
14829: 
14830: sub generate_code {
14831:     my $code;
14832:     my @letts = qw(B C D G H J K M N P Q R S T V W X Z);
14833:     for (my $i=0; $i<6; $i++) {
14834:         my $lettnum = int (rand 2);
14835:         my $item = '';
14836:         if ($lettnum) {
14837:             $item = $letts[int( rand(18) )];
14838:         } else {
14839:             $item = 1+int( rand(8) );
14840:         }
14841:         $code .= $item;
14842:     }
14843:     return $code;
14844: }
14845: 
14846: ############################################################
14847: ############################################################
14848: 
14849: #SD
14850: # only Community and Course, or anything else?
14851: sub course_type {
14852:     my ($cid) = @_;
14853:     if (!defined($cid)) {
14854:         $cid = $env{'request.course.id'};
14855:     }
14856:     if (defined($env{'course.'.$cid.'.type'})) {
14857:         return $env{'course.'.$cid.'.type'};
14858:     } else {
14859:         return 'Course';
14860:     }
14861: }
14862: 
14863: sub group_term {
14864:     my $crstype = &course_type();
14865:     my %names = (
14866:                   'Course' => 'group',
14867:                   'Community' => 'group',
14868:                 );
14869:     return $names{$crstype};
14870: }
14871: 
14872: sub course_types {
14873:     my @types = ('official','unofficial','community','textbook');
14874:     my %typename = (
14875:                          official   => 'Official course',
14876:                          unofficial => 'Unofficial course',
14877:                          community  => 'Community',
14878:                          textbook   => 'Textbook course',
14879:                    );
14880:     return (\@types,\%typename);
14881: }
14882: 
14883: sub icon {
14884:     my ($file)=@_;
14885:     my $curfext = lc((split(/\./,$file))[-1]);
14886:     my $iconname=$Apache::lonnet::perlvar{'lonIconsURL'}.'/unknown.gif';
14887:     my $embstyle = &Apache::loncommon::fileembstyle($curfext);
14888:     if (!(!defined($embstyle) || $embstyle eq 'unk' || $embstyle eq 'hdn')) {
14889: 	if (-e  $Apache::lonnet::perlvar{'lonDocRoot'}.'/'.
14890: 	          $Apache::lonnet::perlvar{'lonIconsURL'}.'/'.
14891: 	            $curfext.".gif") {
14892: 	    $iconname=$Apache::lonnet::perlvar{'lonIconsURL'}.'/'.
14893: 		$curfext.".gif";
14894: 	}
14895:     }
14896:     return &lonhttpdurl($iconname);
14897: } 
14898: 
14899: sub lonhttpdurl {
14900: #
14901: # Had been used for "small fry" static images on separate port 8080.
14902: # Modify here if lightweight http functionality desired again.
14903: # Currently eliminated due to increasing firewall issues.
14904: #
14905:     my ($url)=@_;
14906:     return $url;
14907: }
14908: 
14909: sub connection_aborted {
14910:     my ($r)=@_;
14911:     $r->print(" ");$r->rflush();
14912:     my $c = $r->connection;
14913:     return $c->aborted();
14914: }
14915: 
14916: #    Escapes strings that may have embedded 's that will be put into
14917: #    strings as 'strings'.
14918: sub escape_single {
14919:     my ($input) = @_;
14920:     $input =~ s/\\/\\\\/g;	# Escape the \'s..(must be first)>
14921:     $input =~ s/\'/\\\'/g;	# Esacpe the 's....
14922:     return $input;
14923: }
14924: 
14925: #  Same as escape_single, but escape's "'s  This 
14926: #  can be used for  "strings"
14927: sub escape_double {
14928:     my ($input) = @_;
14929:     $input =~ s/\\/\\\\/g;	# Escape the /'s..(must be first)>
14930:     $input =~ s/\"/\\\"/g;	# Esacpe the "s....
14931:     return $input;
14932: }
14933:  
14934: #   Escapes the last element of a full URL.
14935: sub escape_url {
14936:     my ($url)   = @_;
14937:     my @urlslices = split(/\//, $url,-1);
14938:     my $lastitem = &escape(pop(@urlslices));
14939:     return &HTML::Entities::encode(join('/',@urlslices),"'").'/'.$lastitem;
14940: }
14941: 
14942: sub compare_arrays {
14943:     my ($arrayref1,$arrayref2) = @_;
14944:     my (@difference,%count);
14945:     @difference = ();
14946:     %count = ();
14947:     if ((ref($arrayref1) eq 'ARRAY') && (ref($arrayref2) eq 'ARRAY')) {
14948:         foreach my $element (@{$arrayref1}, @{$arrayref2}) { $count{$element}++; }
14949:         foreach my $element (keys(%count)) {
14950:             if ($count{$element} == 1) {
14951:                 push(@difference,$element);
14952:             }
14953:         }
14954:     }
14955:     return @difference;
14956: }
14957: 
14958: # -------------------------------------------------------- Initialize user login
14959: sub init_user_environment {
14960:     my ($r, $username, $domain, $authhost, $form, $args) = @_;
14961:     my $lonids=$Apache::lonnet::perlvar{'lonIDsDir'};
14962: 
14963:     my $public=($username eq 'public' && $domain eq 'public');
14964: 
14965: # See if old ID present, if so, remove
14966: 
14967:     my ($filename,$cookie,$userroles,$firstaccenv,$timerintenv);
14968:     my $now=time;
14969: 
14970:     if ($public) {
14971: 	my $max_public=100;
14972: 	my $oldest;
14973: 	my $oldest_time=0;
14974: 	for(my $next=1;$next<=$max_public;$next++) {
14975: 	    if (-e $lonids."/publicuser_$next.id") {
14976: 		my $mtime=(stat($lonids."/publicuser_$next.id"))[9];
14977: 		if ($mtime<$oldest_time || !$oldest_time) {
14978: 		    $oldest_time=$mtime;
14979: 		    $oldest=$next;
14980: 		}
14981: 	    } else {
14982: 		$cookie="publicuser_$next";
14983: 		last;
14984: 	    }
14985: 	}
14986: 	if (!$cookie) { $cookie="publicuser_$oldest"; }
14987:     } else {
14988: 	# if this isn't a robot, kill any existing non-robot sessions
14989: 	if (!$args->{'robot'}) {
14990: 	    opendir(DIR,$lonids);
14991: 	    while ($filename=readdir(DIR)) {
14992: 		if ($filename=~/^$username\_\d+\_$domain\_$authhost\.id$/) {
14993: 		    unlink($lonids.'/'.$filename);
14994: 		}
14995: 	    }
14996: 	    closedir(DIR);
14997: # If there is a undeleted lockfile for the user's paste buffer remove it.
14998:             my $namespace = 'nohist_courseeditor';
14999:             my $lockingkey = 'paste'."\0".'locked_num';
15000:             my %lockhash = &Apache::lonnet::get($namespace,[$lockingkey],
15001:                                                 $domain,$username);
15002:             if (exists($lockhash{$lockingkey})) {
15003:                 my $delresult = &Apache::lonnet::del($namespace,[$lockingkey],$domain,$username);
15004:                 unless ($delresult eq 'ok') {
15005:                     &Apache::lonnet::logthis("Failed to delete paste buffer locking key in $namespace for ".$username.":".$domain." Result was: $delresult");
15006:                 }
15007:             }
15008: 	}
15009: # Give them a new cookie
15010: 	my $id = ($args->{'robot'} ? 'robot'.$args->{'robot'}
15011: 		                   : $now.$$.int(rand(10000)));
15012: 	$cookie="$username\_$id\_$domain\_$authhost";
15013:     
15014: # Initialize roles
15015: 
15016: 	($userroles,$firstaccenv,$timerintenv) = 
15017:             &Apache::lonnet::rolesinit($domain,$username,$authhost);
15018:     }
15019: # ------------------------------------ Check browser type and MathML capability
15020: 
15021:     my ($httpbrowser,$clientbrowser,$clientversion,$clientmathml,$clientunicode,
15022:         $clientos,$clientmobile,$clientinfo,$clientosversion) = &decode_user_agent($r);
15023: 
15024: # ------------------------------------------------------------- Get environment
15025: 
15026:     my %userenv = &Apache::lonnet::dump('environment',$domain,$username);
15027:     my ($tmp) = keys(%userenv);
15028:     if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
15029:     } else {
15030: 	undef(%userenv);
15031:     }
15032:     if (($userenv{'interface'}) && (!$form->{'interface'})) {
15033: 	$form->{'interface'}=$userenv{'interface'};
15034:     }
15035:     if ($userenv{'texengine'} eq 'ttm') { $clientmathml=1; }
15036: 
15037: # --------------- Do not trust query string to be put directly into environment
15038:     foreach my $option ('interface','localpath','localres') {
15039:         $form->{$option}=~s/[\n\r\=]//gs;
15040:     }
15041: # --------------------------------------------------------- Write first profile
15042: 
15043:     {
15044: 	my %initial_env = 
15045: 	    ("user.name"          => $username,
15046: 	     "user.domain"        => $domain,
15047: 	     "user.home"          => $authhost,
15048: 	     "browser.type"       => $clientbrowser,
15049: 	     "browser.version"    => $clientversion,
15050: 	     "browser.mathml"     => $clientmathml,
15051: 	     "browser.unicode"    => $clientunicode,
15052: 	     "browser.os"         => $clientos,
15053:              "browser.mobile"     => $clientmobile,
15054:              "browser.info"       => $clientinfo,
15055:              "browser.osversion"  => $clientosversion,
15056: 	     "server.domain"      => $Apache::lonnet::perlvar{'lonDefDomain'},
15057: 	     "request.course.fn"  => '',
15058: 	     "request.course.uri" => '',
15059: 	     "request.course.sec" => '',
15060: 	     "request.role"       => 'cm',
15061: 	     "request.role.adv"   => $env{'user.adv'},
15062: 	     "request.host"       => $ENV{'REMOTE_ADDR'},);
15063: 
15064:         if ($form->{'localpath'}) {
15065: 	    $initial_env{"browser.localpath"}  = $form->{'localpath'};
15066: 	    $initial_env{"browser.localres"}   = $form->{'localres'};
15067:         }
15068: 	
15069: 	if ($form->{'interface'}) {
15070: 	    $form->{'interface'}=~s/\W//gs;
15071: 	    $initial_env{"browser.interface"} = $form->{'interface'};
15072: 	    $env{'browser.interface'}=$form->{'interface'};
15073: 	}
15074: 
15075:         if ($form->{'iptoken'}) {
15076:             my $lonhost = $r->dir_config('lonHostID');
15077:             $initial_env{"user.noloadbalance"} = $lonhost;
15078:             $env{'user.noloadbalance'} = $lonhost;
15079:         }
15080: 
15081:         my %is_adv = ( is_adv => $env{'user.adv'} );
15082:         my %domdef;
15083:         unless ($domain eq 'public') {
15084:             %domdef = &Apache::lonnet::get_domain_defaults($domain);
15085:         }
15086: 
15087:         foreach my $tool ('aboutme','blog','webdav','portfolio') {
15088:             $userenv{'availabletools.'.$tool} = 
15089:                 &Apache::lonnet::usertools_access($username,$domain,$tool,'reload',
15090:                                                   undef,\%userenv,\%domdef,\%is_adv);
15091:         }
15092: 
15093:         foreach my $crstype ('official','unofficial','community','textbook') {
15094:             $userenv{'canrequest.'.$crstype} =
15095:                 &Apache::lonnet::usertools_access($username,$domain,$crstype,
15096:                                                   'reload','requestcourses',
15097:                                                   \%userenv,\%domdef,\%is_adv);
15098:         }
15099: 
15100:         $userenv{'canrequest.author'} =
15101:             &Apache::lonnet::usertools_access($username,$domain,'requestauthor',
15102:                                         'reload','requestauthor',
15103:                                         \%userenv,\%domdef,\%is_adv);
15104:         my %reqauthor = &Apache::lonnet::get('requestauthor',['author_status','author'],
15105:                                              $domain,$username);
15106:         my $reqstatus = $reqauthor{'author_status'};
15107:         if ($reqstatus eq 'approval' || $reqstatus eq 'approved') { 
15108:             if (ref($reqauthor{'author'}) eq 'HASH') {
15109:                 $userenv{'requestauthorqueued'} = $reqstatus.':'.
15110:                                                   $reqauthor{'author'}{'timestamp'};
15111:             }
15112:         }
15113: 
15114: 	$env{'user.environment'} = "$lonids/$cookie.id";
15115: 
15116: 	if (tie(my %disk_env,'GDBM_File',"$lonids/$cookie.id",
15117: 		 &GDBM_WRCREAT(),0640)) {
15118: 	    &_add_to_env(\%disk_env,\%initial_env);
15119: 	    &_add_to_env(\%disk_env,\%userenv,'environment.');
15120: 	    &_add_to_env(\%disk_env,$userroles);
15121:             if (ref($firstaccenv) eq 'HASH') {
15122:                 &_add_to_env(\%disk_env,$firstaccenv);
15123:             }
15124:             if (ref($timerintenv) eq 'HASH') {
15125:                 &_add_to_env(\%disk_env,$timerintenv);
15126:             }
15127: 	    if (ref($args->{'extra_env'})) {
15128: 		&_add_to_env(\%disk_env,$args->{'extra_env'});
15129: 	    }
15130: 	    untie(%disk_env);
15131: 	} else {
15132: 	    &Apache::lonnet::logthis("<span style=\"color:blue;\">WARNING: ".
15133: 			   'Could not create environment storage in lonauth: '.$!.'</span>');
15134: 	    return 'error: '.$!;
15135: 	}
15136:     }
15137:     $env{'request.role'}='cm';
15138:     $env{'request.role.adv'}=$env{'user.adv'};
15139:     $env{'browser.type'}=$clientbrowser;
15140: 
15141:     return $cookie;
15142: 
15143: }
15144: 
15145: sub _add_to_env {
15146:     my ($idf,$env_data,$prefix) = @_;
15147:     if (ref($env_data) eq 'HASH') {
15148:         while (my ($key,$value) = each(%$env_data)) {
15149: 	    $idf->{$prefix.$key} = $value;
15150: 	    $env{$prefix.$key}   = $value;
15151:         }
15152:     }
15153: }
15154: 
15155: # --- Get the symbolic name of a problem and the url
15156: sub get_symb {
15157:     my ($request,$silent) = @_;
15158:     (my $url=$env{'form.url'}) =~ s-^https?\://($ENV{'SERVER_NAME'}|$ENV{'HTTP_HOST'})--;
15159:     my $symb=($env{'form.symb'} ne '' ? $env{'form.symb'} : (&Apache::lonnet::symbread($url)));
15160:     if ($symb eq '') {
15161:         if (!$silent) {
15162:             if (ref($request)) { 
15163:                 $request->print("Unable to handle ambiguous references:$url:.");
15164:             }
15165:             return ();
15166:         }
15167:     }
15168:     &Apache::lonenc::check_decrypt(\$symb);
15169:     return ($symb);
15170: }
15171: 
15172: # --------------------------------------------------------------Get annotation
15173: 
15174: sub get_annotation {
15175:     my ($symb,$enc) = @_;
15176: 
15177:     my $key = $symb;
15178:     if (!$enc) {
15179:         $key =
15180:             &Apache::lonnet::clutter((&Apache::lonnet::decode_symb($symb))[2]);
15181:     }
15182:     my %annotation=&Apache::lonnet::get('nohist_annotations',[$key]);
15183:     return $annotation{$key};
15184: }
15185: 
15186: sub clean_symb {
15187:     my ($symb,$delete_enc) = @_;
15188: 
15189:     &Apache::lonenc::check_decrypt(\$symb);
15190:     my $enc = $env{'request.enc'};
15191:     if ($delete_enc) {
15192:         delete($env{'request.enc'});
15193:     }
15194: 
15195:     return ($symb,$enc);
15196: }
15197: 
15198: ############################################################
15199: ############################################################
15200: 
15201: =pod
15202: 
15203: =head1 Routines for building display used to search for courses
15204: 
15205: 
15206: =over 4
15207: 
15208: =item * &build_filters()
15209: 
15210: Create markup for a table used to set filters to use when selecting
15211: courses in a domain.  Used by lonpickcourse.pm, lonmodifycourse.pm
15212: and quotacheck.pl
15213: 
15214: 
15215: Inputs:
15216: 
15217: filterlist - anonymous array of fields to include as potential filters 
15218: 
15219: crstype - course type
15220: 
15221: roleelement - fifth arg in selectcourse_link() populates fifth arg in javascript: opencrsbrowser() function, used
15222:               to pop-open a course selector (will contain "extra element"). 
15223: 
15224: multelement - if multiple course selections will be allowed, this will be a hidden form element: name: multiple; value: 1
15225: 
15226: filter - anonymous hash of criteria and their values
15227: 
15228: action - form action
15229: 
15230: numfiltersref - ref to scalar (count of number of elements in institutional codes -- e.g., 4 for year, semester, department, and number)
15231: 
15232: caller - caller context (e.g., set to 'modifycourse' when routine is called from lonmodifycourse.pm)
15233: 
15234: cloneruname - username of owner of new course who wants to clone
15235: 
15236: clonerudom - domain of owner of new course who wants to clone
15237: 
15238: typeelem - text to use for left column in row containing course type (i.e., Course, Community or Course/Community) 
15239: 
15240: codetitlesref - reference to array of titles of components in institutional codes (official courses)
15241: 
15242: codedom - domain
15243: 
15244: formname - value of form element named "form". 
15245: 
15246: fixeddom - domain, if fixed.
15247: 
15248: prevphase - value to assign to form element named "phase" when going back to the previous screen  
15249: 
15250: cnameelement - name of form element in form on opener page which will receive title of selected course 
15251: 
15252: cnumelement - name of form element in form on opener page which will receive courseID  of selected course
15253: 
15254: cdomelement - name of form element in form on opener page which will receive domain of selected course
15255: 
15256: setroles - includes access constraint identifier when setting a roles-based condition for acces to a portfolio file
15257: 
15258: clonetext - hidden form elements containing list of courses cloneable by intended course owner when DC creates a course
15259: 
15260: clonewarning - warning message about missing information for intended course owner when DC creates a course
15261: 
15262: 
15263: Returns: $output - HTML for display of search criteria, and hidden form elements.
15264: 
15265: 
15266: Side Effects: None
15267: 
15268: =cut
15269: 
15270: # ---------------------------------------------- search for courses based on last activity etc.
15271: 
15272: sub build_filters {
15273:     my ($filterlist,$crstype,$roleelement,$multelement,$filter,$action,
15274:         $numtitlesref,$caller,$cloneruname,$clonerudom,$typeelement,
15275:         $codetitlesref,$codedom,$formname,$fixeddom,$prevphase,
15276:         $cnameelement,$cnumelement,$cdomelement,$setroles,
15277:         $clonetext,$clonewarning) = @_;
15278:     my ($list,$jscript);
15279:     my $onchange = 'javascript:updateFilters(this)';
15280:     my ($domainselectform,$sincefilterform,$createdfilterform,
15281:         $ownerdomselectform,$persondomselectform,$instcodeform,
15282:         $typeselectform,$instcodetitle);
15283:     if ($formname eq '') {
15284:         $formname = $caller;
15285:     }
15286:     foreach my $item (@{$filterlist}) {
15287:         unless (($item eq 'descriptfilter') || ($item eq 'instcodefilter') ||
15288:                 ($item eq 'sincefilter') || ($item eq 'createdfilter')) {
15289:             if ($item eq 'domainfilter') {
15290:                 $filter->{$item} = &LONCAPA::clean_domain($filter->{$item});
15291:             } elsif ($item eq 'coursefilter') {
15292:                 $filter->{$item} = &LONCAPA::clean_courseid($filter->{$item});
15293:             } elsif ($item eq 'ownerfilter') {
15294:                 $filter->{$item} = &LONCAPA::clean_username($filter->{$item});
15295:             } elsif ($item eq 'ownerdomfilter') {
15296:                 $filter->{'ownerdomfilter'} =
15297:                     &LONCAPA::clean_domain($filter->{$item});
15298:                 $ownerdomselectform = &select_dom_form($filter->{'ownerdomfilter'},
15299:                                                        'ownerdomfilter',1);
15300:             } elsif ($item eq 'personfilter') {
15301:                 $filter->{$item} = &LONCAPA::clean_username($filter->{$item});
15302:             } elsif ($item eq 'persondomfilter') {
15303:                 $persondomselectform = &select_dom_form($filter->{'persondomfilter'},
15304:                                                         'persondomfilter',1);
15305:             } else {
15306:                 $filter->{$item} =~ s/\W//g;
15307:             }
15308:             if (!$filter->{$item}) {
15309:                 $filter->{$item} = '';
15310:             }
15311:         }
15312:         if ($item eq 'domainfilter') {
15313:             my $allow_blank = 1;
15314:             if ($formname eq 'portform') {
15315:                 $allow_blank=0;
15316:             } elsif ($formname eq 'studentform') {
15317:                 $allow_blank=0;
15318:             }
15319:             if ($fixeddom) {
15320:                 $domainselectform = '<input type="hidden" name="domainfilter"'.
15321:                                     ' value="'.$codedom.'" />'.
15322:                                     &Apache::lonnet::domain($codedom,'description');
15323:             } else {
15324:                 $domainselectform = &select_dom_form($filter->{$item},
15325:                                                      'domainfilter',
15326:                                                       $allow_blank,'',$onchange);
15327:             }
15328:         } else {
15329:             $list->{$item} = &HTML::Entities::encode($filter->{$item},'<>&"');
15330:         }
15331:     }
15332: 
15333:     # last course activity filter and selection
15334:     $sincefilterform = &timebased_select_form('sincefilter',$filter);
15335: 
15336:     # course created filter and selection
15337:     if (exists($filter->{'createdfilter'})) {
15338:         $createdfilterform = &timebased_select_form('createdfilter',$filter);
15339:     }
15340: 
15341:     my %lt = &Apache::lonlocal::texthash(
15342:                 'cac' => "$crstype Activity",
15343:                 'ccr' => "$crstype Created",
15344:                 'cde' => "$crstype Title",
15345:                 'cdo' => "$crstype Domain",
15346:                 'ins' => 'Institutional Code',
15347:                 'inc' => 'Institutional Categorization',
15348:                 'cow' => "$crstype Owner/Co-owner",
15349:                 'cop' => "$crstype Personnel Includes",
15350:                 'cog' => 'Type',
15351:              );
15352: 
15353:     if (($formname eq 'ccrs') || ($formname eq 'requestcrs')) {
15354:         my $typeval = 'Course';
15355:         if ($crstype eq 'Community') {
15356:             $typeval = 'Community';
15357:         }
15358:         $typeselectform = '<input type="hidden" name="type" value="'.$typeval.'" />';
15359:     } else {
15360:         $typeselectform =  '<select name="type" size="1"';
15361:         if ($onchange) {
15362:             $typeselectform .= ' onchange="'.$onchange.'"';
15363:         }
15364:         $typeselectform .= '>'."\n";
15365:         foreach my $posstype ('Course','Community') {
15366:             $typeselectform.='<option value="'.$posstype.'"'.
15367:                 ($posstype eq $crstype ? ' selected="selected" ' : ''). ">".&mt($posstype)."</option>\n";
15368:         }
15369:         $typeselectform.="</select>";
15370:     }
15371: 
15372:     my ($cloneableonlyform,$cloneabletitle);
15373:     if (exists($filter->{'cloneableonly'})) {
15374:         my $cloneableon = '';
15375:         my $cloneableoff = ' checked="checked"';
15376:         if ($filter->{'cloneableonly'}) {
15377:             $cloneableon = $cloneableoff;
15378:             $cloneableoff = '';
15379:         }
15380:         $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>';
15381:         if ($formname eq 'ccrs') {
15382:             $cloneabletitle = &mt('Cloneable for [_1]',$cloneruname.':'.$clonerudom);
15383:         } else {
15384:             $cloneabletitle = &mt('Cloneable by you');
15385:         }
15386:     }
15387:     my $officialjs;
15388:     if ($crstype eq 'Course') {
15389:         if (exists($filter->{'instcodefilter'})) {
15390: #            if (($fixeddom) || ($formname eq 'requestcrs') ||
15391: #                ($formname eq 'modifycourse') || ($formname eq 'filterpicker')) {
15392:             if ($codedom) { 
15393:                 $officialjs = 1;
15394:                 ($instcodeform,$jscript,$$numtitlesref) =
15395:                     &Apache::courseclassifier::instcode_selectors($codedom,'filterpicker',
15396:                                                                   $officialjs,$codetitlesref);
15397:                 if ($jscript) {
15398:                     $jscript = '<script type="text/javascript">'."\n".
15399:                                '// <![CDATA['."\n".
15400:                                $jscript."\n".
15401:                                '// ]]>'."\n".
15402:                                '</script>'."\n";
15403:                 }
15404:             }
15405:             if ($instcodeform eq '') {
15406:                 $instcodeform =
15407:                     '<input type="text" name="instcodefilter" size="10" value="'.
15408:                     $list->{'instcodefilter'}.'" />';
15409:                 $instcodetitle = $lt{'ins'};
15410:             } else {
15411:                 $instcodetitle = $lt{'inc'};
15412:             }
15413:             if ($fixeddom) {
15414:                 $instcodetitle .= '<br />('.$codedom.')';
15415:             }
15416:         }
15417:     }
15418:     my $output = qq|
15419: <form method="post" name="filterpicker" action="$action">
15420: <input type="hidden" name="form" value="$formname" />
15421: |;
15422:     if ($formname eq 'modifycourse') {
15423:         $output .= '<input type="hidden" name="phase" value="courselist" />'."\n".
15424:                    '<input type="hidden" name="prevphase" value="'.
15425:                    $prevphase.'" />'."\n";
15426:     } elsif ($formname eq 'quotacheck') {
15427:         $output .= qq|
15428: <input type="hidden" name="sortby" value="" />
15429: <input type="hidden" name="sortorder" value="" />
15430: |;
15431:     } else {
15432:         my $name_input;
15433:         if ($cnameelement ne '') {
15434:             $name_input = '<input type="hidden" name="cnameelement" value="'.
15435:                           $cnameelement.'" />';
15436:         }
15437:         $output .= qq|
15438: <input type="hidden" name="cnumelement" value="$cnumelement" />
15439: <input type="hidden" name="cdomelement" value="$cdomelement" />
15440: $name_input
15441: $roleelement
15442: $multelement
15443: $typeelement
15444: |;
15445:         if ($formname eq 'portform') {
15446:             $output .= '<input type="hidden" name="setroles" value="'.$setroles.'" />'."\n";
15447:         }
15448:     }
15449:     if ($fixeddom) {
15450:         $output .= '<input type="hidden" name="fixeddom" value="'.$fixeddom.'" />'."\n";
15451:     }
15452:     $output .= "<br />\n".&Apache::lonhtmlcommon::start_pick_box();
15453:     if ($sincefilterform) {
15454:         $output .= &Apache::lonhtmlcommon::row_title($lt{'cac'})
15455:                   .$sincefilterform
15456:                   .&Apache::lonhtmlcommon::row_closure();
15457:     }
15458:     if ($createdfilterform) {
15459:         $output .= &Apache::lonhtmlcommon::row_title($lt{'ccr'})
15460:                   .$createdfilterform
15461:                   .&Apache::lonhtmlcommon::row_closure();
15462:     }
15463:     if ($domainselectform) {
15464:         $output .= &Apache::lonhtmlcommon::row_title($lt{'cdo'})
15465:                   .$domainselectform
15466:                   .&Apache::lonhtmlcommon::row_closure();
15467:     }
15468:     if ($typeselectform) {
15469:         if (($formname eq 'ccrs') || ($formname eq 'requestcrs')) {
15470:             $output .= $typeselectform;
15471:         } else {
15472:             $output .= &Apache::lonhtmlcommon::row_title($lt{'cog'})
15473:                       .$typeselectform
15474:                       .&Apache::lonhtmlcommon::row_closure();
15475:         }
15476:     }
15477:     if ($instcodeform) {
15478:         $output .= &Apache::lonhtmlcommon::row_title($instcodetitle)
15479:                   .$instcodeform
15480:                   .&Apache::lonhtmlcommon::row_closure();
15481:     }
15482:     if (exists($filter->{'ownerfilter'})) {
15483:         $output .= &Apache::lonhtmlcommon::row_title($lt{'cow'}).
15484:                    '<table><tr><td>'.&mt('Username').'<br />'.
15485:                    '<input type="text" name="ownerfilter" size="20" value="'.
15486:                    $list->{'ownerfilter'}.'" /></td><td>'.&mt('Domain').'<br />'.
15487:                    $ownerdomselectform.'</td></tr></table>'.
15488:                    &Apache::lonhtmlcommon::row_closure();
15489:     }
15490:     if (exists($filter->{'personfilter'})) {
15491:         $output .= &Apache::lonhtmlcommon::row_title($lt{'cop'}).
15492:                    '<table><tr><td>'.&mt('Username').'<br />'.
15493:                    '<input type="text" name="personfilter" size="20" value="'.
15494:                    $list->{'personfilter'}.'" /></td><td>'.&mt('Domain').'<br />'.
15495:                    $persondomselectform.'</td></tr></table>'.
15496:                    &Apache::lonhtmlcommon::row_closure();
15497:     }
15498:     if (exists($filter->{'coursefilter'})) {
15499:         $output .= &Apache::lonhtmlcommon::row_title(&mt('LON-CAPA course ID'))
15500:                   .'<input type="text" name="coursefilter" size="25" value="'
15501:                   .$list->{'coursefilter'}.'" />'
15502:                   .&Apache::lonhtmlcommon::row_closure();
15503:     }
15504:     if ($cloneableonlyform) {
15505:         $output .= &Apache::lonhtmlcommon::row_title($cloneabletitle).
15506:                    $cloneableonlyform.&Apache::lonhtmlcommon::row_closure();
15507:     }
15508:     if (exists($filter->{'descriptfilter'})) {
15509:         $output .= &Apache::lonhtmlcommon::row_title($lt{'cde'})
15510:                   .'<input type="text" name="descriptfilter" size="40" value="'
15511:                   .$list->{'descriptfilter'}.'" />'
15512:                   .&Apache::lonhtmlcommon::row_closure(1);
15513:     }
15514:     $output .= &Apache::lonhtmlcommon::end_pick_box().'<p>'.$clonetext."\n".
15515:                '<input type="hidden" name="updater" value="" />'."\n".
15516:                '<input type="submit" name="gosearch" value="'.
15517:                &mt('Search').'" /></p>'."\n".'</form>'."\n".'<hr />'."\n";
15518:     return $jscript.$clonewarning.$output;
15519: }
15520: 
15521: =pod 
15522: 
15523: =item * &timebased_select_form()
15524: 
15525: Create markup for a dropdown list used to select a time-based
15526: filter e.g., Course Activity, Course Created, when searching for courses
15527: or communities
15528: 
15529: Inputs:
15530: 
15531: item - name of form element (sincefilter or createdfilter)
15532: 
15533: filter - anonymous hash of criteria and their values
15534: 
15535: Returns: HTML for a select box contained a blank, then six time selections,
15536:          with value set in incoming form variables currently selected. 
15537: 
15538: Side Effects: None
15539: 
15540: =cut
15541: 
15542: sub timebased_select_form {
15543:     my ($item,$filter) = @_;
15544:     if (ref($filter) eq 'HASH') {
15545:         $filter->{$item} =~ s/[^\d-]//g;
15546:         if (!$filter->{$item}) { $filter->{$item}=-1; }
15547:         return &select_form(
15548:                             $filter->{$item},
15549:                             $item,
15550:                             {      '-1' => '',
15551:                                 '86400' => &mt('today'),
15552:                                '604800' => &mt('last week'),
15553:                               '2592000' => &mt('last month'),
15554:                               '7776000' => &mt('last three months'),
15555:                              '15552000' => &mt('last six months'),
15556:                              '31104000' => &mt('last year'),
15557:                     'select_form_order' =>
15558:                            ['-1','86400','604800','2592000','7776000',
15559:                             '15552000','31104000']});
15560:     }
15561: }
15562: 
15563: =pod
15564: 
15565: =item * &js_changer()
15566: 
15567: Create script tag containing Javascript used to submit course search form
15568: when course type or domain is changed, and also to hide 'Searching ...' on
15569: page load completion for page showing search result.
15570: 
15571: Inputs: None
15572: 
15573: Returns: markup containing updateFilters() and hideSearching() javascript functions. 
15574: 
15575: Side Effects: None
15576: 
15577: =cut
15578: 
15579: sub js_changer {
15580:     return <<ENDJS;
15581: <script type="text/javascript">
15582: // <![CDATA[
15583: function updateFilters(caller) {
15584:     if (typeof(caller) != "undefined") {
15585:         document.filterpicker.updater.value = caller.name;
15586:     }
15587:     document.filterpicker.submit();
15588: }
15589: 
15590: function hideSearching() {
15591:     if (document.getElementById('searching')) {
15592:         document.getElementById('searching').style.display = 'none';
15593:     }
15594:     return;
15595: }
15596: 
15597: // ]]>
15598: </script>
15599: 
15600: ENDJS
15601: }
15602: 
15603: =pod
15604: 
15605: =item * &search_courses()
15606: 
15607: Process selected filters form course search form and pass to lonnet::courseiddump
15608: to retrieve a hash for which keys are courseIDs which match the selected filters.
15609: 
15610: Inputs:
15611: 
15612: dom - domain being searched 
15613: 
15614: type - course type ('Course' or 'Community' or '.' if any).
15615: 
15616: filter - anonymous hash of criteria and their values
15617: 
15618: numtitles - for institutional codes - number of categories
15619: 
15620: cloneruname - optional username of new course owner
15621: 
15622: clonerudom - optional domain of new course owner
15623: 
15624: domcloner - Optional "domcloner" flag; has value=1 if user has ccc priv in domain being filtered by, 
15625:             (used when DC is using course creation form)
15626: 
15627: codetitles - reference to array of titles of components in institutional codes (official courses).
15628: 
15629: 
15630: Returns: %courses - hash of courses satisfying search criteria, keys = course IDs, values are corresponding colon-separated escaped description, institutional code, owner and type.
15631: 
15632: 
15633: Side Effects: None
15634: 
15635: =cut
15636: 
15637: 
15638: sub search_courses {
15639:     my ($dom,$type,$filter,$numtitles,$cloneruname,$clonerudom,$domcloner,$codetitles) = @_;
15640:     my (%courses,%showcourses,$cloner);
15641:     if (($filter->{'ownerfilter'} ne '') ||
15642:         ($filter->{'ownerdomfilter'} ne '')) {
15643:         $filter->{'combownerfilter'} = $filter->{'ownerfilter'}.':'.
15644:                                        $filter->{'ownerdomfilter'};
15645:     }
15646:     foreach my $item ('descriptfilter','coursefilter','combownerfilter') {
15647:         if (!$filter->{$item}) {
15648:             $filter->{$item}='.';
15649:         }
15650:     }
15651:     my $now = time;
15652:     my $timefilter =
15653:        ($filter->{'sincefilter'}==-1?1:$now-$filter->{'sincefilter'});
15654:     my ($createdbefore,$createdafter);
15655:     if (($filter->{'createdfilter'} ne '') && ($filter->{'createdfilter'} !=-1)) {
15656:         $createdbefore = $now;
15657:         $createdafter = $now-$filter->{'createdfilter'};
15658:     }
15659:     my ($instcodefilter,$regexpok);
15660:     if ($numtitles) {
15661:         if ($env{'form.official'} eq 'on') {
15662:             $instcodefilter =
15663:                 &Apache::courseclassifier::instcode_search_str($dom,$numtitles,$codetitles);
15664:             $regexpok = 1;
15665:         } elsif ($env{'form.official'} eq 'off') {
15666:             $instcodefilter = &Apache::courseclassifier::instcode_search_str($dom,$numtitles,$codetitles);
15667:             unless ($instcodefilter eq '') {
15668:                 $regexpok = -1;
15669:             }
15670:         }
15671:     } else {
15672:         $instcodefilter = $filter->{'instcodefilter'};
15673:     }
15674:     if ($instcodefilter eq '') { $instcodefilter = '.'; }
15675:     if ($type eq '') { $type = '.'; }
15676: 
15677:     if (($clonerudom ne '') && ($cloneruname ne '')) {
15678:         $cloner = $cloneruname.':'.$clonerudom;
15679:     }
15680:     %courses = &Apache::lonnet::courseiddump($dom,
15681:                                              $filter->{'descriptfilter'},
15682:                                              $timefilter,
15683:                                              $instcodefilter,
15684:                                              $filter->{'combownerfilter'},
15685:                                              $filter->{'coursefilter'},
15686:                                              undef,undef,$type,$regexpok,undef,undef,
15687:                                              undef,undef,$cloner,$env{'form.cc_clone'},
15688:                                              $filter->{'cloneableonly'},
15689:                                              $createdbefore,$createdafter,undef,
15690:                                              $domcloner);
15691:     if (($filter->{'personfilter'} ne '') && ($filter->{'persondomfilter'} ne '')) {
15692:         my $ccrole;
15693:         if ($type eq 'Community') {
15694:             $ccrole = 'co';
15695:         } else {
15696:             $ccrole = 'cc';
15697:         }
15698:         my %rolehash = &Apache::lonnet::get_my_roles($filter->{'personfilter'},
15699:                                                      $filter->{'persondomfilter'},
15700:                                                      'userroles',undef,
15701:                                                      [$ccrole,'in','ad','ep','ta','cr'],
15702:                                                      $dom);
15703:         foreach my $role (keys(%rolehash)) {
15704:             my ($cnum,$cdom,$courserole) = split(':',$role);
15705:             my $cid = $cdom.'_'.$cnum;
15706:             if (exists($courses{$cid})) {
15707:                 if (ref($courses{$cid}) eq 'HASH') {
15708:                     if (ref($courses{$cid}{roles}) eq 'ARRAY') {
15709:                         if (!grep(/^\Q$courserole\E$/,@{$courses{$cid}{roles}})) {
15710:                             push (@{$courses{$cid}{roles}},$courserole);
15711:                         }
15712:                     } else {
15713:                         $courses{$cid}{roles} = [$courserole];
15714:                     }
15715:                     $showcourses{$cid} = $courses{$cid};
15716:                 }
15717:             }
15718:         }
15719:         %courses = %showcourses;
15720:     }
15721:     return %courses;
15722: }
15723: 
15724: =pod
15725: 
15726: =back
15727: 
15728: =head1 Routines for version requirements for current course.
15729: 
15730: =over 4
15731: 
15732: =item * &check_release_required()
15733: 
15734: Compares required LON-CAPA version with version on server, and
15735: if required version is newer looks for a server with the required version.
15736: 
15737: Looks first at servers in user's owen domain; if none suitable, looks at
15738: servers in course's domain are permitted to host sessions for user's domain.
15739: 
15740: Inputs:
15741: 
15742: $loncaparev - Version on current server (format: Major.Minor.Subrelease-datestamp)
15743: 
15744: $courseid - Course ID of current course
15745: 
15746: $rolecode - User's current role in course (for switchserver query string).
15747: 
15748: $required - LON-CAPA version needed by course (format: Major.Minor).
15749: 
15750: 
15751: Returns:
15752: 
15753: $switchserver - query string tp append to /adm/switchserver call (if 
15754:                 current server's LON-CAPA version is too old. 
15755: 
15756: $warning - Message is displayed if no suitable server could be found.
15757: 
15758: =cut
15759: 
15760: sub check_release_required {
15761:     my ($loncaparev,$courseid,$rolecode,$required) = @_;
15762:     my ($switchserver,$warning);
15763:     if ($required ne '') {
15764:         my ($reqdmajor,$reqdminor) = ($required =~ /^(\d+)\.(\d+)$/);
15765:         my ($major,$minor) = ($loncaparev =~ /^\'?(\d+)\.(\d+)\.[\w.\-]+\'?$/);
15766:         if ($reqdmajor ne '' && $reqdminor ne '') {
15767:             my $otherserver;
15768:             if (($major eq '' && $minor eq '') ||
15769:                 (($reqdmajor > $major) || (($reqdmajor == $major) && ($reqdminor > $minor)))) {
15770:                 my ($userdomserver) = &Apache::lonnet::choose_server($env{'user.domain'},undef,$required,1);
15771:                 my $switchlcrev =
15772:                     &Apache::lonnet::get_server_loncaparev($env{'user.domain'},
15773:                                                            $userdomserver);
15774:                 my ($swmajor,$swminor) = ($switchlcrev =~ /^\'?(\d+)\.(\d+)\.[\w.\-]+\'?$/);
15775:                 if (($swmajor eq '' && $swminor eq '') || ($reqdmajor > $swmajor) ||
15776:                     (($reqdmajor == $swmajor) && ($reqdminor > $swminor))) {
15777:                     my $cdom = $env{'course.'.$courseid.'.domain'};
15778:                     if ($cdom ne $env{'user.domain'}) {
15779:                         my ($coursedomserver,$coursehostname) = &Apache::lonnet::choose_server($cdom,undef,$required,1);
15780:                         my $serverhomeID = &Apache::lonnet::get_server_homeID($coursehostname);
15781:                         my $serverhomedom = &Apache::lonnet::host_domain($serverhomeID);
15782:                         my %defdomdefaults = &Apache::lonnet::get_domain_defaults($serverhomedom);
15783:                         my %udomdefaults = &Apache::lonnet::get_domain_defaults($env{'user.domain'});
15784:                         my $remoterev = &Apache::lonnet::get_server_loncaparev($serverhomedom,$coursedomserver);
15785:                         my $canhost =
15786:                             &Apache::lonnet::can_host_session($env{'user.domain'},
15787:                                                               $coursedomserver,
15788:                                                               $remoterev,
15789:                                                               $udomdefaults{'remotesessions'},
15790:                                                               $defdomdefaults{'hostedsessions'});
15791: 
15792:                         if ($canhost) {
15793:                             $otherserver = $coursedomserver;
15794:                         } else {
15795:                             $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.");
15796:                         }
15797:                     } else {
15798:                         $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).");
15799:                     }
15800:                 } else {
15801:                     $otherserver = $userdomserver;
15802:                 }
15803:             }
15804:             if ($otherserver ne '') {
15805:                 $switchserver = 'otherserver='.$otherserver.'&amp;role='.$rolecode;
15806:             }
15807:         }
15808:     }
15809:     return ($switchserver,$warning);
15810: }
15811: 
15812: =pod
15813: 
15814: =item * &check_release_result()
15815: 
15816: Inputs:
15817: 
15818: $switchwarning - Warning message if no suitable server found to host session.
15819: 
15820: $switchserver - query string to append to /adm/switchserver containing lonHostID
15821:                 and current role.
15822: 
15823: Returns: HTML to display with information about requirement to switch server.
15824:          Either displaying warning with link to Roles/Courses screen or
15825:          display link to switchserver.
15826: 
15827: =cut
15828: 
15829: sub check_release_result {
15830:     my ($switchwarning,$switchserver) = @_;
15831:     my $output = &start_page('Selected course unavailable on this server').
15832:                  '<p class="LC_warning">';
15833:     if ($switchwarning) {
15834:         $output .= $switchwarning.'<br /><a href="/adm/roles">';
15835:         if (&show_course()) {
15836:             $output .= &mt('Display courses');
15837:         } else {
15838:             $output .= &mt('Display roles');
15839:         }
15840:         $output .= '</a>';
15841:     } elsif ($switchserver) {
15842:         $output .= &mt('This course requires a newer version of LON-CAPA than is installed on this server.').
15843:                    '<br />'.
15844:                    '<a href="/adm/switchserver?'.$switchserver.'">'.
15845:                    &mt('Switch Server').
15846:                    '</a>';
15847:     }
15848:     $output .= '</p>'.&end_page();
15849:     return $output;
15850: }
15851: 
15852: =pod
15853: 
15854: =item * &needs_coursereinit()
15855: 
15856: Determine if course contents stored for user's session needs to be
15857: refreshed, because content has changed since "Big Hash" last tied.
15858: 
15859: Check for change is made if time last checked is more than 10 minutes ago
15860: (by default).
15861: 
15862: Inputs:
15863: 
15864: $loncaparev - Version on current server (format: Major.Minor.Subrelease-datestamp)
15865: 
15866: $interval (optional) - Time which may elapse (in s) between last check for content
15867:                        change in current course. (default: 600 s).  
15868: 
15869: Returns: an array; first element is:
15870: 
15871: =over 4
15872: 
15873: 'switch' - if content updates mean user's session
15874:            needs to be switched to a server running a newer LON-CAPA version
15875:  
15876: 'update' - if course session needs to be refreshed (i.e., Big Hash needs to be reloaded)
15877:            on current server hosting user's session                
15878: 
15879: ''       - if no action required.
15880: 
15881: =back
15882: 
15883: If first item element is 'switch':
15884: 
15885: second item is $switchwarning - Warning message if no suitable server found to host session. 
15886: 
15887: third item is $switchserver - query string to append to /adm/switchserver containing lonHostID
15888:                               and current role. 
15889: 
15890: otherwise: no other elements returned.
15891: 
15892: =back
15893: 
15894: =cut
15895: 
15896: sub needs_coursereinit {
15897:     my ($loncaparev,$interval) = @_;
15898:     return() unless ($env{'request.course.id'} && $env{'request.course.tied'});
15899:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
15900:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
15901:     my $now = time;
15902:     if ($interval eq '') {
15903:         $interval = 600;
15904:     }
15905:     if (($now-$env{'request.course.timechecked'})>$interval) {
15906:         my $lastchange = &Apache::lonnet::get_coursechange($cdom,$cnum);
15907:         &Apache::lonnet::appenv({'request.course.timechecked'=>$now});
15908:         if ($lastchange > $env{'request.course.tied'}) {
15909:             my %curr_reqd_hash = &Apache::lonnet::userenvironment($cdom,$cnum,'internal.releaserequired');
15910:             if ($curr_reqd_hash{'internal.releaserequired'} ne '') {
15911:                 my $required = $env{'course.'.$cdom.'_'.$cnum.'.internal.releaserequired'};
15912:                 if ($curr_reqd_hash{'internal.releaserequired'} ne $required) {
15913:                     &Apache::lonnet::appenv({'course.'.$cdom.'_'.$cnum.'.internal.releaserequired' =>
15914:                                              $curr_reqd_hash{'internal.releaserequired'}});
15915:                     my ($switchserver,$switchwarning) =
15916:                         &check_release_required($loncaparev,$cdom.'_'.$cnum,$env{'request.role'},
15917:                                                 $curr_reqd_hash{'internal.releaserequired'});
15918:                     if ($switchwarning ne '' || $switchserver ne '') {
15919:                         return ('switch',$switchwarning,$switchserver);
15920:                     }
15921:                 }
15922:             }
15923:             return ('update');
15924:         }
15925:     }
15926:     return ();
15927: }
15928: 
15929: sub update_content_constraints {
15930:     my ($cdom,$cnum,$chome,$cid) = @_;
15931:     my %curr_reqd_hash = &Apache::lonnet::userenvironment($cdom,$cnum,'internal.releaserequired');
15932:     my ($reqdmajor,$reqdminor) = split(/\./,$curr_reqd_hash{'internal.releaserequired'});
15933:     my %checkresponsetypes;
15934:     foreach my $key (keys(%Apache::lonnet::needsrelease)) {
15935:         my ($item,$name,$value) = split(/:/,$key);
15936:         if ($item eq 'resourcetag') {
15937:             if ($name eq 'responsetype') {
15938:                 $checkresponsetypes{$value} = $Apache::lonnet::needsrelease{$key}
15939:             }
15940:         }
15941:     }
15942:     my $navmap = Apache::lonnavmaps::navmap->new();
15943:     if (defined($navmap)) {
15944:         my %allresponses;
15945:         foreach my $res ($navmap->retrieveResources(undef,sub { $_[0]->is_problem() },1,0)) {
15946:             my %responses = $res->responseTypes();
15947:             foreach my $key (keys(%responses)) {
15948:                 next unless(exists($checkresponsetypes{$key}));
15949:                 $allresponses{$key} += $responses{$key};
15950:             }
15951:         }
15952:         foreach my $key (keys(%allresponses)) {
15953:             my ($major,$minor) = split(/\./,$checkresponsetypes{$key});
15954:             if (($major > $reqdmajor) || ($major == $reqdmajor && $minor > $reqdminor)) {
15955:                 ($reqdmajor,$reqdminor) = ($major,$minor);
15956:             }
15957:         }
15958:         undef($navmap);
15959:     }
15960:     unless (($reqdmajor eq '') && ($reqdminor eq '')) {
15961:         &Apache::lonnet::update_released_required($reqdmajor.'.'.$reqdminor,$cdom,$cnum,$chome,$cid);
15962:     }
15963:     return;
15964: }
15965: 
15966: sub allmaps_incourse {
15967:     my ($cdom,$cnum,$chome,$cid) = @_;
15968:     if ($cdom eq '' || $cnum eq '' || $chome eq '' || $cid eq '') {
15969:         $cid = $env{'request.course.id'};
15970:         $cdom = $env{'course.'.$cid.'.domain'};
15971:         $cnum = $env{'course.'.$cid.'.num'};
15972:         $chome = $env{'course.'.$cid.'.home'};
15973:     }
15974:     my %allmaps = ();
15975:     my $lastchange =
15976:         &Apache::lonnet::get_coursechange($cdom,$cnum);
15977:     if ($lastchange > $env{'request.course.tied'}) {
15978:         my ($furl,$ferr) = &Apache::lonuserstate::readmap("$cdom/$cnum");
15979:         unless ($ferr) {
15980:             &update_content_constraints($cdom,$cnum,$chome,$cid);
15981:         }
15982:     }
15983:     my $navmap = Apache::lonnavmaps::navmap->new();
15984:     if (defined($navmap)) {
15985:         foreach my $res ($navmap->retrieveResources(undef,sub { $_[0]->is_map() },1,0,1)) {
15986:             $allmaps{$res->src()} = 1;
15987:         }
15988:     }
15989:     return \%allmaps;
15990: }
15991: 
15992: sub parse_supplemental_title {
15993:     my ($title) = @_;
15994: 
15995:     my ($foldertitle,$renametitle);
15996:     if ($title =~ /&amp;&amp;&amp;/) {
15997:         $title = &HTML::Entites::decode($title);
15998:     }
15999:     if ($title =~ m/^(\d+)___&&&___($match_username)___&&&___($match_domain)___&&&___(.*)$/) {
16000:         $renametitle=$4;
16001:         my ($time,$uname,$udom) = ($1,$2,$3);
16002:         $foldertitle=&Apache::lontexconvert::msgtexconverted($4);
16003:         my $name =  &plainname($uname,$udom);
16004:         $name = &HTML::Entities::encode($name,'"<>&\'');
16005:         $renametitle = &HTML::Entities::encode($renametitle,'"<>&\'');
16006:         $title='<i>'.&Apache::lonlocal::locallocaltime($time).'</i> '.
16007:             $name.': <br />'.$foldertitle;
16008:     }
16009:     if (wantarray) {
16010:         return ($title,$foldertitle,$renametitle);
16011:     }
16012:     return $title;
16013: }
16014: 
16015: sub recurse_supplemental {
16016:     my ($cnum,$cdom,$suppmap,$numfiles,$errors) = @_;
16017:     if ($suppmap) {
16018:         my ($errtext,$fatal) = &LONCAPA::map::mapread('/uploaded/'.$cdom.'/'.$cnum.'/'.$suppmap);
16019:         if ($fatal) {
16020:             $errors ++;
16021:         } else {
16022:             if ($#LONCAPA::map::resources > 0) {
16023:                 foreach my $res (@LONCAPA::map::resources) {
16024:                     my ($title,$src,$ext,$type,$status)=split(/\:/,$res);
16025:                     if (($src ne '') && ($status eq 'res')) {
16026:                         if ($src =~ m{^\Q/uploaded/$cdom/$cnum/\E(supplemental_\d+\.sequence)$}) {
16027:                             ($numfiles,$errors) = &recurse_supplemental($cnum,$cdom,$1,$numfiles,$errors);
16028:                         } else {
16029:                             $numfiles ++;
16030:                         }
16031:                     }
16032:                 }
16033:             }
16034:         }
16035:     }
16036:     return ($numfiles,$errors);
16037: }
16038: 
16039: sub symb_to_docspath {
16040:     my ($symb) = @_;
16041:     return unless ($symb);
16042:     my ($mapurl,$id,$resurl) = &Apache::lonnet::decode_symb($symb);
16043:     if ($resurl=~/\.(sequence|page)$/) {
16044:         $mapurl=$resurl;
16045:     } elsif ($resurl eq 'adm/navmaps') {
16046:         $mapurl=$env{'course.'.$env{'request.course.id'}.'.url'};
16047:     }
16048:     my $mapresobj;
16049:     my $navmap = Apache::lonnavmaps::navmap->new();
16050:     if (ref($navmap)) {
16051:         $mapresobj = $navmap->getResourceByUrl($mapurl);
16052:     }
16053:     $mapurl=~s{^.*/([^/]+)\.(\w+)$}{$1};
16054:     my $type=$2;
16055:     my $path;
16056:     if (ref($mapresobj)) {
16057:         my $pcslist = $mapresobj->map_hierarchy();
16058:         if ($pcslist ne '') {
16059:             foreach my $pc (split(/,/,$pcslist)) {
16060:                 next if ($pc <= 1);
16061:                 my $res = $navmap->getByMapPc($pc);
16062:                 if (ref($res)) {
16063:                     my $thisurl = $res->src();
16064:                     $thisurl=~s{^.*/([^/]+)\.\w+$}{$1};
16065:                     my $thistitle = $res->title();
16066:                     $path .= '&'.
16067:                              &Apache::lonhtmlcommon::entity_encode($thisurl).'&'.
16068:                              &escape($thistitle).
16069:                              ':'.$res->randompick().
16070:                              ':'.$res->randomout().
16071:                              ':'.$res->encrypted().
16072:                              ':'.$res->randomorder().
16073:                              ':'.$res->is_page();
16074:                 }
16075:             }
16076:         }
16077:         $path =~ s/^\&//;
16078:         my $maptitle = $mapresobj->title();
16079:         if ($mapurl eq 'default') {
16080:             $maptitle = 'Main Content';
16081:         }
16082:         $path .= (($path ne '')? '&' : '').
16083:                  &Apache::lonhtmlcommon::entity_encode($mapurl).'&'.
16084:                  &escape($maptitle).
16085:                  ':'.$mapresobj->randompick().
16086:                  ':'.$mapresobj->randomout().
16087:                  ':'.$mapresobj->encrypted().
16088:                  ':'.$mapresobj->randomorder().
16089:                  ':'.$mapresobj->is_page();
16090:     } else {
16091:         my $maptitle = &Apache::lonnet::gettitle($mapurl);
16092:         my $ispage = (($type eq 'page')? 1 : '');
16093:         if ($mapurl eq 'default') {
16094:             $maptitle = 'Main Content';
16095:         }
16096:         $path = &Apache::lonhtmlcommon::entity_encode($mapurl).'&'.
16097:                 &escape($maptitle).':::::'.$ispage;
16098:     }
16099:     unless ($mapurl eq 'default') {
16100:         $path = 'default&'.
16101:                 &escape('Main Content').
16102:                 ':::::&'.$path;
16103:     }
16104:     return $path;
16105: }
16106: 
16107: sub captcha_display {
16108:     my ($context,$lonhost) = @_;
16109:     my ($output,$error);
16110:     my ($captcha,$pubkey,$privkey) = &get_captcha_config($context,$lonhost);
16111:     if ($captcha eq 'original') {
16112:         $output = &create_captcha();
16113:         unless ($output) {
16114:             $error = 'captcha';
16115:         }
16116:     } elsif ($captcha eq 'recaptcha') {
16117:         $output = &create_recaptcha($pubkey);
16118:         unless ($output) {
16119:             $error = 'recaptcha';
16120:         }
16121:     }
16122:     return ($output,$error,$captcha);
16123: }
16124: 
16125: sub captcha_response {
16126:     my ($context,$lonhost) = @_;
16127:     my ($captcha_chk,$captcha_error);
16128:     my ($captcha,$pubkey,$privkey) = &get_captcha_config($context,$lonhost);
16129:     if ($captcha eq 'original') {
16130:         ($captcha_chk,$captcha_error) = &check_captcha();
16131:     } elsif ($captcha eq 'recaptcha') {
16132:         $captcha_chk = &check_recaptcha($privkey);
16133:     } else {
16134:         $captcha_chk = 1;
16135:     }
16136:     return ($captcha_chk,$captcha_error);
16137: }
16138: 
16139: sub get_captcha_config {
16140:     my ($context,$lonhost) = @_;
16141:     my ($captcha,$pubkey,$privkey,$hashtocheck);
16142:     my $hostname = &Apache::lonnet::hostname($lonhost);
16143:     my $serverhomeID = &Apache::lonnet::get_server_homeID($hostname);
16144:     my $serverhomedom = &Apache::lonnet::host_domain($serverhomeID);
16145:     if ($context eq 'usercreation') {
16146:         my %domconfig = &Apache::lonnet::get_dom('configuration',[$context],$serverhomedom);
16147:         if (ref($domconfig{$context}) eq 'HASH') {
16148:             $hashtocheck = $domconfig{$context}{'cancreate'};
16149:             if (ref($hashtocheck) eq 'HASH') {
16150:                 if ($hashtocheck->{'captcha'} eq 'recaptcha') {
16151:                     if (ref($hashtocheck->{'recaptchakeys'}) eq 'HASH') {
16152:                         $pubkey = $hashtocheck->{'recaptchakeys'}{'public'};
16153:                         $privkey = $hashtocheck->{'recaptchakeys'}{'private'};
16154:                     }
16155:                     if ($privkey && $pubkey) {
16156:                         $captcha = 'recaptcha';
16157:                     } else {
16158:                         $captcha = 'original';
16159:                     }
16160:                 } elsif ($hashtocheck->{'captcha'} ne 'notused') {
16161:                     $captcha = 'original';
16162:                 }
16163:             }
16164:         } else {
16165:             $captcha = 'captcha';
16166:         }
16167:     } elsif ($context eq 'login') {
16168:         my %domconfhash = &Apache::loncommon::get_domainconf($serverhomedom);
16169:         if ($domconfhash{$serverhomedom.'.login.captcha'} eq 'recaptcha') {
16170:             $pubkey = $domconfhash{$serverhomedom.'.login.recaptchakeys_public'};
16171:             $privkey = $domconfhash{$serverhomedom.'.login.recaptchakeys_private'};
16172:             if ($privkey && $pubkey) {
16173:                 $captcha = 'recaptcha';
16174:             } else {
16175:                 $captcha = 'original';
16176:             }
16177:         } elsif ($domconfhash{$serverhomedom.'.login.captcha'} eq 'original') {
16178:             $captcha = 'original';
16179:         }
16180:     }
16181:     return ($captcha,$pubkey,$privkey);
16182: }
16183: 
16184: sub create_captcha {
16185:     my %captcha_params = &captcha_settings();
16186:     my ($output,$maxtries,$tries) = ('',10,0);
16187:     while ($tries < $maxtries) {
16188:         $tries ++;
16189:         my $captcha = Authen::Captcha->new (
16190:                                            output_folder => $captcha_params{'output_dir'},
16191:                                            data_folder   => $captcha_params{'db_dir'},
16192:                                           );
16193:         my $md5sum = $captcha->generate_code($captcha_params{'numchars'});
16194: 
16195:         if (-e $Apache::lonnet::perlvar{'lonCaptchaDir'}.'/'.$md5sum.'.png') {
16196:             $output = '<input type="hidden" name="crypt" value="'.$md5sum.'" />'."\n".
16197:                       &mt('Type in the letters/numbers shown below').'&nbsp;'.
16198:                       '<input type="text" size="5" name="code" value="" autocomplete="off" />'.
16199:                       '<br />'.
16200:                       '<img src="'.$captcha_params{'www_output_dir'}.'/'.$md5sum.'.png" alt="captcha" />';
16201:             last;
16202:         }
16203:     }
16204:     return $output;
16205: }
16206: 
16207: sub captcha_settings {
16208:     my %captcha_params = (
16209:                            output_dir     => $Apache::lonnet::perlvar{'lonCaptchaDir'},
16210:                            www_output_dir => "/captchaspool",
16211:                            db_dir         => $Apache::lonnet::perlvar{'lonCaptchaDb'},
16212:                            numchars       => '5',
16213:                          );
16214:     return %captcha_params;
16215: }
16216: 
16217: sub check_captcha {
16218:     my ($captcha_chk,$captcha_error);
16219:     my $code = $env{'form.code'};
16220:     my $md5sum = $env{'form.crypt'};
16221:     my %captcha_params = &captcha_settings();
16222:     my $captcha = Authen::Captcha->new(
16223:                       output_folder => $captcha_params{'output_dir'},
16224:                       data_folder   => $captcha_params{'db_dir'},
16225:                   );
16226:     $captcha_chk = $captcha->check_code($code,$md5sum);
16227:     my %captcha_hash = (
16228:                         0       => 'Code not checked (file error)',
16229:                        -1      => 'Failed: code expired',
16230:                        -2      => 'Failed: invalid code (not in database)',
16231:                        -3      => 'Failed: invalid code (code does not match crypt)',
16232:     );
16233:     if ($captcha_chk != 1) {
16234:         $captcha_error = $captcha_hash{$captcha_chk}
16235:     }
16236:     return ($captcha_chk,$captcha_error);
16237: }
16238: 
16239: sub create_recaptcha {
16240:     my ($pubkey) = @_;
16241:     my $use_ssl;
16242:     if ($ENV{'SERVER_PORT'} == 443) {
16243:         $use_ssl = 1;
16244:     }
16245:     my $captcha = Captcha::reCAPTCHA->new;
16246:     return $captcha->get_options_setter({theme => 'white'})."\n".
16247:            $captcha->get_html($pubkey,undef,$use_ssl).
16248:            &mt('If the text is hard to read, [_1] will replace them.',
16249:                '<img src="/res/adm/pages/refresh.gif" alt="reCAPTCHA refresh" />').
16250:            '<br /><br />';
16251: }
16252: 
16253: sub check_recaptcha {
16254:     my ($privkey) = @_;
16255:     my $captcha_chk;
16256:     my $captcha = Captcha::reCAPTCHA->new;
16257:     my $captcha_result =
16258:         $captcha->check_answer(
16259:                                 $privkey,
16260:                                 $ENV{'REMOTE_ADDR'},
16261:                                 $env{'form.recaptcha_challenge_field'},
16262:                                 $env{'form.recaptcha_response_field'},
16263:                               );
16264:     if ($captcha_result->{is_valid}) {
16265:         $captcha_chk = 1;
16266:     }
16267:     return $captcha_chk;
16268: }
16269: 
16270: sub emailusername_info {
16271:     my @fields = ('firstname','lastname','institution','web','location','officialemail');
16272:     my %titles = &Apache::lonlocal::texthash (
16273:                      lastname      => 'Last Name',
16274:                      firstname     => 'First Name',
16275:                      institution   => 'School/college/university',
16276:                      location      => "School's city, state/province, country",
16277:                      web           => "School's web address",
16278:                      officialemail => 'E-mail address at institution (if different)',
16279:                  );
16280:     return (\@fields,\%titles);
16281: }
16282: 
16283: sub cleanup_html {
16284:     my ($incoming) = @_;
16285:     my $outgoing;
16286:     if ($incoming ne '') {
16287:         $outgoing = $incoming;
16288:         $outgoing =~ s/;/&#059;/g;
16289:         $outgoing =~ s/\#/&#035;/g;
16290:         $outgoing =~ s/\&/&#038;/g;
16291:         $outgoing =~ s/</&#060;/g;
16292:         $outgoing =~ s/>/&#062;/g;
16293:         $outgoing =~ s/\(/&#040/g;
16294:         $outgoing =~ s/\)/&#041;/g;
16295:         $outgoing =~ s/"/&#034;/g;
16296:         $outgoing =~ s/'/&#039;/g;
16297:         $outgoing =~ s/\$/&#036;/g;
16298:         $outgoing =~ s{/}{&#047;}g;
16299:         $outgoing =~ s/=/&#061;/g;
16300:         $outgoing =~ s/\\/&#092;/g
16301:     }
16302:     return $outgoing;
16303: }
16304: 
16305: # Checks for critical messages and returns a redirect url if one exists.
16306: # $interval indicates how often to check for messages.
16307: sub critical_redirect {
16308:     my ($interval) = @_;
16309:     if ((time-$env{'user.criticalcheck.time'})>$interval) {
16310:         my @what=&Apache::lonnet::dump('critical', $env{'user.domain'}, 
16311:                                         $env{'user.name'});
16312:         &Apache::lonnet::appenv({'user.criticalcheck.time'=>time});
16313:         my $redirecturl;
16314:         if ($what[0]) {
16315: 	    if (($what[0] ne 'con_lost') && ($what[0]!~/^error\:/)) {
16316: 	        $redirecturl='/adm/email?critical=display';
16317: 	        my $url=&Apache::lonnet::absolute_url().$redirecturl;
16318:                 return (1, $url);
16319:             }
16320:         }
16321:     } 
16322:     return ();
16323: }
16324: 
16325: # Use:
16326: #   my $answer=reply("encrypt:passwd:$udom:$uname:$upass",$tryserver);
16327: #
16328: ##################################################
16329: #          password associated functions         #
16330: ##################################################
16331: sub des_keys {
16332:     # Make a new key for DES encryption.
16333:     # Each key has two parts which are returned separately.
16334:     # Please note:  Each key must be passed through the &hex function
16335:     # before it is output to the web browser.  The hex versions cannot
16336:     # be used to decrypt.
16337:     my @hexstr=('0','1','2','3','4','5','6','7',
16338:                 '8','9','a','b','c','d','e','f');
16339:     my $lkey='';
16340:     for (0..7) {
16341:         $lkey.=$hexstr[rand(15)];
16342:     }
16343:     my $ukey='';
16344:     for (0..7) {
16345:         $ukey.=$hexstr[rand(15)];
16346:     }
16347:     return ($lkey,$ukey);
16348: }
16349: 
16350: sub des_decrypt {
16351:     my ($key,$cyphertext) = @_;
16352:     my $keybin=pack("H16",$key);
16353:     my $cypher;
16354:     if ($Crypt::DES::VERSION>=2.03) {
16355:         $cypher=new Crypt::DES $keybin;
16356:     } else {
16357:         $cypher=new DES $keybin;
16358:     }
16359:     my $plaintext=
16360:         $cypher->decrypt(unpack("a8",pack("H16",substr($cyphertext,0,16))));
16361:     $plaintext.=
16362:         $cypher->decrypt(unpack("a8",pack("H16",substr($cyphertext,16,16))));
16363:     $plaintext=substr($plaintext,1,ord(substr($plaintext,0,1)) );
16364:     return $plaintext;
16365: }
16366: 
16367: 1;
16368: __END__;
16369: 

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