File:  [LON-CAPA] / loncom / interface / loncommon.pm
Revision 1.1075.2.114: download - view: text, annotated - select for diffs
Sun Sep 18 20:56:04 2016 UTC (7 years, 8 months ago) by raeburn
Branches: version_2_11_X
- For 2.11
  - Backport 1.1253

    1: # The LearningOnline Network with CAPA
    2: # a pile of common routines
    3: #
    4: # $Id: loncommon.pm,v 1.1075.2.114 2016/09/18 20:56:04 raeburn Exp $
    5: #
    6: # Copyright Michigan State University Board of Trustees
    7: #
    8: # This file is part of the LearningOnline Network with CAPA (LON-CAPA).
    9: #
   10: # LON-CAPA is free software; you can redistribute it and/or modify
   11: # it under the terms of the GNU General Public License as published by
   12: # the Free Software Foundation; either version 2 of the License, or
   13: # (at your option) any later version.
   14: #
   15: # LON-CAPA is distributed in the hope that it will be useful,
   16: # but WITHOUT ANY WARRANTY; without even the implied warranty of
   17: # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   18: # GNU General Public License for more details.
   19: #
   20: # You should have received a copy of the GNU General Public License
   21: # along with LON-CAPA; if not, write to the Free Software
   22: # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
   23: #
   24: # /home/httpd/html/adm/gpl.txt
   25: #
   26: # http://www.lon-capa.org/
   27: #
   28: 
   29: # Makes a table out of the previous attempts
   30: # Inputs result_from_symbread, user, domain, course_id
   31: # Reads in non-network-related .tab files
   32: 
   33: # POD header:
   34: 
   35: =pod
   36: 
   37: =head1 NAME
   38: 
   39: Apache::loncommon - pile of common routines
   40: 
   41: =head1 SYNOPSIS
   42: 
   43: Common routines for manipulating connections, student answers,
   44:     domains, common Javascript fragments, etc.
   45: 
   46: =head1 OVERVIEW
   47: 
   48: A collection of commonly used subroutines that don't have a natural
   49: home anywhere else. This collection helps remove
   50: redundancy from other modules and increase efficiency of memory usage.
   51: 
   52: =cut 
   53: 
   54: # End of POD header
   55: package Apache::loncommon;
   56: 
   57: use strict;
   58: use Apache::lonnet;
   59: use GDBM_File;
   60: use POSIX qw(strftime mktime);
   61: use Apache::lonmenu();
   62: use Apache::lonenc();
   63: use Apache::lonlocal;
   64: use Apache::lonnet();
   65: use HTML::Entities;
   66: use Apache::lonhtmlcommon();
   67: use Apache::loncoursedata();
   68: use Apache::lontexconvert();
   69: use Apache::lonclonecourse();
   70: use Apache::lonuserutils();
   71: use Apache::lonuserstate();
   72: use Apache::courseclassifier();
   73: use LONCAPA qw(:DEFAULT :match);
   74: use DateTime::TimeZone;
   75: use DateTime::Locale;
   76: use Encode();
   77: use Authen::Captcha;
   78: use Captcha::reCAPTCHA;
   79: use JSON::DWIW;
   80: use LWP::UserAgent;
   81: use Crypt::DES;
   82: use DynaLoader; # for Crypt::DES version
   83: 
   84: # ---------------------------------------------- Designs
   85: use vars qw(%defaultdesign);
   86: 
   87: my $readit;
   88: 
   89: 
   90: ##
   91: ## Global Variables
   92: ##
   93: 
   94: 
   95: # ----------------------------------------------- SSI with retries:
   96: #
   97: 
   98: =pod
   99: 
  100: =head1 Server Side include with retries:
  101: 
  102: =over 4
  103: 
  104: =item * &ssi_with_retries(resource,retries form)
  105: 
  106: Performs an ssi with some number of retries.  Retries continue either
  107: until the result is ok or until the retry count supplied by the
  108: caller is exhausted.  
  109: 
  110: Inputs:
  111: 
  112: =over 4
  113: 
  114: resource   - Identifies the resource to insert.
  115: 
  116: retries    - Count of the number of retries allowed.
  117: 
  118: form       - Hash that identifies the rendering options.
  119: 
  120: =back
  121: 
  122: Returns:
  123: 
  124: =over 4
  125: 
  126: content    - The content of the response.  If retries were exhausted this is empty.
  127: 
  128: response   - The response from the last attempt (which may or may not have been successful.
  129: 
  130: =back
  131: 
  132: =back
  133: 
  134: =cut
  135: 
  136: sub ssi_with_retries {
  137:     my ($resource, $retries, %form) = @_;
  138: 
  139: 
  140:     my $ok = 0;			# True if we got a good response.
  141:     my $content;
  142:     my $response;
  143: 
  144:     # Try to get the ssi done. within the retries count:
  145: 
  146:     do {
  147: 	($content, $response) = &Apache::lonnet::ssi($resource, %form);
  148: 	$ok      = $response->is_success;
  149:         if (!$ok) {
  150:             &Apache::lonnet::logthis("Failed ssi_with_retries on $resource: ".$response->is_success.', '.$response->code.', '.$response->message);
  151:         }
  152: 	$retries--;
  153:     } while (!$ok && ($retries > 0));
  154: 
  155:     if (!$ok) {
  156: 	$content = '';		# On error return an empty content.
  157:     }
  158:     return ($content, $response);
  159: 
  160: }
  161: 
  162: 
  163: 
  164: # ----------------------------------------------- Filetypes/Languages/Copyright
  165: my %language;
  166: my %supported_language;
  167: my %latex_language;		# For choosing hyphenation in <transl..>
  168: my %latex_language_bykey;	# for choosing hyphenation from metadata
  169: my %cprtag;
  170: my %scprtag;
  171: my %fe; my %fd; my %fm;
  172: my %category_extensions;
  173: 
  174: # ---------------------------------------------- Thesaurus variables
  175: #
  176: # %Keywords:
  177: #      A hash used by &keyword to determine if a word is considered a keyword.
  178: # $thesaurus_db_file 
  179: #      Scalar containing the full path to the thesaurus database.
  180: 
  181: my %Keywords;
  182: my $thesaurus_db_file;
  183: 
  184: #
  185: # Initialize values from language.tab, copyright.tab, filetypes.tab,
  186: # thesaurus.tab, and filecategories.tab.
  187: #
  188: BEGIN {
  189:     # Variable initialization
  190:     $thesaurus_db_file = $Apache::lonnet::perlvar{'lonTabDir'}."/thesaurus.db";
  191:     #
  192:     unless ($readit) {
  193: # ------------------------------------------------------------------- languages
  194:     {
  195:         my $langtabfile = $Apache::lonnet::perlvar{'lonTabDir'}.
  196:                                    '/language.tab';
  197:         if ( open(my $fh,"<$langtabfile") ) {
  198:             while (my $line = <$fh>) {
  199:                 next if ($line=~/^\#/);
  200:                 chomp($line);
  201:                 my ($key,$two,$country,$three,$enc,$val,$sup,$latex)=(split(/\t/,$line));
  202:                 $language{$key}=$val.' - '.$enc;
  203:                 if ($sup) {
  204:                     $supported_language{$key}=$sup;
  205:                 }
  206: 		if ($latex) {
  207: 		    $latex_language_bykey{$key} = $latex;
  208: 		    $latex_language{$two} = $latex;
  209: 		}
  210:             }
  211:             close($fh);
  212:         }
  213:     }
  214: # ------------------------------------------------------------------ copyrights
  215:     {
  216:         my $copyrightfile = $Apache::lonnet::perlvar{'lonIncludes'}.
  217:                                   '/copyright.tab';
  218:         if ( open (my $fh,"<$copyrightfile") ) {
  219:             while (my $line = <$fh>) {
  220:                 next if ($line=~/^\#/);
  221:                 chomp($line);
  222:                 my ($key,$val)=(split(/\s+/,$line,2));
  223:                 $cprtag{$key}=$val;
  224:             }
  225:             close($fh);
  226:         }
  227:     }
  228: # ----------------------------------------------------------- source copyrights
  229:     {
  230:         my $sourcecopyrightfile = $Apache::lonnet::perlvar{'lonIncludes'}.
  231:                                   '/source_copyright.tab';
  232:         if ( open (my $fh,"<$sourcecopyrightfile") ) {
  233:             while (my $line = <$fh>) {
  234:                 next if ($line =~ /^\#/);
  235:                 chomp($line);
  236:                 my ($key,$val)=(split(/\s+/,$line,2));
  237:                 $scprtag{$key}=$val;
  238:             }
  239:             close($fh);
  240:         }
  241:     }
  242: 
  243: # -------------------------------------------------------------- default domain designs
  244:     my $designdir=$Apache::lonnet::perlvar{'lonTabDir'}.'/lonDomColors';
  245:     my $designfile = $designdir.'/default.tab';
  246:     if ( open (my $fh,"<$designfile") ) {
  247:         while (my $line = <$fh>) {
  248:             next if ($line =~ /^\#/);
  249:             chomp($line);
  250:             my ($key,$val)=(split(/\=/,$line));
  251:             if ($val) { $defaultdesign{$key}=$val; }
  252:         }
  253:         close($fh);
  254:     }
  255: 
  256: # ------------------------------------------------------------- file categories
  257:     {
  258:         my $categoryfile = $Apache::lonnet::perlvar{'lonTabDir'}.
  259:                                   '/filecategories.tab';
  260:         if ( open (my $fh,"<$categoryfile") ) {
  261: 	    while (my $line = <$fh>) {
  262: 		next if ($line =~ /^\#/);
  263: 		chomp($line);
  264:                 my ($extension,$category)=(split(/\s+/,$line,2));
  265:                 push @{$category_extensions{lc($category)}},$extension;
  266:             }
  267:             close($fh);
  268:         }
  269: 
  270:     }
  271: # ------------------------------------------------------------------ file types
  272:     {
  273:         my $typesfile = $Apache::lonnet::perlvar{'lonTabDir'}.
  274:                '/filetypes.tab';
  275:         if ( open (my $fh,"<$typesfile") ) {
  276:             while (my $line = <$fh>) {
  277: 		next if ($line =~ /^\#/);
  278: 		chomp($line);
  279:                 my ($ending,$emb,$mime,$descr)=split(/\s+/,$line,4);
  280:                 if ($descr ne '') {
  281:                     $fe{$ending}=lc($emb);
  282:                     $fd{$ending}=$descr;
  283:                     if ($mime ne 'unk') { $fm{$ending}=$mime; }
  284:                 }
  285:             }
  286:             close($fh);
  287:         }
  288:     }
  289:     &Apache::lonnet::logthis(
  290:              "<span style='color:yellow;'>INFO: Read file types</span>");
  291:     $readit=1;
  292:     }  # end of unless($readit) 
  293:     
  294: }
  295: 
  296: ###############################################################
  297: ##           HTML and Javascript Helper Functions            ##
  298: ###############################################################
  299: 
  300: =pod 
  301: 
  302: =head1 HTML and Javascript Functions
  303: 
  304: =over 4
  305: 
  306: =item * &browser_and_searcher_javascript()
  307: 
  308: X<browsing, javascript>X<searching, javascript>Returns a string
  309: containing javascript with two functions, C<openbrowser> and
  310: C<opensearcher>. Returned string does not contain E<lt>scriptE<gt>
  311: tags.
  312: 
  313: =item * &openbrowser(formname,elementname,only,omit) [javascript]
  314: 
  315: inputs: formname, elementname, only, omit
  316: 
  317: formname and elementname indicate the name of the html form and name of
  318: the element that the results of the browsing selection are to be placed in. 
  319: 
  320: Specifying 'only' will restrict the browser to displaying only files
  321: with the given extension.  Can be a comma separated list.
  322: 
  323: Specifying 'omit' will restrict the browser to NOT displaying files
  324: with the given extension.  Can be a comma separated list.
  325: 
  326: =item * &opensearcher(formname,elementname) [javascript]
  327: 
  328: Inputs: formname, elementname
  329: 
  330: formname and elementname specify the name of the html form and the name
  331: of the element the selection from the search results will be placed in.
  332: 
  333: =cut
  334: 
  335: sub browser_and_searcher_javascript {
  336:     my ($mode)=@_;
  337:     if (!defined($mode)) { $mode='edit'; }
  338:     my $resurl=&escape_single(&lastresurl());
  339:     return <<END;
  340: // <!-- BEGIN LON-CAPA Internal
  341:     var editbrowser = null;
  342:     function openbrowser(formname,elementname,only,omit,titleelement) {
  343:         var url = '$resurl/?';
  344:         if (editbrowser == null) {
  345:             url += 'launch=1&';
  346:         }
  347:         url += 'catalogmode=interactive&';
  348:         url += 'mode=$mode&';
  349:         url += 'inhibitmenu=yes&';
  350:         url += 'form=' + formname + '&';
  351:         if (only != null) {
  352:             url += 'only=' + only + '&';
  353:         } else {
  354:             url += 'only=&';
  355: 	}
  356:         if (omit != null) {
  357:             url += 'omit=' + omit + '&';
  358:         } else {
  359:             url += 'omit=&';
  360: 	}
  361:         if (titleelement != null) {
  362:             url += 'titleelement=' + titleelement + '&';
  363:         } else {
  364: 	    url += 'titleelement=&';
  365: 	}
  366:         url += 'element=' + elementname + '';
  367:         var title = 'Browser';
  368:         var options = 'scrollbars=1,resizable=1,menubar=0,toolbar=1,location=1';
  369:         options += ',width=700,height=600';
  370:         editbrowser = open(url,title,options,'1');
  371:         editbrowser.focus();
  372:     }
  373:     var editsearcher;
  374:     function opensearcher(formname,elementname,titleelement) {
  375:         var url = '/adm/searchcat?';
  376:         if (editsearcher == null) {
  377:             url += 'launch=1&';
  378:         }
  379:         url += 'catalogmode=interactive&';
  380:         url += 'mode=$mode&';
  381:         url += 'form=' + formname + '&';
  382:         if (titleelement != null) {
  383:             url += 'titleelement=' + titleelement + '&';
  384:         } else {
  385: 	    url += 'titleelement=&';
  386: 	}
  387:         url += 'element=' + elementname + '';
  388:         var title = 'Search';
  389:         var options = 'scrollbars=1,resizable=1,menubar=0,toolbar=1,location=1';
  390:         options += ',width=700,height=600';
  391:         editsearcher = open(url,title,options,'1');
  392:         editsearcher.focus();
  393:     }
  394: // END LON-CAPA Internal -->
  395: END
  396: }
  397: 
  398: sub lastresurl {
  399:     if ($env{'environment.lastresurl'}) {
  400: 	return $env{'environment.lastresurl'}
  401:     } else {
  402: 	return '/res';
  403:     }
  404: }
  405: 
  406: sub storeresurl {
  407:     my $resurl=&Apache::lonnet::clutter(shift);
  408:     unless ($resurl=~/^\/res/) { return 0; }
  409:     $resurl=~s/\/$//;
  410:     &Apache::lonnet::put('environment',{'lastresurl' => $resurl});
  411:     &Apache::lonnet::appenv({'environment.lastresurl' => $resurl});
  412:     return 1;
  413: }
  414: 
  415: sub studentbrowser_javascript {
  416:    unless (
  417:             (($env{'request.course.id'}) && 
  418:              (&Apache::lonnet::allowed('srm',$env{'request.course.id'})
  419: 	      || &Apache::lonnet::allowed('srm',$env{'request.course.id'}.
  420: 					  '/'.$env{'request.course.sec'})
  421: 	      ))
  422:          || ($env{'request.role'}=~/^(au|dc|su)/)
  423:           ) { return ''; }  
  424:    return (<<'ENDSTDBRW');
  425: <script type="text/javascript" language="Javascript">
  426: // <![CDATA[
  427:     var stdeditbrowser;
  428:     function openstdbrowser(formname,uname,udom,clicker,roleflag,ignorefilter,courseadvonly) {
  429:         var url = '/adm/pickstudent?';
  430:         var filter;
  431: 	if (!ignorefilter) {
  432: 	    eval('filter=document.'+formname+'.'+uname+'.value;');
  433: 	}
  434:         if (filter != null) {
  435:            if (filter != '') {
  436:                url += 'filter='+filter+'&';
  437: 	   }
  438:         }
  439:         url += 'form=' + formname + '&unameelement='+uname+
  440:                                     '&udomelement='+udom+
  441:                                     '&clicker='+clicker;
  442: 	if (roleflag) { url+="&roles=1"; }
  443:         if (courseadvonly) { url+="&courseadvonly=1"; }
  444:         var title = 'Student_Browser';
  445:         var options = 'scrollbars=1,resizable=1,menubar=0';
  446:         options += ',width=700,height=600';
  447:         stdeditbrowser = open(url,title,options,'1');
  448:         stdeditbrowser.focus();
  449:     }
  450: // ]]>
  451: </script>
  452: ENDSTDBRW
  453: }
  454: 
  455: sub resourcebrowser_javascript {
  456:    unless ($env{'request.course.id'}) { return ''; }
  457:    return (<<'ENDRESBRW');
  458: <script type="text/javascript" language="Javascript">
  459: // <![CDATA[
  460:     var reseditbrowser;
  461:     function openresbrowser(formname,reslink) {
  462:         var url = '/adm/pickresource?form='+formname+'&reslink='+reslink;
  463:         var title = 'Resource_Browser';
  464:         var options = 'scrollbars=1,resizable=1,menubar=0';
  465:         options += ',width=700,height=500';
  466:         reseditbrowser = open(url,title,options,'1');
  467:         reseditbrowser.focus();
  468:     }
  469: // ]]>
  470: </script>
  471: ENDRESBRW
  472: }
  473: 
  474: sub selectstudent_link {
  475:    my ($form,$unameele,$udomele,$courseadvonly,$clickerid)=@_;
  476:    my $callargs = "'".&Apache::lonhtmlcommon::entity_encode($form)."','".
  477:                       &Apache::lonhtmlcommon::entity_encode($unameele)."','".
  478:                       &Apache::lonhtmlcommon::entity_encode($udomele)."'";
  479:    if ($env{'request.course.id'}) {  
  480:        if (!&Apache::lonnet::allowed('srm',$env{'request.course.id'})
  481: 	   && !&Apache::lonnet::allowed('srm',$env{'request.course.id'}.
  482: 					'/'.$env{'request.course.sec'})) {
  483: 	   return '';
  484:        }
  485:        $callargs.=",'".&Apache::lonhtmlcommon::entity_encode($clickerid)."'";
  486:        if ($courseadvonly)  {
  487:            $callargs .= ",'',1,1";
  488:        }
  489:        return '<span class="LC_nobreak">'.
  490:               '<a href="javascript:openstdbrowser('.$callargs.');">'.
  491:               &mt('Select User').'</a></span>';
  492:    }
  493:    if ($env{'request.role'}=~/^(au|dc|su)/) {
  494:        $callargs .= ",'',1"; 
  495:        return '<span class="LC_nobreak">'.
  496:               '<a href="javascript:openstdbrowser('.$callargs.');">'.
  497:               &mt('Select User').'</a></span>';
  498:    }
  499:    return '';
  500: }
  501: 
  502: sub selectresource_link {
  503:    my ($form,$reslink,$arg)=@_;
  504:    
  505:    my $callargs = "'".&Apache::lonhtmlcommon::entity_encode($form)."','".
  506:                       &Apache::lonhtmlcommon::entity_encode($reslink)."'";
  507:    unless ($env{'request.course.id'}) { return $arg; }
  508:    return '<span class="LC_nobreak">'.
  509:               '<a href="javascript:openresbrowser('.$callargs.');">'.
  510:               $arg.'</a></span>';
  511: }
  512: 
  513: 
  514: 
  515: sub authorbrowser_javascript {
  516:     return <<"ENDAUTHORBRW";
  517: <script type="text/javascript" language="JavaScript">
  518: // <![CDATA[
  519: var stdeditbrowser;
  520: 
  521: function openauthorbrowser(formname,udom) {
  522:     var url = '/adm/pickauthor?';
  523:     url += 'form='+formname+'&roledom='+udom;
  524:     var title = 'Author_Browser';
  525:     var options = 'scrollbars=1,resizable=1,menubar=0';
  526:     options += ',width=700,height=600';
  527:     stdeditbrowser = open(url,title,options,'1');
  528:     stdeditbrowser.focus();
  529: }
  530: 
  531: // ]]>
  532: </script>
  533: ENDAUTHORBRW
  534: }
  535: 
  536: sub coursebrowser_javascript {
  537:     my ($domainfilter,$sec_element,$formname,$role_element,$crstype,
  538:         $credits_element,$instcode) = @_;
  539:     my $wintitle = 'Course_Browser';
  540:     if ($crstype eq 'Community') {
  541:         $wintitle = 'Community_Browser';
  542:     }
  543:     my $id_functions = &javascript_index_functions();
  544:     my $output = '
  545: <script type="text/javascript" language="JavaScript">
  546: // <![CDATA[
  547:     var stdeditbrowser;'."\n";
  548: 
  549:     $output .= <<"ENDSTDBRW";
  550:     function opencrsbrowser(formname,uname,udom,desc,extra_element,multflag,type,type_elem) {
  551:         var url = '/adm/pickcourse?';
  552:         var formid = getFormIdByName(formname);
  553:         var domainfilter = getDomainFromSelectbox(formname,udom);
  554:         if (domainfilter != null) {
  555:            if (domainfilter != '') {
  556:                url += 'domainfilter='+domainfilter+'&';
  557: 	   }
  558:         }
  559:         url += 'form=' + formname + '&cnumelement='+uname+
  560: 	                            '&cdomelement='+udom+
  561:                                     '&cnameelement='+desc;
  562:         if (extra_element !=null && extra_element != '') {
  563:             if (formname == 'rolechoice' || formname == 'studentform') {
  564:                 url += '&roleelement='+extra_element;
  565:                 if (domainfilter == null || domainfilter == '') {
  566:                     url += '&domainfilter='+extra_element;
  567:                 }
  568:             }
  569:             else {
  570:                 if (formname == 'portform') {
  571:                     url += '&setroles='+extra_element;
  572:                 } else {
  573:                     if (formname == 'rules') {
  574:                         url += '&fixeddom='+extra_element; 
  575:                     }
  576:                 }
  577:             }     
  578:         }
  579:         if (type != null && type != '') {
  580:             url += '&type='+type;
  581:         }
  582:         if (type_elem != null && type_elem != '') {
  583:             url += '&typeelement='+type_elem;
  584:         }
  585:         if (formname == 'ccrs') {
  586:             var ownername = document.forms[formid].ccuname.value;
  587:             var ownerdom =  document.forms[formid].ccdomain.options[document.forms[formid].ccdomain.selectedIndex].value;
  588:             url += '&cloner='+ownername+':'+ownerdom;
  589:             if (type == 'Course') {
  590:                 url += '&crscode='+document.forms[formid].crscode.value;
  591:             }
  592:         }
  593:         if (formname == 'requestcrs') {
  594:             url += '&crsdom=$domainfilter&crscode=$instcode';
  595:         }
  596:         if (multflag !=null && multflag != '') {
  597:             url += '&multiple='+multflag;
  598:         }
  599:         var title = '$wintitle';
  600:         var options = 'scrollbars=1,resizable=1,menubar=0';
  601:         options += ',width=700,height=600';
  602:         stdeditbrowser = open(url,title,options,'1');
  603:         stdeditbrowser.focus();
  604:     }
  605: $id_functions
  606: ENDSTDBRW
  607:     if (($sec_element ne '') || ($role_element ne '') || ($credits_element ne '')) {
  608:         $output .= &setsec_javascript($sec_element,$formname,$role_element,
  609:                                       $credits_element);
  610:     }
  611:     $output .= '
  612: // ]]>
  613: </script>';
  614:     return $output;
  615: }
  616: 
  617: sub javascript_index_functions {
  618:     return <<"ENDJS";
  619: 
  620: function getFormIdByName(formname) {
  621:     for (var i=0;i<document.forms.length;i++) {
  622:         if (document.forms[i].name == formname) {
  623:             return i;
  624:         }
  625:     }
  626:     return -1;
  627: }
  628: 
  629: function getIndexByName(formid,item) {
  630:     for (var i=0;i<document.forms[formid].elements.length;i++) {
  631:         if (document.forms[formid].elements[i].name == item) {
  632:             return i;
  633:         }
  634:     }
  635:     return -1;
  636: }
  637: 
  638: function getDomainFromSelectbox(formname,udom) {
  639:     var userdom;
  640:     var formid = getFormIdByName(formname);
  641:     if (formid > -1) {
  642:         var domid = getIndexByName(formid,udom);
  643:         if (domid > -1) {
  644:             if (document.forms[formid].elements[domid].type == 'select-one') {
  645:                 userdom=document.forms[formid].elements[domid].options[document.forms[formid].elements[domid].selectedIndex].value;
  646:             }
  647:             if (document.forms[formid].elements[domid].type == 'hidden') {
  648:                 userdom=document.forms[formid].elements[domid].value;
  649:             }
  650:         }
  651:     }
  652:     return userdom;
  653: }
  654: 
  655: ENDJS
  656: 
  657: }
  658: 
  659: sub javascript_array_indexof {
  660:     return <<ENDJS;
  661: <script type="text/javascript" language="JavaScript">
  662: // <![CDATA[
  663: 
  664: if (!Array.prototype.indexOf) {
  665:     Array.prototype.indexOf = function (searchElement /*, fromIndex */ ) {
  666:         "use strict";
  667:         if (this === void 0 || this === null) {
  668:             throw new TypeError();
  669:         }
  670:         var t = Object(this);
  671:         var len = t.length >>> 0;
  672:         if (len === 0) {
  673:             return -1;
  674:         }
  675:         var n = 0;
  676:         if (arguments.length > 0) {
  677:             n = Number(arguments[1]);
  678:             if (n !== n) { // shortcut for verifying if it's NaN
  679:                 n = 0;
  680:             } else if (n !== 0 && n !== (1 / 0) && n !== -(1 / 0)) {
  681:                 n = (n > 0 || -1) * Math.floor(Math.abs(n));
  682:             }
  683:         }
  684:         if (n >= len) {
  685:             return -1;
  686:         }
  687:         var k = n >= 0 ? n : Math.max(len - Math.abs(n), 0);
  688:         for (; k < len; k++) {
  689:             if (k in t && t[k] === searchElement) {
  690:                 return k;
  691:             }
  692:         }
  693:         return -1;
  694:     }
  695: }
  696: 
  697: // ]]>
  698: </script>
  699: 
  700: ENDJS
  701: 
  702: }
  703: 
  704: sub userbrowser_javascript {
  705:     my $id_functions = &javascript_index_functions();
  706:     return <<"ENDUSERBRW";
  707: 
  708: function openuserbrowser(formname,uname,udom,ulast,ufirst,uemail,hideudom,crsdom,caller) {
  709:     var url = '/adm/pickuser?';
  710:     var userdom = getDomainFromSelectbox(formname,udom);
  711:     if (userdom != null) {
  712:        if (userdom != '') {
  713:            url += 'srchdom='+userdom+'&';
  714:        }
  715:     }
  716:     url += 'form=' + formname + '&unameelement='+uname+
  717:                                 '&udomelement='+udom+
  718:                                 '&ulastelement='+ulast+
  719:                                 '&ufirstelement='+ufirst+
  720:                                 '&uemailelement='+uemail+
  721:                                 '&hideudomelement='+hideudom+
  722:                                 '&coursedom='+crsdom;
  723:     if ((caller != null) && (caller != undefined)) {
  724:         url += '&caller='+caller;
  725:     }
  726:     var title = 'User_Browser';
  727:     var options = 'scrollbars=1,resizable=1,menubar=0';
  728:     options += ',width=700,height=600';
  729:     var stdeditbrowser = open(url,title,options,'1');
  730:     stdeditbrowser.focus();
  731: }
  732: 
  733: function fix_domain (formname,udom,origdom,uname) {
  734:     var formid = getFormIdByName(formname);
  735:     if (formid > -1) {
  736:         var unameid = getIndexByName(formid,uname);
  737:         var domid = getIndexByName(formid,udom);
  738:         var hidedomid = getIndexByName(formid,origdom);
  739:         if (hidedomid > -1) {
  740:             var fixeddom = document.forms[formid].elements[hidedomid].value;
  741:             var unameval = document.forms[formid].elements[unameid].value;
  742:             if ((fixeddom != '') && (fixeddom != undefined) && (fixeddom != null) && (unameval != '') && (unameval != undefined) && (unameval != null)) {
  743:                 if (domid > -1) {
  744:                     var slct = document.forms[formid].elements[domid];
  745:                     if (slct.type == 'select-one') {
  746:                         var i;
  747:                         for (i=0;i<slct.length;i++) {
  748:                             if (slct.options[i].value==fixeddom) { slct.selectedIndex=i; }
  749:                         }
  750:                     }
  751:                     if (slct.type == 'hidden') {
  752:                         slct.value = fixeddom;
  753:                     }
  754:                 }
  755:             }
  756:         }
  757:     }
  758:     return;
  759: }
  760: 
  761: $id_functions
  762: ENDUSERBRW
  763: }
  764: 
  765: sub setsec_javascript {
  766:     my ($sec_element,$formname,$role_element,$credits_element) = @_;
  767:     my (@courserolenames,@communityrolenames,$rolestr,$courserolestr,
  768:         $communityrolestr);
  769:     if ($role_element ne '') {
  770:         my @allroles = ('st','ta','ep','in','ad');
  771:         foreach my $crstype ('Course','Community') {
  772:             if ($crstype eq 'Community') {
  773:                 foreach my $role (@allroles) {
  774:                     push(@communityrolenames,&Apache::lonnet::plaintext($role,$crstype));
  775:                 }
  776:                 push(@communityrolenames,&Apache::lonnet::plaintext('co'));
  777:             } else {
  778:                 foreach my $role (@allroles) {
  779:                     push(@courserolenames,&Apache::lonnet::plaintext($role,$crstype));
  780:                 }
  781:                 push(@courserolenames,&Apache::lonnet::plaintext('cc'));
  782:             }
  783:         }
  784:         $rolestr = '"'.join('","',@allroles).'"';
  785:         $courserolestr = '"'.join('","',@courserolenames).'"';
  786:         $communityrolestr = '"'.join('","',@communityrolenames).'"';
  787:     }
  788:     my $setsections = qq|
  789: function setSect(sectionlist) {
  790:     var sectionsArray = new Array();
  791:     if ((sectionlist != '') && (typeof sectionlist != "undefined")) {
  792:         sectionsArray = sectionlist.split(",");
  793:     }
  794:     var numSections = sectionsArray.length;
  795:     document.$formname.$sec_element.length = 0;
  796:     if (numSections == 0) {
  797:         document.$formname.$sec_element.multiple=false;
  798:         document.$formname.$sec_element.size=1;
  799:         document.$formname.$sec_element.options[0] = new Option('No existing sections','',false,false)
  800:     } else {
  801:         if (numSections == 1) {
  802:             document.$formname.$sec_element.multiple=false;
  803:             document.$formname.$sec_element.size=1;
  804:             document.$formname.$sec_element.options[0] = new Option('Select','',true,true);
  805:             document.$formname.$sec_element.options[1] = new Option('No section','',false,false)
  806:             document.$formname.$sec_element.options[2] = new Option(sectionsArray[0],sectionsArray[0],false,false);
  807:         } else {
  808:             for (var i=0; i<numSections; i++) {
  809:                 document.$formname.$sec_element.options[i] = new Option(sectionsArray[i],sectionsArray[i],false,false)
  810:             }
  811:             document.$formname.$sec_element.multiple=true
  812:             if (numSections < 3) {
  813:                 document.$formname.$sec_element.size=numSections;
  814:             } else {
  815:                 document.$formname.$sec_element.size=3;
  816:             }
  817:             document.$formname.$sec_element.options[0].selected = false
  818:         }
  819:     }
  820: }
  821: 
  822: function setRole(crstype) {
  823: |;
  824:     if ($role_element eq '') {
  825:         $setsections .= '    return;
  826: }
  827: ';
  828:     } else {
  829:         $setsections .= qq|
  830:     var elementLength = document.$formname.$role_element.length;
  831:     var allroles = Array($rolestr);
  832:     var courserolenames = Array($courserolestr);
  833:     var communityrolenames = Array($communityrolestr);
  834:     if (elementLength != undefined) {
  835:         if (document.$formname.$role_element.options[5].value == 'cc') {
  836:             if (crstype == 'Course') {
  837:                 return;
  838:             } else {
  839:                 allroles[5] = 'co';
  840:                 for (var i=0; i<6; i++) {
  841:                     document.$formname.$role_element.options[i].value = allroles[i];
  842:                     document.$formname.$role_element.options[i].text = communityrolenames[i];
  843:                 }
  844:             }
  845:         } else {
  846:             if (crstype == 'Community') {
  847:                 return;
  848:             } else {
  849:                 allroles[5] = 'cc';
  850:                 for (var i=0; i<6; i++) {
  851:                     document.$formname.$role_element.options[i].value = allroles[i];
  852:                     document.$formname.$role_element.options[i].text = courserolenames[i];
  853:                 }
  854:             }
  855:         }
  856:     }
  857:     return;
  858: }
  859: |;
  860:     }
  861:     if ($credits_element) {
  862:         $setsections .= qq|
  863: function setCredits(defaultcredits) {
  864:     document.$formname.$credits_element.value = defaultcredits;
  865:     return;
  866: }
  867: |;
  868:     }
  869:     return $setsections;
  870: }
  871: 
  872: sub selectcourse_link {
  873:    my ($form,$unameele,$udomele,$desc,$extra_element,$multflag,$selecttype,
  874:        $typeelement) = @_;
  875:    my $type = $selecttype;
  876:    my $linktext = &mt('Select Course');
  877:    if ($selecttype eq 'Community') {
  878:        $linktext = &mt('Select Community');
  879:    } elsif ($selecttype eq 'Course/Community') {
  880:        $linktext = &mt('Select Course/Community');
  881:        $type = '';
  882:    } elsif ($selecttype eq 'Select') {
  883:        $linktext = &mt('Select');
  884:        $type = '';
  885:    }
  886:    return '<span class="LC_nobreak">'
  887:          ."<a href='"
  888:          .'javascript:opencrsbrowser("'.$form.'","'.$unameele
  889:          .'","'.$udomele.'","'.$desc.'","'.$extra_element
  890:          .'","'.$multflag.'","'.$type.'","'.$typeelement.'");'
  891:          ."'>".$linktext.'</a>'
  892:          .'</span>';
  893: }
  894: 
  895: sub selectauthor_link {
  896:    my ($form,$udom)=@_;
  897:    return '<a href="javascript:openauthorbrowser('."'$form','$udom'".');">'.
  898:           &mt('Select Author').'</a>';
  899: }
  900: 
  901: sub selectuser_link {
  902:     my ($form,$unameelem,$domelem,$lastelem,$firstelem,$emailelem,$hdomelem,
  903:         $coursedom,$linktext,$caller) = @_;
  904:     return '<a href="javascript:openuserbrowser('."'$form','$unameelem','$domelem',".
  905:            "'$lastelem','$firstelem','$emailelem','$hdomelem','$coursedom','$caller'".
  906:            ');">'.$linktext.'</a>';
  907: }
  908: 
  909: sub check_uncheck_jscript {
  910:     my $jscript = <<"ENDSCRT";
  911: function checkAll(field) {
  912:     if (field.length > 0) {
  913:         for (i = 0; i < field.length; i++) {
  914:             if (!field[i].disabled) {
  915:                 field[i].checked = true;
  916:             }
  917:         }
  918:     } else {
  919:         if (!field.disabled) {
  920:             field.checked = true;
  921:         }
  922:     }
  923: }
  924:  
  925: function uncheckAll(field) {
  926:     if (field.length > 0) {
  927:         for (i = 0; i < field.length; i++) {
  928:             field[i].checked = false ;
  929:         }
  930:     } else {
  931:         field.checked = false ;
  932:     }
  933: }
  934: ENDSCRT
  935:     return $jscript;
  936: }
  937: 
  938: sub select_timezone {
  939:    my ($name,$selected,$onchange,$includeempty)=@_;
  940:    my $output='<select name="'.$name.'" '.$onchange.'>'."\n";
  941:    if ($includeempty) {
  942:        $output .= '<option value=""';
  943:        if (($selected eq '') || ($selected eq 'local')) {
  944:            $output .= ' selected="selected" ';
  945:        }
  946:        $output .= '> </option>';
  947:    }
  948:    my @timezones = DateTime::TimeZone->all_names;
  949:    foreach my $tzone (@timezones) {
  950:        $output.= '<option value="'.$tzone.'"';
  951:        if ($tzone eq $selected) {
  952:            $output.=' selected="selected"';
  953:        }
  954:        $output.=">$tzone</option>\n";
  955:    }
  956:    $output.="</select>";
  957:    return $output;
  958: }
  959: 
  960: sub select_datelocale {
  961:     my ($name,$selected,$onchange,$includeempty)=@_;
  962:     my $output='<select name="'.$name.'" '.$onchange.'>'."\n";
  963:     if ($includeempty) {
  964:         $output .= '<option value=""';
  965:         if ($selected eq '') {
  966:             $output .= ' selected="selected" ';
  967:         }
  968:         $output .= '> </option>';
  969:     }
  970:     my @languages = &Apache::lonlocal::preferred_languages();
  971:     my (@possibles,%locale_names);
  972:     my @locales = DateTime::Locale->ids();
  973:     foreach my $id (@locales) {
  974:         if ($id ne '') {
  975:             my ($en_terr,$native_terr);
  976:             my $loc = DateTime::Locale->load($id);
  977:             if (ref($loc)) {
  978:                 $en_terr = $loc->name();
  979:                 $native_terr = $loc->native_name();
  980:                 if (grep(/^en$/,@languages) || !@languages) {
  981:                     if ($en_terr ne '') {
  982:                         $locale_names{$id} = '('.$en_terr.')';
  983:                     } elsif ($native_terr ne '') {
  984:                         $locale_names{$id} = $native_terr;
  985:                     }
  986:                 } else {
  987:                     if ($native_terr ne '') {
  988:                         $locale_names{$id} = $native_terr.' ';
  989:                     } elsif ($en_terr ne '') {
  990:                         $locale_names{$id} = '('.$en_terr.')';
  991:                     }
  992:                 }
  993:                 $locale_names{$id} = Encode::encode('UTF-8',$locale_names{$id});
  994:                 push(@possibles,$id);
  995:             }
  996:         }
  997:     }
  998:     foreach my $item (sort(@possibles)) {
  999:         $output.= '<option value="'.$item.'"';
 1000:         if ($item eq $selected) {
 1001:             $output.=' selected="selected"';
 1002:         }
 1003:         $output.=">$item";
 1004:         if ($locale_names{$item} ne '') {
 1005:             $output.='  '.$locale_names{$item};
 1006:         }
 1007:         $output.="</option>\n";
 1008:     }
 1009:     $output.="</select>";
 1010:     return $output;
 1011: }
 1012: 
 1013: sub select_language {
 1014:     my ($name,$selected,$includeempty) = @_;
 1015:     my %langchoices;
 1016:     if ($includeempty) {
 1017:         %langchoices = ('' => 'No language preference');
 1018:     }
 1019:     foreach my $id (&languageids()) {
 1020:         my $code = &supportedlanguagecode($id);
 1021:         if ($code) {
 1022:             $langchoices{$code} = &plainlanguagedescription($id);
 1023:         }
 1024:     }
 1025:     %langchoices = &Apache::lonlocal::texthash(%langchoices);
 1026:     return &select_form($selected,$name,\%langchoices);
 1027: }
 1028: 
 1029: =pod
 1030: 
 1031: =item * &linked_select_forms(...)
 1032: 
 1033: linked_select_forms returns a string containing a <script></script> block
 1034: and html for two <select> menus.  The select menus will be linked in that
 1035: changing the value of the first menu will result in new values being placed
 1036: in the second menu.  The values in the select menu will appear in alphabetical
 1037: order unless a defined order is provided.
 1038: 
 1039: linked_select_forms takes the following ordered inputs:
 1040: 
 1041: =over 4
 1042: 
 1043: =item * $formname, the name of the <form> tag
 1044: 
 1045: =item * $middletext, the text which appears between the <select> tags
 1046: 
 1047: =item * $firstdefault, the default value for the first menu
 1048: 
 1049: =item * $firstselectname, the name of the first <select> tag
 1050: 
 1051: =item * $secondselectname, the name of the second <select> tag
 1052: 
 1053: =item * $hashref, a reference to a hash containing the data for the menus.
 1054: 
 1055: =item * $menuorder, the order of values in the first menu
 1056: 
 1057: =item * $onchangefirst, additional javascript call to execute for an onchange
 1058:         event for the first <select> tag
 1059: 
 1060: =item * $onchangesecond, additional javascript call to execute for an onchange
 1061:         event for the second <select> tag
 1062: 
 1063: =back 
 1064: 
 1065: Below is an example of such a hash.  Only the 'text', 'default', and 
 1066: 'select2' keys must appear as stated.  keys(%menu) are the possible 
 1067: values for the first select menu.  The text that coincides with the 
 1068: first menu value is given in $menu{$choice1}->{'text'}.  The values 
 1069: and text for the second menu are given in the hash pointed to by 
 1070: $menu{$choice1}->{'select2'}.  
 1071: 
 1072:  my %menu = ( A1 => { text =>"Choice A1" ,
 1073:                        default => "B3",
 1074:                        select2 => { 
 1075:                            B1 => "Choice B1",
 1076:                            B2 => "Choice B2",
 1077:                            B3 => "Choice B3",
 1078:                            B4 => "Choice B4"
 1079:                            },
 1080:                        order => ['B4','B3','B1','B2'],
 1081:                    },
 1082:                A2 => { text =>"Choice A2" ,
 1083:                        default => "C2",
 1084:                        select2 => { 
 1085:                            C1 => "Choice C1",
 1086:                            C2 => "Choice C2",
 1087:                            C3 => "Choice C3"
 1088:                            },
 1089:                        order => ['C2','C1','C3'],
 1090:                    },
 1091:                A3 => { text =>"Choice A3" ,
 1092:                        default => "D6",
 1093:                        select2 => { 
 1094:                            D1 => "Choice D1",
 1095:                            D2 => "Choice D2",
 1096:                            D3 => "Choice D3",
 1097:                            D4 => "Choice D4",
 1098:                            D5 => "Choice D5",
 1099:                            D6 => "Choice D6",
 1100:                            D7 => "Choice D7"
 1101:                            },
 1102:                        order => ['D4','D3','D2','D1','D7','D6','D5'],
 1103:                    }
 1104:                );
 1105: 
 1106: =cut
 1107: 
 1108: sub linked_select_forms {
 1109:     my ($formname,
 1110:         $middletext,
 1111:         $firstdefault,
 1112:         $firstselectname,
 1113:         $secondselectname, 
 1114:         $hashref,
 1115:         $menuorder,
 1116:         $onchangefirst,
 1117:         $onchangesecond
 1118:         ) = @_;
 1119:     my $second = "document.$formname.$secondselectname";
 1120:     my $first = "document.$formname.$firstselectname";
 1121:     # output the javascript to do the changing
 1122:     my $result = '';
 1123:     $result.='<script type="text/javascript" language="JavaScript">'."\n";
 1124:     $result.="// <![CDATA[\n";
 1125:     $result.="var select2data = new Object();\n";
 1126:     $" = '","';
 1127:     my $debug = '';
 1128:     foreach my $s1 (sort(keys(%$hashref))) {
 1129:         $result.="select2data.d_$s1 = new Object();\n";        
 1130:         $result.="select2data.d_$s1.def = new String('".
 1131:             $hashref->{$s1}->{'default'}."');\n";
 1132:         $result.="select2data.d_$s1.values = new Array(";
 1133:         my @s2values = sort(keys( %{ $hashref->{$s1}->{'select2'} } ));
 1134:         if (ref($hashref->{$s1}->{'order'}) eq 'ARRAY') {
 1135:             @s2values = @{$hashref->{$s1}->{'order'}};
 1136:         }
 1137:         $result.="\"@s2values\");\n";
 1138:         $result.="select2data.d_$s1.texts = new Array(";        
 1139:         my @s2texts;
 1140:         foreach my $value (@s2values) {
 1141:             push @s2texts, $hashref->{$s1}->{'select2'}->{$value};
 1142:         }
 1143:         $result.="\"@s2texts\");\n";
 1144:     }
 1145:     $"=' ';
 1146:     $result.= <<"END";
 1147: 
 1148: function select1_changed() {
 1149:     // Determine new choice
 1150:     var newvalue = "d_" + $first.value;
 1151:     // update select2
 1152:     var values     = select2data[newvalue].values;
 1153:     var texts      = select2data[newvalue].texts;
 1154:     var select2def = select2data[newvalue].def;
 1155:     var i;
 1156:     // out with the old
 1157:     for (i = 0; i < $second.options.length; i++) {
 1158:         $second.options[i] = null;
 1159:     }
 1160:     // in with the nuclear
 1161:     for (i=0;i<values.length; i++) {
 1162:         $second.options[i] = new Option(values[i]);
 1163:         $second.options[i].value = values[i];
 1164:         $second.options[i].text = texts[i];
 1165:         if (values[i] == select2def) {
 1166:             $second.options[i].selected = true;
 1167:         }
 1168:     }
 1169: }
 1170: // ]]>
 1171: </script>
 1172: END
 1173:     # output the initial values for the selection lists
 1174:     $result .= "<select size=\"1\" name=\"$firstselectname\" onchange=\"select1_changed();$onchangefirst\">\n";
 1175:     my @order = sort(keys(%{$hashref}));
 1176:     if (ref($menuorder) eq 'ARRAY') {
 1177:         @order = @{$menuorder};
 1178:     }
 1179:     foreach my $value (@order) {
 1180:         $result.="    <option value=\"$value\" ";
 1181:         $result.=" selected=\"selected\" " if ($value eq $firstdefault);
 1182:         $result.=">".&mt($hashref->{$value}->{'text'})."</option>\n";
 1183:     }
 1184:     $result .= "</select>\n";
 1185:     my %select2 = %{$hashref->{$firstdefault}->{'select2'}};
 1186:     $result .= $middletext;
 1187:     $result .= "<select size=\"1\" name=\"$secondselectname\"";
 1188:     if ($onchangesecond) {
 1189:         $result .= ' onchange="'.$onchangesecond.'"';
 1190:     }
 1191:     $result .= ">\n";
 1192:     my $seconddefault = $hashref->{$firstdefault}->{'default'};
 1193:     
 1194:     my @secondorder = sort(keys(%select2));
 1195:     if (ref($hashref->{$firstdefault}->{'order'}) eq 'ARRAY') {
 1196:         @secondorder = @{$hashref->{$firstdefault}->{'order'}};
 1197:     }
 1198:     foreach my $value (@secondorder) {
 1199:         $result.="    <option value=\"$value\" ";        
 1200:         $result.=" selected=\"selected\" " if ($value eq $seconddefault);
 1201:         $result.=">".&mt($select2{$value})."</option>\n";
 1202:     }
 1203:     $result .= "</select>\n";
 1204:     #    return $debug;
 1205:     return $result;
 1206: }   #  end of sub linked_select_forms {
 1207: 
 1208: =pod
 1209: 
 1210: =item * &help_open_topic($topic,$text,$stayOnPage,$width,$height,$imgid)
 1211: 
 1212: Returns a string corresponding to an HTML link to the given help
 1213: $topic, where $topic corresponds to the name of a .tex file in
 1214: /home/httpd/html/adm/help/tex, with underscores replaced by
 1215: spaces. 
 1216: 
 1217: $text will optionally be linked to the same topic, allowing you to
 1218: link text in addition to the graphic. If you do not want to link
 1219: text, but wish to specify one of the later parameters, pass an
 1220: empty string. 
 1221: 
 1222: $stayOnPage is a value that will be interpreted as a boolean. If true,
 1223: the link will not open a new window. If false, the link will open
 1224: a new window using Javascript. (Default is false.) 
 1225: 
 1226: $width and $height are optional numerical parameters that will
 1227: override the width and height of the popped up window, which may
 1228: be useful for certain help topics with big pictures included.
 1229: 
 1230: $imgid is the id of the img tag used for the help icon. This may be
 1231: used in a javascript call to switch the image src.  See 
 1232: lonhtmlcommon::htmlareaselectactive() for an example.
 1233: 
 1234: =cut
 1235: 
 1236: sub help_open_topic {
 1237:     my ($topic, $text, $stayOnPage, $width, $height, $imgid) = @_;
 1238:     $text = "" if (not defined $text);
 1239:     $stayOnPage = 0 if (not defined $stayOnPage);
 1240:     $width = 500 if (not defined $width);
 1241:     $height = 400 if (not defined $height);
 1242:     my $filename = $topic;
 1243:     $filename =~ s/ /_/g;
 1244: 
 1245:     my $template = "";
 1246:     my $link;
 1247:     
 1248:     $topic=~s/\W/\_/g;
 1249: 
 1250:     if (!$stayOnPage) {
 1251:         if ($env{'browser.mobile'}) {
 1252: 	    $link = "javascript:openMyModal('/adm/help/${filename}.hlp',$width,$height,'yes');";
 1253:         } else {
 1254:             $link = "javascript:void(open('/adm/help/${filename}.hlp', 'Help_for_$topic', 'menubar=0,toolbar=1,scrollbars=1,width=$width,height=$height,resizable=yes'))";
 1255:         }
 1256:     } elsif ($stayOnPage eq 'popup') {
 1257:         $link = "javascript:void(open('/adm/help/${filename}.hlp', 'Help_for_$topic', 'menubar=0,toolbar=1,scrollbars=1,width=$width,height=$height,resizable=yes'))";
 1258:     } else {
 1259: 	$link = "/adm/help/${filename}.hlp";
 1260:     }
 1261: 
 1262:     # Add the text
 1263:     if ($text ne "") {	
 1264: 	$template.='<span class="LC_help_open_topic">'
 1265:                   .'<a target="_top" href="'.$link.'">'
 1266:                   .$text.'</a>';
 1267:     }
 1268: 
 1269:     # (Always) Add the graphic
 1270:     my $title = &mt('Online Help');
 1271:     my $helpicon=&lonhttpdurl("/adm/help/help.png");
 1272:     if ($imgid ne '') {
 1273:         $imgid = ' id="'.$imgid.'"';
 1274:     }
 1275:     $template.=' <a target="_top" href="'.$link.'" title="'.$title.'">'
 1276:               .'<img src="'.$helpicon.'" border="0"'
 1277:               .' alt="'.&mt('Help: [_1]',$topic).'"'
 1278:               .' title="'.$title.'" style="vertical-align:middle;"'.$imgid 
 1279:               .' /></a>';
 1280:     if ($text ne "") {	
 1281:         $template.='</span>';
 1282:     }
 1283:     return $template;
 1284: 
 1285: }
 1286: 
 1287: # This is a quicky function for Latex cheatsheet editing, since it 
 1288: # appears in at least four places
 1289: sub helpLatexCheatsheet {
 1290:     my ($topic,$text,$not_author,$stayOnPage) = @_;
 1291:     my $out;
 1292:     my $addOther = '';
 1293:     if ($topic) {
 1294: 	$addOther = '<span>'.&help_open_topic($topic,&mt($text),$stayOnPage, undef, 600).'</span> ';
 1295:     }
 1296:     $out = '<span>' # Start cheatsheet
 1297: 	  .$addOther
 1298:           .'<span>'
 1299: 	  .&help_open_topic('Greek_Symbols',&mt('Greek Symbols'),$stayOnPage,undef,600)
 1300: 	  .'</span> <span>'
 1301: 	  .&help_open_topic('Other_Symbols',&mt('Other Symbols'),$stayOnPage,undef,600)
 1302: 	  .'</span>';
 1303:     unless ($not_author) {
 1304:         $out .= ' <span>'
 1305: 	       .&help_open_topic('Authoring_Output_Tags',&mt('Output Tags'),$stayOnPage,undef,600)
 1306: 	       .'</span> <span>'
 1307:                .&help_open_topic('Authoring_Multilingual_Problems',&mt('Languages'),$stayOnPage,undef,600)
 1308:                .'</span>';
 1309:     }
 1310:     $out .= '</span>'; # End cheatsheet
 1311:     return $out;
 1312: }
 1313: 
 1314: sub general_help {
 1315:     my $helptopic='Student_Intro';
 1316:     if ($env{'request.role'}=~/^(ca|au)/) {
 1317: 	$helptopic='Authoring_Intro';
 1318:     } elsif ($env{'request.role'}=~/^(cc|co)/) {
 1319: 	$helptopic='Course_Coordination_Intro';
 1320:     } elsif ($env{'request.role'}=~/^dc/) {
 1321:         $helptopic='Domain_Coordination_Intro';
 1322:     }
 1323:     return $helptopic;
 1324: }
 1325: 
 1326: sub update_help_link {
 1327:     my ($topic,$component_help,$faq,$bug,$stayOnPage) = @_;
 1328:     my $origurl = $ENV{'REQUEST_URI'};
 1329:     $origurl=~s|^/~|/priv/|;
 1330:     my $timestamp = time;
 1331:     foreach my $datum (\$topic,\$component_help,\$faq,\$bug,\$origurl) {
 1332:         $$datum = &escape($$datum);
 1333:     }
 1334: 
 1335:     my $banner_link = "/adm/helpmenu?page=banner&amp;topic=$topic&amp;component_help=$component_help&amp;faq=$faq&amp;bug=$bug&amp;origurl=$origurl&amp;stamp=$timestamp&amp;stayonpage=$stayOnPage";
 1336:     my $output .= <<"ENDOUTPUT";
 1337: <script type="text/javascript">
 1338: // <![CDATA[
 1339: banner_link = '$banner_link';
 1340: // ]]>
 1341: </script>
 1342: ENDOUTPUT
 1343:     return $output;
 1344: }
 1345: 
 1346: # now just updates the help link and generates a blue icon
 1347: sub help_open_menu {
 1348:     my ($topic,$component_help,$faq,$bug,$stayOnPage,$width,$height,$text) 
 1349: 	= @_;    
 1350:     $stayOnPage = 1;
 1351:     my $output;
 1352:     if ($component_help) {
 1353: 	if (!$text) {
 1354: 	    $output=&help_open_topic($component_help,undef,$stayOnPage,
 1355: 				       $width,$height);
 1356: 	} else {
 1357: 	    my $help_text;
 1358: 	    $help_text=&unescape($topic);
 1359: 	    $output='<table><tr><td>'.
 1360: 		&help_open_topic($component_help,$help_text,$stayOnPage,
 1361: 				 $width,$height).'</td></tr></table>';
 1362: 	}
 1363:     }
 1364:     my $banner_link = &update_help_link($topic,$component_help,$faq,$bug,$stayOnPage);
 1365:     return $output.$banner_link;
 1366: }
 1367: 
 1368: sub top_nav_help {
 1369:     my ($text) = @_;
 1370:     $text = &mt($text);
 1371:     my $stay_on_page;
 1372:     unless ($env{'environment.remote'} eq 'on') {
 1373:         $stay_on_page = 1;
 1374:     }
 1375:     my ($link,$banner_link);
 1376:     unless ($env{'request.noversionuri'} =~ m{^/adm/helpmenu}) {
 1377:         $link = ($stay_on_page) ? "javascript:helpMenu('display')"
 1378: 	                         : "javascript:helpMenu('open')";
 1379:         $banner_link = &update_help_link(undef,undef,undef,undef,$stay_on_page);
 1380:     }
 1381:     my $title = &mt('Get help');
 1382:     if ($link) {
 1383:         return <<"END";
 1384: $banner_link
 1385: <a href="$link" title="$title">$text</a>
 1386: END
 1387:     } else {
 1388:         return '&nbsp;'.$text.'&nbsp;';
 1389:     }
 1390: }
 1391: 
 1392: sub help_menu_js {
 1393:     my ($httphost) = @_;
 1394:     my $stayOnPage = 1;
 1395:     my $width = 620;
 1396:     my $height = 600;
 1397:     my $helptopic=&general_help();
 1398:     my $details_link = $httphost.'/adm/help/'.$helptopic.'.hlp';
 1399:     my $nothing=&Apache::lonhtmlcommon::javascript_nothing();
 1400:     my $start_page =
 1401:         &Apache::loncommon::start_page('Help Menu', undef,
 1402: 				       {'frameset'    => 1,
 1403: 					'js_ready'    => 1,
 1404:                                         'use_absolute' => $httphost, 
 1405: 					'add_entries' => {
 1406: 					    'border' => '0',
 1407: 					    'rows'   => "110,*",},});
 1408:     my $end_page =
 1409:         &Apache::loncommon::end_page({'frameset' => 1,
 1410: 				      'js_ready' => 1,});
 1411: 
 1412:     my $template .= <<"ENDTEMPLATE";
 1413: <script type="text/javascript">
 1414: // <![CDATA[
 1415: // <!-- BEGIN LON-CAPA Internal
 1416: var banner_link = '';
 1417: function helpMenu(target) {
 1418:     var caller = this;
 1419:     if (target == 'open') {
 1420:         var newWindow = null;
 1421:         try {
 1422:             newWindow =  window.open($nothing,"helpmenu","HEIGHT=$height,WIDTH=$width,resizable=yes,scrollbars=yes" )
 1423:         }
 1424:         catch(error) {
 1425:             writeHelp(caller);
 1426:             return;
 1427:         }
 1428:         if (newWindow) {
 1429:             caller = newWindow;
 1430:         }
 1431:     }
 1432:     writeHelp(caller);
 1433:     return;
 1434: }
 1435: function writeHelp(caller) {
 1436:     caller.document.writeln('$start_page\\n<frame name="bannerframe" src="'+banner_link+'" marginwidth="0" marginheight="0" frameborder="0">\\n');
 1437:     caller.document.writeln('<frame name="bodyframe" src="$details_link" marginwidth="0" marginheight="0" frameborder="0">\\n$end_page');
 1438:     caller.document.close();
 1439:     caller.focus();
 1440: }
 1441: // END LON-CAPA Internal -->
 1442: // ]]>
 1443: </script>
 1444: ENDTEMPLATE
 1445:     return $template;
 1446: }
 1447: 
 1448: sub help_open_bug {
 1449:     my ($topic, $text, $stayOnPage, $width, $height) = @_;
 1450:     unless ($env{'user.adv'}) { return ''; }
 1451:     unless ($Apache::lonnet::perlvar{'BugzillaHost'}) { return ''; }
 1452:     $text = "" if (not defined $text);
 1453: 	$stayOnPage=1;
 1454:     $width = 600 if (not defined $width);
 1455:     $height = 600 if (not defined $height);
 1456: 
 1457:     $topic=~s/\W+/\+/g;
 1458:     my $link='';
 1459:     my $template='';
 1460:     my $url=$Apache::lonnet::perlvar{'BugzillaHost'}.'enter_bug.cgi?product=LON-CAPA&amp;bug_file_loc='.
 1461: 	&escape($ENV{'REQUEST_URI'}).'&amp;component='.$topic;
 1462:     if (!$stayOnPage)
 1463:     {
 1464: 	$link = "javascript:void(open('$url', 'Bugzilla', 'menubar=0,toolbar=1,scrollbars=1,width=$width,height=$height,resizable=yes'))";
 1465:     }
 1466:     else
 1467:     {
 1468: 	$link = $url;
 1469:     }
 1470:     # Add the text
 1471:     if ($text ne "")
 1472:     {
 1473: 	$template .= 
 1474:   "<table bgcolor='#AA3333' cellspacing='1' cellpadding='1' border='0'><tr>".
 1475:   "<td bgcolor='#FF5555'><a target=\"_top\" href=\"$link\"><span style=\"color:#FFFFFF;font-size:10pt;\">$text</span></a>";
 1476:     }
 1477: 
 1478:     # Add the graphic
 1479:     my $title = &mt('Report a Bug');
 1480:     my $bugicon=&lonhttpdurl("/adm/lonMisc/smallBug.gif");
 1481:     $template .= <<"ENDTEMPLATE";
 1482:  <a target="_top" href="$link" title="$title"><img src="$bugicon" border="0" alt="(Bug: $topic)" /></a>
 1483: ENDTEMPLATE
 1484:     if ($text ne '') { $template.='</td></tr></table>' };
 1485:     return $template;
 1486: 
 1487: }
 1488: 
 1489: sub help_open_faq {
 1490:     my ($topic, $text, $stayOnPage, $width, $height) = @_;
 1491:     unless ($env{'user.adv'}) { return ''; }
 1492:     unless ($Apache::lonnet::perlvar{'FAQHost'}) { return ''; }
 1493:     $text = "" if (not defined $text);
 1494: 	$stayOnPage=1;
 1495:     $width = 350 if (not defined $width);
 1496:     $height = 400 if (not defined $height);
 1497: 
 1498:     $topic=~s/\W+/\+/g;
 1499:     my $link='';
 1500:     my $template='';
 1501:     my $url=$Apache::lonnet::perlvar{'FAQHost'}.'/fom/cache/'.$topic.'.html';
 1502:     if (!$stayOnPage)
 1503:     {
 1504: 	$link = "javascript:void(open('$url', 'FAQ-O-Matic', 'menubar=0,toolbar=1,scrollbars=1,width=$width,height=$height,resizable=yes'))";
 1505:     }
 1506:     else
 1507:     {
 1508: 	$link = $url;
 1509:     }
 1510: 
 1511:     # Add the text
 1512:     if ($text ne "")
 1513:     {
 1514: 	$template .= 
 1515:   "<table bgcolor='#337733' cellspacing='1' cellpadding='1' border='0'><tr>".
 1516:   "<td bgcolor='#448844'><a target=\"_top\" href=\"$link\"><span style=\"color:#FFFFFF; font-size:10pt;\">$text</span></a>";
 1517:     }
 1518: 
 1519:     # Add the graphic
 1520:     my $title = &mt('View the FAQ');
 1521:     my $faqicon=&lonhttpdurl("/adm/lonMisc/smallFAQ.gif");
 1522:     $template .= <<"ENDTEMPLATE";
 1523:  <a target="_top" href="$link" title="$title"><img src="$faqicon" border="0" alt="(FAQ: $topic)" /></a>
 1524: ENDTEMPLATE
 1525:     if ($text ne '') { $template.='</td></tr></table>' };
 1526:     return $template;
 1527: 
 1528: }
 1529: 
 1530: ###############################################################
 1531: ###############################################################
 1532: 
 1533: =pod
 1534: 
 1535: =item * &change_content_javascript():
 1536: 
 1537: This and the next function allow you to create small sections of an
 1538: otherwise static HTML page that you can update on the fly with
 1539: Javascript, even in Netscape 4.
 1540: 
 1541: The Javascript fragment returned by this function (no E<lt>scriptE<gt> tag)
 1542: must be written to the HTML page once. It will prove the Javascript
 1543: function "change(name, content)". Calling the change function with the
 1544: name of the section 
 1545: you want to update, matching the name passed to C<changable_area>, and
 1546: the new content you want to put in there, will put the content into
 1547: that area.
 1548: 
 1549: B<Note>: Netscape 4 only reserves enough space for the changable area
 1550: to contain room for the original contents. You need to "make space"
 1551: for whatever changes you wish to make, and be B<sure> to check your
 1552: code in Netscape 4. This feature in Netscape 4 is B<not> powerful;
 1553: it's adequate for updating a one-line status display, but little more.
 1554: This script will set the space to 100% width, so you only need to
 1555: worry about height in Netscape 4.
 1556: 
 1557: Modern browsers are much less limiting, and if you can commit to the
 1558: user not using Netscape 4, this feature may be used freely with
 1559: pretty much any HTML.
 1560: 
 1561: =cut
 1562: 
 1563: sub change_content_javascript {
 1564:     # If we're on Netscape 4, we need to use Layer-based code
 1565:     if ($env{'browser.type'} eq 'netscape' &&
 1566: 	$env{'browser.version'} =~ /^4\./) {
 1567: 	return (<<NETSCAPE4);
 1568: 	function change(name, content) {
 1569: 	    doc = document.layers[name+"___escape"].layers[0].document;
 1570: 	    doc.open();
 1571: 	    doc.write(content);
 1572: 	    doc.close();
 1573: 	}
 1574: NETSCAPE4
 1575:     } else {
 1576: 	# Otherwise, we need to use semi-standards-compliant code
 1577: 	# (technically, "innerHTML" isn't standard but the equivalent
 1578: 	# is really scary, and every useful browser supports it
 1579: 	return (<<DOMBASED);
 1580: 	function change(name, content) {
 1581: 	    element = document.getElementById(name);
 1582: 	    element.innerHTML = content;
 1583: 	}
 1584: DOMBASED
 1585:     }
 1586: }
 1587: 
 1588: =pod
 1589: 
 1590: =item * &changable_area($name,$origContent):
 1591: 
 1592: This provides a "changable area" that can be modified on the fly via
 1593: the Javascript code provided in C<change_content_javascript>. $name is
 1594: the name you will use to reference the area later; do not repeat the
 1595: same name on a given HTML page more then once. $origContent is what
 1596: the area will originally contain, which can be left blank.
 1597: 
 1598: =cut
 1599: 
 1600: sub changable_area {
 1601:     my ($name, $origContent) = @_;
 1602: 
 1603:     if ($env{'browser.type'} eq 'netscape' &&
 1604: 	$env{'browser.version'} =~ /^4\./) {
 1605: 	# If this is netscape 4, we need to use the Layer tag
 1606: 	return "<ilayer width='100%' id='${name}___escape' overflow='none'><layer width='100%' id='$name' overflow='none'>$origContent</layer></ilayer>";
 1607:     } else {
 1608: 	return "<span id='$name'>$origContent</span>";
 1609:     }
 1610: }
 1611: 
 1612: =pod
 1613: 
 1614: =item * &viewport_geometry_js 
 1615: 
 1616: Provides javascript object (Geometry) which can provide information about the viewport geometry for the client browser.
 1617: 
 1618: =cut
 1619: 
 1620: 
 1621: sub viewport_geometry_js { 
 1622:     return <<"GEOMETRY";
 1623: var Geometry = {};
 1624: function init_geometry() {
 1625:     if (Geometry.init) { return };
 1626:     Geometry.init=1;
 1627:     if (window.innerHeight) {
 1628:         Geometry.getViewportHeight   = function() { return window.innerHeight; };
 1629:         Geometry.getViewportWidth   = function() { return window.innerWidth; };
 1630:         Geometry.getHorizontalScroll = function() { return window.pageXOffset; };
 1631:         Geometry.getVerticalScroll   = function() { return window.pageYOffset; };
 1632:     }
 1633:     else if (document.documentElement && document.documentElement.clientHeight) {
 1634:         Geometry.getViewportHeight =
 1635:             function() { return document.documentElement.clientHeight; };
 1636:         Geometry.getViewportWidth =
 1637:             function() { return document.documentElement.clientWidth; };
 1638: 
 1639:         Geometry.getHorizontalScroll =
 1640:             function() { return document.documentElement.scrollLeft; };
 1641:         Geometry.getVerticalScroll =
 1642:             function() { return document.documentElement.scrollTop; };
 1643:     }
 1644:     else if (document.body.clientHeight) {
 1645:         Geometry.getViewportHeight =
 1646:             function() { return document.body.clientHeight; };
 1647:         Geometry.getViewportWidth =
 1648:             function() { return document.body.clientWidth; };
 1649:         Geometry.getHorizontalScroll =
 1650:             function() { return document.body.scrollLeft; };
 1651:         Geometry.getVerticalScroll =
 1652:             function() { return document.body.scrollTop; };
 1653:     }
 1654: }
 1655: 
 1656: GEOMETRY
 1657: }
 1658: 
 1659: =pod
 1660: 
 1661: =item * &viewport_size_js()
 1662: 
 1663: Provides a javascript function to set values of two form elements - width and height (elements are passed in as arguments to the javascript function) to the dimensions of the user's browser window. 
 1664: 
 1665: =cut
 1666: 
 1667: sub viewport_size_js {
 1668:     my $geometry = &viewport_geometry_js();
 1669:     return <<"DIMS";
 1670: 
 1671: $geometry
 1672: 
 1673: function getViewportDims(width,height) {
 1674:     init_geometry();
 1675:     width.value = Geometry.getViewportWidth();
 1676:     height.value = Geometry.getViewportHeight();
 1677:     return;
 1678: }
 1679: 
 1680: DIMS
 1681: }
 1682: 
 1683: =pod
 1684: 
 1685: =item * &resize_textarea_js()
 1686: 
 1687: emits the needed javascript to resize a textarea to be as big as possible
 1688: 
 1689: creates a function resize_textrea that takes two IDs first should be
 1690: the id of the element to resize, second should be the id of a div that
 1691: surrounds everything that comes after the textarea, this routine needs
 1692: to be attached to the <body> for the onload and onresize events.
 1693: 
 1694: =back
 1695: 
 1696: =cut
 1697: 
 1698: sub resize_textarea_js {
 1699:     my $geometry = &viewport_geometry_js();
 1700:     return <<"RESIZE";
 1701:     <script type="text/javascript">
 1702: // <![CDATA[
 1703: $geometry
 1704: 
 1705: function getX(element) {
 1706:     var x = 0;
 1707:     while (element) {
 1708: 	x += element.offsetLeft;
 1709: 	element = element.offsetParent;
 1710:     }
 1711:     return x;
 1712: }
 1713: function getY(element) {
 1714:     var y = 0;
 1715:     while (element) {
 1716: 	y += element.offsetTop;
 1717: 	element = element.offsetParent;
 1718:     }
 1719:     return y;
 1720: }
 1721: 
 1722: 
 1723: function resize_textarea(textarea_id,bottom_id) {
 1724:     init_geometry();
 1725:     var textarea        = document.getElementById(textarea_id);
 1726:     //alert(textarea);
 1727: 
 1728:     var textarea_top    = getY(textarea);
 1729:     var textarea_height = textarea.offsetHeight;
 1730:     var bottom          = document.getElementById(bottom_id);
 1731:     var bottom_top      = getY(bottom);
 1732:     var bottom_height   = bottom.offsetHeight;
 1733:     var window_height   = Geometry.getViewportHeight();
 1734:     var fudge           = 23;
 1735:     var new_height      = window_height-fudge-textarea_top-bottom_height;
 1736:     if (new_height < 300) {
 1737: 	new_height = 300;
 1738:     }
 1739:     textarea.style.height=new_height+'px';
 1740: }
 1741: // ]]>
 1742: </script>
 1743: RESIZE
 1744: 
 1745: }
 1746: 
 1747: sub colorfuleditor_js {
 1748:     return <<"COLORFULEDIT"
 1749: <script type="text/javascript">
 1750: // <![CDATA[>
 1751:     function fold_box(curDepth, lastresource){
 1752: 
 1753:     // we need a list because there can be several blocks you need to fold in one tag
 1754:         var block = document.getElementsByName('foldblock_'+curDepth);
 1755:     // but there is only one folding button per tag
 1756:         var foldbutton = document.getElementById('folding_btn_'+curDepth);
 1757: 
 1758:         if(block.item(0).style.display == 'none'){
 1759: 
 1760:             foldbutton.value = '@{[&mt("Hide")]}';
 1761:             for (i = 0; i < block.length; i++){
 1762:                 block.item(i).style.display = '';
 1763:             }
 1764:         }else{
 1765: 
 1766:             foldbutton.value = '@{[&mt("Show")]}';
 1767:             for (i = 0; i < block.length; i++){
 1768:                 // block.item(i).style.visibility = 'collapse';
 1769:                 block.item(i).style.display = 'none';
 1770:             }
 1771:         };
 1772:         saveState(lastresource);
 1773:     }
 1774: 
 1775:     function saveState (lastresource) {
 1776: 
 1777:         var tag_list = getTagList();
 1778:         if(tag_list != null){
 1779:             var timestamp = new Date().getTime();
 1780:             var key = lastresource;
 1781: 
 1782:             // the value pattern is: 'time;key1,value1;key2,value2; ... '
 1783:             // starting with timestamp
 1784:             var value = timestamp+';';
 1785: 
 1786:             // building the list of key-value pairs
 1787:             for(var i = 0; i < tag_list.length; i++){
 1788:                 value += tag_list[i]+',';
 1789:                 value += document.getElementsByName(tag_list[i])[0].style.display+';';
 1790:             }
 1791: 
 1792:             // only iterate whole storage if nothing to override
 1793:             if(localStorage.getItem(key) == null){
 1794: 
 1795:                 // prevent storage from growing large
 1796:                 if(localStorage.length > 50){
 1797:                     var regex_getTimestamp = /^(?:\d)+;/;
 1798:                     var oldest_timestamp = regex_getTimestamp.exec(localStorage.key(0));
 1799:                     var oldest_key;
 1800: 
 1801:                     for(var i = 1; i < localStorage.length; i++){
 1802:                         if (regex_getTimestamp.exec(localStorage.key(i)) < oldest_timestamp) {
 1803:                             oldest_key = localStorage.key(i);
 1804:                             oldest_timestamp = regex_getTimestamp.exec(oldest_key);
 1805:                         }
 1806:                     }
 1807:                     localStorage.removeItem(oldest_key);
 1808:                 }
 1809:             }
 1810:             localStorage.setItem(key,value);
 1811:         }
 1812:     }
 1813: 
 1814:     // restore folding status of blocks (on page load)
 1815:     function restoreState (lastresource) {
 1816:         if(localStorage.getItem(lastresource) != null){
 1817:             var key = lastresource;
 1818:             var value = localStorage.getItem(key);
 1819:             var regex_delTimestamp = /^\d+;/;
 1820: 
 1821:             value.replace(regex_delTimestamp, '');
 1822: 
 1823:             var valueArr = value.split(';');
 1824:             var pairs;
 1825:             var elements;
 1826:             for (var i = 0; i < valueArr.length; i++){
 1827:                 pairs = valueArr[i].split(',');
 1828:                 elements = document.getElementsByName(pairs[0]);
 1829: 
 1830:                 for (var j = 0; j < elements.length; j++){
 1831:                     elements[j].style.display = pairs[1];
 1832:                     if (pairs[1] == "none"){
 1833:                         var regex_id = /([_\\d]+)\$/;
 1834:                         regex_id.exec(pairs[0]);
 1835:                         document.getElementById("folding_btn"+RegExp.\$1).value = "Show";
 1836:                     }
 1837:                 }
 1838:             }
 1839:         }
 1840:     }
 1841: 
 1842:     function getTagList () {
 1843: 
 1844:         var stringToSearch = document.lonhomework.innerHTML;
 1845: 
 1846:         var ret = new Array();
 1847:         var regex_findBlock = /(foldblock_.*?)"/g;
 1848:         var tag_list = stringToSearch.match(regex_findBlock);
 1849: 
 1850:         if(tag_list != null){
 1851:             for(var i = 0; i < tag_list.length; i++){
 1852:                 ret.push(tag_list[i].replace(/"/, ''));
 1853:             }
 1854:         }
 1855:         return ret;
 1856:     }
 1857: 
 1858:     function saveScrollPosition (resource) {
 1859:         var tag_list = getTagList();
 1860: 
 1861:         // we dont always want to jump to the first block
 1862:         // 170 is roughly above the "Problem Editing" header. we just want to save if the user scrolled down further than this
 1863:         if(\$(window).scrollTop() > 170){
 1864:             if(tag_list != null){
 1865:                 var result;
 1866:                 for(var i = 0; i < tag_list.length; i++){
 1867:                     if(isElementInViewport(tag_list[i])){
 1868:                         result += tag_list[i]+';';
 1869:                     }
 1870:                 }
 1871:                 sessionStorage.setItem('anchor_'+resource, result);
 1872:             }
 1873:         } else {
 1874:             // we dont need to save zero, just delete the item to leave everything tidy
 1875:             sessionStorage.removeItem('anchor_'+resource);
 1876:         }
 1877:     }
 1878: 
 1879:     function restoreScrollPosition(resource){
 1880: 
 1881:         var elem = sessionStorage.getItem('anchor_'+resource);
 1882:         if(elem != null){
 1883:             var tag_list = elem.split(';');
 1884:             var elem_list;
 1885: 
 1886:             for(var i = 0; i < tag_list.length; i++){
 1887:                 elem_list = document.getElementsByName(tag_list[i]);
 1888: 
 1889:                 if(elem_list.length > 0){
 1890:                     elem = elem_list[0];
 1891:                     break;
 1892:                 }
 1893:             }
 1894:             elem.scrollIntoView();
 1895:         }
 1896:     }
 1897: 
 1898:     function isElementInViewport(el) {
 1899: 
 1900:         // change to last element instead of first
 1901:         var elem = document.getElementsByName(el);
 1902:         var rect = elem[0].getBoundingClientRect();
 1903: 
 1904:         return (
 1905:             rect.top >= 0 &&
 1906:             rect.left >= 0 &&
 1907:             rect.bottom <= (window.innerHeight || document.documentElement.clientHeight) && /*or $(window).height() */
 1908:             rect.right <= (window.innerWidth || document.documentElement.clientWidth) /*or $(window).width() */
 1909:         );
 1910:     }
 1911: 
 1912:     function autosize(depth){
 1913:         var cmInst = window['cm'+depth];
 1914:         var fitsizeButton = document.getElementById('fitsize'+depth);
 1915: 
 1916:         // is fixed size, switching to dynamic
 1917:         if (sessionStorage.getItem("autosized_"+depth) == null) {
 1918:             cmInst.setSize("","auto");
 1919:             fitsizeButton.value = "@{[&mt('Fixed size')]}";
 1920:             sessionStorage.setItem("autosized_"+depth, "yes");
 1921: 
 1922:         // is dynamic size, switching to fixed
 1923:         } else {
 1924:             cmInst.setSize("","300px");
 1925:             fitsizeButton.value = "@{[&mt('Dynamic size')]}";
 1926:             sessionStorage.removeItem("autosized_"+depth);
 1927:         }
 1928:     }
 1929: 
 1930: 
 1931: 
 1932: // ]]>
 1933: </script>
 1934: COLORFULEDIT
 1935: }
 1936: 
 1937: sub xmleditor_js {
 1938:     return <<XMLEDIT
 1939: <script type="text/javascript" src="/adm/jQuery/addons/jquery-scrolltofixed.js"></script>
 1940: <script type="text/javascript">
 1941: // <![CDATA[>
 1942: 
 1943:     function saveScrollPosition (resource) {
 1944: 
 1945:         var scrollPos = \$(window).scrollTop();
 1946:         sessionStorage.setItem(resource,scrollPos);
 1947:     }
 1948: 
 1949:     function restoreScrollPosition(resource){
 1950: 
 1951:         var scrollPos = sessionStorage.getItem(resource);
 1952:         \$(window).scrollTop(scrollPos);
 1953:     }
 1954: 
 1955:     // unless internet explorer
 1956:     if (!(window.navigator.appName == "Microsoft Internet Explorer" && (document.documentMode || document.compatMode))){
 1957: 
 1958:         \$(document).ready(function() {
 1959:              \$(".LC_edit_actionbar").scrollToFixed(\{zIndex: 100\});
 1960:         });
 1961:     }
 1962: 
 1963:     // inserts text at cursor position into codemirror (xml editor only)
 1964:     function insertText(text){
 1965:         cm.focus();
 1966:         var curPos = cm.getCursor();
 1967:         cm.replaceRange(text.replace(/ESCAPEDSCRIPT/g,'script'), {line: curPos.line,ch: curPos.ch});
 1968:     }
 1969: // ]]>
 1970: </script>
 1971: XMLEDIT
 1972: }
 1973: 
 1974: sub insert_folding_button {
 1975:     my $curDepth = $Apache::lonxml::curdepth;
 1976:     my $lastresource = $env{'request.ambiguous'};
 1977: 
 1978:     return "<input type=\"button\" id=\"folding_btn_$curDepth\"
 1979:             value=\"".&mt('Hide')."\" onclick=\"fold_box('$curDepth','$lastresource')\">";
 1980: }
 1981: 
 1982: 
 1983: =pod
 1984: 
 1985: =head1 Excel and CSV file utility routines
 1986: 
 1987: =cut
 1988: 
 1989: ###############################################################
 1990: ###############################################################
 1991: 
 1992: =pod
 1993: 
 1994: =over 4
 1995: 
 1996: =item * &csv_translate($text) 
 1997: 
 1998: Translate $text to allow it to be output as a 'comma separated values' 
 1999: format.
 2000: 
 2001: =cut
 2002: 
 2003: ###############################################################
 2004: ###############################################################
 2005: sub csv_translate {
 2006:     my $text = shift;
 2007:     $text =~ s/\"/\"\"/g;
 2008:     $text =~ s/\n/ /g;
 2009:     return $text;
 2010: }
 2011: 
 2012: ###############################################################
 2013: ###############################################################
 2014: 
 2015: =pod
 2016: 
 2017: =item * &define_excel_formats()
 2018: 
 2019: Define some commonly used Excel cell formats.
 2020: 
 2021: Currently supported formats:
 2022: 
 2023: =over 4
 2024: 
 2025: =item header
 2026: 
 2027: =item bold
 2028: 
 2029: =item h1
 2030: 
 2031: =item h2
 2032: 
 2033: =item h3
 2034: 
 2035: =item h4
 2036: 
 2037: =item i
 2038: 
 2039: =item date
 2040: 
 2041: =back
 2042: 
 2043: Inputs: $workbook
 2044: 
 2045: Returns: $format, a hash reference.
 2046: 
 2047: 
 2048: =cut
 2049: 
 2050: ###############################################################
 2051: ###############################################################
 2052: sub define_excel_formats {
 2053:     my ($workbook) = @_;
 2054:     my $format;
 2055:     $format->{'header'} = $workbook->add_format(bold      => 1, 
 2056:                                                 bottom    => 1,
 2057:                                                 align     => 'center');
 2058:     $format->{'bold'} = $workbook->add_format(bold=>1);
 2059:     $format->{'h1'}   = $workbook->add_format(bold=>1, size=>18);
 2060:     $format->{'h2'}   = $workbook->add_format(bold=>1, size=>16);
 2061:     $format->{'h3'}   = $workbook->add_format(bold=>1, size=>14);
 2062:     $format->{'h4'}   = $workbook->add_format(bold=>1, size=>12);
 2063:     $format->{'i'}    = $workbook->add_format(italic=>1);
 2064:     $format->{'date'} = $workbook->add_format(num_format=>
 2065:                                             'mm/dd/yyyy hh:mm:ss');
 2066:     return $format;
 2067: }
 2068: 
 2069: ###############################################################
 2070: ###############################################################
 2071: 
 2072: =pod
 2073: 
 2074: =item * &create_workbook()
 2075: 
 2076: Create an Excel worksheet.  If it fails, output message on the
 2077: request object and return undefs.
 2078: 
 2079: Inputs: Apache request object
 2080: 
 2081: Returns (undef) on failure, 
 2082:     Excel worksheet object, scalar with filename, and formats 
 2083:     from &Apache::loncommon::define_excel_formats on success
 2084: 
 2085: =cut
 2086: 
 2087: ###############################################################
 2088: ###############################################################
 2089: sub create_workbook {
 2090:     my ($r) = @_;
 2091:         #
 2092:     # Create the excel spreadsheet
 2093:     my $filename = '/prtspool/'.
 2094:         $env{'user.name'}.'_'.$env{'user.domain'}.'_'.
 2095:         time.'_'.rand(1000000000).'.xls';
 2096:     my $workbook  = Spreadsheet::WriteExcel->new('/home/httpd'.$filename);
 2097:     if (! defined($workbook)) {
 2098:         $r->log_error("Error creating excel spreadsheet $filename: $!");
 2099:         $r->print(
 2100:             '<p class="LC_error">'
 2101:            .&mt('Problems occurred in creating the new Excel file.')
 2102:            .' '.&mt('This error has been logged.')
 2103:            .' '.&mt('Please alert your LON-CAPA administrator.')
 2104:            .'</p>'
 2105:         );
 2106:         return (undef);
 2107:     }
 2108:     #
 2109:     $workbook->set_tempdir(LONCAPA::tempdir());
 2110:     #
 2111:     my $format = &Apache::loncommon::define_excel_formats($workbook);
 2112:     return ($workbook,$filename,$format);
 2113: }
 2114: 
 2115: ###############################################################
 2116: ###############################################################
 2117: 
 2118: =pod
 2119: 
 2120: =item * &create_text_file()
 2121: 
 2122: Create a file to write to and eventually make available to the user.
 2123: If file creation fails, outputs an error message on the request object and 
 2124: return undefs.
 2125: 
 2126: Inputs: Apache request object, and file suffix
 2127: 
 2128: Returns (undef) on failure, 
 2129:     Filehandle and filename on success.
 2130: 
 2131: =cut
 2132: 
 2133: ###############################################################
 2134: ###############################################################
 2135: sub create_text_file {
 2136:     my ($r,$suffix) = @_;
 2137:     if (! defined($suffix)) { $suffix = 'txt'; };
 2138:     my $fh;
 2139:     my $filename = '/prtspool/'.
 2140:         $env{'user.name'}.'_'.$env{'user.domain'}.'_'.
 2141:         time.'_'.rand(1000000000).'.'.$suffix;
 2142:     $fh = Apache::File->new('>/home/httpd'.$filename);
 2143:     if (! defined($fh)) {
 2144:         $r->log_error("Couldn't open $filename for output $!");
 2145:         $r->print(
 2146:             '<p class="LC_error">'
 2147:            .&mt('Problems occurred in creating the output file.')
 2148:            .' '.&mt('This error has been logged.')
 2149:            .' '.&mt('Please alert your LON-CAPA administrator.')
 2150:            .'</p>'
 2151:         );
 2152:     }
 2153:     return ($fh,$filename)
 2154: }
 2155: 
 2156: 
 2157: =pod 
 2158: 
 2159: =back
 2160: 
 2161: =cut
 2162: 
 2163: ###############################################################
 2164: ##        Home server <option> list generating code          ##
 2165: ###############################################################
 2166: 
 2167: # ------------------------------------------
 2168: 
 2169: sub domain_select {
 2170:     my ($name,$value,$multiple)=@_;
 2171:     my %domains=map { 
 2172: 	$_ => $_.' '. &Apache::lonnet::domain($_,'description') 
 2173:     } &Apache::lonnet::all_domains();
 2174:     if ($multiple) {
 2175: 	$domains{''}=&mt('Any domain');
 2176: 	$domains{'select_form_order'} = [sort {lc($a) cmp lc($b) } (keys(%domains))];
 2177: 	return &multiple_select_form($name,$value,4,\%domains);
 2178:     } else {
 2179: 	$domains{'select_form_order'} = [sort {lc($a) cmp lc($b) } (keys(%domains))];
 2180: 	return &select_form($name,$value,\%domains);
 2181:     }
 2182: }
 2183: 
 2184: #-------------------------------------------
 2185: 
 2186: =pod
 2187: 
 2188: =head1 Routines for form select boxes
 2189: 
 2190: =over 4
 2191: 
 2192: =item * &multiple_select_form($name,$value,$size,$hash,$order)
 2193: 
 2194: Returns a string containing a <select> element int multiple mode
 2195: 
 2196: 
 2197: Args:
 2198:   $name - name of the <select> element
 2199:   $value - scalar or array ref of values that should already be selected
 2200:   $size - number of rows long the select element is
 2201:   $hash - the elements should be 'option' => 'shown text'
 2202:           (shown text should already have been &mt())
 2203:   $order - (optional) array ref of the order to show the elements in
 2204: 
 2205: =cut
 2206: 
 2207: #-------------------------------------------
 2208: sub multiple_select_form {
 2209:     my ($name,$value,$size,$hash,$order)=@_;
 2210:     my %selected = map { $_ => 1 } ref($value)?@{$value}:($value);
 2211:     my $output='';
 2212:     if (! defined($size)) {
 2213:         $size = 4;
 2214:         if (scalar(keys(%$hash))<4) {
 2215:             $size = scalar(keys(%$hash));
 2216:         }
 2217:     }
 2218:     $output.="\n".'<select name="'.$name.'" size="'.$size.'" multiple="multiple">';
 2219:     my @order;
 2220:     if (ref($order) eq 'ARRAY')  {
 2221:         @order = @{$order};
 2222:     } else {
 2223:         @order = sort(keys(%$hash));
 2224:     }
 2225:     if (exists($$hash{'select_form_order'})) {
 2226:         @order = @{$$hash{'select_form_order'}};
 2227:     }
 2228:         
 2229:     foreach my $key (@order) {
 2230:         $output.='<option value="'.&HTML::Entities::encode($key,'"<>&').'" ';
 2231:         $output.='selected="selected" ' if ($selected{$key});
 2232:         $output.='>'.$hash->{$key}."</option>\n";
 2233:     }
 2234:     $output.="</select>\n";
 2235:     return $output;
 2236: }
 2237: 
 2238: #-------------------------------------------
 2239: 
 2240: =pod
 2241: 
 2242: =item * &select_form($defdom,$name,$hashref,$onchange)
 2243: 
 2244: Returns a string containing a <select name='$name' size='1'> form to 
 2245: allow a user to select options from a ref to a hash containing:
 2246: option_name => displayed text. An optional $onchange can include
 2247: a javascript onchange item, e.g., onchange="this.form.submit();"  
 2248: 
 2249: See lonrights.pm for an example invocation and use.
 2250: 
 2251: =cut
 2252: 
 2253: #-------------------------------------------
 2254: sub select_form {
 2255:     my ($def,$name,$hashref,$onchange) = @_;
 2256:     return unless (ref($hashref) eq 'HASH');
 2257:     if ($onchange) {
 2258:         $onchange = ' onchange="'.$onchange.'"';
 2259:     }
 2260:     my $selectform = "<select name=\"$name\" size=\"1\"$onchange>\n";
 2261:     my @keys;
 2262:     if (exists($hashref->{'select_form_order'})) {
 2263: 	@keys=@{$hashref->{'select_form_order'}};
 2264:     } else {
 2265: 	@keys=sort(keys(%{$hashref}));
 2266:     }
 2267:     foreach my $key (@keys) {
 2268:         $selectform.=
 2269: 	    '<option value="'.&HTML::Entities::encode($key,'"<>&').'" '.
 2270:             ($key eq $def ? 'selected="selected" ' : '').
 2271:                 ">".$hashref->{$key}."</option>\n";
 2272:     }
 2273:     $selectform.="</select>";
 2274:     return $selectform;
 2275: }
 2276: 
 2277: # For display filters
 2278: 
 2279: sub display_filter {
 2280:     my ($context) = @_;
 2281:     if (!$env{'form.show'}) { $env{'form.show'}=10; }
 2282:     if (!$env{'form.displayfilter'}) { $env{'form.displayfilter'}='currentfolder'; }
 2283:     my $phraseinput = 'hidden';
 2284:     my $includeinput = 'hidden';
 2285:     my ($checked,$includetypestext);
 2286:     if ($env{'form.displayfilter'} eq 'containing') {
 2287:         $phraseinput = 'text'; 
 2288:         if ($context eq 'parmslog') {
 2289:             $includeinput = 'checkbox';
 2290:             if ($env{'form.includetypes'}) {
 2291:                 $checked = ' checked="checked"';
 2292:             }
 2293:             $includetypestext = &mt('Include parameter types');
 2294:         }
 2295:     } else {
 2296:         $includetypestext = '&nbsp;';
 2297:     }
 2298:     my ($additional,$secondid,$thirdid);
 2299:     if ($context eq 'parmslog') {
 2300:         $additional = 
 2301:             '<label><input type="'.$includeinput.'" name="includetypes"'. 
 2302:             $checked.' name="includetypes" value="1" id="includetypes" />'.
 2303:             '&nbsp;<span id="includetypestext">'.$includetypestext.'</span>'.
 2304:             '</label>';
 2305:         $secondid = 'includetypes';
 2306:         $thirdid = 'includetypestext';
 2307:     }
 2308:     my $onchange = "javascript:toggleHistoryOptions(this,'containingphrase','$context',
 2309:                                                     '$secondid','$thirdid')";
 2310:     return '<span class="LC_nobreak"><label>'.&mt('Records: [_1]',
 2311: 			       &Apache::lonmeta::selectbox('show',$env{'form.show'},undef,
 2312: 							   (&mt('all'),10,20,50,100,1000,10000))).
 2313: 	   '</label></span> <span class="LC_nobreak">'.
 2314:            &mt('Filter: [_1]',
 2315: 	   &select_form($env{'form.displayfilter'},
 2316: 			'displayfilter',
 2317: 			{'currentfolder' => 'Current folder/page',
 2318: 			 'containing' => 'Containing phrase',
 2319: 			 'none' => 'None'},$onchange)).'&nbsp;'.
 2320: 			 '<input type="'.$phraseinput.'" name="containingphrase" id="containingphrase" size="30" value="'.
 2321:                          &HTML::Entities::encode($env{'form.containingphrase'}).
 2322:                          '" />'.$additional;
 2323: }
 2324: 
 2325: sub display_filter_js {
 2326:     my $includetext = &mt('Include parameter types');
 2327:     return <<"ENDJS";
 2328:   
 2329: function toggleHistoryOptions(setter,firstid,context,secondid,thirdid) {
 2330:     var firstType = 'hidden';
 2331:     if (setter.options[setter.selectedIndex].value == 'containing') {
 2332:         firstType = 'text';
 2333:     }
 2334:     firstObject = document.getElementById(firstid);
 2335:     if (typeof(firstObject) == 'object') {
 2336:         if (firstObject.type != firstType) {
 2337:             changeInputType(firstObject,firstType);
 2338:         }
 2339:     }
 2340:     if (context == 'parmslog') {
 2341:         var secondType = 'hidden';
 2342:         if (firstType == 'text') {
 2343:             secondType = 'checkbox';
 2344:         }
 2345:         secondObject = document.getElementById(secondid);  
 2346:         if (typeof(secondObject) == 'object') {
 2347:             if (secondObject.type != secondType) {
 2348:                 changeInputType(secondObject,secondType);
 2349:             }
 2350:         }
 2351:         var textItem = document.getElementById(thirdid);
 2352:         var currtext = textItem.innerHTML;
 2353:         var newtext;
 2354:         if (firstType == 'text') {
 2355:             newtext = '$includetext';
 2356:         } else {
 2357:             newtext = '&nbsp;';
 2358:         }
 2359:         if (currtext != newtext) {
 2360:             textItem.innerHTML = newtext;
 2361:         }
 2362:     }
 2363:     return;
 2364: }
 2365: 
 2366: function changeInputType(oldObject,newType) {
 2367:     var newObject = document.createElement('input');
 2368:     newObject.type = newType;
 2369:     if (oldObject.size) {
 2370:         newObject.size = oldObject.size;
 2371:     }
 2372:     if (oldObject.value) {
 2373:         newObject.value = oldObject.value;
 2374:     }
 2375:     if (oldObject.name) {
 2376:         newObject.name = oldObject.name;
 2377:     }
 2378:     if (oldObject.id) {
 2379:         newObject.id = oldObject.id;
 2380:     }
 2381:     oldObject.parentNode.replaceChild(newObject,oldObject);
 2382:     return;
 2383: }
 2384: 
 2385: ENDJS
 2386: }
 2387: 
 2388: sub gradeleveldescription {
 2389:     my $gradelevel=shift;
 2390:     my %gradelevels=(0 => 'Not specified',
 2391: 		     1 => 'Grade 1',
 2392: 		     2 => 'Grade 2',
 2393: 		     3 => 'Grade 3',
 2394: 		     4 => 'Grade 4',
 2395: 		     5 => 'Grade 5',
 2396: 		     6 => 'Grade 6',
 2397: 		     7 => 'Grade 7',
 2398: 		     8 => 'Grade 8',
 2399: 		     9 => 'Grade 9',
 2400: 		     10 => 'Grade 10',
 2401: 		     11 => 'Grade 11',
 2402: 		     12 => 'Grade 12',
 2403: 		     13 => 'Grade 13',
 2404: 		     14 => '100 Level',
 2405: 		     15 => '200 Level',
 2406: 		     16 => '300 Level',
 2407: 		     17 => '400 Level',
 2408: 		     18 => 'Graduate Level');
 2409:     return &mt($gradelevels{$gradelevel});
 2410: }
 2411: 
 2412: sub select_level_form {
 2413:     my ($deflevel,$name)=@_;
 2414:     unless ($deflevel) { $deflevel=0; }
 2415:     my $selectform = "<select name=\"$name\" size=\"1\">\n";
 2416:     for (my $i=0; $i<=18; $i++) {
 2417:         $selectform.="<option value=\"$i\" ".
 2418:             ($i==$deflevel ? 'selected="selected" ' : '').
 2419:                 ">".&gradeleveldescription($i)."</option>\n";
 2420:     }
 2421:     $selectform.="</select>";
 2422:     return $selectform;
 2423: }
 2424: 
 2425: #-------------------------------------------
 2426: 
 2427: =pod
 2428: 
 2429: =item * &select_dom_form($defdom,$name,$includeempty,$showdomdesc,$onchange,$incdoms,$excdoms)
 2430: 
 2431: Returns a string containing a <select name='$name' size='1'> form to 
 2432: allow a user to select the domain to preform an operation in.  
 2433: See loncreateuser.pm for an example invocation and use.
 2434: 
 2435: If the $includeempty flag is set, it also includes an empty choice ("no domain
 2436: selected");
 2437: 
 2438: If the $showdomdesc flag is set, the domain name is followed by the domain description.
 2439: 
 2440: 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.
 2441: 
 2442: The optional $incdoms is a reference to an array of domains which will be the only available options.
 2443: 
 2444: The optional $excdoms is a reference to an array of domains which will be excluded from the available options. 
 2445: 
 2446: =cut
 2447: 
 2448: #-------------------------------------------
 2449: sub select_dom_form {
 2450:     my ($defdom,$name,$includeempty,$showdomdesc,$onchange,$incdoms,$excdoms) = @_;
 2451:     if ($onchange) {
 2452:         $onchange = ' onchange="'.$onchange.'"';
 2453:     }
 2454:     my (@domains,%exclude);
 2455:     if (ref($incdoms) eq 'ARRAY') {
 2456:         @domains = sort {lc($a) cmp lc($b)} (@{$incdoms});
 2457:     } else {
 2458:         @domains = sort {lc($a) cmp lc($b)} (&Apache::lonnet::all_domains());
 2459:     }
 2460:     if ($includeempty) { @domains=('',@domains); }
 2461:     if (ref($excdoms) eq 'ARRAY') {
 2462:         map { $exclude{$_} = 1; } @{$excdoms};
 2463:     }
 2464:     my $selectdomain = "<select name=\"$name\" size=\"1\"$onchange>\n";
 2465:     foreach my $dom (@domains) {
 2466:         next if ($exclude{$dom});
 2467:         $selectdomain.="<option value=\"$dom\" ".
 2468:             ($dom eq $defdom ? 'selected="selected" ' : '').'>'.$dom;
 2469:         if ($showdomdesc) {
 2470:             if ($dom ne '') {
 2471:                 my $domdesc = &Apache::lonnet::domain($dom,'description');
 2472:                 if ($domdesc ne '') {
 2473:                     $selectdomain .= ' ('.$domdesc.')';
 2474:                 }
 2475:             } 
 2476:         }
 2477:         $selectdomain .= "</option>\n";
 2478:     }
 2479:     $selectdomain.="</select>";
 2480:     return $selectdomain;
 2481: }
 2482: 
 2483: #-------------------------------------------
 2484: 
 2485: =pod
 2486: 
 2487: =item * &home_server_form_item($domain,$name,$defaultflag)
 2488: 
 2489: input: 4 arguments (two required, two optional) - 
 2490:     $domain - domain of new user
 2491:     $name - name of form element
 2492:     $default - Value of 'default' causes a default item to be first 
 2493:                             option, and selected by default. 
 2494:     $hide - Value of 'hide' causes hiding of the name of the server, 
 2495:                             if 1 server found, or default, if 0 found.
 2496: output: returns 2 items: 
 2497: (a) form element which contains either:
 2498:    (i) <select name="$name">
 2499:         <option value="$hostid1">$hostid $servers{$hostid}</option>
 2500:         <option value="$hostid2">$hostid $servers{$hostid}</option>       
 2501:        </select>
 2502:        form item if there are multiple library servers in $domain, or
 2503:    (ii) an <input type="hidden" name="$name" value="$hostid" /> form item 
 2504:        if there is only one library server in $domain.
 2505: 
 2506: (b) number of library servers found.
 2507: 
 2508: See loncreateuser.pm for example of use.
 2509: 
 2510: =cut
 2511: 
 2512: #-------------------------------------------
 2513: sub home_server_form_item {
 2514:     my ($domain,$name,$default,$hide) = @_;
 2515:     my %servers = &Apache::lonnet::get_servers($domain,'library');
 2516:     my $result;
 2517:     my $numlib = keys(%servers);
 2518:     if ($numlib > 1) {
 2519:         $result .= '<select name="'.$name.'" />'."\n";
 2520:         if ($default) {
 2521:             $result .= '<option value="default" selected="selected">'.&mt('default').
 2522:                        '</option>'."\n";
 2523:         }
 2524:         foreach my $hostid (sort(keys(%servers))) {
 2525:             $result.= '<option value="'.$hostid.'">'.
 2526: 	              $hostid.' '.$servers{$hostid}."</option>\n";
 2527:         }
 2528:         $result .= '</select>'."\n";
 2529:     } elsif ($numlib == 1) {
 2530:         my $hostid;
 2531:         foreach my $item (keys(%servers)) {
 2532:             $hostid = $item;
 2533:         }
 2534:         $result .= '<input type="hidden" name="'.$name.'" value="'.
 2535:                    $hostid.'" />';
 2536:                    if (!$hide) {
 2537:                        $result .= $hostid.' '.$servers{$hostid};
 2538:                    }
 2539:                    $result .= "\n";
 2540:     } elsif ($default) {
 2541:         $result .= '<input type="hidden" name="'.$name.
 2542:                    '" value="default" />';
 2543:                    if (!$hide) {
 2544:                        $result .= &mt('default');
 2545:                    }
 2546:                    $result .= "\n";
 2547:     }
 2548:     return ($result,$numlib);
 2549: }
 2550: 
 2551: =pod
 2552: 
 2553: =back 
 2554: 
 2555: =cut
 2556: 
 2557: ###############################################################
 2558: ##                  Decoding User Agent                      ##
 2559: ###############################################################
 2560: 
 2561: =pod
 2562: 
 2563: =head1 Decoding the User Agent
 2564: 
 2565: =over 4
 2566: 
 2567: =item * &decode_user_agent()
 2568: 
 2569: Inputs: $r
 2570: 
 2571: Outputs:
 2572: 
 2573: =over 4
 2574: 
 2575: =item * $httpbrowser
 2576: 
 2577: =item * $clientbrowser
 2578: 
 2579: =item * $clientversion
 2580: 
 2581: =item * $clientmathml
 2582: 
 2583: =item * $clientunicode
 2584: 
 2585: =item * $clientos
 2586: 
 2587: =item * $clientmobile
 2588: 
 2589: =item * $clientinfo
 2590: 
 2591: =item * $clientosversion
 2592: 
 2593: =back
 2594: 
 2595: =back 
 2596: 
 2597: =cut
 2598: 
 2599: ###############################################################
 2600: ###############################################################
 2601: sub decode_user_agent {
 2602:     my ($r)=@_;
 2603:     my @browsertype=split(/\&/,$Apache::lonnet::perlvar{"lonBrowsDet"});
 2604:     my %mathcap=split(/\&/,$$Apache::lonnet::perlvar{"lonMathML"});
 2605:     my $httpbrowser=$ENV{"HTTP_USER_AGENT"};
 2606:     if (!$httpbrowser && $r) { $httpbrowser=$r->header_in('User-Agent'); }
 2607:     my $clientbrowser='unknown';
 2608:     my $clientversion='0';
 2609:     my $clientmathml='';
 2610:     my $clientunicode='0';
 2611:     my $clientmobile=0;
 2612:     my $clientosversion='';
 2613:     for (my $i=0;$i<=$#browsertype;$i++) {
 2614:         my ($bname,$match,$notmatch,$vreg,$minv,$univ)=split(/\%/,$browsertype[$i]);
 2615: 	if (($httpbrowser=~/$match/i)  && ($httpbrowser!~/$notmatch/i)) {
 2616: 	    $clientbrowser=$bname;
 2617:             $httpbrowser=~/$vreg/i;
 2618: 	    $clientversion=$1;
 2619:             $clientmathml=($clientversion>=$minv);
 2620:             $clientunicode=($clientversion>=$univ);
 2621: 	}
 2622:     }
 2623:     my $clientos='unknown';
 2624:     my $clientinfo;
 2625:     if (($httpbrowser=~/linux/i) ||
 2626:         ($httpbrowser=~/unix/i) ||
 2627:         ($httpbrowser=~/ux/i) ||
 2628:         ($httpbrowser=~/solaris/i)) { $clientos='unix'; }
 2629:     if (($httpbrowser=~/vax/i) ||
 2630:         ($httpbrowser=~/vms/i)) { $clientos='vms'; }
 2631:     if ($httpbrowser=~/next/i) { $clientos='next'; }
 2632:     if (($httpbrowser=~/mac/i) ||
 2633:         ($httpbrowser=~/powerpc/i)) { $clientos='mac'; }
 2634:     if ($httpbrowser=~/win/i) {
 2635:         $clientos='win';
 2636:         if ($httpbrowser =~/Windows\s+NT\s+(\d+\.\d+)/i) {
 2637:             $clientosversion = $1;
 2638:         }
 2639:     }
 2640:     if ($httpbrowser=~/embed/i) { $clientos='pda'; }
 2641:     if ($httpbrowser=~/(Android|iPod|iPad|iPhone|webOS|Blackberry|Windows Phone|Opera m(?:ob|in)|Fennec)/i) {
 2642:         $clientmobile=lc($1);
 2643:     }
 2644:     if ($httpbrowser=~ m{Firefox/(\d+\.\d+)}) {
 2645:         $clientinfo = 'firefox-'.$1;
 2646:     } elsif ($httpbrowser=~ m{chromeframe/(\d+\.\d+)\.}) {
 2647:         $clientinfo = 'chromeframe-'.$1;
 2648:     }
 2649:     return ($httpbrowser,$clientbrowser,$clientversion,$clientmathml,
 2650:             $clientunicode,$clientos,$clientmobile,$clientinfo,
 2651:             $clientosversion);
 2652: }
 2653: 
 2654: ###############################################################
 2655: ##    Authentication changing form generation subroutines    ##
 2656: ###############################################################
 2657: ##
 2658: ## All of the authform_xxxxxxx subroutines take their inputs in a
 2659: ## hash, and have reasonable default values.
 2660: ##
 2661: ##    formname = the name given in the <form> tag.
 2662: #-------------------------------------------
 2663: 
 2664: =pod
 2665: 
 2666: =head1 Authentication Routines
 2667: 
 2668: =over 4
 2669: 
 2670: =item * &authform_xxxxxx()
 2671: 
 2672: The authform_xxxxxx subroutines provide javascript and html forms which 
 2673: handle some of the conveniences required for authentication forms.  
 2674: This is not an optimal method, but it works.  
 2675: 
 2676: =over 4
 2677: 
 2678: =item * authform_header
 2679: 
 2680: =item * authform_authorwarning
 2681: 
 2682: =item * authform_nochange
 2683: 
 2684: =item * authform_kerberos
 2685: 
 2686: =item * authform_internal
 2687: 
 2688: =item * authform_filesystem
 2689: 
 2690: =back
 2691: 
 2692: See loncreateuser.pm for invocation and use examples.
 2693: 
 2694: =cut
 2695: 
 2696: #-------------------------------------------
 2697: sub authform_header{  
 2698:     my %in = (
 2699:         formname => 'cu',
 2700:         kerb_def_dom => '',
 2701:         @_,
 2702:     );
 2703:     $in{'formname'} = 'document.' . $in{'formname'};
 2704:     my $result='';
 2705: 
 2706: #---------------------------------------------- Code for upper case translation
 2707:     my $Javascript_toUpperCase;
 2708:     unless ($in{kerb_def_dom}) {
 2709:         $Javascript_toUpperCase =<<"END";
 2710:         switch (choice) {
 2711:            case 'krb': currentform.elements[choicearg].value =
 2712:                currentform.elements[choicearg].value.toUpperCase();
 2713:                break;
 2714:            default:
 2715:         }
 2716: END
 2717:     } else {
 2718:         $Javascript_toUpperCase = "";
 2719:     }
 2720: 
 2721:     my $radioval = "'nochange'";
 2722:     if (defined($in{'curr_authtype'})) {
 2723:         if ($in{'curr_authtype'} ne '') {
 2724:             $radioval = "'".$in{'curr_authtype'}."arg'";
 2725:         }
 2726:     }
 2727:     my $argfield = 'null';
 2728:     if (defined($in{'mode'})) {
 2729:         if ($in{'mode'} eq 'modifycourse')  {
 2730:             if (defined($in{'curr_autharg'})) {
 2731:                 if ($in{'curr_autharg'} ne '') {
 2732:                     $argfield = "'$in{'curr_autharg'}'";
 2733:                 }
 2734:             }
 2735:         }
 2736:     }
 2737: 
 2738:     $result.=<<"END";
 2739: var current = new Object();
 2740: current.radiovalue = $radioval;
 2741: current.argfield = $argfield;
 2742: 
 2743: function changed_radio(choice,currentform) {
 2744:     var choicearg = choice + 'arg';
 2745:     // If a radio button in changed, we need to change the argfield
 2746:     if (current.radiovalue != choice) {
 2747:         current.radiovalue = choice;
 2748:         if (current.argfield != null) {
 2749:             currentform.elements[current.argfield].value = '';
 2750:         }
 2751:         if (choice == 'nochange') {
 2752:             current.argfield = null;
 2753:         } else {
 2754:             current.argfield = choicearg;
 2755:             switch(choice) {
 2756:                 case 'krb': 
 2757:                     currentform.elements[current.argfield].value = 
 2758:                         "$in{'kerb_def_dom'}";
 2759:                 break;
 2760:               default:
 2761:                 break;
 2762:             }
 2763:         }
 2764:     }
 2765:     return;
 2766: }
 2767: 
 2768: function changed_text(choice,currentform) {
 2769:     var choicearg = choice + 'arg';
 2770:     if (currentform.elements[choicearg].value !='') {
 2771:         $Javascript_toUpperCase
 2772:         // clear old field
 2773:         if ((current.argfield != choicearg) && (current.argfield != null)) {
 2774:             currentform.elements[current.argfield].value = '';
 2775:         }
 2776:         current.argfield = choicearg;
 2777:     }
 2778:     set_auth_radio_buttons(choice,currentform);
 2779:     return;
 2780: }
 2781: 
 2782: function set_auth_radio_buttons(newvalue,currentform) {
 2783:     var numauthchoices = currentform.login.length;
 2784:     if (typeof numauthchoices  == "undefined") {
 2785:         return;
 2786:     } 
 2787:     var i=0;
 2788:     while (i < numauthchoices) {
 2789:         if (currentform.login[i].value == newvalue) { break; }
 2790:         i++;
 2791:     }
 2792:     if (i == numauthchoices) {
 2793:         return;
 2794:     }
 2795:     current.radiovalue = newvalue;
 2796:     currentform.login[i].checked = true;
 2797:     return;
 2798: }
 2799: END
 2800:     return $result;
 2801: }
 2802: 
 2803: sub authform_authorwarning {
 2804:     my $result='';
 2805:     $result='<i>'.
 2806:         &mt('As a general rule, only authors or co-authors should be '.
 2807:             'filesystem authenticated '.
 2808:             '(which allows access to the server filesystem).')."</i>\n";
 2809:     return $result;
 2810: }
 2811: 
 2812: sub authform_nochange {
 2813:     my %in = (
 2814:               formname => 'document.cu',
 2815:               kerb_def_dom => 'MSU.EDU',
 2816:               @_,
 2817:           );
 2818:     my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'}); 
 2819:     my $result;
 2820:     if (!$authnum) {
 2821:         $result = &mt('Under your current role you are not permitted to change login settings for this user');
 2822:     } else {
 2823:         $result = '<label>'.&mt('[_1] Do not change login data',
 2824:                   '<input type="radio" name="login" value="nochange" '.
 2825:                   'checked="checked" onclick="'.
 2826:             "javascript:changed_radio('nochange',$in{'formname'});".'" />').
 2827: 	    '</label>';
 2828:     }
 2829:     return $result;
 2830: }
 2831: 
 2832: sub authform_kerberos {
 2833:     my %in = (
 2834:               formname => 'document.cu',
 2835:               kerb_def_dom => 'MSU.EDU',
 2836:               kerb_def_auth => 'krb4',
 2837:               @_,
 2838:               );
 2839:     my ($check4,$check5,$krbcheck,$krbarg,$krbver,$result,$authtype,
 2840:         $autharg,$jscall);
 2841:     my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
 2842:     if ($in{'kerb_def_auth'} eq 'krb5') {
 2843:        $check5 = ' checked="checked"';
 2844:     } else {
 2845:        $check4 = ' checked="checked"';
 2846:     }
 2847:     $krbarg = $in{'kerb_def_dom'};
 2848:     if (defined($in{'curr_authtype'})) {
 2849:         if ($in{'curr_authtype'} eq 'krb') {
 2850:             $krbcheck = ' checked="checked"';
 2851:             if (defined($in{'mode'})) {
 2852:                 if ($in{'mode'} eq 'modifyuser') {
 2853:                     $krbcheck = '';
 2854:                 }
 2855:             }
 2856:             if (defined($in{'curr_kerb_ver'})) {
 2857:                 if ($in{'curr_krb_ver'} eq '5') {
 2858:                     $check5 = ' checked="checked"';
 2859:                     $check4 = '';
 2860:                 } else {
 2861:                     $check4 = ' checked="checked"';
 2862:                     $check5 = '';
 2863:                 }
 2864:             }
 2865:             if (defined($in{'curr_autharg'})) {
 2866:                 $krbarg = $in{'curr_autharg'};
 2867:             }
 2868:             if (!$can_assign{'krb4'} && !$can_assign{'krb5'}) {
 2869:                 if (defined($in{'curr_autharg'})) {
 2870:                     $result = 
 2871:     &mt('Currently Kerberos authenticated with domain [_1] Version [_2].',
 2872:         $in{'curr_autharg'},$krbver);
 2873:                 } else {
 2874:                     $result =
 2875:     &mt('Currently Kerberos authenticated, Version [_1].',$krbver);
 2876:                 }
 2877:                 return $result; 
 2878:             }
 2879:         }
 2880:     } else {
 2881:         if ($authnum == 1) {
 2882:             $authtype = '<input type="hidden" name="login" value="krb" />';
 2883:         }
 2884:     }
 2885:     if (!$can_assign{'krb4'} && !$can_assign{'krb5'}) {
 2886:         return;
 2887:     } elsif ($authtype eq '') {
 2888:         if (defined($in{'mode'})) {
 2889:             if ($in{'mode'} eq 'modifycourse') {
 2890:                 if ($authnum == 1) {
 2891:                     $authtype = '<input type="radio" name="login" value="krb" />';
 2892:                 }
 2893:             }
 2894:         }
 2895:     }
 2896:     $jscall = "javascript:changed_radio('krb',$in{'formname'});";
 2897:     if ($authtype eq '') {
 2898:         $authtype = '<input type="radio" name="login" value="krb" '.
 2899:                     'onclick="'.$jscall.'" onchange="'.$jscall.'"'.
 2900:                     $krbcheck.' />';
 2901:     }
 2902:     if (($can_assign{'krb4'} && $can_assign{'krb5'}) ||
 2903:         ($can_assign{'krb4'} && !$can_assign{'krb5'} &&
 2904:          $in{'curr_authtype'} eq 'krb5') ||
 2905:         (!$can_assign{'krb4'} && $can_assign{'krb5'} &&
 2906:          $in{'curr_authtype'} eq 'krb4')) {
 2907:         $result .= &mt
 2908:         ('[_1] Kerberos authenticated with domain [_2] '.
 2909:          '[_3] Version 4 [_4] Version 5 [_5]',
 2910:          '<label>'.$authtype,
 2911:          '</label><input type="text" size="10" name="krbarg" '.
 2912:              'value="'.$krbarg.'" '.
 2913:              'onchange="'.$jscall.'" />',
 2914:          '<label><input type="radio" name="krbver" value="4" '.$check4.' />',
 2915:          '</label><label><input type="radio" name="krbver" value="5" '.$check5.' />',
 2916: 	 '</label>');
 2917:     } elsif ($can_assign{'krb4'}) {
 2918:         $result .= &mt
 2919:         ('[_1] Kerberos authenticated with domain [_2] '.
 2920:          '[_3] Version 4 [_4]',
 2921:          '<label>'.$authtype,
 2922:          '</label><input type="text" size="10" name="krbarg" '.
 2923:              'value="'.$krbarg.'" '.
 2924:              'onchange="'.$jscall.'" />',
 2925:          '<label><input type="hidden" name="krbver" value="4" />',
 2926:          '</label>');
 2927:     } elsif ($can_assign{'krb5'}) {
 2928:         $result .= &mt
 2929:         ('[_1] Kerberos authenticated with domain [_2] '.
 2930:          '[_3] Version 5 [_4]',
 2931:          '<label>'.$authtype,
 2932:          '</label><input type="text" size="10" name="krbarg" '.
 2933:              'value="'.$krbarg.'" '.
 2934:              'onchange="'.$jscall.'" />',
 2935:          '<label><input type="hidden" name="krbver" value="5" />',
 2936:          '</label>');
 2937:     }
 2938:     return $result;
 2939: }
 2940: 
 2941: sub authform_internal {
 2942:     my %in = (
 2943:                 formname => 'document.cu',
 2944:                 kerb_def_dom => 'MSU.EDU',
 2945:                 @_,
 2946:                 );
 2947:     my ($intcheck,$intarg,$result,$authtype,$autharg,$jscall);
 2948:     my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
 2949:     if (defined($in{'curr_authtype'})) {
 2950:         if ($in{'curr_authtype'} eq 'int') {
 2951:             if ($can_assign{'int'}) {
 2952:                 $intcheck = 'checked="checked" ';
 2953:                 if (defined($in{'mode'})) {
 2954:                     if ($in{'mode'} eq 'modifyuser') {
 2955:                         $intcheck = '';
 2956:                     }
 2957:                 }
 2958:                 if (defined($in{'curr_autharg'})) {
 2959:                     $intarg = $in{'curr_autharg'};
 2960:                 }
 2961:             } else {
 2962:                 $result = &mt('Currently internally authenticated.');
 2963:                 return $result;
 2964:             }
 2965:         }
 2966:     } else {
 2967:         if ($authnum == 1) {
 2968:             $authtype = '<input type="hidden" name="login" value="int" />';
 2969:         }
 2970:     }
 2971:     if (!$can_assign{'int'}) {
 2972:         return;
 2973:     } elsif ($authtype eq '') {
 2974:         if (defined($in{'mode'})) {
 2975:             if ($in{'mode'} eq 'modifycourse') {
 2976:                 if ($authnum == 1) {
 2977:                     $authtype = '<input type="radio" name="login" value="int" />';
 2978:                 }
 2979:             }
 2980:         }
 2981:     }
 2982:     $jscall = "javascript:changed_radio('int',$in{'formname'});";
 2983:     if ($authtype eq '') {
 2984:         $authtype = '<input type="radio" name="login" value="int" '.$intcheck.
 2985:                     ' onchange="'.$jscall.'" onclick="'.$jscall.'" />';
 2986:     }
 2987:     $autharg = '<input type="password" size="10" name="intarg" value="'.
 2988:                $intarg.'" onchange="'.$jscall.'" />';
 2989:     $result = &mt
 2990:         ('[_1] Internally authenticated (with initial password [_2])',
 2991:          '<label>'.$authtype,'</label>'.$autharg);
 2992:     $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>';
 2993:     return $result;
 2994: }
 2995: 
 2996: sub authform_local {
 2997:     my %in = (
 2998:               formname => 'document.cu',
 2999:               kerb_def_dom => 'MSU.EDU',
 3000:               @_,
 3001:               );
 3002:     my ($loccheck,$locarg,$result,$authtype,$autharg,$jscall);
 3003:     my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
 3004:     if (defined($in{'curr_authtype'})) {
 3005:         if ($in{'curr_authtype'} eq 'loc') {
 3006:             if ($can_assign{'loc'}) {
 3007:                 $loccheck = 'checked="checked" ';
 3008:                 if (defined($in{'mode'})) {
 3009:                     if ($in{'mode'} eq 'modifyuser') {
 3010:                         $loccheck = '';
 3011:                     }
 3012:                 }
 3013:                 if (defined($in{'curr_autharg'})) {
 3014:                     $locarg = $in{'curr_autharg'};
 3015:                 }
 3016:             } else {
 3017:                 $result = &mt('Currently using local (institutional) authentication.');
 3018:                 return $result;
 3019:             }
 3020:         }
 3021:     } else {
 3022:         if ($authnum == 1) {
 3023:             $authtype = '<input type="hidden" name="login" value="loc" />';
 3024:         }
 3025:     }
 3026:     if (!$can_assign{'loc'}) {
 3027:         return;
 3028:     } elsif ($authtype eq '') {
 3029:         if (defined($in{'mode'})) {
 3030:             if ($in{'mode'} eq 'modifycourse') {
 3031:                 if ($authnum == 1) {
 3032:                     $authtype = '<input type="radio" name="login" value="loc" />';
 3033:                 }
 3034:             }
 3035:         }
 3036:     }
 3037:     $jscall = "javascript:changed_radio('loc',$in{'formname'});";
 3038:     if ($authtype eq '') {
 3039:         $authtype = '<input type="radio" name="login" value="loc" '.
 3040:                     $loccheck.' onchange="'.$jscall.'" onclick="'.
 3041:                     $jscall.'" />';
 3042:     }
 3043:     $autharg = '<input type="text" size="10" name="locarg" value="'.
 3044:                $locarg.'" onchange="'.$jscall.'" />';
 3045:     $result = &mt('[_1] Local Authentication with argument [_2]',
 3046:                   '<label>'.$authtype,'</label>'.$autharg);
 3047:     return $result;
 3048: }
 3049: 
 3050: sub authform_filesystem {
 3051:     my %in = (
 3052:               formname => 'document.cu',
 3053:               kerb_def_dom => 'MSU.EDU',
 3054:               @_,
 3055:               );
 3056:     my ($fsyscheck,$result,$authtype,$autharg,$jscall);
 3057:     my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
 3058:     if (defined($in{'curr_authtype'})) {
 3059:         if ($in{'curr_authtype'} eq 'fsys') {
 3060:             if ($can_assign{'fsys'}) {
 3061:                 $fsyscheck = 'checked="checked" ';
 3062:                 if (defined($in{'mode'})) {
 3063:                     if ($in{'mode'} eq 'modifyuser') {
 3064:                         $fsyscheck = '';
 3065:                     }
 3066:                 }
 3067:             } else {
 3068:                 $result = &mt('Currently Filesystem Authenticated.');
 3069:                 return $result;
 3070:             }           
 3071:         }
 3072:     } else {
 3073:         if ($authnum == 1) {
 3074:             $authtype = '<input type="hidden" name="login" value="fsys" />';
 3075:         }
 3076:     }
 3077:     if (!$can_assign{'fsys'}) {
 3078:         return;
 3079:     } elsif ($authtype eq '') {
 3080:         if (defined($in{'mode'})) {
 3081:             if ($in{'mode'} eq 'modifycourse') {
 3082:                 if ($authnum == 1) {
 3083:                     $authtype = '<input type="radio" name="login" value="fsys" />';
 3084:                 }
 3085:             }
 3086:         }
 3087:     }
 3088:     $jscall = "javascript:changed_radio('fsys',$in{'formname'});";
 3089:     if ($authtype eq '') {
 3090:         $authtype = '<input type="radio" name="login" value="fsys" '.
 3091:                     $fsyscheck.' onchange="'.$jscall.'" onclick="'.
 3092:                     $jscall.'" />';
 3093:     }
 3094:     $autharg = '<input type="text" size="10" name="fsysarg" value=""'.
 3095:                ' onchange="'.$jscall.'" />';
 3096:     $result = &mt
 3097:         ('[_1] Filesystem Authenticated (with initial password [_2])',
 3098:          '<label><input type="radio" name="login" value="fsys" '.
 3099:          $fsyscheck.'onchange="'.$jscall.'" onclick="'.$jscall.'" />',
 3100:          '</label><input type="password" size="10" name="fsysarg" value="" '.
 3101:                   'onchange="'.$jscall.'" />');
 3102:     return $result;
 3103: }
 3104: 
 3105: sub get_assignable_auth {
 3106:     my ($dom) = @_;
 3107:     if ($dom eq '') {
 3108:         $dom = $env{'request.role.domain'};
 3109:     }
 3110:     my %can_assign = (
 3111:                           krb4 => 1,
 3112:                           krb5 => 1,
 3113:                           int  => 1,
 3114:                           loc  => 1,
 3115:                      );
 3116:     my %domconfig = &Apache::lonnet::get_dom('configuration',['usercreation'],$dom);
 3117:     if (ref($domconfig{'usercreation'}) eq 'HASH') {
 3118:         if (ref($domconfig{'usercreation'}{'authtypes'}) eq 'HASH') {
 3119:             my $authhash = $domconfig{'usercreation'}{'authtypes'};
 3120:             my $context;
 3121:             if ($env{'request.role'} =~ /^au/) {
 3122:                 $context = 'author';
 3123:             } elsif ($env{'request.role'} =~ /^dc/) {
 3124:                 $context = 'domain';
 3125:             } elsif ($env{'request.course.id'}) {
 3126:                 $context = 'course';
 3127:             }
 3128:             if ($context) {
 3129:                 if (ref($authhash->{$context}) eq 'HASH') {
 3130:                    %can_assign = %{$authhash->{$context}}; 
 3131:                 }
 3132:             }
 3133:         }
 3134:     }
 3135:     my $authnum = 0;
 3136:     foreach my $key (keys(%can_assign)) {
 3137:         if ($can_assign{$key}) {
 3138:             $authnum ++;
 3139:         }
 3140:     }
 3141:     if ($can_assign{'krb4'} && $can_assign{'krb5'}) {
 3142:         $authnum --;
 3143:     }
 3144:     return ($authnum,%can_assign);
 3145: }
 3146: 
 3147: ###############################################################
 3148: ##    Get Kerberos Defaults for Domain                 ##
 3149: ###############################################################
 3150: ##
 3151: ## Returns default kerberos version and an associated argument
 3152: ## as listed in file domain.tab. If not listed, provides
 3153: ## appropriate default domain and kerberos version.
 3154: ##
 3155: #-------------------------------------------
 3156: 
 3157: =pod
 3158: 
 3159: =item * &get_kerberos_defaults()
 3160: 
 3161: get_kerberos_defaults($target_domain) returns the default kerberos
 3162: version and domain. If not found, it defaults to version 4 and the 
 3163: domain of the server.
 3164: 
 3165: =over 4
 3166: 
 3167: ($def_version, $def_krb_domain) = &get_kerberos_defaults($target_domain);
 3168: 
 3169: =back
 3170: 
 3171: =back
 3172: 
 3173: =cut
 3174: 
 3175: #-------------------------------------------
 3176: sub get_kerberos_defaults {
 3177:     my $domain=shift;
 3178:     my ($krbdef,$krbdefdom);
 3179:     my %domdefaults = &Apache::lonnet::get_domain_defaults($domain);
 3180:     if (($domdefaults{'auth_def'} =~/^krb(4|5)$/) && ($domdefaults{'auth_arg_def'} ne '')) {
 3181:         $krbdef = $domdefaults{'auth_def'};
 3182:         $krbdefdom = $domdefaults{'auth_arg_def'};
 3183:     } else {
 3184:         $ENV{'SERVER_NAME'}=~/(\w+\.\w+)$/;
 3185:         my $krbdefdom=$1;
 3186:         $krbdefdom=~tr/a-z/A-Z/;
 3187:         $krbdef = "krb4";
 3188:     }
 3189:     return ($krbdef,$krbdefdom);
 3190: }
 3191: 
 3192: 
 3193: ###############################################################
 3194: ##                Thesaurus Functions                        ##
 3195: ###############################################################
 3196: 
 3197: =pod
 3198: 
 3199: =head1 Thesaurus Functions
 3200: 
 3201: =over 4
 3202: 
 3203: =item * &initialize_keywords()
 3204: 
 3205: Initializes the package variable %Keywords if it is empty.  Uses the
 3206: package variable $thesaurus_db_file.
 3207: 
 3208: =cut
 3209: 
 3210: ###################################################
 3211: 
 3212: sub initialize_keywords {
 3213:     return 1 if (scalar keys(%Keywords));
 3214:     # If we are here, %Keywords is empty, so fill it up
 3215:     #   Make sure the file we need exists...
 3216:     if (! -e $thesaurus_db_file) {
 3217:         &Apache::lonnet::logthis("Attempt to access $thesaurus_db_file".
 3218:                                  " failed because it does not exist");
 3219:         return 0;
 3220:     }
 3221:     #   Set up the hash as a database
 3222:     my %thesaurus_db;
 3223:     if (! tie(%thesaurus_db,'GDBM_File',
 3224:               $thesaurus_db_file,&GDBM_READER(),0640)){
 3225:         &Apache::lonnet::logthis("Could not tie \%thesaurus_db to ".
 3226:                                  $thesaurus_db_file);
 3227:         return 0;
 3228:     } 
 3229:     #  Get the average number of appearances of a word.
 3230:     my $avecount = $thesaurus_db{'average.count'};
 3231:     #  Put keywords (those that appear > average) into %Keywords
 3232:     while (my ($word,$data)=each (%thesaurus_db)) {
 3233:         my ($count,undef) = split /:/,$data;
 3234:         $Keywords{$word}++ if ($count > $avecount);
 3235:     }
 3236:     untie %thesaurus_db;
 3237:     # Remove special values from %Keywords.
 3238:     foreach my $value ('total.count','average.count') {
 3239:         delete($Keywords{$value}) if (exists($Keywords{$value}));
 3240:   }
 3241:     return 1;
 3242: }
 3243: 
 3244: ###################################################
 3245: 
 3246: =pod
 3247: 
 3248: =item * &keyword($word)
 3249: 
 3250: Returns true if $word is a keyword.  A keyword is a word that appears more 
 3251: than the average number of times in the thesaurus database.  Calls 
 3252: &initialize_keywords
 3253: 
 3254: =cut
 3255: 
 3256: ###################################################
 3257: 
 3258: sub keyword {
 3259:     return if (!&initialize_keywords());
 3260:     my $word=lc(shift());
 3261:     $word=~s/\W//g;
 3262:     return exists($Keywords{$word});
 3263: }
 3264: 
 3265: ###############################################################
 3266: 
 3267: =pod 
 3268: 
 3269: =item * &get_related_words()
 3270: 
 3271: Look up a word in the thesaurus.  Takes a scalar argument and returns
 3272: an array of words.  If the keyword is not in the thesaurus, an empty array
 3273: will be returned.  The order of the words returned is determined by the
 3274: database which holds them.
 3275: 
 3276: Uses global $thesaurus_db_file.
 3277: 
 3278: 
 3279: =cut
 3280: 
 3281: ###############################################################
 3282: sub get_related_words {
 3283:     my $keyword = shift;
 3284:     my %thesaurus_db;
 3285:     if (! -e $thesaurus_db_file) {
 3286:         &Apache::lonnet::logthis("Attempt to access $thesaurus_db_file ".
 3287:                                  "failed because the file does not exist");
 3288:         return ();
 3289:     }
 3290:     if (! tie(%thesaurus_db,'GDBM_File',
 3291:               $thesaurus_db_file,&GDBM_READER(),0640)){
 3292:         return ();
 3293:     } 
 3294:     my @Words=();
 3295:     my $count=0;
 3296:     if (exists($thesaurus_db{$keyword})) {
 3297: 	# The first element is the number of times
 3298: 	# the word appears.  We do not need it now.
 3299: 	my (undef,@RelatedWords) = (split(/:/,$thesaurus_db{$keyword}));
 3300: 	my (undef,$mostfrequentcount)=split(/\,/,$RelatedWords[0]);
 3301: 	my $threshold=$mostfrequentcount/10;
 3302:         foreach my $possibleword (@RelatedWords) {
 3303:             my ($word,$wordcount)=split(/\,/,$possibleword);
 3304:             if ($wordcount>$threshold) {
 3305: 		push(@Words,$word);
 3306:                 $count++;
 3307:                 if ($count>10) { last; }
 3308: 	    }
 3309:         }
 3310:     }
 3311:     untie %thesaurus_db;
 3312:     return @Words;
 3313: }
 3314: 
 3315: =pod
 3316: 
 3317: =back
 3318: 
 3319: =cut
 3320: 
 3321: # -------------------------------------------------------------- Plaintext name
 3322: =pod
 3323: 
 3324: =head1 User Name Functions
 3325: 
 3326: =over 4
 3327: 
 3328: =item * &plainname($uname,$udom,$first)
 3329: 
 3330: Takes a users logon name and returns it as a string in
 3331: "first middle last generation" form 
 3332: if $first is set to 'lastname' then it returns it as
 3333: 'lastname generation, firstname middlename' if their is a lastname
 3334: 
 3335: =cut
 3336: 
 3337: 
 3338: ###############################################################
 3339: sub plainname {
 3340:     my ($uname,$udom,$first)=@_;
 3341:     return if (!defined($uname) || !defined($udom));
 3342:     my %names=&getnames($uname,$udom);
 3343:     my $name=&Apache::lonnet::format_name($names{'firstname'},
 3344: 					  $names{'middlename'},
 3345: 					  $names{'lastname'},
 3346: 					  $names{'generation'},$first);
 3347:     $name=~s/^\s+//;
 3348:     $name=~s/\s+$//;
 3349:     $name=~s/\s+/ /g;
 3350:     if ($name !~ /\S/) { $name=$uname.':'.$udom; }
 3351:     return $name;
 3352: }
 3353: 
 3354: # -------------------------------------------------------------------- Nickname
 3355: =pod
 3356: 
 3357: =item * &nickname($uname,$udom)
 3358: 
 3359: Gets a users name and returns it as a string as
 3360: 
 3361: "&quot;nickname&quot;"
 3362: 
 3363: if the user has a nickname or
 3364: 
 3365: "first middle last generation"
 3366: 
 3367: if the user does not
 3368: 
 3369: =cut
 3370: 
 3371: sub nickname {
 3372:     my ($uname,$udom)=@_;
 3373:     return if (!defined($uname) || !defined($udom));
 3374:     my %names=&getnames($uname,$udom);
 3375:     my $name=$names{'nickname'};
 3376:     if ($name) {
 3377:        $name='&quot;'.$name.'&quot;'; 
 3378:     } else {
 3379:        $name=$names{'firstname'}.' '.$names{'middlename'}.' '.
 3380: 	     $names{'lastname'}.' '.$names{'generation'};
 3381:        $name=~s/\s+$//;
 3382:        $name=~s/\s+/ /g;
 3383:     }
 3384:     return $name;
 3385: }
 3386: 
 3387: sub getnames {
 3388:     my ($uname,$udom)=@_;
 3389:     return if (!defined($uname) || !defined($udom));
 3390:     if ($udom eq 'public' && $uname eq 'public') {
 3391: 	return ('lastname' => &mt('Public'));
 3392:     }
 3393:     my $id=$uname.':'.$udom;
 3394:     my ($names,$cached)=&Apache::lonnet::is_cached_new('namescache',$id);
 3395:     if ($cached) {
 3396: 	return %{$names};
 3397:     } else {
 3398: 	my %loadnames=&Apache::lonnet::get('environment',
 3399:                     ['firstname','middlename','lastname','generation','nickname'],
 3400: 					 $udom,$uname);
 3401: 	&Apache::lonnet::do_cache_new('namescache',$id,\%loadnames);
 3402: 	return %loadnames;
 3403:     }
 3404: }
 3405: 
 3406: # -------------------------------------------------------------------- getemails
 3407: 
 3408: =pod
 3409: 
 3410: =item * &getemails($uname,$udom)
 3411: 
 3412: Gets a user's email information and returns it as a hash with keys:
 3413: notification, critnotification, permanentemail
 3414: 
 3415: For notification and critnotification, values are comma-separated lists 
 3416: of e-mail addresses; for permanentemail, value is a single e-mail address.
 3417:  
 3418: 
 3419: =cut
 3420: 
 3421: 
 3422: sub getemails {
 3423:     my ($uname,$udom)=@_;
 3424:     if ($udom eq 'public' && $uname eq 'public') {
 3425: 	return;
 3426:     }
 3427:     if (!$udom) { $udom=$env{'user.domain'}; }
 3428:     if (!$uname) { $uname=$env{'user.name'}; }
 3429:     my $id=$uname.':'.$udom;
 3430:     my ($names,$cached)=&Apache::lonnet::is_cached_new('emailscache',$id);
 3431:     if ($cached) {
 3432: 	return %{$names};
 3433:     } else {
 3434: 	my %loadnames=&Apache::lonnet::get('environment',
 3435:                     			   ['notification','critnotification',
 3436: 					    'permanentemail'],
 3437: 					   $udom,$uname);
 3438: 	&Apache::lonnet::do_cache_new('emailscache',$id,\%loadnames);
 3439: 	return %loadnames;
 3440:     }
 3441: }
 3442: 
 3443: sub flush_email_cache {
 3444:     my ($uname,$udom)=@_;
 3445:     if (!$udom)  { $udom =$env{'user.domain'}; }
 3446:     if (!$uname) { $uname=$env{'user.name'};   }
 3447:     return if ($udom eq 'public' && $uname eq 'public');
 3448:     my $id=$uname.':'.$udom;
 3449:     &Apache::lonnet::devalidate_cache_new('emailscache',$id);
 3450: }
 3451: 
 3452: # -------------------------------------------------------------------- getlangs
 3453: 
 3454: =pod
 3455: 
 3456: =item * &getlangs($uname,$udom)
 3457: 
 3458: Gets a user's language preference and returns it as a hash with key:
 3459: language.
 3460: 
 3461: =cut
 3462: 
 3463: 
 3464: sub getlangs {
 3465:     my ($uname,$udom) = @_;
 3466:     if (!$udom)  { $udom =$env{'user.domain'}; }
 3467:     if (!$uname) { $uname=$env{'user.name'};   }
 3468:     my $id=$uname.':'.$udom;
 3469:     my ($langs,$cached)=&Apache::lonnet::is_cached_new('userlangs',$id);
 3470:     if ($cached) {
 3471:         return %{$langs};
 3472:     } else {
 3473:         my %loadlangs=&Apache::lonnet::get('environment',['languages'],
 3474:                                            $udom,$uname);
 3475:         &Apache::lonnet::do_cache_new('userlangs',$id,\%loadlangs);
 3476:         return %loadlangs;
 3477:     }
 3478: }
 3479: 
 3480: sub flush_langs_cache {
 3481:     my ($uname,$udom)=@_;
 3482:     if (!$udom)  { $udom =$env{'user.domain'}; }
 3483:     if (!$uname) { $uname=$env{'user.name'};   }
 3484:     return if ($udom eq 'public' && $uname eq 'public');
 3485:     my $id=$uname.':'.$udom;
 3486:     &Apache::lonnet::devalidate_cache_new('userlangs',$id);
 3487: }
 3488: 
 3489: # ------------------------------------------------------------------ Screenname
 3490: 
 3491: =pod
 3492: 
 3493: =item * &screenname($uname,$udom)
 3494: 
 3495: Gets a users screenname and returns it as a string
 3496: 
 3497: =cut
 3498: 
 3499: sub screenname {
 3500:     my ($uname,$udom)=@_;
 3501:     if ($uname eq $env{'user.name'} &&
 3502: 	$udom eq $env{'user.domain'}) {return $env{'environment.screenname'};}
 3503:     my %names=&Apache::lonnet::get('environment',['screenname'],$udom,$uname);
 3504:     return $names{'screenname'};
 3505: }
 3506: 
 3507: 
 3508: # ------------------------------------------------------------- Confirm Wrapper
 3509: =pod
 3510: 
 3511: =item * &confirmwrapper($message)
 3512: 
 3513: Wrap messages about completion of operation in box
 3514: 
 3515: =cut
 3516: 
 3517: sub confirmwrapper {
 3518:     my ($message)=@_;
 3519:     if ($message) {
 3520:         return "\n".'<div class="LC_confirm_box">'."\n"
 3521:                .$message."\n"
 3522:                .'</div>'."\n";
 3523:     } else {
 3524:         return $message;
 3525:     }
 3526: }
 3527: 
 3528: # ------------------------------------------------------------- Message Wrapper
 3529: 
 3530: sub messagewrapper {
 3531:     my ($link,$username,$domain,$subject,$text)=@_;
 3532:     return 
 3533:         '<a href="/adm/email?compose=individual&amp;'.
 3534:         'recname='.$username.'&amp;recdom='.$domain.
 3535: 	'&amp;subject='.&escape($subject).'&amp;text='.&escape($text).'" '.
 3536:         'title="'.&mt('Send message').'">'.$link.'</a>';
 3537: }
 3538: 
 3539: # --------------------------------------------------------------- Notes Wrapper
 3540: 
 3541: sub noteswrapper {
 3542:     my ($link,$un,$do)=@_;
 3543:     return 
 3544: "<a href='/adm/email?recordftf=retrieve&amp;recname=$un&amp;recdom=$do'>$link</a>";
 3545: }
 3546: 
 3547: # ------------------------------------------------------------- Aboutme Wrapper
 3548: 
 3549: sub aboutmewrapper {
 3550:     my ($link,$username,$domain,$target,$class)=@_;
 3551:     if (!defined($username)  && !defined($domain)) {
 3552:         return;
 3553:     }
 3554:     return '<a href="/adm/'.$domain.'/'.$username.'/aboutme"'.
 3555: 	($target?' target="'.$target.'"':'').($class?' class="'.$class.'"':'').' title="'.&mt("View this user's personal information page").'">'.$link.'</a>';
 3556: }
 3557: 
 3558: # ------------------------------------------------------------ Syllabus Wrapper
 3559: 
 3560: sub syllabuswrapper {
 3561:     my ($linktext,$coursedir,$domain)=@_;
 3562:     return qq{<a href="/public/$domain/$coursedir/syllabus">$linktext</a>};
 3563: }
 3564: 
 3565: # -----------------------------------------------------------------------------
 3566: 
 3567: sub track_student_link {
 3568:     my ($linktext,$sname,$sdom,$target,$start,$only_body) = @_;
 3569:     my $link ="/adm/trackstudent?";
 3570:     my $title = 'View recent activity';
 3571:     if (defined($sname) && $sname !~ /^\s*$/ &&
 3572:         defined($sdom)  && $sdom  !~ /^\s*$/) {
 3573:         $link .= "selected_student=$sname:$sdom";
 3574:         $title .= ' of this student';
 3575:     } 
 3576:     if (defined($target) && $target !~ /^\s*$/) {
 3577:         $target = qq{target="$target"};
 3578:     } else {
 3579:         $target = '';
 3580:     }
 3581:     if ($start) { $link.='&amp;start='.$start; }
 3582:     if ($only_body) { $link .= '&amp;only_body=1'; }
 3583:     $title = &mt($title);
 3584:     $linktext = &mt($linktext);
 3585:     return qq{<a href="$link" title="$title" $target>$linktext</a>}.
 3586: 	&help_open_topic('View_recent_activity');
 3587: }
 3588: 
 3589: sub slot_reservations_link {
 3590:     my ($linktext,$sname,$sdom,$target) = @_;
 3591:     my $link ="/adm/slotrequest?command=showresv&amp;origin=aboutme";
 3592:     my $title = 'View slot reservation history';
 3593:     if (defined($sname) && $sname !~ /^\s*$/ &&
 3594:         defined($sdom)  && $sdom  !~ /^\s*$/) {
 3595:         $link .= "&amp;uname=$sname&amp;udom=$sdom";
 3596:         $title .= ' of this student';
 3597:     }
 3598:     if (defined($target) && $target !~ /^\s*$/) {
 3599:         $target = qq{target="$target"};
 3600:     } else {
 3601:         $target = '';
 3602:     }
 3603:     $title = &mt($title);
 3604:     $linktext = &mt($linktext);
 3605:     return qq{<a href="$link" title="$title" $target>$linktext</a>};
 3606: # FIXME uncomment when help item created: &help_open_topic('Slot_Reservation_History');
 3607: 
 3608: }
 3609: 
 3610: # ===================================================== Display a student photo
 3611: 
 3612: 
 3613: sub student_image_tag {
 3614:     my ($domain,$user)=@_;
 3615:     my $imgsrc=&Apache::lonnet::studentphoto($domain,$user,'jpg');
 3616:     if (($imgsrc) && ($imgsrc ne '/adm/lonKaputt/lonlogo_broken.gif')) {
 3617: 	return '<img src="'.$imgsrc.'" align="right" />';
 3618:     } else {
 3619: 	return '';
 3620:     }
 3621: }
 3622: 
 3623: =pod
 3624: 
 3625: =back
 3626: 
 3627: =head1 Access .tab File Data
 3628: 
 3629: =over 4
 3630: 
 3631: =item * &languageids() 
 3632: 
 3633: returns list of all language ids
 3634: 
 3635: =cut
 3636: 
 3637: sub languageids {
 3638:     return sort(keys(%language));
 3639: }
 3640: 
 3641: =pod
 3642: 
 3643: =item * &languagedescription() 
 3644: 
 3645: returns description of a specified language id
 3646: 
 3647: =cut
 3648: 
 3649: sub languagedescription {
 3650:     my $code=shift;
 3651:     return  ($supported_language{$code}?'* ':'').
 3652:             $language{$code}.
 3653: 	    ($supported_language{$code}?' ('.&mt('interface available').')':'');
 3654: }
 3655: 
 3656: =pod
 3657: 
 3658: =item * &plainlanguagedescription
 3659: 
 3660: Returns both the plain language description (e.g. 'Creoles and Pidgins, English-based (Other)')
 3661: and the language character encoding (e.g. ISO) separated by a ' - ' string.
 3662: 
 3663: =cut
 3664: 
 3665: sub plainlanguagedescription {
 3666:     my $code=shift;
 3667:     return $language{$code};
 3668: }
 3669: 
 3670: =pod
 3671: 
 3672: =item * &supportedlanguagecode
 3673: 
 3674: Returns the supported language code (e.g. sptutf maps to pt) given a language
 3675: code.
 3676: 
 3677: =cut
 3678: 
 3679: sub supportedlanguagecode {
 3680:     my $code=shift;
 3681:     return $supported_language{$code};
 3682: }
 3683: 
 3684: =pod
 3685: 
 3686: =item * &latexlanguage()
 3687: 
 3688: Given a language key code returns the correspondnig language to use
 3689: to select the correct hyphenation on LaTeX printouts.  This is undef if there
 3690: is no supported hyphenation for the language code.
 3691: 
 3692: =cut
 3693: 
 3694: sub latexlanguage {
 3695:     my $code = shift;
 3696:     return $latex_language{$code};
 3697: }
 3698: 
 3699: =pod
 3700: 
 3701: =item * &latexhyphenation()
 3702: 
 3703: Same as above but what's supplied is the language as it might be stored
 3704: in the metadata.
 3705: 
 3706: =cut
 3707: 
 3708: sub latexhyphenation {
 3709:     my $key = shift;
 3710:     return $latex_language_bykey{$key};
 3711: }
 3712: 
 3713: =pod
 3714: 
 3715: =item * &copyrightids() 
 3716: 
 3717: returns list of all copyrights
 3718: 
 3719: =cut
 3720: 
 3721: sub copyrightids {
 3722:     return sort(keys(%cprtag));
 3723: }
 3724: 
 3725: =pod
 3726: 
 3727: =item * &copyrightdescription() 
 3728: 
 3729: returns description of a specified copyright id
 3730: 
 3731: =cut
 3732: 
 3733: sub copyrightdescription {
 3734:     return &mt($cprtag{shift(@_)});
 3735: }
 3736: 
 3737: =pod
 3738: 
 3739: =item * &source_copyrightids() 
 3740: 
 3741: returns list of all source copyrights
 3742: 
 3743: =cut
 3744: 
 3745: sub source_copyrightids {
 3746:     return sort(keys(%scprtag));
 3747: }
 3748: 
 3749: =pod
 3750: 
 3751: =item * &source_copyrightdescription() 
 3752: 
 3753: returns description of a specified source copyright id
 3754: 
 3755: =cut
 3756: 
 3757: sub source_copyrightdescription {
 3758:     return &mt($scprtag{shift(@_)});
 3759: }
 3760: 
 3761: =pod
 3762: 
 3763: =item * &filecategories() 
 3764: 
 3765: returns list of all file categories
 3766: 
 3767: =cut
 3768: 
 3769: sub filecategories {
 3770:     return sort(keys(%category_extensions));
 3771: }
 3772: 
 3773: =pod
 3774: 
 3775: =item * &filecategorytypes() 
 3776: 
 3777: returns list of file types belonging to a given file
 3778: category
 3779: 
 3780: =cut
 3781: 
 3782: sub filecategorytypes {
 3783:     my ($cat) = @_;
 3784:     return @{$category_extensions{lc($cat)}};
 3785: }
 3786: 
 3787: =pod
 3788: 
 3789: =item * &fileembstyle() 
 3790: 
 3791: returns embedding style for a specified file type
 3792: 
 3793: =cut
 3794: 
 3795: sub fileembstyle {
 3796:     return $fe{lc(shift(@_))};
 3797: }
 3798: 
 3799: sub filemimetype {
 3800:     return $fm{lc(shift(@_))};
 3801: }
 3802: 
 3803: 
 3804: sub filecategoryselect {
 3805:     my ($name,$value)=@_;
 3806:     return &select_form($value,$name,
 3807:                         {'' => &mt('Any category'), map { $_,$_ } sort(keys(%category_extensions))});
 3808: }
 3809: 
 3810: =pod
 3811: 
 3812: =item * &filedescription() 
 3813: 
 3814: returns description for a specified file type
 3815: 
 3816: =cut
 3817: 
 3818: sub filedescription {
 3819:     my $file_description = $fd{lc(shift())};
 3820:     $file_description =~ s:([\[\]]):~$1:g;
 3821:     return &mt($file_description);
 3822: }
 3823: 
 3824: =pod
 3825: 
 3826: =item * &filedescriptionex() 
 3827: 
 3828: returns description for a specified file type with
 3829: extra formatting
 3830: 
 3831: =cut
 3832: 
 3833: sub filedescriptionex {
 3834:     my $ex=shift;
 3835:     my $file_description = $fd{lc($ex)};
 3836:     $file_description =~ s:([\[\]]):~$1:g;
 3837:     return '.'.$ex.' '.&mt($file_description);
 3838: }
 3839: 
 3840: # End of .tab access
 3841: =pod
 3842: 
 3843: =back
 3844: 
 3845: =cut
 3846: 
 3847: # ------------------------------------------------------------------ File Types
 3848: sub fileextensions {
 3849:     return sort(keys(%fe));
 3850: }
 3851: 
 3852: # ----------------------------------------------------------- Display Languages
 3853: # returns a hash with all desired display languages
 3854: #
 3855: 
 3856: sub display_languages {
 3857:     my %languages=();
 3858:     foreach my $lang (&Apache::lonlocal::preferred_languages()) {
 3859: 	$languages{$lang}=1;
 3860:     }
 3861:     &get_unprocessed_cgi($ENV{'QUERY_STRING'},['displaylanguage']);
 3862:     if ($env{'form.displaylanguage'}) {
 3863: 	foreach my $lang (split(/\s*(\,|\;|\:)\s*/,$env{'form.displaylanguage'})) {
 3864: 	    $languages{$lang}=1;
 3865:         }
 3866:     }
 3867:     return %languages;
 3868: }
 3869: 
 3870: sub languages {
 3871:     my ($possible_langs) = @_;
 3872:     my @preferred_langs = &Apache::lonlocal::preferred_languages();
 3873:     if (!ref($possible_langs)) {
 3874: 	if( wantarray ) {
 3875: 	    return @preferred_langs;
 3876: 	} else {
 3877: 	    return $preferred_langs[0];
 3878: 	}
 3879:     }
 3880:     my %possibilities = map { $_ => 1 } (@$possible_langs);
 3881:     my @preferred_possibilities;
 3882:     foreach my $preferred_lang (@preferred_langs) {
 3883: 	if (exists($possibilities{$preferred_lang})) {
 3884: 	    push(@preferred_possibilities, $preferred_lang);
 3885: 	}
 3886:     }
 3887:     if( wantarray ) {
 3888: 	return @preferred_possibilities;
 3889:     }
 3890:     return $preferred_possibilities[0];
 3891: }
 3892: 
 3893: sub user_lang {
 3894:     my ($touname,$toudom,$fromcid) = @_;
 3895:     my @userlangs;
 3896:     if (($fromcid ne '') && ($env{'course.'.$fromcid.'.languages'} ne '')) {
 3897:         @userlangs=(@userlangs,split(/\s*(\,|\;|\:)\s*/,
 3898:                     $env{'course.'.$fromcid.'.languages'}));
 3899:     } else {
 3900:         my %langhash = &getlangs($touname,$toudom);
 3901:         if ($langhash{'languages'} ne '') {
 3902:             @userlangs = split(/\s*(\,|\;|\:)\s*/,$langhash{'languages'});
 3903:         } else {
 3904:             my %domdefs = &Apache::lonnet::get_domain_defaults($toudom);
 3905:             if ($domdefs{'lang_def'} ne '') {
 3906:                 @userlangs = ($domdefs{'lang_def'});
 3907:             }
 3908:         }
 3909:     }
 3910:     my @languages=&Apache::lonlocal::get_genlanguages(@userlangs);
 3911:     my $user_lh = Apache::localize->get_handle(@languages);
 3912:     return $user_lh;
 3913: }
 3914: 
 3915: 
 3916: ###############################################################
 3917: ##               Student Answer Attempts                     ##
 3918: ###############################################################
 3919: 
 3920: =pod
 3921: 
 3922: =head1 Alternate Problem Views
 3923: 
 3924: =over 4
 3925: 
 3926: =item * &get_previous_attempt($symb, $username, $domain, $course,
 3927:     $getattempt, $regexp, $gradesub, $usec, $identifier)
 3928: 
 3929: Return string with previous attempt on problem. Arguments:
 3930: 
 3931: =over 4
 3932: 
 3933: =item * $symb: Problem, including path
 3934: 
 3935: =item * $username: username of the desired student
 3936: 
 3937: =item * $domain: domain of the desired student
 3938: 
 3939: =item * $course: Course ID
 3940: 
 3941: =item * $getattempt: Leave blank for all attempts, otherwise put
 3942:     something
 3943: 
 3944: =item * $regexp: if string matches this regexp, the string will be
 3945:     sent to $gradesub
 3946: 
 3947: =item * $gradesub: routine that processes the string if it matches $regexp
 3948: 
 3949: =item * $usec: section of the desired student
 3950: 
 3951: =item * $identifier: counter for student (multiple students one problem) or
 3952:     problem (one student; whole sequence).
 3953: 
 3954: =back
 3955: 
 3956: The output string is a table containing all desired attempts, if any.
 3957: 
 3958: =cut
 3959: 
 3960: sub get_previous_attempt {
 3961:   my ($symb,$username,$domain,$course,$getattempt,$regexp,$gradesub,$usec,$identifier)=@_;
 3962:   my $prevattempts='';
 3963:   no strict 'refs';
 3964:   if ($symb) {
 3965:     my (%returnhash)=
 3966:       &Apache::lonnet::restore($symb,$course,$domain,$username);
 3967:     if ($returnhash{'version'}) {
 3968:       my %lasthash=();
 3969:       my $version;
 3970:       for ($version=1;$version<=$returnhash{'version'};$version++) {
 3971:         foreach my $key (reverse(sort(split(/\:/,$returnhash{$version.':keys'})))) {
 3972:             if ($key =~ /\.rawrndseed$/) {
 3973:                 my ($id) = ($key =~ /^(.+)\.rawrndseed$/);
 3974:                 $lasthash{$id.'.rndseed'} = $returnhash{$version.':'.$key};
 3975:             } else {
 3976:                 $lasthash{$key}=$returnhash{$version.':'.$key};
 3977:             }
 3978:         }
 3979:       }
 3980:       $prevattempts=&start_data_table().&start_data_table_header_row();
 3981:       $prevattempts.='<th>'.&mt('History').'</th>';
 3982:       my (%typeparts,%lasthidden,%regraded,%hidestatus);
 3983:       my $showsurv=&Apache::lonnet::allowed('vas',$env{'request.course.id'});
 3984:       foreach my $key (sort(keys(%lasthash))) {
 3985: 	my ($ign,@parts) = split(/\./,$key);
 3986: 	if ($#parts > 0) {
 3987: 	  my $data=$parts[-1];
 3988:           next if ($data eq 'foilorder');
 3989: 	  pop(@parts);
 3990:           $prevattempts.='<th>'.&mt('Part ').join('.',@parts).'<br />'.$data.'&nbsp;</th>';
 3991:           if ($data eq 'type') {
 3992:               unless ($showsurv) {
 3993:                   my $id = join(',',@parts);
 3994:                   $typeparts{$ign.'.'.$id} = $lasthash{$key};
 3995:                   if (($lasthash{$key} eq 'anonsurvey') || ($lasthash{$key} eq 'anonsurveycred')) {
 3996:                       $lasthidden{$ign.'.'.$id} = 1;
 3997:                   }
 3998:               }
 3999:               if ($identifier ne '') {
 4000:                   my $id = join(',',@parts);
 4001:                   if (&Apache::lonnet::EXT("resource.$id.problemstatus",$symb,
 4002:                                                $domain,$username,$usec,undef,$course) =~ /^no/) {
 4003:                       $hidestatus{$ign.'.'.$id} = 1;
 4004:                   }
 4005:               }
 4006:           } elsif ($data eq 'regrader') {
 4007:               if (($identifier ne '') && (@parts)) {
 4008:                   my $id = join(',',@parts);
 4009:                   $regraded{$ign.'.'.$id} = 1;
 4010:               }
 4011:           } 
 4012: 	} else {
 4013: 	  if ($#parts == 0) {
 4014: 	    $prevattempts.='<th>'.$parts[0].'</th>';
 4015: 	  } else {
 4016: 	    $prevattempts.='<th>'.$ign.'</th>';
 4017: 	  }
 4018: 	}
 4019:       }
 4020:       $prevattempts.=&end_data_table_header_row();
 4021:       if ($getattempt eq '') {
 4022:         my (%solved,%resets,%probstatus);
 4023:         if (($identifier ne '') && (keys(%regraded) > 0)) {
 4024:             for ($version=1;$version<=$returnhash{'version'};$version++) {
 4025:                 foreach my $id (keys(%regraded)) {
 4026:                     if (($returnhash{$version.':'.$id.'.regrader'}) &&
 4027:                         ($returnhash{$version.':'.$id.'.tries'} eq '') &&
 4028:                         ($returnhash{$version.':'.$id.'.award'} eq '')) {
 4029:                         push(@{$resets{$id}},$version);
 4030:                     }
 4031:                 }
 4032:             }
 4033:         }
 4034: 	for ($version=1;$version<=$returnhash{'version'};$version++) {
 4035:             my (@hidden,@unsolved);
 4036:             if (%typeparts) {
 4037:                 foreach my $id (keys(%typeparts)) {
 4038:                     if (($returnhash{$version.':'.$id.'.type'} eq 'anonsurvey') ||
 4039:                         ($returnhash{$version.':'.$id.'.type'} eq 'anonsurveycred')) {
 4040:                         push(@hidden,$id);
 4041:                     } elsif ($identifier ne '') {
 4042:                         unless (($returnhash{$version.':'.$id.'.type'} eq 'survey') ||
 4043:                                 ($returnhash{$version.':'.$id.'.type'} eq 'surveycred') ||
 4044:                                 ($hidestatus{$id})) {
 4045:                             next if ((ref($resets{$id}) eq 'ARRAY') && grep(/^\Q$version\E$/,@{$resets{$id}}));
 4046:                             if ($returnhash{$version.':'.$id.'.solved'} eq 'correct_by_student') {
 4047:                                 push(@{$solved{$id}},$version);
 4048:                             } elsif (($returnhash{$version.':'.$id.'.solved'} ne '') &&
 4049:                                      (ref($solved{$id}) eq 'ARRAY')) {
 4050:                                 my $skip;
 4051:                                 if (ref($resets{$id}) eq 'ARRAY') {
 4052:                                     foreach my $reset (@{$resets{$id}}) {
 4053:                                         if ($reset > $solved{$id}[-1]) {
 4054:                                             $skip=1;
 4055:                                             last;
 4056:                                         }
 4057:                                     }
 4058:                                 }
 4059:                                 unless ($skip) {
 4060:                                     my ($ign,$partslist) = split(/\./,$id,2);
 4061:                                     push(@unsolved,$partslist);
 4062:                                 }
 4063:                             }
 4064:                         }
 4065:                     }
 4066:                 }
 4067:             }
 4068:             $prevattempts.=&start_data_table_row().
 4069:                            '<td>'.&mt('Transaction [_1]',$version);
 4070:             if (@unsolved) {
 4071:                 $prevattempts .= '<span class="LC_nobreak"><label>'.
 4072:                                  '<input type="checkbox" name="HIDE'.$identifier.'" value="'.$version.':'.join('_',@unsolved).'" />'.
 4073:                                  &mt('Hide').'</label></span>';
 4074:             }
 4075:             $prevattempts .= '</td>';
 4076:             if (@hidden) {
 4077:                 foreach my $key (sort(keys(%lasthash))) {
 4078:                     next if ($key =~ /\.foilorder$/);
 4079:                     my $hide;
 4080:                     foreach my $id (@hidden) {
 4081:                         if ($key =~ /^\Q$id\E/) {
 4082:                             $hide = 1;
 4083:                             last;
 4084:                         }
 4085:                     }
 4086:                     if ($hide) {
 4087:                         my ($id,$data) = ($key =~ /^(.+)\.([^.]+)$/);
 4088:                         if (($data eq 'award') || ($data eq 'awarddetail')) {
 4089:                             my $value = &format_previous_attempt_value($key,
 4090:                                              $returnhash{$version.':'.$key});
 4091:                             $prevattempts.='<td>'.$value.'&nbsp;</td>';
 4092:                         } else {
 4093:                             $prevattempts.='<td>&nbsp;</td>';
 4094:                         }
 4095:                     } else {
 4096:                         if ($key =~ /\./) {
 4097:                             my $value = $returnhash{$version.':'.$key};
 4098:                             if ($key =~ /\.rndseed$/) {
 4099:                                 my ($id) = ($key =~ /^(.+)\.rndseed$/);
 4100:                                 if (exists($returnhash{$version.':'.$id.'.rawrndseed'})) {
 4101:                                     $value = $returnhash{$version.':'.$id.'.rawrndseed'};
 4102:                                 }
 4103:                             }
 4104:                             $prevattempts.='<td>'.&format_previous_attempt_value($key,$value).
 4105:                                            '&nbsp;</td>';
 4106:                         } else {
 4107:                             $prevattempts.='<td>&nbsp;</td>';
 4108:                         }
 4109:                     }
 4110:                 }
 4111:             } else {
 4112: 	        foreach my $key (sort(keys(%lasthash))) {
 4113:                     next if ($key =~ /\.foilorder$/);
 4114:                     my $value = $returnhash{$version.':'.$key};
 4115:                     if ($key =~ /\.rndseed$/) {
 4116:                         my ($id) = ($key =~ /^(.+)\.rndseed$/);
 4117:                         if (exists($returnhash{$version.':'.$id.'.rawrndseed'})) {
 4118:                             $value = $returnhash{$version.':'.$id.'.rawrndseed'};
 4119:                         }
 4120:                     }
 4121:                     $prevattempts.='<td>'.&format_previous_attempt_value($key,$value).
 4122:                                    '&nbsp;</td>';
 4123: 	        }
 4124:             }
 4125: 	    $prevattempts.=&end_data_table_row();
 4126: 	 }
 4127:       }
 4128:       my @currhidden = keys(%lasthidden);
 4129:       $prevattempts.=&start_data_table_row().'<td>'.&mt('Current').'</td>';
 4130:       foreach my $key (sort(keys(%lasthash))) {
 4131:           next if ($key =~ /\.foilorder$/);
 4132:           if (%typeparts) {
 4133:               my $hidden;
 4134:               foreach my $id (@currhidden) {
 4135:                   if ($key =~ /^\Q$id\E/) {
 4136:                       $hidden = 1;
 4137:                       last;
 4138:                   }
 4139:               }
 4140:               if ($hidden) {
 4141:                   my ($id,$data) = ($key =~ /^(.+)\.([^.]+)$/);
 4142:                   if (($data eq 'award') || ($data eq 'awarddetail')) {
 4143:                       my $value = &format_previous_attempt_value($key,$lasthash{$key});
 4144:                       if ($key =~/$regexp$/ && (defined &$gradesub)) {
 4145:                           $value = &$gradesub($value);
 4146:                       }
 4147:                       $prevattempts.='<td>'.$value.'&nbsp;</td>';
 4148:                   } else {
 4149:                       $prevattempts.='<td>&nbsp;</td>';
 4150:                   }
 4151:               } else {
 4152:                   my $value = &format_previous_attempt_value($key,$lasthash{$key});
 4153:                   if ($key =~/$regexp$/ && (defined &$gradesub)) {
 4154:                       $value = &$gradesub($value);
 4155:                   }
 4156:                   $prevattempts.='<td>'.$value.'&nbsp;</td>';
 4157:               }
 4158:           } else {
 4159: 	      my $value = &format_previous_attempt_value($key,$lasthash{$key});
 4160: 	      if ($key =~/$regexp$/ && (defined &$gradesub)) {
 4161:                   $value = &$gradesub($value);
 4162:               }
 4163: 	      $prevattempts.='<td>'.$value.'&nbsp;</td>';
 4164:           }
 4165:       }
 4166:       $prevattempts.= &end_data_table_row().&end_data_table();
 4167:     } else {
 4168:       $prevattempts=
 4169: 	  &start_data_table().&start_data_table_row().
 4170: 	  '<td>'.&mt('Nothing submitted - no attempts.').'</td>'.
 4171: 	  &end_data_table_row().&end_data_table();
 4172:     }
 4173:   } else {
 4174:     $prevattempts=
 4175: 	  &start_data_table().&start_data_table_row().
 4176: 	  '<td>'.&mt('No data.').'</td>'.
 4177: 	  &end_data_table_row().&end_data_table();
 4178:   }
 4179: }
 4180: 
 4181: sub format_previous_attempt_value {
 4182:     my ($key,$value) = @_;
 4183:     if (($key =~ /timestamp/) || ($key=~/duedate/)) {
 4184: 	$value = &Apache::lonlocal::locallocaltime($value);
 4185:     } elsif (ref($value) eq 'ARRAY') {
 4186: 	$value = '('.join(', ', @{ $value }).')';
 4187:     } elsif ($key =~ /answerstring$/) {
 4188:         my %answers = &Apache::lonnet::str2hash($value);
 4189:         my @anskeys = sort(keys(%answers));
 4190:         if (@anskeys == 1) {
 4191:             my $answer = $answers{$anskeys[0]};
 4192:             if ($answer =~ m{\0}) {
 4193:                 $answer =~ s{\0}{,}g;
 4194:             }
 4195:             my $tag_internal_answer_name = 'INTERNAL';
 4196:             if ($anskeys[0] eq $tag_internal_answer_name) {
 4197:                 $value = $answer; 
 4198:             } else {
 4199:                 $value = $anskeys[0].'='.$answer;
 4200:             }
 4201:         } else {
 4202:             foreach my $ans (@anskeys) {
 4203:                 my $answer = $answers{$ans};
 4204:                 if ($answer =~ m{\0}) {
 4205:                     $answer =~ s{\0}{,}g;
 4206:                 }
 4207:                 $value .=  $ans.'='.$answer.'<br />';;
 4208:             } 
 4209:         }
 4210:     } else {
 4211: 	$value = &unescape($value);
 4212:     }
 4213:     return $value;
 4214: }
 4215: 
 4216: 
 4217: sub relative_to_absolute {
 4218:     my ($url,$output)=@_;
 4219:     my $parser=HTML::TokeParser->new(\$output);
 4220:     my $token;
 4221:     my $thisdir=$url;
 4222:     my @rlinks=();
 4223:     while ($token=$parser->get_token) {
 4224: 	if ($token->[0] eq 'S') {
 4225: 	    if ($token->[1] eq 'a') {
 4226: 		if ($token->[2]->{'href'}) {
 4227: 		    $rlinks[$#rlinks+1]=$token->[2]->{'href'};
 4228: 		}
 4229: 	    } elsif ($token->[1] eq 'img' || $token->[1] eq 'embed' ) {
 4230: 		$rlinks[$#rlinks+1]=$token->[2]->{'src'};
 4231: 	    } elsif ($token->[1] eq 'base') {
 4232: 		$thisdir=$token->[2]->{'href'};
 4233: 	    }
 4234: 	}
 4235:     }
 4236:     $thisdir=~s-/[^/]*$--;
 4237:     foreach my $link (@rlinks) {
 4238: 	unless (($link=~/^https?\:\/\//i) ||
 4239: 		($link=~/^\//) ||
 4240: 		($link=~/^javascript:/i) ||
 4241: 		($link=~/^mailto:/i) ||
 4242: 		($link=~/^\#/)) {
 4243: 	    my $newlocation=&Apache::lonnet::hreflocation($thisdir,$link);
 4244: 	    $output=~s/(\"|\'|\=\s*)\Q$link\E(\"|\'|\s|\>)/$1$newlocation$2/;
 4245: 	}
 4246:     }
 4247: # -------------------------------------------------- Deal with Applet codebases
 4248:     $output=~s/(\<applet[^\>]+)(codebase\=[^\S\>]+)*([^\>]*)\>/$1.($2?$2:' codebase="'.$thisdir.'"').$3.'>'/gei;
 4249:     return $output;
 4250: }
 4251: 
 4252: =pod
 4253: 
 4254: =item * &get_student_view()
 4255: 
 4256: show a snapshot of what student was looking at
 4257: 
 4258: =cut
 4259: 
 4260: sub get_student_view {
 4261:   my ($symb,$username,$domain,$courseid,$target,$moreenv) = @_;
 4262:   my ($map,$id,$feedurl) = &Apache::lonnet::decode_symb($symb);
 4263:   my (%form);
 4264:   my @elements=('symb','courseid','domain','username');
 4265:   foreach my $element (@elements) {
 4266:       $form{'grade_'.$element}=eval '$'.$element #'
 4267:   }
 4268:   if (defined($moreenv)) {
 4269:       %form=(%form,%{$moreenv});
 4270:   }
 4271:   if (defined($target)) { $form{'grade_target'} = $target; }
 4272:   $feedurl=&Apache::lonnet::clutter($feedurl);
 4273:   my ($userview,$response)=&Apache::lonnet::ssi_body($feedurl,%form);
 4274:   $userview=~s/\<body[^\>]*\>//gi;
 4275:   $userview=~s/\<\/body\>//gi;
 4276:   $userview=~s/\<html\>//gi;
 4277:   $userview=~s/\<\/html\>//gi;
 4278:   $userview=~s/\<head\>//gi;
 4279:   $userview=~s/\<\/head\>//gi;
 4280:   $userview=~s/action\s*\=/would_be_action\=/gi;
 4281:   $userview=&relative_to_absolute($feedurl,$userview);
 4282:   if (wantarray) {
 4283:      return ($userview,$response);
 4284:   } else {
 4285:      return $userview;
 4286:   }
 4287: }
 4288: 
 4289: sub get_student_view_with_retries {
 4290:   my ($symb,$retries,$username,$domain,$courseid,$target,$moreenv) = @_;
 4291: 
 4292:     my $ok = 0;                 # True if we got a good response.
 4293:     my $content;
 4294:     my $response;
 4295: 
 4296:     # Try to get the student_view done. within the retries count:
 4297:     
 4298:     do {
 4299:          ($content, $response) = &get_student_view($symb,$username,$domain,$courseid,$target,$moreenv);
 4300:          $ok      = $response->is_success;
 4301:          if (!$ok) {
 4302:             &Apache::lonnet::logthis("Failed get_student_view_with_retries on $symb: ".$response->is_success.', '.$response->code.', '.$response->message);
 4303:          }
 4304:          $retries--;
 4305:     } while (!$ok && ($retries > 0));
 4306:     
 4307:     if (!$ok) {
 4308:        $content = '';          # On error return an empty content.
 4309:     }
 4310:     if (wantarray) {
 4311:        return ($content, $response);
 4312:     } else {
 4313:        return $content;
 4314:     }
 4315: }
 4316: 
 4317: =pod
 4318: 
 4319: =item * &get_student_answers() 
 4320: 
 4321: show a snapshot of how student was answering problem
 4322: 
 4323: =cut
 4324: 
 4325: sub get_student_answers {
 4326:   my ($symb,$username,$domain,$courseid,%form) = @_;
 4327:   my ($map,$id,$feedurl) = &Apache::lonnet::decode_symb($symb);
 4328:   my (%moreenv);
 4329:   my @elements=('symb','courseid','domain','username');
 4330:   foreach my $element (@elements) {
 4331:     $moreenv{'grade_'.$element}=eval '$'.$element #'
 4332:   }
 4333:   $moreenv{'grade_target'}='answer';
 4334:   %moreenv=(%form,%moreenv);
 4335:   $feedurl = &Apache::lonnet::clutter($feedurl);
 4336:   my $userview=&Apache::lonnet::ssi($feedurl,%moreenv);
 4337:   return $userview;
 4338: }
 4339: 
 4340: =pod
 4341: 
 4342: =item * &submlink()
 4343: 
 4344: Inputs: $text $uname $udom $symb $target
 4345: 
 4346: Returns: A link to grades.pm such as to see the SUBM view of a student
 4347: 
 4348: =cut
 4349: 
 4350: ###############################################
 4351: sub submlink {
 4352:     my ($text,$uname,$udom,$symb,$target)=@_;
 4353:     if (!($uname && $udom)) {
 4354: 	(my $cursymb, my $courseid,$udom,$uname)=
 4355: 	    &Apache::lonnet::whichuser($symb);
 4356: 	if (!$symb) { $symb=$cursymb; }
 4357:     }
 4358:     if (!$symb) { $symb=&Apache::lonnet::symbread(); }
 4359:     $symb=&escape($symb);
 4360:     if ($target) { $target=" target=\"$target\""; }
 4361:     return
 4362:         '<a href="/adm/grades?command=submission'.
 4363:         '&amp;symb='.$symb.
 4364:         '&amp;student='.$uname.
 4365:         '&amp;userdom='.$udom.'"'.
 4366:         $target.'>'.$text.'</a>';
 4367: }
 4368: ##############################################
 4369: 
 4370: =pod
 4371: 
 4372: =item * &pgrdlink()
 4373: 
 4374: Inputs: $text $uname $udom $symb $target
 4375: 
 4376: Returns: A link to grades.pm such as to see the PGRD view of a student
 4377: 
 4378: =cut
 4379: 
 4380: ###############################################
 4381: sub pgrdlink {
 4382:     my $link=&submlink(@_);
 4383:     $link=~s/(&command=submission)/$1&showgrading=yes/;
 4384:     return $link;
 4385: }
 4386: ##############################################
 4387: 
 4388: =pod
 4389: 
 4390: =item * &pprmlink()
 4391: 
 4392: Inputs: $text $uname $udom $symb $target
 4393: 
 4394: Returns: A link to parmset.pm such as to see the PPRM view of a
 4395: student and a specific resource
 4396: 
 4397: =cut
 4398: 
 4399: ###############################################
 4400: sub pprmlink {
 4401:     my ($text,$uname,$udom,$symb,$target)=@_;
 4402:     if (!($uname && $udom)) {
 4403: 	(my $cursymb, my $courseid,$udom,$uname)=
 4404: 	    &Apache::lonnet::whichuser($symb);
 4405: 	if (!$symb) { $symb=$cursymb; }
 4406:     }
 4407:     if (!$symb) { $symb=&Apache::lonnet::symbread(); }
 4408:     $symb=&escape($symb);
 4409:     if ($target) { $target="target=\"$target\""; }
 4410:     return '<a href="/adm/parmset?command=set&amp;'.
 4411: 	'symb='.$symb.'&amp;uname='.$uname.
 4412: 	'&amp;udom='.$udom.'" '.$target.'>'.$text.'</a>';
 4413: }
 4414: ##############################################
 4415: 
 4416: =pod
 4417: 
 4418: =back
 4419: 
 4420: =cut
 4421: 
 4422: ###############################################
 4423: 
 4424: 
 4425: sub timehash {
 4426:     my ($thistime) = @_;
 4427:     my $timezone = &Apache::lonlocal::gettimezone();
 4428:     my $dt = DateTime->from_epoch(epoch => $thistime)
 4429:                      ->set_time_zone($timezone);
 4430:     my $wday = $dt->day_of_week();
 4431:     if ($wday == 7) { $wday = 0; }
 4432:     return ( 'second' => $dt->second(),
 4433:              'minute' => $dt->minute(),
 4434:              'hour'   => $dt->hour(),
 4435:              'day'     => $dt->day_of_month(),
 4436:              'month'   => $dt->month(),
 4437:              'year'    => $dt->year(),
 4438:              'weekday' => $wday,
 4439:              'dayyear' => $dt->day_of_year(),
 4440:              'dlsav'   => $dt->is_dst() );
 4441: }
 4442: 
 4443: sub utc_string {
 4444:     my ($date)=@_;
 4445:     return strftime("%Y%m%dT%H%M%SZ",gmtime($date));
 4446: }
 4447: 
 4448: sub maketime {
 4449:     my %th=@_;
 4450:     my ($epoch_time,$timezone,$dt);
 4451:     $timezone = &Apache::lonlocal::gettimezone();
 4452:     eval {
 4453:         $dt = DateTime->new( year   => $th{'year'},
 4454:                              month  => $th{'month'},
 4455:                              day    => $th{'day'},
 4456:                              hour   => $th{'hour'},
 4457:                              minute => $th{'minute'},
 4458:                              second => $th{'second'},
 4459:                              time_zone => $timezone,
 4460:                          );
 4461:     };
 4462:     if (!$@) {
 4463:         $epoch_time = $dt->epoch;
 4464:         if ($epoch_time) {
 4465:             return $epoch_time;
 4466:         }
 4467:     }
 4468:     return POSIX::mktime(
 4469:         ($th{'seconds'},$th{'minutes'},$th{'hours'},
 4470:          $th{'day'},$th{'month'}-1,$th{'year'}-1900,0,0,-1));
 4471: }
 4472: 
 4473: #########################################
 4474: 
 4475: sub findallcourses {
 4476:     my ($roles,$uname,$udom) = @_;
 4477:     my %roles;
 4478:     if (ref($roles)) { %roles = map { $_ => 1 } @{$roles}; }
 4479:     my %courses;
 4480:     my $now=time;
 4481:     if (!defined($uname)) {
 4482:         $uname = $env{'user.name'};
 4483:     }
 4484:     if (!defined($udom)) {
 4485:         $udom = $env{'user.domain'};
 4486:     }
 4487:     if (($uname ne $env{'user.name'}) || ($udom ne $env{'user.domain'})) {
 4488:         my %roleshash = &Apache::lonnet::dump('roles',$udom,$uname);
 4489:         if (!%roles) {
 4490:             %roles = (
 4491:                        cc => 1,
 4492:                        co => 1,
 4493:                        in => 1,
 4494:                        ep => 1,
 4495:                        ta => 1,
 4496:                        cr => 1,
 4497:                        st => 1,
 4498:              );
 4499:         }
 4500:         foreach my $entry (keys(%roleshash)) {
 4501:             my ($trole,$tend,$tstart) = split(/_/,$roleshash{$entry});
 4502:             if ($trole =~ /^cr/) { 
 4503:                 next if (!exists($roles{$trole}) && !exists($roles{'cr'}));
 4504:             } else {
 4505:                 next if (!exists($roles{$trole}));
 4506:             }
 4507:             if ($tend) {
 4508:                 next if ($tend < $now);
 4509:             }
 4510:             if ($tstart) {
 4511:                 next if ($tstart > $now);
 4512:             }
 4513:             my ($cdom,$cnum,$sec,$cnumpart,$secpart,$role);
 4514:             (undef,$cdom,$cnumpart,$secpart) = split(/\//,$entry);
 4515:             my $value = $trole.'/'.$cdom.'/';
 4516:             if ($secpart eq '') {
 4517:                 ($cnum,$role) = split(/_/,$cnumpart); 
 4518:                 $sec = 'none';
 4519:                 $value .= $cnum.'/';
 4520:             } else {
 4521:                 $cnum = $cnumpart;
 4522:                 ($sec,$role) = split(/_/,$secpart);
 4523:                 $value .= $cnum.'/'.$sec;
 4524:             }
 4525:             if (ref($courses{$cdom.'_'.$cnum}{$sec}) eq 'ARRAY') {
 4526:                 unless (grep(/^\Q$value\E$/,@{$courses{$cdom.'_'.$cnum}{$sec}})) {
 4527:                     push(@{$courses{$cdom.'_'.$cnum}{$sec}},$value);
 4528:                 }
 4529:             } else {
 4530:                 @{$courses{$cdom.'_'.$cnum}{$sec}} = ($value);
 4531:             }
 4532:         }
 4533:     } else {
 4534:         foreach my $key (keys(%env)) {
 4535: 	    if ( $key=~m{^user\.role\.(\w+)\./($match_domain)/($match_courseid)/?(\w*)$} ||
 4536:                  $key=~m{^user\.role\.(cr/$match_domain/$match_username/\w+)\./($match_domain)/($match_courseid)/?(\w*)$}) {
 4537: 	        my ($role,$cdom,$cnum,$sec) = ($1,$2,$3,$4);
 4538: 	        next if ($role eq 'ca' || $role eq 'aa');
 4539: 	        next if (%roles && !exists($roles{$role}));
 4540: 	        my ($starttime,$endtime)=split(/\./,$env{$key});
 4541:                 my $active=1;
 4542:                 if ($starttime) {
 4543: 		    if ($now<$starttime) { $active=0; }
 4544:                 }
 4545:                 if ($endtime) {
 4546:                     if ($now>$endtime) { $active=0; }
 4547:                 }
 4548:                 if ($active) {
 4549:                     my $value = $role.'/'.$cdom.'/'.$cnum.'/';
 4550:                     if ($sec eq '') {
 4551:                         $sec = 'none';
 4552:                     } else {
 4553:                         $value .= $sec;
 4554:                     }
 4555:                     if (ref($courses{$cdom.'_'.$cnum}{$sec}) eq 'ARRAY') {
 4556:                         unless (grep(/^\Q$value\E$/,@{$courses{$cdom.'_'.$cnum}{$sec}})) {
 4557:                             push(@{$courses{$cdom.'_'.$cnum}{$sec}},$value);
 4558:                         }
 4559:                     } else {
 4560:                         @{$courses{$cdom.'_'.$cnum}{$sec}} = ($value);
 4561:                     }
 4562:                 }
 4563:             }
 4564:         }
 4565:     }
 4566:     return %courses;
 4567: }
 4568: 
 4569: ###############################################
 4570: 
 4571: sub blockcheck {
 4572:     my ($setters,$activity,$uname,$udom,$url,$is_course) = @_;
 4573: 
 4574:     if (defined($udom) && defined($uname)) {
 4575:         # If uname and udom are for a course, check for blocks in the course.
 4576:         if (($is_course) || (&Apache::lonnet::is_course($udom,$uname))) {
 4577:             my ($startblock,$endblock,$triggerblock) =
 4578:                 &get_blocks($setters,$activity,$udom,$uname,$url);
 4579:             return ($startblock,$endblock,$triggerblock);
 4580:         }
 4581:     } else {
 4582:         $udom = $env{'user.domain'};
 4583:         $uname = $env{'user.name'};
 4584:     }
 4585: 
 4586:     my $startblock = 0;
 4587:     my $endblock = 0;
 4588:     my $triggerblock = '';
 4589:     my %live_courses = &findallcourses(undef,$uname,$udom);
 4590: 
 4591:     # If uname is for a user, and activity is course-specific, i.e.,
 4592:     # boards, chat or groups, check for blocking in current course only.
 4593: 
 4594:     if (($activity eq 'boards' || $activity eq 'chat' ||
 4595:          $activity eq 'groups' || $activity eq 'printout') &&
 4596:         ($env{'request.course.id'})) {
 4597:         foreach my $key (keys(%live_courses)) {
 4598:             if ($key ne $env{'request.course.id'}) {
 4599:                 delete($live_courses{$key});
 4600:             }
 4601:         }
 4602:     }
 4603: 
 4604:     my $otheruser = 0;
 4605:     my %own_courses;
 4606:     if ((($uname ne $env{'user.name'})) || ($udom ne $env{'user.domain'})) {
 4607:         # Resource belongs to user other than current user.
 4608:         $otheruser = 1;
 4609:         # Gather courses for current user
 4610:         %own_courses = 
 4611:             &findallcourses(undef,$env{'user.name'},$env{'user.domain'});
 4612:     }
 4613: 
 4614:     # Gather active course roles - course coordinator, instructor, 
 4615:     # exam proctor, ta, student, or custom role.
 4616: 
 4617:     foreach my $course (keys(%live_courses)) {
 4618:         my ($cdom,$cnum);
 4619:         if ((defined($env{'course.'.$course.'.domain'})) && (defined($env{'course.'.$course.'.num'}))) {
 4620:             $cdom = $env{'course.'.$course.'.domain'};
 4621:             $cnum = $env{'course.'.$course.'.num'};
 4622:         } else {
 4623:             ($cdom,$cnum) = split(/_/,$course); 
 4624:         }
 4625:         my $no_ownblock = 0;
 4626:         my $no_userblock = 0;
 4627:         if ($otheruser && $activity ne 'com') {
 4628:             # Check if current user has 'evb' priv for this
 4629:             if (defined($own_courses{$course})) {
 4630:                 foreach my $sec (keys(%{$own_courses{$course}})) {
 4631:                     my $checkrole = 'cm./'.$cdom.'/'.$cnum;
 4632:                     if ($sec ne 'none') {
 4633:                         $checkrole .= '/'.$sec;
 4634:                     }
 4635:                     if (&Apache::lonnet::allowed('evb',undef,undef,$checkrole)) {
 4636:                         $no_ownblock = 1;
 4637:                         last;
 4638:                     }
 4639:                 }
 4640:             }
 4641:             # if they have 'evb' priv and are currently not playing student
 4642:             next if (($no_ownblock) &&
 4643:                  ($env{'request.role'} !~ m{^st\./$cdom/$cnum}));
 4644:         }
 4645:         foreach my $sec (keys(%{$live_courses{$course}})) {
 4646:             my $checkrole = 'cm./'.$cdom.'/'.$cnum;
 4647:             if ($sec ne 'none') {
 4648:                 $checkrole .= '/'.$sec;
 4649:             }
 4650:             if ($otheruser) {
 4651:                 # Resource belongs to user other than current user.
 4652:                 # Assemble privs for that user, and check for 'evb' priv.
 4653:                 my (%allroles,%userroles);
 4654:                 if (ref($live_courses{$course}{$sec}) eq 'ARRAY') {
 4655:                     foreach my $entry (@{$live_courses{$course}{$sec}}) { 
 4656:                         my ($trole,$tdom,$tnum,$tsec);
 4657:                         if ($entry =~ /^cr/) {
 4658:                             ($trole,$tdom,$tnum,$tsec) = 
 4659:                                 ($entry =~ m|^(cr/$match_domain/$match_username/\w+)\./($match_domain)/($match_username)/?(\w*)$|);
 4660:                         } else {
 4661:                            ($trole,$tdom,$tnum,$tsec) = split(/\//,$entry);
 4662:                         }
 4663:                         my ($spec,$area,$trest);
 4664:                         $area = '/'.$tdom.'/'.$tnum;
 4665:                         $trest = $tnum;
 4666:                         if ($tsec ne '') {
 4667:                             $area .= '/'.$tsec;
 4668:                             $trest .= '/'.$tsec;
 4669:                         }
 4670:                         $spec = $trole.'.'.$area;
 4671:                         if ($trole =~ /^cr/) {
 4672:                             &Apache::lonnet::custom_roleprivs(\%allroles,$trole,
 4673:                                                               $tdom,$spec,$trest,$area);
 4674:                         } else {
 4675:                             &Apache::lonnet::standard_roleprivs(\%allroles,$trole,
 4676:                                                                 $tdom,$spec,$trest,$area);
 4677:                         }
 4678:                     }
 4679:                     my ($author,$adv) = &Apache::lonnet::set_userprivs(\%userroles,\%allroles);
 4680:                     if ($userroles{'user.priv.'.$checkrole} =~ /evb\&([^\:]*)/) {
 4681:                         if ($1) {
 4682:                             $no_userblock = 1;
 4683:                             last;
 4684:                         }
 4685:                     }
 4686:                 }
 4687:             } else {
 4688:                 # Resource belongs to current user
 4689:                 # Check for 'evb' priv via lonnet::allowed().
 4690:                 if (&Apache::lonnet::allowed('evb',undef,undef,$checkrole)) {
 4691:                     $no_ownblock = 1;
 4692:                     last;
 4693:                 }
 4694:             }
 4695:         }
 4696:         # if they have the evb priv and are currently not playing student
 4697:         next if (($no_ownblock) &&
 4698:                  ($env{'request.role'} !~ m{^st\./\Q$cdom\E/\Q$cnum\E}));
 4699:         next if ($no_userblock);
 4700: 
 4701:         # Retrieve blocking times and identity of locker for course
 4702:         # of specified user, unless user has 'evb' privilege.
 4703:         
 4704:         my ($start,$end,$trigger) = 
 4705:             &get_blocks($setters,$activity,$cdom,$cnum,$url);
 4706:         if (($start != 0) && 
 4707:             (($startblock == 0) || ($startblock > $start))) {
 4708:             $startblock = $start;
 4709:             if ($trigger ne '') {
 4710:                 $triggerblock = $trigger;
 4711:             }
 4712:         }
 4713:         if (($end != 0)  &&
 4714:             (($endblock == 0) || ($endblock < $end))) {
 4715:             $endblock = $end;
 4716:             if ($trigger ne '') {
 4717:                 $triggerblock = $trigger;
 4718:             }
 4719:         }
 4720:     }
 4721:     return ($startblock,$endblock,$triggerblock);
 4722: }
 4723: 
 4724: sub get_blocks {
 4725:     my ($setters,$activity,$cdom,$cnum,$url) = @_;
 4726:     my $startblock = 0;
 4727:     my $endblock = 0;
 4728:     my $triggerblock = '';
 4729:     my $course = $cdom.'_'.$cnum;
 4730:     $setters->{$course} = {};
 4731:     $setters->{$course}{'staff'} = [];
 4732:     $setters->{$course}{'times'} = [];
 4733:     $setters->{$course}{'triggers'} = [];
 4734:     my (@blockers,%triggered);
 4735:     my $now = time;
 4736:     my %commblocks = &Apache::lonnet::get_comm_blocks($cdom,$cnum);
 4737:     if ($activity eq 'docs') {
 4738:         @blockers = &Apache::lonnet::has_comm_blocking('bre',undef,$url,\%commblocks);
 4739:         foreach my $block (@blockers) {
 4740:             if ($block =~ /^firstaccess____(.+)$/) {
 4741:                 my $item = $1;
 4742:                 my $type = 'map';
 4743:                 my $timersymb = $item;
 4744:                 if ($item eq 'course') {
 4745:                     $type = 'course';
 4746:                 } elsif ($item =~ /___\d+___/) {
 4747:                     $type = 'resource';
 4748:                 } else {
 4749:                     $timersymb = &Apache::lonnet::symbread($item);
 4750:                 }
 4751:                 my $start = $env{'course.'.$cdom.'_'.$cnum.'.firstaccess.'.$timersymb};
 4752:                 my $end = $start + $env{'course.'.$cdom.'_'.$cnum.'.timerinterval.'.$timersymb};
 4753:                 $triggered{$block} = {
 4754:                                        start => $start,
 4755:                                        end   => $end,
 4756:                                        type  => $type,
 4757:                                      };
 4758:             }
 4759:         }
 4760:     } else {
 4761:         foreach my $block (keys(%commblocks)) {
 4762:             if ($block =~ m/^(\d+)____(\d+)$/) { 
 4763:                 my ($start,$end) = ($1,$2);
 4764:                 if ($start <= time && $end >= time) {
 4765:                     if (ref($commblocks{$block}) eq 'HASH') {
 4766:                         if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
 4767:                             if ($commblocks{$block}{'blocks'}{$activity} eq 'on') {
 4768:                                 unless(grep(/^\Q$block\E$/,@blockers)) {
 4769:                                     push(@blockers,$block);
 4770:                                 }
 4771:                             }
 4772:                         }
 4773:                     }
 4774:                 }
 4775:             } elsif ($block =~ /^firstaccess____(.+)$/) {
 4776:                 my $item = $1;
 4777:                 my $timersymb = $item; 
 4778:                 my $type = 'map';
 4779:                 if ($item eq 'course') {
 4780:                     $type = 'course';
 4781:                 } elsif ($item =~ /___\d+___/) {
 4782:                     $type = 'resource';
 4783:                 } else {
 4784:                     $timersymb = &Apache::lonnet::symbread($item);
 4785:                 }
 4786:                 my $start = $env{'course.'.$cdom.'_'.$cnum.'.firstaccess.'.$timersymb};
 4787:                 my $end = $start + $env{'course.'.$cdom.'_'.$cnum.'.timerinterval.'.$timersymb}; 
 4788:                 if ($start && $end) {
 4789:                     if (($start <= time) && ($end >= time)) {
 4790:                         unless (grep(/^\Q$block\E$/,@blockers)) {
 4791:                             push(@blockers,$block);
 4792:                             $triggered{$block} = {
 4793:                                                    start => $start,
 4794:                                                    end   => $end,
 4795:                                                    type  => $type,
 4796:                                                  };
 4797:                         }
 4798:                     }
 4799:                 }
 4800:             }
 4801:         }
 4802:     }
 4803:     foreach my $blocker (@blockers) {
 4804:         my ($staff_name,$staff_dom,$title,$blocks) =
 4805:             &parse_block_record($commblocks{$blocker});
 4806:         push(@{$$setters{$course}{'staff'}},[$staff_name,$staff_dom]);
 4807:         my ($start,$end,$triggertype);
 4808:         if ($blocker =~ m/^(\d+)____(\d+)$/) {
 4809:             ($start,$end) = ($1,$2);
 4810:         } elsif (ref($triggered{$blocker}) eq 'HASH') {
 4811:             $start = $triggered{$blocker}{'start'};
 4812:             $end = $triggered{$blocker}{'end'};
 4813:             $triggertype = $triggered{$blocker}{'type'};
 4814:         }
 4815:         if ($start) {
 4816:             push(@{$$setters{$course}{'times'}}, [$start,$end]);
 4817:             if ($triggertype) {
 4818:                 push(@{$$setters{$course}{'triggers'}},$triggertype);
 4819:             } else {
 4820:                 push(@{$$setters{$course}{'triggers'}},0);
 4821:             }
 4822:             if ( ($startblock == 0) || ($startblock > $start) ) {
 4823:                 $startblock = $start;
 4824:                 if ($triggertype) {
 4825:                     $triggerblock = $blocker;
 4826:                 }
 4827:             }
 4828:             if ( ($endblock == 0) || ($endblock < $end) ) {
 4829:                $endblock = $end;
 4830:                if ($triggertype) {
 4831:                    $triggerblock = $blocker;
 4832:                }
 4833:             }
 4834:         }
 4835:     }
 4836:     return ($startblock,$endblock,$triggerblock);
 4837: }
 4838: 
 4839: sub parse_block_record {
 4840:     my ($record) = @_;
 4841:     my ($setuname,$setudom,$title,$blocks);
 4842:     if (ref($record) eq 'HASH') {
 4843:         ($setuname,$setudom) = split(/:/,$record->{'setter'});
 4844:         $title = &unescape($record->{'event'});
 4845:         $blocks = $record->{'blocks'};
 4846:     } else {
 4847:         my @data = split(/:/,$record,3);
 4848:         if (scalar(@data) eq 2) {
 4849:             $title = $data[1];
 4850:             ($setuname,$setudom) = split(/@/,$data[0]);
 4851:         } else {
 4852:             ($setuname,$setudom,$title) = @data;
 4853:         }
 4854:         $blocks = { 'com' => 'on' };
 4855:     }
 4856:     return ($setuname,$setudom,$title,$blocks);
 4857: }
 4858: 
 4859: sub blocking_status {
 4860:     my ($activity,$uname,$udom,$url,$is_course) = @_;
 4861:     my %setters;
 4862: 
 4863: # check for active blocking
 4864:     my ($startblock,$endblock,$triggerblock) = 
 4865:         &blockcheck(\%setters,$activity,$uname,$udom,$url,$is_course);
 4866:     my $blocked = 0;
 4867:     if ($startblock && $endblock) {
 4868:         $blocked = 1;
 4869:     }
 4870: 
 4871: # caller just wants to know whether a block is active
 4872:     if (!wantarray) { return $blocked; }
 4873: 
 4874: # build a link to a popup window containing the details
 4875:     my $querystring  = "?activity=$activity";
 4876: # $uname and $udom decide whose portfolio the user is trying to look at
 4877:     if (($activity eq 'port') || ($activity eq 'passwd')) {
 4878:         $querystring .= "&amp;udom=$udom"      if ($udom =~ /^$match_domain$/);
 4879:         $querystring .= "&amp;uname=$uname"    if ($uname =~ /^$match_username$/);
 4880:     } elsif ($activity eq 'docs') {
 4881:         $querystring .= '&amp;url='.&HTML::Entities::encode($url,'&"');
 4882:     }
 4883: 
 4884:     my $output .= <<'END_MYBLOCK';
 4885: function openWindow(url, wdwName, w, h, toolbar,scrollbar) {
 4886:     var options = "width=" + w + ",height=" + h + ",";
 4887:     options += "resizable=yes,scrollbars="+scrollbar+",status=no,";
 4888:     options += "menubar=no,toolbar="+toolbar+",location=no,directories=no";
 4889:     var newWin = window.open(url, wdwName, options);
 4890:     newWin.focus();
 4891: }
 4892: END_MYBLOCK
 4893: 
 4894:     $output = Apache::lonhtmlcommon::scripttag($output);
 4895:   
 4896:     my $popupUrl = "/adm/blockingstatus/$querystring";
 4897:     my $text = &mt('Communication Blocked');
 4898:     my $class = 'LC_comblock';
 4899:     if ($activity eq 'docs') {
 4900:         $text = &mt('Content Access Blocked');
 4901:         $class = '';
 4902:     } elsif ($activity eq 'printout') {
 4903:         $text = &mt('Printing Blocked');
 4904:     } elsif ($activity eq 'passwd') {
 4905:         $text = &mt('Password Changing Blocked');
 4906:     }
 4907:     $output .= <<"END_BLOCK";
 4908: <div class='$class'>
 4909:   <a onclick='openWindow("$popupUrl","Blocking Table",600,300,"no","no");return false;' href='/adm/blockingstatus/$querystring'
 4910:   title='$text'>
 4911:   <img class='LC_noBorder LC_middle' title='$text' src='/res/adm/pages/comblock.png' alt='$text'/></a>
 4912:   <a onclick='openWindow("$popupUrl","Blocking Table",600,300,"no","no");return false;' href='/adm/blockingstatus/$querystring' 
 4913:   title='$text'>$text</a>
 4914: </div>
 4915: 
 4916: END_BLOCK
 4917: 
 4918:     return ($blocked, $output);
 4919: }
 4920: 
 4921: ###############################################
 4922: 
 4923: sub check_ip_acc {
 4924:     my ($acc,$clientip)=@_;
 4925:     &Apache::lonxml::debug("acc is $acc");
 4926:     if (!defined($acc) || $acc =~ /^\s*$/ || $acc =~/^\s*no\s*$/i) {
 4927:         return 1;
 4928:     }
 4929:     my $allowed=0;
 4930:     my $ip=$ENV{'REMOTE_ADDR'} || $clientip || $env{'request.host'};
 4931: 
 4932:     my $name;
 4933:     foreach my $pattern (split(',',$acc)) {
 4934:         $pattern =~ s/^\s*//;
 4935:         $pattern =~ s/\s*$//;
 4936:         if ($pattern =~ /\*$/) {
 4937:             #35.8.*
 4938:             $pattern=~s/\*//;
 4939:             if ($ip =~ /^\Q$pattern\E/) { $allowed=1; }
 4940:         } elsif ($pattern =~ /(\d+\.\d+\.\d+)\.\[(\d+)-(\d+)\]$/) {
 4941:             #35.8.3.[34-56]
 4942:             my $low=$2;
 4943:             my $high=$3;
 4944:             $pattern=$1;
 4945:             if ($ip =~ /^\Q$pattern\E/) {
 4946:                 my $last=(split(/\./,$ip))[3];
 4947:                 if ($last <=$high && $last >=$low) { $allowed=1; }
 4948:             }
 4949:         } elsif ($pattern =~ /^\*/) {
 4950:             #*.msu.edu
 4951:             $pattern=~s/\*//;
 4952:             if (!defined($name)) {
 4953:                 use Socket;
 4954:                 my $netaddr=inet_aton($ip);
 4955:                 ($name)=gethostbyaddr($netaddr,AF_INET);
 4956:             }
 4957:             if ($name =~ /\Q$pattern\E$/i) { $allowed=1; }
 4958:         } elsif ($pattern =~ /\d+\.\d+\.\d+\.\d+/) {
 4959:             #127.0.0.1
 4960:             if ($ip =~ /^\Q$pattern\E/) { $allowed=1; }
 4961:         } else {
 4962:             #some.name.com
 4963:             if (!defined($name)) {
 4964:                 use Socket;
 4965:                 my $netaddr=inet_aton($ip);
 4966:                 ($name)=gethostbyaddr($netaddr,AF_INET);
 4967:             }
 4968:             if ($name =~ /\Q$pattern\E$/i) { $allowed=1; }
 4969:         }
 4970:         if ($allowed) { last; }
 4971:     }
 4972:     return $allowed;
 4973: }
 4974: 
 4975: ###############################################
 4976: 
 4977: =pod
 4978: 
 4979: =head1 Domain Template Functions
 4980: 
 4981: =over 4
 4982: 
 4983: =item * &determinedomain()
 4984: 
 4985: Inputs: $domain (usually will be undef)
 4986: 
 4987: Returns: Determines which domain should be used for designs
 4988: 
 4989: =cut
 4990: 
 4991: ###############################################
 4992: sub determinedomain {
 4993:     my $domain=shift;
 4994:     if (! $domain) {
 4995:         # Determine domain if we have not been given one
 4996:         $domain = &Apache::lonnet::default_login_domain();
 4997:         if ($env{'user.domain'}) { $domain=$env{'user.domain'}; }
 4998:         if ($env{'request.role.domain'}) { 
 4999:             $domain=$env{'request.role.domain'}; 
 5000:         }
 5001:     }
 5002:     return $domain;
 5003: }
 5004: ###############################################
 5005: 
 5006: sub devalidate_domconfig_cache {
 5007:     my ($udom)=@_;
 5008:     &Apache::lonnet::devalidate_cache_new('domainconfig',$udom);
 5009: }
 5010: 
 5011: # ---------------------- Get domain configuration for a domain
 5012: sub get_domainconf {
 5013:     my ($udom) = @_;
 5014:     my $cachetime=1800;
 5015:     my ($result,$cached)=&Apache::lonnet::is_cached_new('domainconfig',$udom);
 5016:     if (defined($cached)) { return %{$result}; }
 5017: 
 5018:     my %domconfig = &Apache::lonnet::get_dom('configuration',
 5019: 					     ['login','rolecolors','autoenroll'],$udom);
 5020:     my (%designhash,%legacy);
 5021:     if (keys(%domconfig) > 0) {
 5022:         if (ref($domconfig{'login'}) eq 'HASH') {
 5023:             if (keys(%{$domconfig{'login'}})) {
 5024:                 foreach my $key (keys(%{$domconfig{'login'}})) {
 5025:                     if (ref($domconfig{'login'}{$key}) eq 'HASH') {
 5026:                         if (($key eq 'loginvia') || ($key eq 'headtag')) {
 5027:                             if (ref($domconfig{'login'}{$key}) eq 'HASH') {
 5028:                                 foreach my $hostname (keys(%{$domconfig{'login'}{$key}})) {
 5029:                                     if (ref($domconfig{'login'}{$key}{$hostname}) eq 'HASH') {
 5030:                                         if ($key eq 'loginvia') {
 5031:                                             if ($domconfig{'login'}{'loginvia'}{$hostname}{'server'}) {
 5032:                                                 my $server = $domconfig{'login'}{'loginvia'}{$hostname}{'server'};
 5033:                                                 $designhash{$udom.'.login.loginvia'} = $server;
 5034:                                                 if ($domconfig{'login'}{'loginvia'}{$hostname}{'serverpath'} eq 'custom') {
 5035:                                                     $designhash{$udom.'.login.loginvia_'.$hostname} = $server.':'.$domconfig{'login'}{'loginvia'}{$hostname}{'custompath'};
 5036:                                                 } else {
 5037:                                                     $designhash{$udom.'.login.loginvia_'.$hostname} = $server.':'.$domconfig{'login'}{'loginvia'}{$hostname}{'serverpath'};
 5038:                                                 }
 5039:                                             }
 5040:                                         } elsif ($key eq 'headtag') {
 5041:                                             if ($domconfig{'login'}{'headtag'}{$hostname}{'url'}) {
 5042:                                                 $designhash{$udom.'.login.headtag_'.$hostname} = $domconfig{'login'}{'headtag'}{$hostname}{'url'};
 5043:                                             }
 5044:                                         }
 5045:                                         if ($domconfig{'login'}{$key}{$hostname}{'exempt'}) {
 5046:                                             $designhash{$udom.'.login.'.$key.'_exempt_'.$hostname} = $domconfig{'login'}{$key}{$hostname}{'exempt'};
 5047:                                         }
 5048:                                     }
 5049:                                 }
 5050:                             }
 5051:                         } else {
 5052:                             foreach my $img (keys(%{$domconfig{'login'}{$key}})) {
 5053:                                 $designhash{$udom.'.login.'.$key.'_'.$img} = 
 5054:                                     $domconfig{'login'}{$key}{$img};
 5055:                             }
 5056:                         }
 5057:                     } else {
 5058:                         $designhash{$udom.'.login.'.$key}=$domconfig{'login'}{$key};
 5059:                     }
 5060:                 }
 5061:             } else {
 5062:                 $legacy{'login'} = 1;
 5063:             }
 5064:         } else {
 5065:             $legacy{'login'} = 1;
 5066:         }
 5067:         if (ref($domconfig{'rolecolors'}) eq 'HASH') {
 5068:             if (keys(%{$domconfig{'rolecolors'}})) {
 5069:                 foreach my $role (keys(%{$domconfig{'rolecolors'}})) {
 5070:                     if (ref($domconfig{'rolecolors'}{$role}) eq 'HASH') {
 5071:                         foreach my $item (keys(%{$domconfig{'rolecolors'}{$role}})) {
 5072:                             $designhash{$udom.'.'.$role.'.'.$item}=$domconfig{'rolecolors'}{$role}{$item};
 5073:                         }
 5074:                     }
 5075:                 }
 5076:             } else {
 5077:                 $legacy{'rolecolors'} = 1;
 5078:             }
 5079:         } else {
 5080:             $legacy{'rolecolors'} = 1;
 5081:         }
 5082:         if (ref($domconfig{'autoenroll'}) eq 'HASH') {
 5083:             if ($domconfig{'autoenroll'}{'co-owners'}) {
 5084:                 $designhash{$udom.'.autoassign.co-owners'}=$domconfig{'autoenroll'}{'co-owners'};
 5085:             }
 5086:         }
 5087:         if (keys(%legacy) > 0) {
 5088:             my %legacyhash = &get_legacy_domconf($udom);
 5089:             foreach my $item (keys(%legacyhash)) {
 5090:                 if ($item =~ /^\Q$udom\E\.login/) {
 5091:                     if ($legacy{'login'}) { 
 5092:                         $designhash{$item} = $legacyhash{$item};
 5093:                     }
 5094:                 } else {
 5095:                     if ($legacy{'rolecolors'}) {
 5096:                         $designhash{$item} = $legacyhash{$item};
 5097:                     }
 5098:                 }
 5099:             }
 5100:         }
 5101:     } else {
 5102:         %designhash = &get_legacy_domconf($udom); 
 5103:     }
 5104:     &Apache::lonnet::do_cache_new('domainconfig',$udom,\%designhash,
 5105: 				  $cachetime);
 5106:     return %designhash;
 5107: }
 5108: 
 5109: sub get_legacy_domconf {
 5110:     my ($udom) = @_;
 5111:     my %legacyhash;
 5112:     my $designdir=$Apache::lonnet::perlvar{'lonTabDir'}.'/lonDomColors';
 5113:     my $designfile =  $designdir.'/'.$udom.'.tab';
 5114:     if (-e $designfile) {
 5115:         if ( open (my $fh,"<$designfile") ) {
 5116:             while (my $line = <$fh>) {
 5117:                 next if ($line =~ /^\#/);
 5118:                 chomp($line);
 5119:                 my ($key,$val)=(split(/\=/,$line));
 5120:                 if ($val) { $legacyhash{$udom.'.'.$key}=$val; }
 5121:             }
 5122:             close($fh);
 5123:         }
 5124:     }
 5125:     if (-e $Apache::lonnet::perlvar{'lonDocRoot'}.'/adm/lonDomLogos/'.$udom.'.gif') {
 5126:         $legacyhash{$udom.'.login.domlogo'} = "/adm/lonDomLogos/$udom.gif";
 5127:     }
 5128:     return %legacyhash;
 5129: }
 5130: 
 5131: =pod
 5132: 
 5133: =item * &domainlogo()
 5134: 
 5135: Inputs: $domain (usually will be undef)
 5136: 
 5137: Returns: A link to a domain logo, if the domain logo exists.
 5138: If the domain logo does not exist, a description of the domain.
 5139: 
 5140: =cut
 5141: 
 5142: ###############################################
 5143: sub domainlogo {
 5144:     my $domain = &determinedomain(shift);
 5145:     my %designhash = &get_domainconf($domain);    
 5146:     # See if there is a logo
 5147:     if ($designhash{$domain.'.login.domlogo'} ne '') {
 5148:         my $imgsrc = $designhash{$domain.'.login.domlogo'};
 5149:         if ($imgsrc =~ m{^/(adm|res)/}) {
 5150: 	    if ($imgsrc =~ m{^/res/}) {
 5151: 		my $local_name = &Apache::lonnet::filelocation('',$imgsrc);
 5152: 		&Apache::lonnet::repcopy($local_name);
 5153: 	    }
 5154: 	   $imgsrc = &lonhttpdurl($imgsrc);
 5155:         } 
 5156:         return '<img src="'.$imgsrc.'" alt="'.$domain.'" />';
 5157:     } elsif (defined(&Apache::lonnet::domain($domain,'description'))) {
 5158:         return &Apache::lonnet::domain($domain,'description');
 5159:     } else {
 5160:         return '';
 5161:     }
 5162: }
 5163: ##############################################
 5164: 
 5165: =pod
 5166: 
 5167: =item * &designparm()
 5168: 
 5169: Inputs: $which parameter; $domain (usually will be undef)
 5170: 
 5171: Returns: value of designparamter $which
 5172: 
 5173: =cut
 5174: 
 5175: 
 5176: ##############################################
 5177: sub designparm {
 5178:     my ($which,$domain)=@_;
 5179:     if (exists($env{'environment.color.'.$which})) {
 5180:         return $env{'environment.color.'.$which};
 5181:     }
 5182:     $domain=&determinedomain($domain);
 5183:     my %domdesign;
 5184:     unless ($domain eq 'public') {
 5185:         %domdesign = &get_domainconf($domain);
 5186:     }
 5187:     my $output;
 5188:     if ($domdesign{$domain.'.'.$which} ne '') {
 5189:         $output = $domdesign{$domain.'.'.$which};
 5190:     } else {
 5191:         $output = $defaultdesign{$which};
 5192:     }
 5193:     if (($which =~ /^(student|coordinator|author|admin)\.img$/) ||
 5194:         ($which =~ /login\.(img|logo|domlogo|login)/)) {
 5195:         if ($output =~ m{^/(adm|res)/}) {
 5196:             if ($output =~ m{^/res/}) {
 5197:                 my $local_name = &Apache::lonnet::filelocation('',$output);
 5198:                 &Apache::lonnet::repcopy($local_name);
 5199:             }
 5200:             $output = &lonhttpdurl($output);
 5201:         }
 5202:     }
 5203:     return $output;
 5204: }
 5205: 
 5206: ##############################################
 5207: =pod
 5208: 
 5209: =item * &authorspace()
 5210: 
 5211: Inputs: $url (usually will be undef).
 5212: 
 5213: Returns: Path to Authoring Space containing the resource or 
 5214:          directory being viewed (or for which action is being taken). 
 5215:          If $url is provided, and begins /priv/<domain>/<uname>
 5216:          the path will be that portion of the $context argument.
 5217:          Otherwise the path will be for the author space of the current
 5218:          user when the current role is author, or for that of the 
 5219:          co-author/assistant co-author space when the current role 
 5220:          is co-author or assistant co-author.
 5221: 
 5222: =cut
 5223: 
 5224: sub authorspace {
 5225:     my ($url) = @_;
 5226:     if ($url ne '') {
 5227:         if ($url =~ m{^(/priv/$match_domain/$match_username/)}) {
 5228:            return $1;
 5229:         }
 5230:     }
 5231:     my $caname = '';
 5232:     my $cadom = '';
 5233:     if ($env{'request.role'} =~ /^(?:ca|aa)/) {
 5234:         ($cadom,$caname) =
 5235:             ($env{'request.role'}=~/($match_domain)\/($match_username)$/);
 5236:     } elsif ($env{'request.role'} =~ m{^au\./($match_domain)/}) {
 5237:         $caname = $env{'user.name'};
 5238:         $cadom = $env{'user.domain'};
 5239:     }
 5240:     if (($caname ne '') && ($cadom ne '')) {
 5241:         return "/priv/$cadom/$caname/";
 5242:     }
 5243:     return;
 5244: }
 5245: 
 5246: ##############################################
 5247: =pod
 5248: 
 5249: =item * &head_subbox()
 5250: 
 5251: Inputs: $content (contains HTML code with page functions, etc.)
 5252: 
 5253: Returns: HTML div with $content
 5254:          To be included in page header
 5255: 
 5256: =cut
 5257: 
 5258: sub head_subbox {
 5259:     my ($content)=@_;
 5260:     my $output =
 5261:         '<div class="LC_head_subbox">'
 5262:        .$content
 5263:        .'</div>'
 5264: }
 5265: 
 5266: ##############################################
 5267: =pod
 5268: 
 5269: =item * &CSTR_pageheader()
 5270: 
 5271: Input: (optional) filename from which breadcrumb trail is built.
 5272:        In most cases no input as needed, as $env{'request.filename'}
 5273:        is appropriate for use in building the breadcrumb trail.
 5274: 
 5275: Returns: HTML div with CSTR path and recent box
 5276:          To be included on Authoring Space pages
 5277: 
 5278: =cut
 5279: 
 5280: sub CSTR_pageheader {
 5281:     my ($trailfile) = @_;
 5282:     if ($trailfile eq '') {
 5283:         $trailfile = $env{'request.filename'};
 5284:     }
 5285: 
 5286: # this is for resources; directories have customtitle, and crumbs
 5287: # and select recent are created in lonpubdir.pm
 5288: 
 5289:     my $londocroot = $Apache::lonnet::perlvar{'lonDocRoot'};
 5290:     my ($udom,$uname,$thisdisfn)=
 5291:         ($trailfile =~ m{^\Q$londocroot\E/priv/([^/]+)/([^/]+)(?:|/(.*))$});
 5292:     my $formaction = "/priv/$udom/$uname/$thisdisfn";
 5293:     $formaction =~ s{/+}{/}g;
 5294: 
 5295:     my $parentpath = '';
 5296:     my $lastitem = '';
 5297:     if ($thisdisfn =~ m-(.+/)([^/]*)$-) {
 5298:         $parentpath = $1;
 5299:         $lastitem = $2;
 5300:     } else {
 5301:         $lastitem = $thisdisfn;
 5302:     }
 5303: 
 5304:     my $output =
 5305:          '<div>'
 5306:         .&Apache::loncommon::help_open_menu('','',3,'Authoring') #FIXME: Broken? Where is it?
 5307:         .'<b>'.&mt('Authoring Space:').'</b> '
 5308:         .'<form name="dirs" method="post" action="'.$formaction
 5309:         .'" target="_top">' #FIXME lonpubdir: target="_parent"
 5310:         .&Apache::lonhtmlcommon::crumbs($uname.'/'.$parentpath,'_top','/priv/'.$udom,undef,undef);
 5311: 
 5312:     if ($lastitem) {
 5313:         $output .=
 5314:              '<span class="LC_filename">'
 5315:             .$lastitem
 5316:             .'</span>';
 5317:     }
 5318:     $output .=
 5319:          '<br />'
 5320:         #FIXME lonpubdir: &Apache::lonhtmlcommon::crumbs($uname.$thisdisfn.'/','_top','/priv','','+1',1)."</b></tt><br />"
 5321:         .&Apache::lonhtmlcommon::select_recent('construct','recent','this.form.action=this.form.recent.value;this.form.submit()')
 5322:         .'</form>'
 5323:         .&Apache::lonmenu::constspaceform()
 5324:         .'</div>';
 5325: 
 5326:     return $output;
 5327: }
 5328: 
 5329: ###############################################
 5330: ###############################################
 5331: 
 5332: =pod
 5333: 
 5334: =back
 5335: 
 5336: =head1 HTML Helpers
 5337: 
 5338: =over 4
 5339: 
 5340: =item * &bodytag()
 5341: 
 5342: Returns a uniform header for LON-CAPA web pages.
 5343: 
 5344: Inputs: 
 5345: 
 5346: =over 4
 5347: 
 5348: =item * $title, A title to be displayed on the page.
 5349: 
 5350: =item * $function, the current role (can be undef).
 5351: 
 5352: =item * $addentries, extra parameters for the <body> tag.
 5353: 
 5354: =item * $bodyonly, if defined, only return the <body> tag.
 5355: 
 5356: =item * $domain, if defined, force a given domain.
 5357: 
 5358: =item * $forcereg, if page should register as content page (relevant for 
 5359:             text interface only)
 5360: 
 5361: =item * $no_nav_bar, if true, keep the 'what is this' info but remove the
 5362:                      navigational links
 5363: 
 5364: =item * $bgcolor, used to override the bgcolor on a webpage to a specific value
 5365: 
 5366: =item * $no_inline_link, if true and in remote mode, don't show the
 5367:          'Switch To Inline Menu' link
 5368: 
 5369: =item * $args, optional argument valid values are
 5370:             no_auto_mt_title -> prevents &mt()ing the title arg
 5371: 
 5372: =item * $advtoolsref, optional argument, ref to an array containing
 5373:             inlineremote items to be added in "Functions" menu below
 5374:             breadcrumbs.
 5375: 
 5376: =back
 5377: 
 5378: Returns: A uniform header for LON-CAPA web pages.  
 5379: If $bodyonly is nonzero, a string containing a <body> tag will be returned.
 5380: If $bodyonly is undef or zero, an html string containing a <body> tag and 
 5381: other decorations will be returned.
 5382: 
 5383: =cut
 5384: 
 5385: sub bodytag {
 5386:     my ($title,$function,$addentries,$bodyonly,$domain,$forcereg,
 5387:         $no_nav_bar,$bgcolor,$no_inline_link,$args,$advtoolsref)=@_;
 5388: 
 5389:     my $public;
 5390:     if ((($env{'user.name'} eq 'public') && ($env{'user.domain'} eq 'public'))
 5391:         || ($env{'user.name'} eq '') && ($env{'user.domain'} eq '')) {
 5392:         $public = 1;
 5393:     }
 5394:     if (!$args->{'no_auto_mt_title'}) { $title = &mt($title); }
 5395:     my $httphost = $args->{'use_absolute'};
 5396: 
 5397:     $function = &get_users_function() if (!$function);
 5398:     my $img =    &designparm($function.'.img',$domain);
 5399:     my $font =   &designparm($function.'.font',$domain);
 5400:     my $pgbg   = $bgcolor || &designparm($function.'.pgbg',$domain);
 5401: 
 5402:     my %design = ( 'style'   => 'margin-top: 0',
 5403: 		   'bgcolor' => $pgbg,
 5404: 		   'text'    => $font,
 5405:                    'alink'   => &designparm($function.'.alink',$domain),
 5406: 		   'vlink'   => &designparm($function.'.vlink',$domain),
 5407: 		   'link'    => &designparm($function.'.link',$domain),);
 5408:     @design{keys(%$addentries)} = @$addentries{keys(%$addentries)}; 
 5409: 
 5410:  # role and realm
 5411:     my ($role,$realm) = split(m{\./},$env{'request.role'},2);
 5412:     if ($realm) {
 5413:         $realm = '/'.$realm;
 5414:     }
 5415:     if ($role  eq 'ca') {
 5416:         my ($rdom,$rname) = ($realm =~ m{^/($match_domain)/($match_username)$});
 5417:         $realm = &plainname($rname,$rdom);
 5418:     } 
 5419: # realm
 5420:     if ($env{'request.course.id'}) {
 5421:         if ($env{'request.role'} !~ /^cr/) {
 5422:             $role = &Apache::lonnet::plaintext($role,&course_type());
 5423:         }
 5424:         if ($env{'request.course.sec'}) {
 5425:             $role .= ('&nbsp;'x2).'-&nbsp;'.&mt('section:').'&nbsp;'.$env{'request.course.sec'};
 5426:         }   
 5427: 	$realm = $env{'course.'.$env{'request.course.id'}.'.description'};
 5428:     } else {
 5429:         $role = &Apache::lonnet::plaintext($role);
 5430:     }
 5431: 
 5432:     if (!$realm) { $realm='&nbsp;'; }
 5433: 
 5434:     my $extra_body_attr = &make_attr_string($forcereg,\%design);
 5435: 
 5436: # construct main body tag
 5437:     my $bodytag = "<body $extra_body_attr>".
 5438: 	&Apache::lontexconvert::init_math_support();
 5439: 
 5440:     &get_unprocessed_cgi($ENV{'QUERY_STRING'}, ['inhibitmenu']);
 5441: 
 5442:     if (($bodyonly) || ($no_nav_bar) || ($env{'form.inhibitmenu'} eq 'yes')) {
 5443:         return $bodytag;
 5444:     }
 5445: 
 5446:     if ($public) {
 5447: 	undef($role);
 5448:     }
 5449:     
 5450:     my $titleinfo = '<h1>'.$title.'</h1>';
 5451:     #
 5452:     # Extra info if you are the DC
 5453:     my $dc_info = '';
 5454:     if ($env{'user.adv'} && exists($env{'user.role.dc./'.
 5455:                         $env{'course.'.$env{'request.course.id'}.
 5456:                                  '.domain'}.'/'})) {
 5457:         my $cid = $env{'request.course.id'};
 5458:         $dc_info = $cid.' '.$env{'course.'.$cid.'.internal.coursecode'};
 5459:         $dc_info =~ s/\s+$//;
 5460:     }
 5461: 
 5462:     $role = '<span class="LC_nobreak">('.$role.')</span>' if ($role && !$env{'browser.mobile'});
 5463: 
 5464:     if ($env{'request.state'} eq 'construct') { $forcereg=1; }
 5465: 
 5466: 
 5467: 
 5468:     my $funclist;
 5469:     if (($env{'environment.remote'} eq 'on') && ($env{'request.state'} ne 'construct')) {
 5470:         $bodytag .= Apache::lonhtmlcommon::scripttag(Apache::lonmenu::utilityfunctions($httphost), 'start')."\n".
 5471:                     Apache::lonmenu::serverform();
 5472:         my $forbodytag;
 5473:         &Apache::lonmenu::prepare_functions($env{'request.noversionuri'},
 5474:                                             $forcereg,$args->{'group'},
 5475:                                             $args->{'bread_crumbs'},
 5476:                                             $advtoolsref,'',\$forbodytag);
 5477:         unless (ref($args->{'bread_crumbs'}) eq 'ARRAY') {
 5478:             $funclist = $forbodytag;
 5479:         }
 5480:     } else {
 5481: 
 5482:         #    if ($env{'request.state'} eq 'construct') {
 5483:         #        $titleinfo = &CSTR_pageheader(); #FIXME: Will be removed once all scripts have their own calls
 5484:         #    }
 5485: 
 5486:         $bodytag .= Apache::lonhtmlcommon::scripttag(
 5487:             Apache::lonmenu::utilityfunctions($httphost), 'start');
 5488: 
 5489:         my ($left,$right) = Apache::lonmenu::primary_menu();
 5490: 
 5491:         if ($env{'request.noversionuri'} =~ m{^/res/adm/pages/}) {
 5492:             if ($dc_info) {
 5493:                  $dc_info = qq|<span class="LC_cusr_subheading">$dc_info</span>|;
 5494:             }
 5495:             $bodytag .= qq|<div id="LC_nav_bar">$left $role<br />
 5496:                            <em>$realm</em> $dc_info</div>|;
 5497:             return $bodytag;
 5498:         }
 5499: 
 5500:         unless ($env{'request.symb'} =~ m/\.page___\d+___/) {
 5501:             $bodytag .= qq|<div id="LC_nav_bar">$left $role</div>|;
 5502:         }
 5503: 
 5504:         $bodytag .= $right;
 5505: 
 5506:         if ($dc_info) {
 5507:             $dc_info = &dc_courseid_toggle($dc_info);
 5508:         }
 5509:         $bodytag .= qq|<div id="LC_realm">$realm $dc_info</div>|;
 5510: 
 5511:         #if directed to not display the secondary menu, don't.
 5512:         if ($args->{'no_secondary_menu'}) {
 5513:             return $bodytag;
 5514:         }
 5515:         #don't show menus for public users
 5516:         if (!$public){
 5517:             $bodytag .= Apache::lonmenu::secondary_menu($httphost);
 5518:             $bodytag .= Apache::lonmenu::serverform();
 5519:             $bodytag .= Apache::lonhtmlcommon::scripttag('', 'end');
 5520:             if ($env{'request.state'} eq 'construct') {
 5521:                 $bodytag .= &Apache::lonmenu::innerregister($forcereg,
 5522:                                 $args->{'bread_crumbs'});
 5523:             } elsif ($forcereg) { 
 5524:                 $bodytag .= &Apache::lonmenu::innerregister($forcereg,undef,
 5525:                                                             $args->{'group'});
 5526:             } else {
 5527:                 my $forbodytag;
 5528:                 &Apache::lonmenu::prepare_functions($env{'request.noversionuri'},
 5529:                                                     $forcereg,$args->{'group'},
 5530:                                                     $args->{'bread_crumbs'},
 5531:                                                     $advtoolsref,'',\$forbodytag);
 5532:                 unless (ref($args->{'bread_crumbs'}) eq 'ARRAY') {
 5533:                     $bodytag .= $forbodytag;
 5534:                 }
 5535:             }
 5536:         }else{
 5537:             # this is to seperate menu from content when there's no secondary
 5538:             # menu. Especially needed for public accessible ressources.
 5539:             $bodytag .= '<hr style="clear:both" />';
 5540:             $bodytag .= Apache::lonhtmlcommon::scripttag('', 'end'); 
 5541:         }
 5542: 
 5543:         return $bodytag;
 5544:     }
 5545: 
 5546: #
 5547: # Top frame rendering, Remote is up
 5548: #
 5549: 
 5550:     my $imgsrc = $img;
 5551:     if ($img =~ /^\/adm/) {
 5552:         $imgsrc = &lonhttpdurl($img);
 5553:     }
 5554:     my $upperleft='<img src="'.$imgsrc.'" alt="'.$function.'" />';
 5555: 
 5556:     my $help=($no_inline_link?''
 5557:               :&Apache::loncommon::top_nav_help('Help'));
 5558: 
 5559:     # Explicit link to get inline menu
 5560:     my $menu= ($no_inline_link?''
 5561:                :'<a href="/adm/remote?action=collapse" target="_top">'.&mt('Switch to Inline Menu Mode').'</a>');
 5562: 
 5563:     if ($dc_info) {
 5564:         $dc_info = qq|<span class="LC_cusr_subheading">($dc_info)</span>|;
 5565:     }
 5566: 
 5567:     my $name = &plainname($env{'user.name'},$env{'user.domain'});
 5568:     unless ($public) {
 5569:         $name = &aboutmewrapper($name,$env{'user.name'},$env{'user.domain'},
 5570:                                 undef,'LC_menubuttons_link');
 5571:     }
 5572: 
 5573:     unless ($env{'form.inhibitmenu'}) {
 5574:         $bodytag .= qq|<div id="LC_nav_bar">$name $role</div>
 5575:                        <ol class="LC_primary_menu LC_floatright LC_right">
 5576:                        <li>$help</li>
 5577:                        <li>$menu</li>
 5578:                        </ol><div id="LC_realm"> $realm $dc_info</div>|;
 5579:     }
 5580:     if ($env{'request.state'} eq 'construct') {
 5581:         if (!$public){
 5582:             if ($env{'request.state'} eq 'construct') {
 5583:                 $funclist = &Apache::lonhtmlcommon::scripttag(
 5584:                                 &Apache::lonmenu::utilityfunctions($httphost), 'start').
 5585:                             &Apache::lonhtmlcommon::scripttag('','end').
 5586:                             &Apache::lonmenu::innerregister($forcereg,
 5587:                                                             $args->{'bread_crumbs'});
 5588:             }
 5589:         }
 5590:     }
 5591:     return $bodytag."\n".$funclist;
 5592: }
 5593: 
 5594: sub dc_courseid_toggle {
 5595:     my ($dc_info) = @_;
 5596:     return ' <span id="dccidtext" class="LC_cusr_subheading LC_nobreak">'.
 5597:            '<a href="javascript:showCourseID();" class="LC_menubuttons_link">'.
 5598:            &mt('(More ...)').'</a></span>'.
 5599:            '<div id="dccid" class="LC_dccid">'.$dc_info.'</div>';
 5600: }
 5601: 
 5602: sub make_attr_string {
 5603:     my ($register,$attr_ref) = @_;
 5604: 
 5605:     if ($attr_ref && !ref($attr_ref)) {
 5606: 	die("addentries Must be a hash ref ".
 5607: 	    join(':',caller(1))." ".
 5608: 	    join(':',caller(0))." ");
 5609:     }
 5610: 
 5611:     if ($register) {
 5612: 	my ($on_load,$on_unload);
 5613: 	foreach my $key (keys(%{$attr_ref})) {
 5614: 	    if      (lc($key) eq 'onload') {
 5615: 		$on_load.=$attr_ref->{$key}.';';
 5616: 		delete($attr_ref->{$key});
 5617: 
 5618: 	    } elsif (lc($key) eq 'onunload') {
 5619: 		$on_unload.=$attr_ref->{$key}.';';
 5620: 		delete($attr_ref->{$key});
 5621: 	    }
 5622: 	}
 5623:         if ($env{'environment.remote'} eq 'on') {
 5624:             $attr_ref->{'onload'}  =
 5625:                 &Apache::lonmenu::loadevents().  $on_load;
 5626:             $attr_ref->{'onunload'}=
 5627:                 &Apache::lonmenu::unloadevents().$on_unload;
 5628:         } else {  
 5629: 	    $attr_ref->{'onload'}  = $on_load;
 5630: 	    $attr_ref->{'onunload'}= $on_unload;
 5631:         }
 5632:     }
 5633: 
 5634:     my $attr_string;
 5635:     foreach my $attr (sort(keys(%$attr_ref))) {
 5636: 	$attr_string .= " $attr=\"".$attr_ref->{$attr}.'" ';
 5637:     }
 5638:     return $attr_string;
 5639: }
 5640: 
 5641: 
 5642: ###############################################
 5643: ###############################################
 5644: 
 5645: =pod
 5646: 
 5647: =item * &endbodytag()
 5648: 
 5649: Returns a uniform footer for LON-CAPA web pages.
 5650: 
 5651: Inputs: 1 - optional reference to an args hash
 5652: If in the hash, key for noredirectlink has a value which evaluates to true,
 5653: a 'Continue' link is not displayed if the page contains an
 5654: internal redirect in the <head></head> section,
 5655: i.e., $env{'internal.head.redirect'} exists   
 5656: 
 5657: =cut
 5658: 
 5659: sub endbodytag {
 5660:     my ($args) = @_;
 5661:     my $endbodytag;
 5662:     unless ((ref($args) eq 'HASH') && ($args->{'notbody'})) {
 5663:         $endbodytag='</body>';
 5664:     }
 5665:     if ( exists( $env{'internal.head.redirect'} ) ) {
 5666:         if (!(ref($args) eq 'HASH' && $args->{'noredirectlink'})) {
 5667: 	    $endbodytag=
 5668: 	        "<br /><a href=\"$env{'internal.head.redirect'}\">".
 5669: 	        &mt('Continue').'</a>'.
 5670: 	        $endbodytag;
 5671:         }
 5672:     }
 5673:     return $endbodytag;
 5674: }
 5675: 
 5676: =pod
 5677: 
 5678: =item * &standard_css()
 5679: 
 5680: Returns a style sheet
 5681: 
 5682: Inputs: (all optional)
 5683:             domain         -> force to color decorate a page for a specific
 5684:                                domain
 5685:             function       -> force usage of a specific rolish color scheme
 5686:             bgcolor        -> override the default page bgcolor
 5687: 
 5688: =cut
 5689: 
 5690: sub standard_css {
 5691:     my ($function,$domain,$bgcolor) = @_;
 5692:     $function  = &get_users_function() if (!$function);
 5693:     my $img    = &designparm($function.'.img',   $domain);
 5694:     my $tabbg  = &designparm($function.'.tabbg', $domain);
 5695:     my $font   = &designparm($function.'.font',  $domain);
 5696:     my $fontmenu = &designparm($function.'.fontmenu', $domain);
 5697: #second colour for later usage
 5698:     my $sidebg = &designparm($function.'.sidebg',$domain);
 5699:     my $pgbg_or_bgcolor =
 5700: 	         $bgcolor ||
 5701: 	         &designparm($function.'.pgbg',  $domain);
 5702:     my $pgbg   = &designparm($function.'.pgbg',  $domain);
 5703:     my $alink  = &designparm($function.'.alink', $domain);
 5704:     my $vlink  = &designparm($function.'.vlink', $domain);
 5705:     my $link   = &designparm($function.'.link',  $domain);
 5706: 
 5707:     my $sans                 = 'Verdana,Arial,Helvetica,sans-serif';
 5708:     my $mono                 = 'monospace';
 5709:     my $data_table_head      = $sidebg;
 5710:     my $data_table_light     = '#FAFAFA';
 5711:     my $data_table_dark      = '#E0E0E0';
 5712:     my $data_table_darker    = '#CCCCCC';
 5713:     my $data_table_highlight = '#FFFF00';
 5714:     my $mail_new             = '#FFBB77';
 5715:     my $mail_new_hover       = '#DD9955';
 5716:     my $mail_read            = '#BBBB77';
 5717:     my $mail_read_hover      = '#999944';
 5718:     my $mail_replied         = '#AAAA88';
 5719:     my $mail_replied_hover   = '#888855';
 5720:     my $mail_other           = '#99BBBB';
 5721:     my $mail_other_hover     = '#669999';
 5722:     my $table_header         = '#DDDDDD';
 5723:     my $feedback_link_bg     = '#BBBBBB';
 5724:     my $lg_border_color      = '#C8C8C8';
 5725:     my $button_hover         = '#BF2317';
 5726: 
 5727:     my $border = ($env{'browser.type'} eq 'explorer' ||
 5728:       $env{'browser.type'} eq 'safari'     ) ? '0 2px 0 2px'
 5729:                                              : '0 3px 0 4px';
 5730: 
 5731: 
 5732:     return <<END;
 5733: 
 5734: /* needed for iframe to allow 100% height in FF */
 5735: body, html { 
 5736:     margin: 0;
 5737:     padding: 0 0.5%;
 5738:     height: 99%; /* to avoid scrollbars */
 5739: }
 5740: 
 5741: body {
 5742:   font-family: $sans;
 5743:   line-height:130%;
 5744:   font-size:0.83em;
 5745:   color:$font;
 5746: }
 5747: 
 5748: a:focus,
 5749: a:focus img {
 5750:   color: red;
 5751: }
 5752: 
 5753: form, .inline {
 5754:   display: inline;
 5755: }
 5756: 
 5757: .LC_right {
 5758:   text-align:right;
 5759: }
 5760: 
 5761: .LC_middle {
 5762:   vertical-align:middle;
 5763: }
 5764: 
 5765: .LC_floatleft {
 5766:   float: left;
 5767: }
 5768: 
 5769: .LC_floatright {
 5770:   float: right;
 5771: }
 5772: 
 5773: .LC_400Box {
 5774:   width:400px;
 5775: }
 5776: 
 5777: .LC_iframecontainer {
 5778:     width: 98%;
 5779:     margin: 0;
 5780:     position: fixed;
 5781:     top: 8.5em;
 5782:     bottom: 0;
 5783: }
 5784: 
 5785: .LC_iframecontainer iframe{
 5786:     border: none;
 5787:     width: 100%;
 5788:     height: 100%;
 5789: }
 5790: 
 5791: .LC_filename {
 5792:   font-family: $mono;
 5793:   white-space:pre;
 5794:   font-size: 120%;
 5795: }
 5796: 
 5797: .LC_fileicon {
 5798:   border: none;
 5799:   height: 1.3em;
 5800:   vertical-align: text-bottom;
 5801:   margin-right: 0.3em;
 5802:   text-decoration:none;
 5803: }
 5804: 
 5805: .LC_setting {
 5806:   text-decoration:underline;
 5807: }
 5808: 
 5809: .LC_error {
 5810:   color: red;
 5811: }
 5812: 
 5813: .LC_warning {
 5814:   color: darkorange;
 5815: }
 5816: 
 5817: .LC_diff_removed {
 5818:   color: red;
 5819: }
 5820: 
 5821: .LC_info,
 5822: .LC_success,
 5823: .LC_diff_added {
 5824:   color: green;
 5825: }
 5826: 
 5827: div.LC_confirm_box {
 5828:   background-color: #FAFAFA;
 5829:   border: 1px solid $lg_border_color;
 5830:   margin-right: 0;
 5831:   padding: 5px;
 5832: }
 5833: 
 5834: div.LC_confirm_box .LC_error img,
 5835: div.LC_confirm_box .LC_success img {
 5836:   vertical-align: middle;
 5837: }
 5838: 
 5839: .LC_maxwidth {
 5840:   max-width: 100%;
 5841:   height: auto;
 5842: }
 5843: 
 5844: .LC_textsize_mobile {
 5845:   \@media only screen and (max-device-width: 480px) {
 5846:       -webkit-text-size-adjust:100%; -moz-text-size-adjust:100%; -ms-text-size-adjust:100%;
 5847:   }
 5848: }
 5849: 
 5850: .LC_icon {
 5851:   border: none;
 5852:   vertical-align: middle;
 5853: }
 5854: 
 5855: .LC_docs_spacer {
 5856:   width: 25px;
 5857:   height: 1px;
 5858:   border: none;
 5859: }
 5860: 
 5861: .LC_internal_info {
 5862:   color: #999999;
 5863: }
 5864: 
 5865: .LC_discussion {
 5866:   background: $data_table_dark;
 5867:   border: 1px solid black;
 5868:   margin: 2px;
 5869: }
 5870: 
 5871: .LC_disc_action_left {
 5872:   background: $sidebg;
 5873:   text-align: left;
 5874:   padding: 4px;
 5875:   margin: 2px;
 5876: }
 5877: 
 5878: .LC_disc_action_right {
 5879:   background: $sidebg;
 5880:   text-align: right;
 5881:   padding: 4px;
 5882:   margin: 2px;
 5883: }
 5884: 
 5885: .LC_disc_new_item {
 5886:   background: white;
 5887:   border: 2px solid red;
 5888:   margin: 4px;
 5889:   padding: 4px;
 5890: }
 5891: 
 5892: .LC_disc_old_item {
 5893:   background: white;
 5894:   margin: 4px;
 5895:   padding: 4px;
 5896: }
 5897: 
 5898: table.LC_pastsubmission {
 5899:   border: 1px solid black;
 5900:   margin: 2px;
 5901: }
 5902: 
 5903: table#LC_menubuttons {
 5904:   width: 100%;
 5905:   background: $pgbg;
 5906:   border: 2px;
 5907:   border-collapse: separate;
 5908:   padding: 0;
 5909: }
 5910: 
 5911: table#LC_title_bar a {
 5912:   color: $fontmenu;
 5913: }
 5914: 
 5915: table#LC_title_bar {
 5916:   clear: both;
 5917:   display: none;
 5918: }
 5919: 
 5920: table#LC_title_bar,
 5921: table.LC_breadcrumbs, /* obsolete? */
 5922: table#LC_title_bar.LC_with_remote {
 5923:   width: 100%;
 5924:   border-color: $pgbg;
 5925:   border-style: solid;
 5926:   border-width: $border;
 5927:   background: $pgbg;
 5928:   color: $fontmenu;
 5929:   border-collapse: collapse;
 5930:   padding: 0;
 5931:   margin: 0;
 5932: }
 5933: 
 5934: ul.LC_breadcrumb_tools_outerlist {
 5935:     margin: 0;
 5936:     padding: 0;
 5937:     position: relative;
 5938:     list-style: none;
 5939: }
 5940: ul.LC_breadcrumb_tools_outerlist li {
 5941:     display: inline;
 5942: }
 5943: 
 5944: .LC_breadcrumb_tools_navigation {
 5945:     padding: 0;
 5946:     margin: 0;
 5947:     float: left;
 5948: }
 5949: .LC_breadcrumb_tools_tools {
 5950:     padding: 0;
 5951:     margin: 0;
 5952:     float: right;
 5953: }
 5954: 
 5955: table#LC_title_bar td {
 5956:   background: $tabbg;
 5957: }
 5958: 
 5959: table#LC_menubuttons img {
 5960:   border: none;
 5961: }
 5962: 
 5963: .LC_breadcrumbs_component {
 5964:   float: right;
 5965:   margin: 0 1em;
 5966: }
 5967: .LC_breadcrumbs_component img {
 5968:   vertical-align: middle;
 5969: }
 5970: 
 5971: .LC_breadcrumbs_hoverable {
 5972:   background: $sidebg;
 5973: }
 5974: 
 5975: td.LC_table_cell_checkbox {
 5976:   text-align: center;
 5977: }
 5978: 
 5979: .LC_fontsize_small {
 5980:   font-size: 70%;
 5981: }
 5982: 
 5983: #LC_breadcrumbs {
 5984:   clear:both;
 5985:   background: $sidebg;
 5986:   border-bottom: 1px solid $lg_border_color;
 5987:   line-height: 2.5em;
 5988:   overflow: hidden;
 5989:   margin: 0;
 5990:   padding: 0;
 5991:   text-align: left;
 5992: }
 5993: 
 5994: .LC_head_subbox, .LC_actionbox {
 5995:   clear:both;
 5996:   background: #F8F8F8; /* $sidebg; */
 5997:   border: 1px solid $sidebg;
 5998:   margin: 0 0 10px 0;
 5999:   padding: 3px;
 6000:   text-align: left;
 6001: }
 6002: 
 6003: .LC_fontsize_medium {
 6004:   font-size: 85%;
 6005: }
 6006: 
 6007: .LC_fontsize_large {
 6008:   font-size: 120%;
 6009: }
 6010: 
 6011: .LC_menubuttons_inline_text {
 6012:   color: $font;
 6013:   font-size: 90%;
 6014:   padding-left:3px;
 6015: }
 6016: 
 6017: .LC_menubuttons_inline_text img{
 6018:   vertical-align: middle;
 6019: }
 6020: 
 6021: li.LC_menubuttons_inline_text img {
 6022:   cursor:pointer;
 6023:   text-decoration: none;
 6024: }
 6025: 
 6026: .LC_menubuttons_link {
 6027:   text-decoration: none;
 6028: }
 6029: 
 6030: .LC_menubuttons_category {
 6031:   color: $font;
 6032:   background: $pgbg;
 6033:   font-size: larger;
 6034:   font-weight: bold;
 6035: }
 6036: 
 6037: td.LC_menubuttons_text {
 6038:   color: $font;
 6039: }
 6040: 
 6041: .LC_current_location {
 6042:   background: $tabbg;
 6043: }
 6044: 
 6045: table.LC_data_table {
 6046:   border: 1px solid #000000;
 6047:   border-collapse: separate;
 6048:   border-spacing: 1px;
 6049:   background: $pgbg;
 6050: }
 6051: 
 6052: .LC_data_table_dense {
 6053:   font-size: small;
 6054: }
 6055: 
 6056: table.LC_nested_outer {
 6057:   border: 1px solid #000000;
 6058:   border-collapse: collapse;
 6059:   border-spacing: 0;
 6060:   width: 100%;
 6061: }
 6062: 
 6063: table.LC_innerpickbox,
 6064: table.LC_nested {
 6065:   border: none;
 6066:   border-collapse: collapse;
 6067:   border-spacing: 0;
 6068:   width: 100%;
 6069: }
 6070: 
 6071: table.LC_data_table tr th,
 6072: table.LC_calendar tr th,
 6073: table.LC_prior_tries tr th,
 6074: table.LC_innerpickbox tr th {
 6075:   font-weight: bold;
 6076:   background-color: $data_table_head;
 6077:   color:$fontmenu;
 6078:   font-size:90%;
 6079: }
 6080: 
 6081: table.LC_innerpickbox tr th,
 6082: table.LC_innerpickbox tr td {
 6083:   vertical-align: top;
 6084: }
 6085: 
 6086: table.LC_data_table tr.LC_info_row > td {
 6087:   background-color: #CCCCCC;
 6088:   font-weight: bold;
 6089:   text-align: left;
 6090: }
 6091: 
 6092: table.LC_data_table tr.LC_odd_row > td {
 6093:   background-color: $data_table_light;
 6094:   padding: 2px;
 6095:   vertical-align: top;
 6096: }
 6097: 
 6098: table.LC_pick_box tr > td.LC_odd_row {
 6099:   background-color: $data_table_light;
 6100:   vertical-align: top;
 6101: }
 6102: 
 6103: table.LC_data_table tr.LC_even_row > td {
 6104:   background-color: $data_table_dark;
 6105:   padding: 2px;
 6106:   vertical-align: top;
 6107: }
 6108: 
 6109: table.LC_pick_box tr > td.LC_even_row {
 6110:   background-color: $data_table_dark;
 6111:   vertical-align: top;
 6112: }
 6113: 
 6114: table.LC_data_table tr.LC_data_table_highlight td {
 6115:   background-color: $data_table_darker;
 6116: }
 6117: 
 6118: table.LC_data_table tr td.LC_leftcol_header {
 6119:   background-color: $data_table_head;
 6120:   font-weight: bold;
 6121: }
 6122: 
 6123: table.LC_data_table tr.LC_empty_row td,
 6124: table.LC_nested tr.LC_empty_row td {
 6125:   font-weight: bold;
 6126:   font-style: italic;
 6127:   text-align: center;
 6128:   padding: 8px;
 6129: }
 6130: 
 6131: table.LC_data_table tr.LC_empty_row td,
 6132: table.LC_data_table tr.LC_footer_row td {
 6133:   background-color: $sidebg;
 6134: }
 6135: 
 6136: table.LC_nested tr.LC_empty_row td {
 6137:   background-color: #FFFFFF;
 6138: }
 6139: 
 6140: table.LC_caption {
 6141: }
 6142: 
 6143: table.LC_nested tr.LC_empty_row td {
 6144:   padding: 4ex
 6145: }
 6146: 
 6147: table.LC_nested_outer tr th {
 6148:   font-weight: bold;
 6149:   color:$fontmenu;
 6150:   background-color: $data_table_head;
 6151:   font-size: small;
 6152:   border-bottom: 1px solid #000000;
 6153: }
 6154: 
 6155: table.LC_nested_outer tr td.LC_subheader {
 6156:   background-color: $data_table_head;
 6157:   font-weight: bold;
 6158:   font-size: small;
 6159:   border-bottom: 1px solid #000000;
 6160:   text-align: right;
 6161: }
 6162: 
 6163: table.LC_nested tr.LC_info_row td {
 6164:   background-color: #CCCCCC;
 6165:   font-weight: bold;
 6166:   font-size: small;
 6167:   text-align: center;
 6168: }
 6169: 
 6170: table.LC_nested tr.LC_info_row td.LC_left_item,
 6171: table.LC_nested_outer tr th.LC_left_item {
 6172:   text-align: left;
 6173: }
 6174: 
 6175: table.LC_nested td {
 6176:   background-color: #FFFFFF;
 6177:   font-size: small;
 6178: }
 6179: 
 6180: table.LC_nested_outer tr th.LC_right_item,
 6181: table.LC_nested tr.LC_info_row td.LC_right_item,
 6182: table.LC_nested tr.LC_odd_row td.LC_right_item,
 6183: table.LC_nested tr td.LC_right_item {
 6184:   text-align: right;
 6185: }
 6186: 
 6187: table.LC_nested tr.LC_odd_row td {
 6188:   background-color: #EEEEEE;
 6189: }
 6190: 
 6191: table.LC_createuser {
 6192: }
 6193: 
 6194: table.LC_createuser tr.LC_section_row td {
 6195:   font-size: small;
 6196: }
 6197: 
 6198: table.LC_createuser tr.LC_info_row td  {
 6199:   background-color: #CCCCCC;
 6200:   font-weight: bold;
 6201:   text-align: center;
 6202: }
 6203: 
 6204: table.LC_calendar {
 6205:   border: 1px solid #000000;
 6206:   border-collapse: collapse;
 6207:   width: 98%;
 6208: }
 6209: 
 6210: table.LC_calendar_pickdate {
 6211:   font-size: xx-small;
 6212: }
 6213: 
 6214: table.LC_calendar tr td {
 6215:   border: 1px solid #000000;
 6216:   vertical-align: top;
 6217:   width: 14%;
 6218: }
 6219: 
 6220: table.LC_calendar tr td.LC_calendar_day_empty {
 6221:   background-color: $data_table_dark;
 6222: }
 6223: 
 6224: table.LC_calendar tr td.LC_calendar_day_current {
 6225:   background-color: $data_table_highlight;
 6226: }
 6227: 
 6228: table.LC_data_table tr td.LC_mail_new {
 6229:   background-color: $mail_new;
 6230: }
 6231: 
 6232: table.LC_data_table tr.LC_mail_new:hover {
 6233:   background-color: $mail_new_hover;
 6234: }
 6235: 
 6236: table.LC_data_table tr td.LC_mail_read {
 6237:   background-color: $mail_read;
 6238: }
 6239: 
 6240: /*
 6241: table.LC_data_table tr.LC_mail_read:hover {
 6242:   background-color: $mail_read_hover;
 6243: }
 6244: */
 6245: 
 6246: table.LC_data_table tr td.LC_mail_replied {
 6247:   background-color: $mail_replied;
 6248: }
 6249: 
 6250: /*
 6251: table.LC_data_table tr.LC_mail_replied:hover {
 6252:   background-color: $mail_replied_hover;
 6253: }
 6254: */
 6255: 
 6256: table.LC_data_table tr td.LC_mail_other {
 6257:   background-color: $mail_other;
 6258: }
 6259: 
 6260: /*
 6261: table.LC_data_table tr.LC_mail_other:hover {
 6262:   background-color: $mail_other_hover;
 6263: }
 6264: */
 6265: 
 6266: table.LC_data_table tr > td.LC_browser_file,
 6267: table.LC_data_table tr > td.LC_browser_file_published {
 6268:   background: #AAEE77;
 6269: }
 6270: 
 6271: table.LC_data_table tr > td.LC_browser_file_locked,
 6272: table.LC_data_table tr > td.LC_browser_file_unpublished {
 6273:   background: #FFAA99;
 6274: }
 6275: 
 6276: table.LC_data_table tr > td.LC_browser_file_obsolete {
 6277:   background: #888888;
 6278: }
 6279: 
 6280: table.LC_data_table tr > td.LC_browser_file_modified,
 6281: table.LC_data_table tr > td.LC_browser_file_metamodified {
 6282:   background: #F8F866;
 6283: }
 6284: 
 6285: table.LC_data_table tr.LC_browser_folder > td {
 6286:   background: #E0E8FF;
 6287: }
 6288: 
 6289: table.LC_data_table tr > td.LC_roles_is {
 6290:   /* background: #77FF77; */
 6291: }
 6292: 
 6293: table.LC_data_table tr > td.LC_roles_future {
 6294:   border-right: 8px solid #FFFF77;
 6295: }
 6296: 
 6297: table.LC_data_table tr > td.LC_roles_will {
 6298:   border-right: 8px solid #FFAA77;
 6299: }
 6300: 
 6301: table.LC_data_table tr > td.LC_roles_expired {
 6302:   border-right: 8px solid #FF7777;
 6303: }
 6304: 
 6305: table.LC_data_table tr > td.LC_roles_will_not {
 6306:   border-right: 8px solid #AAFF77;
 6307: }
 6308: 
 6309: table.LC_data_table tr > td.LC_roles_selected {
 6310:   border-right: 8px solid #11CC55;
 6311: }
 6312: 
 6313: span.LC_current_location {
 6314:   font-size:larger;
 6315:   background: $pgbg;
 6316: }
 6317: 
 6318: span.LC_current_nav_location {
 6319:   font-weight:bold;
 6320:   background: $sidebg;
 6321: }
 6322: 
 6323: span.LC_parm_menu_item {
 6324:   font-size: larger;
 6325: }
 6326: 
 6327: span.LC_parm_scope_all {
 6328:   color: red;
 6329: }
 6330: 
 6331: span.LC_parm_scope_folder {
 6332:   color: green;
 6333: }
 6334: 
 6335: span.LC_parm_scope_resource {
 6336:   color: orange;
 6337: }
 6338: 
 6339: span.LC_parm_part {
 6340:   color: blue;
 6341: }
 6342: 
 6343: span.LC_parm_folder,
 6344: span.LC_parm_symb {
 6345:   font-size: x-small;
 6346:   font-family: $mono;
 6347:   color: #AAAAAA;
 6348: }
 6349: 
 6350: ul.LC_parm_parmlist li {
 6351:   display: inline-block;
 6352:   padding: 0.3em 0.8em;
 6353:   vertical-align: top;
 6354:   width: 150px;
 6355:   border-top:1px solid $lg_border_color;
 6356: }
 6357: 
 6358: td.LC_parm_overview_level_menu,
 6359: td.LC_parm_overview_map_menu,
 6360: td.LC_parm_overview_parm_selectors,
 6361: td.LC_parm_overview_restrictions  {
 6362:   border: 1px solid black;
 6363:   border-collapse: collapse;
 6364: }
 6365: 
 6366: table.LC_parm_overview_restrictions td {
 6367:   border-width: 1px 4px 1px 4px;
 6368:   border-style: solid;
 6369:   border-color: $pgbg;
 6370:   text-align: center;
 6371: }
 6372: 
 6373: table.LC_parm_overview_restrictions th {
 6374:   background: $tabbg;
 6375:   border-width: 1px 4px 1px 4px;
 6376:   border-style: solid;
 6377:   border-color: $pgbg;
 6378: }
 6379: 
 6380: table#LC_helpmenu {
 6381:   border: none;
 6382:   height: 55px;
 6383:   border-spacing: 0;
 6384: }
 6385: 
 6386: table#LC_helpmenu fieldset legend {
 6387:   font-size: larger;
 6388: }
 6389: 
 6390: table#LC_helpmenu_links {
 6391:   width: 100%;
 6392:   border: 1px solid black;
 6393:   background: $pgbg;
 6394:   padding: 0;
 6395:   border-spacing: 1px;
 6396: }
 6397: 
 6398: table#LC_helpmenu_links tr td {
 6399:   padding: 1px;
 6400:   background: $tabbg;
 6401:   text-align: center;
 6402:   font-weight: bold;
 6403: }
 6404: 
 6405: table#LC_helpmenu_links a:link,
 6406: table#LC_helpmenu_links a:visited,
 6407: table#LC_helpmenu_links a:active {
 6408:   text-decoration: none;
 6409:   color: $font;
 6410: }
 6411: 
 6412: table#LC_helpmenu_links a:hover {
 6413:   text-decoration: underline;
 6414:   color: $vlink;
 6415: }
 6416: 
 6417: .LC_chrt_popup_exists {
 6418:   border: 1px solid #339933;
 6419:   margin: -1px;
 6420: }
 6421: 
 6422: .LC_chrt_popup_up {
 6423:   border: 1px solid yellow;
 6424:   margin: -1px;
 6425: }
 6426: 
 6427: .LC_chrt_popup {
 6428:   border: 1px solid #8888FF;
 6429:   background: #CCCCFF;
 6430: }
 6431: 
 6432: table.LC_pick_box {
 6433:   border-collapse: separate;
 6434:   background: white;
 6435:   border: 1px solid black;
 6436:   border-spacing: 1px;
 6437: }
 6438: 
 6439: table.LC_pick_box td.LC_pick_box_title {
 6440:   background: $sidebg;
 6441:   font-weight: bold;
 6442:   text-align: left;
 6443:   vertical-align: top;
 6444:   width: 184px;
 6445:   padding: 8px;
 6446: }
 6447: 
 6448: table.LC_pick_box td.LC_pick_box_value {
 6449:   text-align: left;
 6450:   padding: 8px;
 6451: }
 6452: 
 6453: table.LC_pick_box td.LC_pick_box_select {
 6454:   text-align: left;
 6455:   padding: 8px;
 6456: }
 6457: 
 6458: table.LC_pick_box td.LC_pick_box_separator {
 6459:   padding: 0;
 6460:   height: 1px;
 6461:   background: black;
 6462: }
 6463: 
 6464: table.LC_pick_box td.LC_pick_box_submit {
 6465:   text-align: right;
 6466: }
 6467: 
 6468: table.LC_pick_box td.LC_evenrow_value {
 6469:   text-align: left;
 6470:   padding: 8px;
 6471:   background-color: $data_table_light;
 6472: }
 6473: 
 6474: table.LC_pick_box td.LC_oddrow_value {
 6475:   text-align: left;
 6476:   padding: 8px;
 6477:   background-color: $data_table_light;
 6478: }
 6479: 
 6480: span.LC_helpform_receipt_cat {
 6481:   font-weight: bold;
 6482: }
 6483: 
 6484: table.LC_group_priv_box {
 6485:   background: white;
 6486:   border: 1px solid black;
 6487:   border-spacing: 1px;
 6488: }
 6489: 
 6490: table.LC_group_priv_box td.LC_pick_box_title {
 6491:   background: $tabbg;
 6492:   font-weight: bold;
 6493:   text-align: right;
 6494:   width: 184px;
 6495: }
 6496: 
 6497: table.LC_group_priv_box td.LC_groups_fixed {
 6498:   background: $data_table_light;
 6499:   text-align: center;
 6500: }
 6501: 
 6502: table.LC_group_priv_box td.LC_groups_optional {
 6503:   background: $data_table_dark;
 6504:   text-align: center;
 6505: }
 6506: 
 6507: table.LC_group_priv_box td.LC_groups_functionality {
 6508:   background: $data_table_darker;
 6509:   text-align: center;
 6510:   font-weight: bold;
 6511: }
 6512: 
 6513: table.LC_group_priv td {
 6514:   text-align: left;
 6515:   padding: 0;
 6516: }
 6517: 
 6518: .LC_navbuttons {
 6519:   margin: 2ex 0ex 2ex 0ex;
 6520: }
 6521: 
 6522: .LC_topic_bar {
 6523:   font-weight: bold;
 6524:   background: $tabbg;
 6525:   margin: 1em 0em 1em 2em;
 6526:   padding: 3px;
 6527:   font-size: 1.2em;
 6528: }
 6529: 
 6530: .LC_topic_bar span {
 6531:   left: 0.5em;
 6532:   position: absolute;
 6533:   vertical-align: middle;
 6534:   font-size: 1.2em;
 6535: }
 6536: 
 6537: table.LC_course_group_status {
 6538:   margin: 20px;
 6539: }
 6540: 
 6541: table.LC_status_selector td {
 6542:   vertical-align: top;
 6543:   text-align: center;
 6544:   padding: 4px;
 6545: }
 6546: 
 6547: div.LC_feedback_link {
 6548:   clear: both;
 6549:   background: $sidebg;
 6550:   width: 100%;
 6551:   padding-bottom: 10px;
 6552:   border: 1px $tabbg solid;
 6553:   height: 22px;
 6554:   line-height: 22px;
 6555:   padding-top: 5px;
 6556: }
 6557: 
 6558: div.LC_feedback_link img {
 6559:   height: 22px;
 6560:   vertical-align:middle;
 6561: }
 6562: 
 6563: div.LC_feedback_link a {
 6564:   text-decoration: none;
 6565: }
 6566: 
 6567: div.LC_comblock {
 6568:   display:inline;
 6569:   color:$font;
 6570:   font-size:90%;
 6571: }
 6572: 
 6573: div.LC_feedback_link div.LC_comblock {
 6574:   padding-left:5px;
 6575: }
 6576: 
 6577: div.LC_feedback_link div.LC_comblock a {
 6578:   color:$font;
 6579: }
 6580: 
 6581: span.LC_feedback_link {
 6582:   /* background: $feedback_link_bg; */
 6583:   font-size: larger;
 6584: }
 6585: 
 6586: span.LC_message_link {
 6587:   /* background: $feedback_link_bg; */
 6588:   font-size: larger;
 6589:   position: absolute;
 6590:   right: 1em;
 6591: }
 6592: 
 6593: table.LC_prior_tries {
 6594:   border: 1px solid #000000;
 6595:   border-collapse: separate;
 6596:   border-spacing: 1px;
 6597: }
 6598: 
 6599: table.LC_prior_tries td {
 6600:   padding: 2px;
 6601: }
 6602: 
 6603: .LC_answer_correct {
 6604:   background: lightgreen;
 6605:   color: darkgreen;
 6606:   padding: 6px;
 6607: }
 6608: 
 6609: .LC_answer_charged_try {
 6610:   background: #FFAAAA;
 6611:   color: darkred;
 6612:   padding: 6px;
 6613: }
 6614: 
 6615: .LC_answer_not_charged_try,
 6616: .LC_answer_no_grade,
 6617: .LC_answer_late {
 6618:   background: lightyellow;
 6619:   color: black;
 6620:   padding: 6px;
 6621: }
 6622: 
 6623: .LC_answer_previous {
 6624:   background: lightblue;
 6625:   color: darkblue;
 6626:   padding: 6px;
 6627: }
 6628: 
 6629: .LC_answer_no_message {
 6630:   background: #FFFFFF;
 6631:   color: black;
 6632:   padding: 6px;
 6633: }
 6634: 
 6635: .LC_answer_unknown {
 6636:   background: orange;
 6637:   color: black;
 6638:   padding: 6px;
 6639: }
 6640: 
 6641: span.LC_prior_numerical,
 6642: span.LC_prior_string,
 6643: span.LC_prior_custom,
 6644: span.LC_prior_reaction,
 6645: span.LC_prior_math {
 6646:   font-family: $mono;
 6647:   white-space: pre;
 6648: }
 6649: 
 6650: span.LC_prior_string {
 6651:   font-family: $mono;
 6652:   white-space: pre;
 6653: }
 6654: 
 6655: table.LC_prior_option {
 6656:   width: 100%;
 6657:   border-collapse: collapse;
 6658: }
 6659: 
 6660: table.LC_prior_rank,
 6661: table.LC_prior_match {
 6662:   border-collapse: collapse;
 6663: }
 6664: 
 6665: table.LC_prior_option tr td,
 6666: table.LC_prior_rank tr td,
 6667: table.LC_prior_match tr td {
 6668:   border: 1px solid #000000;
 6669: }
 6670: 
 6671: .LC_nobreak {
 6672:   white-space: nowrap;
 6673: }
 6674: 
 6675: span.LC_cusr_emph {
 6676:   font-style: italic;
 6677: }
 6678: 
 6679: span.LC_cusr_subheading {
 6680:   font-weight: normal;
 6681:   font-size: 85%;
 6682: }
 6683: 
 6684: div.LC_docs_entry_move {
 6685:   border: 1px solid #BBBBBB;
 6686:   background: #DDDDDD;
 6687:   width: 22px;
 6688:   padding: 1px;
 6689:   margin: 0;
 6690: }
 6691: 
 6692: table.LC_data_table tr > td.LC_docs_entry_commands,
 6693: table.LC_data_table tr > td.LC_docs_entry_parameter {
 6694:   font-size: x-small;
 6695: }
 6696: 
 6697: .LC_docs_entry_parameter {
 6698:   white-space: nowrap;
 6699: }
 6700: 
 6701: .LC_docs_copy {
 6702:   color: #000099;
 6703: }
 6704: 
 6705: .LC_docs_cut {
 6706:   color: #550044;
 6707: }
 6708: 
 6709: .LC_docs_rename {
 6710:   color: #009900;
 6711: }
 6712: 
 6713: .LC_docs_remove {
 6714:   color: #990000;
 6715: }
 6716: 
 6717: .LC_docs_reinit_warn,
 6718: .LC_docs_ext_edit {
 6719:   font-size: x-small;
 6720: }
 6721: 
 6722: table.LC_docs_adddocs td,
 6723: table.LC_docs_adddocs th {
 6724:   border: 1px solid #BBBBBB;
 6725:   padding: 4px;
 6726:   background: #DDDDDD;
 6727: }
 6728: 
 6729: table.LC_sty_begin {
 6730:   background: #BBFFBB;
 6731: }
 6732: 
 6733: table.LC_sty_end {
 6734:   background: #FFBBBB;
 6735: }
 6736: 
 6737: table.LC_double_column {
 6738:   border-width: 0;
 6739:   border-collapse: collapse;
 6740:   width: 100%;
 6741:   padding: 2px;
 6742: }
 6743: 
 6744: table.LC_double_column tr td.LC_left_col {
 6745:   top: 2px;
 6746:   left: 2px;
 6747:   width: 47%;
 6748:   vertical-align: top;
 6749: }
 6750: 
 6751: table.LC_double_column tr td.LC_right_col {
 6752:   top: 2px;
 6753:   right: 2px;
 6754:   width: 47%;
 6755:   vertical-align: top;
 6756: }
 6757: 
 6758: div.LC_left_float {
 6759:   float: left;
 6760:   padding-right: 5%;
 6761:   padding-bottom: 4px;
 6762: }
 6763: 
 6764: div.LC_clear_float_header {
 6765:   padding-bottom: 2px;
 6766: }
 6767: 
 6768: div.LC_clear_float_footer {
 6769:   padding-top: 10px;
 6770:   clear: both;
 6771: }
 6772: 
 6773: div.LC_grade_show_user {
 6774: /*  border-left: 5px solid $sidebg; */
 6775:   border-top: 5px solid #000000;
 6776:   margin: 50px 0 0 0;
 6777:   padding: 15px 0 5px 10px;
 6778: }
 6779: 
 6780: div.LC_grade_show_user_odd_row {
 6781: /*  border-left: 5px solid #000000; */
 6782: }
 6783: 
 6784: div.LC_grade_show_user div.LC_Box {
 6785:   margin-right: 50px;
 6786: }
 6787: 
 6788: div.LC_grade_submissions,
 6789: div.LC_grade_message_center,
 6790: div.LC_grade_info_links {
 6791:   margin: 5px;
 6792:   width: 99%;
 6793:   background: #FFFFFF;
 6794: }
 6795: 
 6796: div.LC_grade_submissions_header,
 6797: div.LC_grade_message_center_header {
 6798:   font-weight: bold;
 6799:   font-size: large;
 6800: }
 6801: 
 6802: div.LC_grade_submissions_body,
 6803: div.LC_grade_message_center_body {
 6804:   border: 1px solid black;
 6805:   width: 99%;
 6806:   background: #FFFFFF;
 6807: }
 6808: 
 6809: table.LC_scantron_action {
 6810:   width: 100%;
 6811: }
 6812: 
 6813: table.LC_scantron_action tr th {
 6814:   font-weight:bold;
 6815:   font-style:normal;
 6816: }
 6817: 
 6818: .LC_edit_problem_header,
 6819: div.LC_edit_problem_footer {
 6820:   font-weight: normal;
 6821:   font-size:  medium;
 6822:   margin: 2px;
 6823:   background-color: $sidebg;
 6824: }
 6825: 
 6826: div.LC_edit_problem_header,
 6827: div.LC_edit_problem_header div,
 6828: div.LC_edit_problem_footer,
 6829: div.LC_edit_problem_footer div,
 6830: div.LC_edit_problem_editxml_header,
 6831: div.LC_edit_problem_editxml_header div {
 6832:   z-index: 100;
 6833: }
 6834: 
 6835: div.LC_edit_problem_header_title {
 6836:   font-weight: bold;
 6837:   font-size: larger;
 6838:   background: $tabbg;
 6839:   padding: 3px;
 6840:   margin: 0 0 5px 0;
 6841: }
 6842: 
 6843: table.LC_edit_problem_header_title {
 6844:   width: 100%;
 6845:   background: $tabbg;
 6846: }
 6847: 
 6848: div.LC_edit_actionbar {
 6849:     background-color: $sidebg;
 6850:     margin: 0;
 6851:     padding: 0;
 6852:     line-height: 200%;
 6853: }
 6854: 
 6855: div.LC_edit_actionbar div{
 6856:     padding: 0;
 6857:     margin: 0;
 6858:     display: inline-block;
 6859: }
 6860: 
 6861: .LC_edit_opt {
 6862:   padding-left: 1em;
 6863:   white-space: nowrap;
 6864: }
 6865: 
 6866: .LC_edit_problem_latexhelper{
 6867:     text-align: right;
 6868: }
 6869: 
 6870: #LC_edit_problem_colorful div{
 6871:     margin-left: 40px;
 6872: }
 6873: 
 6874: #LC_edit_problem_codemirror div{
 6875:     margin-left: 0px;
 6876: }
 6877: 
 6878: img.stift {
 6879:   border-width: 0;
 6880:   vertical-align: middle;
 6881: }
 6882: 
 6883: table td.LC_mainmenu_col_fieldset {
 6884:   vertical-align: top;
 6885: }
 6886: 
 6887: div.LC_createcourse {
 6888:   margin: 10px 10px 10px 10px;
 6889: }
 6890: 
 6891: .LC_dccid {
 6892:   float: right;
 6893:   margin: 0.2em 0 0 0;
 6894:   padding: 0;
 6895:   font-size: 90%;
 6896:   display:none;
 6897: }
 6898: 
 6899: ol.LC_primary_menu a:hover,
 6900: ol#LC_MenuBreadcrumbs a:hover,
 6901: ol#LC_PathBreadcrumbs a:hover,
 6902: ul#LC_secondary_menu a:hover,
 6903: .LC_FormSectionClearButton input:hover
 6904: ul.LC_TabContent   li:hover a {
 6905:   color:$button_hover;
 6906:   text-decoration:none;
 6907: }
 6908: 
 6909: h1 {
 6910:   padding: 0;
 6911:   line-height:130%;
 6912: }
 6913: 
 6914: h2,
 6915: h3,
 6916: h4,
 6917: h5,
 6918: h6 {
 6919:   margin: 5px 0 5px 0;
 6920:   padding: 0;
 6921:   line-height:130%;
 6922: }
 6923: 
 6924: .LC_hcell {
 6925:   padding:3px 15px 3px 15px;
 6926:   margin: 0;
 6927:   background-color:$tabbg;
 6928:   color:$fontmenu;
 6929:   border-bottom:solid 1px $lg_border_color;
 6930: }
 6931: 
 6932: .LC_Box > .LC_hcell {
 6933:   margin: 0 -10px 10px -10px;
 6934: }
 6935: 
 6936: .LC_noBorder {
 6937:   border: 0;
 6938: }
 6939: 
 6940: .LC_FormSectionClearButton input {
 6941:   background-color:transparent;
 6942:   border: none;
 6943:   cursor:pointer;
 6944:   text-decoration:underline;
 6945: }
 6946: 
 6947: .LC_help_open_topic {
 6948:   color: #FFFFFF;
 6949:   background-color: #EEEEFF;
 6950:   margin: 1px;
 6951:   padding: 4px;
 6952:   border: 1px solid #000033;
 6953:   white-space: nowrap;
 6954:   /* vertical-align: middle; */
 6955: }
 6956: 
 6957: dl,
 6958: ul,
 6959: div,
 6960: fieldset {
 6961:   margin: 10px 10px 10px 0;
 6962:   /* overflow: hidden; */
 6963: }
 6964: 
 6965: article.geogebraweb div {
 6966:     margin: 0;
 6967: }
 6968: 
 6969: fieldset > legend {
 6970:   font-weight: bold;
 6971:   padding: 0 5px 0 5px;
 6972: }
 6973: 
 6974: #LC_nav_bar {
 6975:   float: left;
 6976:   background-color: $pgbg_or_bgcolor;
 6977:   margin: 0 0 2px 0;
 6978: }
 6979: 
 6980: #LC_realm {
 6981:   margin: 0.2em 0 0 0;
 6982:   padding: 0;
 6983:   font-weight: bold;
 6984:   text-align: center;
 6985:   background-color: $pgbg_or_bgcolor;
 6986: }
 6987: 
 6988: #LC_nav_bar em {
 6989:   font-weight: bold;
 6990:   font-style: normal;
 6991: }
 6992: 
 6993: ol.LC_primary_menu {
 6994:   margin: 0;
 6995:   padding: 0;
 6996: }
 6997: 
 6998: ol#LC_PathBreadcrumbs {
 6999:   margin: 0;
 7000: }
 7001: 
 7002: ol.LC_primary_menu li {
 7003:   color: RGB(80, 80, 80);
 7004:   vertical-align: middle;
 7005:   text-align: left;
 7006:   list-style: none;
 7007:   position: relative;
 7008:   float: left;
 7009:   z-index: 100; /* will be displayed above codemirror and underneath the help-layer */
 7010:   line-height: 1.5em;
 7011: }
 7012: 
 7013: ol.LC_primary_menu li a, 
 7014: ol.LC_primary_menu li p {
 7015:   display: block;
 7016:   margin: 0;
 7017:   padding: 0 5px 0 10px;
 7018:   text-decoration: none;
 7019: }
 7020: 
 7021: ol.LC_primary_menu li p span.LC_primary_menu_innertitle {
 7022:   display: inline-block;
 7023:   width: 95%;
 7024:   text-align: left;
 7025: }
 7026: 
 7027: ol.LC_primary_menu li p span.LC_primary_menu_innerarrow {
 7028:   display: inline-block;
 7029:   width: 5%;
 7030:   float: right;
 7031:   text-align: right;
 7032:   font-size: 70%;
 7033: }
 7034: 
 7035: ol.LC_primary_menu ul {
 7036:   display: none;
 7037:   width: 15em;
 7038:   background-color: $data_table_light;
 7039:   position: absolute;
 7040:   top: 100%;
 7041: }
 7042: 
 7043: ol.LC_primary_menu ul ul {
 7044:   left: 100%;
 7045:   top: 0;
 7046: }
 7047: 
 7048: ol.LC_primary_menu li:hover > ul, ol.LC_primary_menu li.hover > ul {
 7049:   display: block;
 7050:   position: absolute;
 7051:   margin: 0;
 7052:   padding: 0;
 7053:   z-index: 2;
 7054: }
 7055: 
 7056: ol.LC_primary_menu li:hover li, ol.LC_primary_menu li.hover li {
 7057: /* First Submenu -> size should be smaller than the menu title of the whole menu */
 7058:   font-size: 90%;
 7059:   vertical-align: top;
 7060:   float: none;
 7061:   border-left: 1px solid black;
 7062:   border-right: 1px solid black;
 7063: /* A dark bottom border to visualize different menu options;
 7064: overwritten in the create_submenu routine for the last border-bottom of the menu */
 7065:   border-bottom: 1px solid $data_table_dark;
 7066: }
 7067: 
 7068: ol.LC_primary_menu li li p:hover {
 7069:   color:$button_hover;
 7070:   text-decoration:none;
 7071:   background-color:$data_table_dark;
 7072: }
 7073: 
 7074: ol.LC_primary_menu li li a:hover {
 7075:    color:$button_hover;
 7076:    background-color:$data_table_dark;
 7077: }
 7078: 
 7079: /* Font-size equal to the size of the predecessors*/
 7080: ol.LC_primary_menu li:hover li li {
 7081:   font-size: 100%;
 7082: }
 7083: 
 7084: ol.LC_primary_menu li img {
 7085:   vertical-align: bottom;
 7086:   height: 1.1em;
 7087:   margin: 0.2em 0 0 0;
 7088: }
 7089: 
 7090: ol.LC_primary_menu a {
 7091:   color: RGB(80, 80, 80);
 7092:   text-decoration: none;
 7093: }
 7094: 
 7095: ol.LC_primary_menu a.LC_new_message {
 7096:   font-weight:bold;
 7097:   color: darkred;
 7098: }
 7099: 
 7100: ol.LC_docs_parameters {
 7101:   margin-left: 0;
 7102:   padding: 0;
 7103:   list-style: none;
 7104: }
 7105: 
 7106: ol.LC_docs_parameters li {
 7107:   margin: 0;
 7108:   padding-right: 20px;
 7109:   display: inline;
 7110: }
 7111: 
 7112: ol.LC_docs_parameters li:before {
 7113:   content: "\\002022 \\0020";
 7114: }
 7115: 
 7116: li.LC_docs_parameters_title {
 7117:   font-weight: bold;
 7118: }
 7119: 
 7120: ol.LC_docs_parameters li.LC_docs_parameters_title:before {
 7121:   content: "";
 7122: }
 7123: 
 7124: ul#LC_secondary_menu {
 7125:   clear: right;
 7126:   color: $fontmenu;
 7127:   background: $tabbg;
 7128:   list-style: none;
 7129:   padding: 0;
 7130:   margin: 0;
 7131:   width: 100%;
 7132:   text-align: left;
 7133:   float: left;
 7134: }
 7135: 
 7136: ul#LC_secondary_menu li {
 7137:   font-weight: bold;
 7138:   line-height: 1.8em;
 7139:   border-right: 1px solid black;
 7140:   float: left;
 7141: }
 7142: 
 7143: ul#LC_secondary_menu li.LC_hoverable:hover, ul#LC_secondary_menu li.hover {
 7144:   background-color: $data_table_light;
 7145: }
 7146: 
 7147: ul#LC_secondary_menu li a {
 7148:   padding: 0 0.8em;
 7149: }
 7150: 
 7151: ul#LC_secondary_menu li ul {
 7152:   display: none;
 7153: }
 7154: 
 7155: ul#LC_secondary_menu li:hover ul, ul#LC_secondary_menu li.hover ul {
 7156:   display: block;
 7157:   position: absolute;
 7158:   margin: 0;
 7159:   padding: 0;
 7160:   list-style:none;
 7161:   float: none;
 7162:   background-color: $data_table_light;
 7163:   z-index: 2;
 7164:   margin-left: -1px;
 7165: }
 7166: 
 7167: ul#LC_secondary_menu li ul li {
 7168:   font-size: 90%;
 7169:   vertical-align: top;
 7170:   border-left: 1px solid black;
 7171:   border-right: 1px solid black;
 7172:   background-color: $data_table_light;
 7173:   list-style:none;
 7174:   float: none;
 7175: }
 7176: 
 7177: ul#LC_secondary_menu li ul li:hover, ul#LC_secondary_menu li ul li.hover {
 7178:   background-color: $data_table_dark;
 7179: }
 7180: 
 7181: ul.LC_TabContent {
 7182:   display:block;
 7183:   background: $sidebg;
 7184:   border-bottom: solid 1px $lg_border_color;
 7185:   list-style:none;
 7186:   margin: -1px -10px 0 -10px;
 7187:   padding: 0;
 7188: }
 7189: 
 7190: ul.LC_TabContent li,
 7191: ul.LC_TabContentBigger li {
 7192:   float:left;
 7193: }
 7194: 
 7195: ul#LC_secondary_menu li a {
 7196:   color: $fontmenu;
 7197:   text-decoration: none;
 7198: }
 7199: 
 7200: ul.LC_TabContent {
 7201:   min-height:20px;
 7202: }
 7203: 
 7204: ul.LC_TabContent li {
 7205:   vertical-align:middle;
 7206:   padding: 0 16px 0 10px;
 7207:   background-color:$tabbg;
 7208:   border-bottom:solid 1px $lg_border_color;
 7209:   border-left: solid 1px $font;
 7210: }
 7211: 
 7212: ul.LC_TabContent .right {
 7213:   float:right;
 7214: }
 7215: 
 7216: ul.LC_TabContent li a,
 7217: ul.LC_TabContent li {
 7218:   color:rgb(47,47,47);
 7219:   text-decoration:none;
 7220:   font-size:95%;
 7221:   font-weight:bold;
 7222:   min-height:20px;
 7223: }
 7224: 
 7225: ul.LC_TabContent li a:hover,
 7226: ul.LC_TabContent li a:focus {
 7227:   color: $button_hover;
 7228:   background:none;
 7229:   outline:none;
 7230: }
 7231: 
 7232: ul.LC_TabContent li:hover {
 7233:   color: $button_hover;
 7234:   cursor:pointer;
 7235: }
 7236: 
 7237: ul.LC_TabContent li.active {
 7238:   color: $font;
 7239:   background:#FFFFFF url(/adm/lonIcons/open.gif) no-repeat scroll right center;
 7240:   border-bottom:solid 1px #FFFFFF;
 7241:   cursor: default;
 7242: }
 7243: 
 7244: ul.LC_TabContent li.active a {
 7245:   color:$font;
 7246:   background:#FFFFFF;
 7247:   outline: none;
 7248: }
 7249: 
 7250: ul.LC_TabContent li.goback {
 7251:   float: left;
 7252:   border-left: none;
 7253: }
 7254: 
 7255: #maincoursedoc {
 7256:   clear:both;
 7257: }
 7258: 
 7259: ul.LC_TabContentBigger {
 7260:   display:block;
 7261:   list-style:none;
 7262:   padding: 0;
 7263: }
 7264: 
 7265: ul.LC_TabContentBigger li {
 7266:   vertical-align:bottom;
 7267:   height: 30px;
 7268:   font-size:110%;
 7269:   font-weight:bold;
 7270:   color: #737373;
 7271: }
 7272: 
 7273: ul.LC_TabContentBigger li.active {
 7274:   position: relative;
 7275:   top: 1px;
 7276: }
 7277: 
 7278: ul.LC_TabContentBigger li a {
 7279:   background:url('/adm/lonIcons/tabbgleft.gif') left bottom no-repeat;
 7280:   height: 30px;
 7281:   line-height: 30px;
 7282:   text-align: center;
 7283:   display: block;
 7284:   text-decoration: none;
 7285:   outline: none;  
 7286: }
 7287: 
 7288: ul.LC_TabContentBigger li.active a {
 7289:   background:url('/adm/lonIcons/tabbgleft.gif') left top no-repeat;
 7290:   color:$font;
 7291: }
 7292: 
 7293: ul.LC_TabContentBigger li b {
 7294:   background: url('/adm/lonIcons/tabbgright.gif') no-repeat right bottom;
 7295:   display: block;
 7296:   float: left;
 7297:   padding: 0 30px;
 7298:   border-bottom: 1px solid $lg_border_color;
 7299: }
 7300: 
 7301: ul.LC_TabContentBigger li:hover b {
 7302:   color:$button_hover;
 7303: }
 7304: 
 7305: ul.LC_TabContentBigger li.active b {
 7306:   background:url('/adm/lonIcons/tabbgright.gif') right top no-repeat;
 7307:   color:$font;
 7308:   border: 0;
 7309: }
 7310: 
 7311: 
 7312: ul.LC_CourseBreadcrumbs {
 7313:   background: $sidebg;
 7314:   height: 2em;
 7315:   padding-left: 10px;
 7316:   margin: 0;
 7317:   list-style-position: inside;
 7318: }
 7319: 
 7320: ol#LC_MenuBreadcrumbs,
 7321: ol#LC_PathBreadcrumbs {
 7322:   padding-left: 10px;
 7323:   margin: 0;
 7324:   height: 2.5em;  /* equal to #LC_breadcrumbs line-height */
 7325: }
 7326: 
 7327: ol#LC_MenuBreadcrumbs li,
 7328: ol#LC_PathBreadcrumbs li,
 7329: ul.LC_CourseBreadcrumbs li {
 7330:   display: inline;
 7331:   white-space: normal;  
 7332: }
 7333: 
 7334: ol#LC_MenuBreadcrumbs li a,
 7335: ul.LC_CourseBreadcrumbs li a {
 7336:   text-decoration: none;
 7337:   font-size:90%;
 7338: }
 7339: 
 7340: ol#LC_MenuBreadcrumbs h1 {
 7341:   display: inline;
 7342:   font-size: 90%;
 7343:   line-height: 2.5em;
 7344:   margin: 0;
 7345:   padding: 0;
 7346: }
 7347: 
 7348: ol#LC_PathBreadcrumbs li a {
 7349:   text-decoration:none;
 7350:   font-size:100%;
 7351:   font-weight:bold;
 7352: }
 7353: 
 7354: .LC_Box {
 7355:   border: solid 1px $lg_border_color;
 7356:   padding: 0 10px 10px 10px;
 7357: }
 7358: 
 7359: .LC_DocsBox {
 7360:   border: solid 1px $lg_border_color;
 7361:   padding: 0 0 10px 10px;
 7362: }
 7363: 
 7364: .LC_AboutMe_Image {
 7365:   float:left;
 7366:   margin-right:10px;
 7367: }
 7368: 
 7369: .LC_Clear_AboutMe_Image {
 7370:   clear:left;
 7371: }
 7372: 
 7373: dl.LC_ListStyleClean dt {
 7374:   padding-right: 5px;
 7375:   display: table-header-group;
 7376: }
 7377: 
 7378: dl.LC_ListStyleClean dd {
 7379:   display: table-row;
 7380: }
 7381: 
 7382: .LC_ListStyleClean,
 7383: .LC_ListStyleSimple,
 7384: .LC_ListStyleNormal,
 7385: .LC_ListStyleSpecial {
 7386:   /* display:block; */
 7387:   list-style-position: inside;
 7388:   list-style-type: none;
 7389:   overflow: hidden;
 7390:   padding: 0;
 7391: }
 7392: 
 7393: .LC_ListStyleSimple li,
 7394: .LC_ListStyleSimple dd,
 7395: .LC_ListStyleNormal li,
 7396: .LC_ListStyleNormal dd,
 7397: .LC_ListStyleSpecial li,
 7398: .LC_ListStyleSpecial dd {
 7399:   margin: 0;
 7400:   padding: 5px 5px 5px 10px;
 7401:   clear: both;
 7402: }
 7403: 
 7404: .LC_ListStyleClean li,
 7405: .LC_ListStyleClean dd {
 7406:   padding-top: 0;
 7407:   padding-bottom: 0;
 7408: }
 7409: 
 7410: .LC_ListStyleSimple dd,
 7411: .LC_ListStyleSimple li {
 7412:   border-bottom: solid 1px $lg_border_color;
 7413: }
 7414: 
 7415: .LC_ListStyleSpecial li,
 7416: .LC_ListStyleSpecial dd {
 7417:   list-style-type: none;
 7418:   background-color: RGB(220, 220, 220);
 7419:   margin-bottom: 4px;
 7420: }
 7421: 
 7422: table.LC_SimpleTable {
 7423:   margin:5px;
 7424:   border:solid 1px $lg_border_color;
 7425: }
 7426: 
 7427: table.LC_SimpleTable tr {
 7428:   padding: 0;
 7429:   border:solid 1px $lg_border_color;
 7430: }
 7431: 
 7432: table.LC_SimpleTable thead {
 7433:   background:rgb(220,220,220);
 7434: }
 7435: 
 7436: div.LC_columnSection {
 7437:   display: block;
 7438:   clear: both;
 7439:   overflow: hidden;
 7440:   margin: 0;
 7441: }
 7442: 
 7443: div.LC_columnSection>* {
 7444:   float: left;
 7445:   margin: 10px 20px 10px 0;
 7446:   overflow:hidden;
 7447: }
 7448: 
 7449: table em {
 7450:   font-weight: bold;
 7451:   font-style: normal;
 7452: }
 7453: 
 7454: table.LC_tableBrowseRes,
 7455: table.LC_tableOfContent {
 7456:   border:none;
 7457:   border-spacing: 1px;
 7458:   padding: 3px;
 7459:   background-color: #FFFFFF;
 7460:   font-size: 90%;
 7461: }
 7462: 
 7463: table.LC_tableOfContent {
 7464:   border-collapse: collapse;
 7465: }
 7466: 
 7467: table.LC_tableBrowseRes a,
 7468: table.LC_tableOfContent a {
 7469:   background-color: transparent;
 7470:   text-decoration: none;
 7471: }
 7472: 
 7473: table.LC_tableOfContent img {
 7474:   border: none;
 7475:   height: 1.3em;
 7476:   vertical-align: text-bottom;
 7477:   margin-right: 0.3em;
 7478: }
 7479: 
 7480: a#LC_content_toolbar_firsthomework {
 7481:   background-image:url(/res/adm/pages/open-first-problem.gif);
 7482: }
 7483: 
 7484: a#LC_content_toolbar_everything {
 7485:   background-image:url(/res/adm/pages/show-all.gif);
 7486: }
 7487: 
 7488: a#LC_content_toolbar_uncompleted {
 7489:   background-image:url(/res/adm/pages/show-incomplete-problems.gif);
 7490: }
 7491: 
 7492: #LC_content_toolbar_clearbubbles {
 7493:   background-image:url(/res/adm/pages/mark-discussionentries-read.gif);
 7494: }
 7495: 
 7496: a#LC_content_toolbar_changefolder {
 7497:   background : url(/res/adm/pages/close-all-folders.gif) top center ;
 7498: }
 7499: 
 7500: a#LC_content_toolbar_changefolder_toggled {
 7501:   background-image:url(/res/adm/pages/open-all-folders.gif);
 7502: }
 7503: 
 7504: a#LC_content_toolbar_edittoplevel {
 7505:   background-image:url(/res/adm/pages/edittoplevel.gif);
 7506: }
 7507: 
 7508: ul#LC_toolbar li a:hover {
 7509:   background-position: bottom center;
 7510: }
 7511: 
 7512: ul#LC_toolbar {
 7513:   padding: 0;
 7514:   margin: 2px;
 7515:   list-style:none;
 7516:   position:relative;
 7517:   background-color:white;
 7518:   overflow: auto;
 7519: }
 7520: 
 7521: ul#LC_toolbar li {
 7522:   border:1px solid white;
 7523:   padding: 0;
 7524:   margin: 0;
 7525:   float: left;
 7526:   display:inline;
 7527:   vertical-align:middle;
 7528:   white-space: nowrap;
 7529: }
 7530: 
 7531: 
 7532: a.LC_toolbarItem {
 7533:   display:block;
 7534:   padding: 0;
 7535:   margin: 0;
 7536:   height: 32px;
 7537:   width: 32px;
 7538:   color:white;
 7539:   border: none;
 7540:   background-repeat:no-repeat;
 7541:   background-color:transparent;
 7542: }
 7543: 
 7544: ul.LC_funclist {
 7545:     margin: 0;
 7546:     padding: 0.5em 1em 0.5em 0;
 7547: }
 7548: 
 7549: ul.LC_funclist > li:first-child {
 7550:     font-weight:bold; 
 7551:     margin-left:0.8em;
 7552: }
 7553: 
 7554: ul.LC_funclist + ul.LC_funclist {
 7555:     /* 
 7556:        left border as a seperator if we have more than
 7557:        one list 
 7558:     */
 7559:     border-left: 1px solid $sidebg;
 7560:     /* 
 7561:        this hides the left border behind the border of the 
 7562:        outer box if element is wrapped to the next 'line' 
 7563:     */
 7564:     margin-left: -1px;
 7565: }
 7566: 
 7567: ul.LC_funclist li {
 7568:   display: inline;
 7569:   white-space: nowrap;
 7570:   margin: 0 0 0 25px;
 7571:   line-height: 150%;
 7572: }
 7573: 
 7574: .LC_hidden {
 7575:   display: none;
 7576: }
 7577: 
 7578: .LCmodal-overlay {
 7579: 		position:fixed;
 7580: 		top:0;
 7581: 		right:0;
 7582: 		bottom:0;
 7583: 		left:0;
 7584: 		height:100%;
 7585: 		width:100%;
 7586: 		margin:0;
 7587: 		padding:0;
 7588: 		background:#999;
 7589: 		opacity:.75;
 7590: 		filter: alpha(opacity=75);
 7591: 		-moz-opacity: 0.75;
 7592: 		z-index:101;
 7593: }
 7594: 
 7595: * html .LCmodal-overlay {   
 7596: 		position: absolute;
 7597: 		height: expression(document.body.scrollHeight > document.body.offsetHeight ? document.body.scrollHeight : document.body.offsetHeight + 'px');
 7598: }
 7599: 
 7600: .LCmodal-window {
 7601: 		position:fixed;
 7602: 		top:50%;
 7603: 		left:50%;
 7604: 		margin:0;
 7605: 		padding:0;
 7606: 		z-index:102;
 7607: 	}
 7608: 
 7609: * html .LCmodal-window {
 7610: 		position:absolute;
 7611: }
 7612: 
 7613: .LCclose-window {
 7614: 		position:absolute;
 7615: 		width:32px;
 7616: 		height:32px;
 7617: 		right:8px;
 7618: 		top:8px;
 7619: 		background:transparent url('/res/adm/pages/process-stop.png') no-repeat scroll right top;
 7620: 		text-indent:-99999px;
 7621: 		overflow:hidden;
 7622: 		cursor:pointer;
 7623: }
 7624: 
 7625: /*
 7626:   styles used by TTH when "Default set of options to pass to tth/m
 7627:   when converting TeX" in course settings has been set
 7628: 
 7629:   option passed: -t
 7630: 
 7631: */
 7632: 
 7633: td div.comp { margin-top: -0.6ex; margin-bottom: -1ex;}
 7634: td div.comb { margin-top: -0.6ex; margin-bottom: -.6ex;}
 7635: td div.hrcomp { line-height: 0.9; margin-top: -0.8ex; margin-bottom: -1ex;}
 7636: td div.norm {line-height:normal;}
 7637: 
 7638: /*
 7639:   option passed -y3
 7640: */
 7641: 
 7642: span.roman {font-family: serif; font-style: normal; font-weight: normal;}
 7643: span.overacc2 {position: relative;  left: .8em; top: -1.2ex;}
 7644: span.overacc1 {position: relative;  left: .6em; top: -1.2ex;}
 7645: 
 7646: END
 7647: }
 7648: 
 7649: =pod
 7650: 
 7651: =item * &headtag()
 7652: 
 7653: Returns a uniform footer for LON-CAPA web pages.
 7654: 
 7655: Inputs: $title - optional title for the head
 7656:         $head_extra - optional extra HTML to put inside the <head>
 7657:         $args - optional arguments
 7658:             force_register - if is true call registerurl so the remote is 
 7659:                              informed
 7660:             redirect       -> array ref of
 7661:                                    1- seconds before redirect occurs
 7662:                                    2- url to redirect to
 7663:                                    3- whether the side effect should occur
 7664:                            (side effect of setting 
 7665:                                $env{'internal.head.redirect'} to the url 
 7666:                                redirected too)
 7667:             domain         -> force to color decorate a page for a specific
 7668:                                domain
 7669:             function       -> force usage of a specific rolish color scheme
 7670:             bgcolor        -> override the default page bgcolor
 7671:             no_auto_mt_title
 7672:                            -> prevent &mt()ing the title arg
 7673: 
 7674: =cut
 7675: 
 7676: sub headtag {
 7677:     my ($title,$head_extra,$args) = @_;
 7678:     
 7679:     my $function = $args->{'function'} || &get_users_function();
 7680:     my $domain   = $args->{'domain'}   || &determinedomain();
 7681:     my $bgcolor  = $args->{'bgcolor'}  || &designparm($function.'.pgbg',$domain);
 7682:     my $httphost = $args->{'use_absolute'};
 7683:     my $url = join(':',$env{'user.name'},$env{'user.domain'},
 7684: 		   $Apache::lonnet::perlvar{'lonVersion'},
 7685: 		   #time(),
 7686: 		   $env{'environment.color.timestamp'},
 7687: 		   $function,$domain,$bgcolor);
 7688: 
 7689:     $url = '/adm/css/'.&escape($url).'.css';
 7690: 
 7691:     my $result =
 7692: 	'<head>'.
 7693: 	&font_settings($args);
 7694: 
 7695:     my $inhibitprint;
 7696:     if ($args->{'print_suppress'}) {
 7697:         $inhibitprint = &print_suppression();
 7698:     }
 7699: 
 7700:     if (!$args->{'frameset'}) {
 7701: 	$result .= &Apache::lonhtmlcommon::htmlareaheaders();
 7702:     }
 7703:     if ($args->{'force_register'}) {
 7704:         $result .= &Apache::lonmenu::registerurl(1);
 7705:     }
 7706:     if (!$args->{'no_nav_bar'} 
 7707: 	&& !$args->{'only_body'}
 7708: 	&& !$args->{'frameset'}) {
 7709: 	$result .= &help_menu_js($httphost);
 7710:         $result.=&modal_window();
 7711:         $result.=&togglebox_script();
 7712:         $result.=&wishlist_window();
 7713:         $result.=&LCprogressbarUpdate_script();
 7714:     } else {
 7715:         if ($args->{'add_modal'}) {
 7716:            $result.=&modal_window();
 7717:         }
 7718:         if ($args->{'add_wishlist'}) {
 7719:            $result.=&wishlist_window();
 7720:         }
 7721:         if ($args->{'add_togglebox'}) {
 7722:            $result.=&togglebox_script();
 7723:         }
 7724:         if ($args->{'add_progressbar'}) {
 7725:            $result.=&LCprogressbarUpdate_script();
 7726:         }
 7727:     }
 7728:     if (ref($args->{'redirect'})) {
 7729: 	my ($time,$url,$inhibit_continue) = @{$args->{'redirect'}};
 7730: 	$url = &Apache::lonenc::check_encrypt($url);
 7731: 	if (!$inhibit_continue) {
 7732: 	    $env{'internal.head.redirect'} = $url;
 7733: 	}
 7734: 	$result.=<<ADDMETA
 7735: <meta http-equiv="pragma" content="no-cache" />
 7736: <meta http-equiv="Refresh" content="$time; url=$url" />
 7737: ADDMETA
 7738:     } else {
 7739:         unless (($args->{'frameset'}) || ($args->{'js_ready'}) || ($args->{'only_body'}) || ($args->{'no_nav_bar'})) {
 7740:             my $requrl = $env{'request.uri'};
 7741:             if ($requrl eq '') {
 7742:                 $requrl = $ENV{'REQUEST_URI'};
 7743:                 $requrl =~ s/\?.+$//;
 7744:             }
 7745:             unless (($requrl =~ m{^/adm/(?:switchserver|login|authenticate|logout|groupsort|cleanup|helper|slotrequest|grades)(\?|$)}) ||
 7746:                     (($requrl =~ m{^/res/}) && (($env{'form.submitted'} eq 'scantron') ||
 7747:                      ($env{'form.grade_symb'}) || ($Apache::lonhomework::scantronmode)))) {
 7748:                 my $dom_in_use = $Apache::lonnet::perlvar{'lonDefDomain'};
 7749:                 unless (&Apache::lonnet::allowed('mau',$dom_in_use)) {
 7750:                     my %domdefs = &Apache::lonnet::get_domain_defaults($dom_in_use);
 7751:                     if (ref($domdefs{'offloadnow'}) eq 'HASH') {
 7752:                         my $lonhost = $Apache::lonnet::perlvar{'lonHostID'};
 7753:                         if ($domdefs{'offloadnow'}{$lonhost}) {
 7754:                             my $newserver = &Apache::lonnet::spareserver(30000,undef,1,$dom_in_use);
 7755:                             if (($newserver) && ($newserver ne $lonhost)) {
 7756:                                 my $numsec = 5;
 7757:                                 my $timeout = $numsec * 1000;
 7758:                                 my ($newurl,$locknum,%locks,$msg);
 7759:                                 if ($env{'request.role.adv'}) {
 7760:                                     ($locknum,%locks) = &Apache::lonnet::get_locks();
 7761:                                 }
 7762:                                 my $disable_submit = 0;
 7763:                                 if ($requrl =~ /$LONCAPA::assess_re/) {
 7764:                                     $disable_submit = 1;
 7765:                                 }
 7766:                                 if ($locknum) {
 7767:                                     my @lockinfo = sort(values(%locks));
 7768:                                     $msg = &mt('Once the following tasks are complete: ')."\\n".
 7769:                                            join(", ",sort(values(%locks)))."\\n".
 7770:                                            &mt('your session will be transferred to a different server, after you click "Roles".');
 7771:                                 } else {
 7772:                                     if (($requrl =~ m{^/res/}) && ($env{'form.submitted'} =~ /^part_/)) {
 7773:                                         $msg = &mt('Your LON-CAPA submission has been recorded')."\\n";
 7774:                                     }
 7775:                                     $msg .= &mt('Your current LON-CAPA session will be transferred to a different server in [quant,_1,second].',$numsec);
 7776:                                     $newurl = '/adm/switchserver?otherserver='.$newserver;
 7777:                                     if (($env{'request.role'}) && ($env{'request.role'} ne 'cm')) {
 7778:                                         $newurl .= '&role='.$env{'request.role'};
 7779:                                     }
 7780:                                     if ($env{'request.symb'}) {
 7781:                                         $newurl .= '&symb='.$env{'request.symb'};
 7782:                                     } else {
 7783:                                         $newurl .= '&origurl='.$requrl;
 7784:                                     }
 7785:                                 }
 7786:                                 &js_escape(\$msg);
 7787:                                 $result.=<<OFFLOAD
 7788: <meta http-equiv="pragma" content="no-cache" />
 7789: <script type="text/javascript">
 7790: // <![CDATA[
 7791: function LC_Offload_Now() {
 7792:     var dest = "$newurl";
 7793:     if (dest != '') {
 7794:         window.location.href="$newurl";
 7795:     }
 7796: }
 7797: \$(document).ready(function () {
 7798:     window.alert('$msg');
 7799:     if ($disable_submit) {
 7800:         \$(".LC_hwk_submit").prop("disabled", true);
 7801:         \$( ".LC_textline" ).prop( "readonly", "readonly");
 7802:     }
 7803:     setTimeout('LC_Offload_Now()', $timeout);
 7804: });
 7805: // ]]>
 7806: </script>
 7807: OFFLOAD
 7808:                             }
 7809:                         }
 7810:                     }
 7811:                 }
 7812:             }
 7813:         }
 7814:     }
 7815:     if (!defined($title)) {
 7816: 	$title = 'The LearningOnline Network with CAPA';
 7817:     }
 7818:     if (!$args->{'no_auto_mt_title'}) { $title = &mt($title); }
 7819:     $result .= '<title> LON-CAPA '.$title.'</title>'
 7820: 	.'<link rel="stylesheet" type="text/css" href="'.$url.'"';
 7821:     if (!$args->{'frameset'}) {
 7822:         $result .= ' /';
 7823:     }
 7824:     $result .= '>'
 7825:         .$inhibitprint
 7826: 	.$head_extra;
 7827:     my $clientmobile;
 7828:     if (($env{'user.name'} eq '') && ($env{'user.domain'} eq '')) {
 7829:         (undef,undef,undef,undef,undef,undef,$clientmobile) = &decode_user_agent();
 7830:     } else {
 7831:         $clientmobile = $env{'browser.mobile'};
 7832:     }
 7833:     if ($clientmobile) {
 7834:         $result .= '
 7835: <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=0, minimum-scale=1.0, maximum-scale=1.0">
 7836: <meta name="apple-mobile-web-app-capable" content="yes" />';
 7837:     }
 7838:     return $result.'</head>';
 7839: }
 7840: 
 7841: =pod
 7842: 
 7843: =item * &font_settings()
 7844: 
 7845: Returns neccessary <meta> to set the proper encoding
 7846: 
 7847: Inputs: optional reference to HASH -- $args passed to &headtag()
 7848: 
 7849: =cut
 7850: 
 7851: sub font_settings {
 7852:     my ($args) = @_;
 7853:     my $headerstring='';
 7854:     if ((!$env{'browser.mathml'} && $env{'browser.unicode'}) ||
 7855:         ((ref($args) eq 'HASH') && ($args->{'browser.unicode'}))) {
 7856: 	$headerstring.=
 7857: 	    '<meta http-equiv="Content-Type" content="text/html; charset=utf-8"';
 7858:         if (!$args->{'frameset'}) {
 7859:             $headerstring.= ' /';
 7860:         }
 7861:         $headerstring .= '>'."\n";
 7862:     }
 7863:     return $headerstring;
 7864: }
 7865: 
 7866: =pod
 7867: 
 7868: =item * &print_suppression()
 7869: 
 7870: In course context returns css which causes the body to be blank when media="print",
 7871: if printout generation is unavailable for the current resource.
 7872: 
 7873: This could be because:
 7874: 
 7875: (a) printstartdate is in the future
 7876: 
 7877: (b) printenddate is in the past
 7878: 
 7879: (c) there is an active exam block with "printout"
 7880: functionality blocked
 7881: 
 7882: Users with pav, pfo or evb privileges are exempt.
 7883: 
 7884: Inputs: none
 7885: 
 7886: =cut
 7887: 
 7888: 
 7889: sub print_suppression {
 7890:     my $noprint;
 7891:     if ($env{'request.course.id'}) {
 7892:         my $scope = $env{'request.course.id'};
 7893:         if ((&Apache::lonnet::allowed('pav',$scope)) ||
 7894:             (&Apache::lonnet::allowed('pfo',$scope))) {
 7895:             return;
 7896:         }
 7897:         if ($env{'request.course.sec'} ne '') {
 7898:             $scope .= "/$env{'request.course.sec'}";
 7899:             if ((&Apache::lonnet::allowed('pav',$scope)) ||
 7900:                 (&Apache::lonnet::allowed('pfo',$scope))) {
 7901:                 return;
 7902:             }
 7903:         }
 7904:         my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 7905:         my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 7906:         my $blocked = &blocking_status('printout',$cnum,$cdom,undef,1);
 7907:         if ($blocked) {
 7908:             my $checkrole = "cm./$cdom/$cnum";
 7909:             if ($env{'request.course.sec'} ne '') {
 7910:                 $checkrole .= "/$env{'request.course.sec'}";
 7911:             }
 7912:             unless ((&Apache::lonnet::allowed('evb',undef,undef,$checkrole)) &&
 7913:                     ($env{'request.role'} !~ m{^st\./$cdom/$cnum})) {
 7914:                 $noprint = 1;
 7915:             }
 7916:         }
 7917:         unless ($noprint) {
 7918:             my $symb = &Apache::lonnet::symbread();
 7919:             if ($symb ne '') {
 7920:                 my $navmap = Apache::lonnavmaps::navmap->new();
 7921:                 if (ref($navmap)) {
 7922:                     my $res = $navmap->getBySymb($symb);
 7923:                     if (ref($res)) {
 7924:                         if (!$res->resprintable()) {
 7925:                             $noprint = 1;
 7926:                         }
 7927:                     }
 7928:                 }
 7929:             }
 7930:         }
 7931:         if ($noprint) {
 7932:             return <<"ENDSTYLE";
 7933: <style type="text/css" media="print">
 7934:     body { display:none }
 7935: </style>
 7936: ENDSTYLE
 7937:         }
 7938:     }
 7939:     return;
 7940: }
 7941: 
 7942: =pod
 7943: 
 7944: =item * &xml_begin()
 7945: 
 7946: Returns the needed doctype and <html>
 7947: 
 7948: Inputs: none
 7949: 
 7950: =cut
 7951: 
 7952: sub xml_begin {
 7953:     my ($is_frameset) = @_;
 7954:     my $output='';
 7955: 
 7956:     if ($env{'browser.mathml'}) {
 7957: 	$output='<?xml version="1.0"?>'
 7958:             #.'<?xml-stylesheet type="text/css" href="/adm/MathML/mathml.css"?>'."\n"
 7959: #            .'<!DOCTYPE html SYSTEM "/adm/MathML/mathml.dtd" '
 7960:             
 7961: #	    .'<!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">] >'
 7962: 	    .'<!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">'
 7963:             .'<html xmlns:math="http://www.w3.org/1998/Math/MathML" ' 
 7964: 	    .'xmlns="http://www.w3.org/1999/xhtml">';
 7965:     } elsif ($is_frameset) {
 7966:         $output='<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Frameset//EN" "http://www.w3.org/TR/html4/frameset.dtd">'."\n".
 7967:                 '<html>'."\n";
 7968:     } else {
 7969: 	$output='<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">'."\n".
 7970:                 '<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">'."\n";
 7971:     }
 7972:     return $output;
 7973: }
 7974: 
 7975: =pod
 7976: 
 7977: =item * &start_page()
 7978: 
 7979: Returns a complete <html> .. <body> section for LON-CAPA web pages.
 7980: 
 7981: Inputs:
 7982: 
 7983: =over 4
 7984: 
 7985: $title - optional title for the page
 7986: 
 7987: $head_extra - optional extra HTML to incude inside the <head>
 7988: 
 7989: $args - additional optional args supported are:
 7990: 
 7991: =over 8
 7992: 
 7993:              only_body      -> is true will set &bodytag() onlybodytag
 7994:                                     arg on
 7995:              no_nav_bar     -> is true will set &bodytag() no_nav_bar arg on
 7996:              add_entries    -> additional attributes to add to the  <body>
 7997:              domain         -> force to color decorate a page for a 
 7998:                                     specific domain
 7999:              function       -> force usage of a specific rolish color
 8000:                                     scheme
 8001:              redirect       -> see &headtag()
 8002:              bgcolor        -> override the default page bg color
 8003:              js_ready       -> return a string ready for being used in 
 8004:                                     a javascript writeln
 8005:              html_encode    -> return a string ready for being used in 
 8006:                                     a html attribute
 8007:              force_register -> if is true will turn on the &bodytag()
 8008:                                     $forcereg arg
 8009:              frameset       -> if true will start with a <frameset>
 8010:                                     rather than <body>
 8011:              skip_phases    -> hash ref of 
 8012:                                     head -> skip the <html><head> generation
 8013:                                     body -> skip all <body> generation
 8014:              no_inline_link -> if true and in remote mode, don't show the
 8015:                                     'Switch To Inline Menu' link
 8016:              no_auto_mt_title -> prevent &mt()ing the title arg
 8017:              bread_crumbs ->             Array containing breadcrumbs
 8018:              bread_crumbs_component ->  if exists show it as headline else show only the breadcrumbs
 8019:              group          -> includes the current group, if page is for a
 8020:                                specific group
 8021: 
 8022: =back
 8023: 
 8024: =back
 8025: 
 8026: =cut
 8027: 
 8028: sub start_page {
 8029:     my ($title,$head_extra,$args) = @_;
 8030:     #&Apache::lonnet::logthis("start_page ".join(':',caller(0)));
 8031: 
 8032:     $env{'internal.start_page'}++;
 8033:     my ($result,@advtools);
 8034: 
 8035:     if (! exists($args->{'skip_phases'}{'head'}) ) {
 8036:         $result .= &xml_begin($args->{'frameset'}) . &headtag($title, $head_extra, $args);
 8037:     }
 8038:     
 8039:     if (! exists($args->{'skip_phases'}{'body'}) ) {
 8040: 	if ($args->{'frameset'}) {
 8041: 	    my $attr_string = &make_attr_string($args->{'force_register'},
 8042: 						$args->{'add_entries'});
 8043: 	    $result .= "\n<frameset $attr_string>\n";
 8044:         } else {
 8045:             $result .=
 8046:                 &bodytag($title, 
 8047:                          $args->{'function'},       $args->{'add_entries'},
 8048:                          $args->{'only_body'},      $args->{'domain'},
 8049:                          $args->{'force_register'}, $args->{'no_nav_bar'},
 8050:                          $args->{'bgcolor'},        $args->{'no_inline_link'},
 8051:                          $args,                     \@advtools);
 8052:         }
 8053:     }
 8054: 
 8055:     if ($args->{'js_ready'}) {
 8056: 		$result = &js_ready($result);
 8057:     }
 8058:     if ($args->{'html_encode'}) {
 8059: 		$result = &html_encode($result);
 8060:     }
 8061: 
 8062:     # Preparation for new and consistent functionlist at top of screen
 8063:     # if ($args->{'functionlist'}) {
 8064:     #            $result .= &build_functionlist();
 8065:     #}
 8066: 
 8067:     # Don't add anything more if only_body wanted or in const space
 8068:     return $result if    $args->{'only_body'} 
 8069:                       || $env{'request.state'} eq 'construct';
 8070: 
 8071:     #Breadcrumbs
 8072:     if (exists($args->{'bread_crumbs'}) or exists($args->{'bread_crumbs_component'})) {
 8073: 		&Apache::lonhtmlcommon::clear_breadcrumbs();
 8074: 		#if any br links exists, add them to the breadcrumbs
 8075: 		if (exists($args->{'bread_crumbs'}) and ref($args->{'bread_crumbs'}) eq 'ARRAY') {         
 8076: 			foreach my $crumb (@{$args->{'bread_crumbs'}}){
 8077: 				&Apache::lonhtmlcommon::add_breadcrumb($crumb);
 8078: 			}
 8079: 		}
 8080:                 # if @advtools array contains items add then to the breadcrumbs
 8081:                 if (@advtools > 0) {
 8082:                     &Apache::lonmenu::advtools_crumbs(@advtools);
 8083:                 }
 8084: 
 8085: 		#if bread_crumbs_component exists show it as headline else show only the breadcrumbs
 8086: 		if(exists($args->{'bread_crumbs_component'})){
 8087: 			$result .= &Apache::lonhtmlcommon::breadcrumbs($args->{'bread_crumbs_component'});
 8088: 		}else{
 8089: 			$result .= &Apache::lonhtmlcommon::breadcrumbs();
 8090: 		}
 8091:     } elsif (($env{'environment.remote'} eq 'on') &&
 8092:              ($env{'form.inhibitmenu'} ne 'yes') &&
 8093:              ($env{'request.noversionuri'} =~ m{^/res/}) &&
 8094:              ($env{'request.noversionuri'} !~ m{^/res/adm/pages/})) {
 8095:         $result .= '<div style="padding:0;margin:0;clear:both"><hr /></div>';
 8096:     }
 8097:     return $result;
 8098: }
 8099: 
 8100: sub end_page {
 8101:     my ($args) = @_;
 8102:     $env{'internal.end_page'}++;
 8103:     my $result;
 8104:     if ($args->{'discussion'}) {
 8105: 	my ($target,$parser);
 8106: 	if (ref($args->{'discussion'})) {
 8107: 	    ($target,$parser) =($args->{'discussion'}{'target'},
 8108: 				$args->{'discussion'}{'parser'});
 8109: 	}
 8110: 	$result .= &Apache::lonxml::xmlend($target,$parser);
 8111:     }
 8112:     if ($args->{'frameset'}) {
 8113: 	$result .= '</frameset>';
 8114:     } else {
 8115: 	$result .= &endbodytag($args);
 8116:     }
 8117:     unless ($args->{'notbody'}) {
 8118:         $result .= "\n</html>";
 8119:     }
 8120: 
 8121:     if ($args->{'js_ready'}) {
 8122: 	$result = &js_ready($result);
 8123:     }
 8124: 
 8125:     if ($args->{'html_encode'}) {
 8126: 	$result = &html_encode($result);
 8127:     }
 8128: 
 8129:     return $result;
 8130: }
 8131: 
 8132: sub wishlist_window {
 8133:     return(<<'ENDWISHLIST');
 8134: <script type="text/javascript">
 8135: // <![CDATA[
 8136: // <!-- BEGIN LON-CAPA Internal
 8137: function set_wishlistlink(title, path) {
 8138:     if (!title) {
 8139:         title = document.title;
 8140:         title = title.replace(/^LON-CAPA /,'');
 8141:     }
 8142:     title = encodeURIComponent(title);
 8143:     title = title.replace("'","\\\'");
 8144:     if (!path) {
 8145:         path = location.pathname;
 8146:     }
 8147:     path = encodeURIComponent(path);
 8148:     path = path.replace("'","\\\'");
 8149:     Win = window.open('/adm/wishlist?mode=newLink&setTitle='+title+'&setPath='+path,
 8150:                       'wishlistNewLink','width=560,height=350,scrollbars=0');
 8151: }
 8152: // END LON-CAPA Internal -->
 8153: // ]]>
 8154: </script>
 8155: ENDWISHLIST
 8156: }
 8157: 
 8158: sub modal_window {
 8159:     return(<<'ENDMODAL');
 8160: <script type="text/javascript">
 8161: // <![CDATA[
 8162: // <!-- BEGIN LON-CAPA Internal
 8163: var modalWindow = {
 8164: 	parent:"body",
 8165: 	windowId:null,
 8166: 	content:null,
 8167: 	width:null,
 8168: 	height:null,
 8169: 	close:function()
 8170: 	{
 8171: 	        $(".LCmodal-window").remove();
 8172: 	        $(".LCmodal-overlay").remove();
 8173: 	},
 8174: 	open:function()
 8175: 	{
 8176: 		var modal = "";
 8177: 		modal += "<div class=\"LCmodal-overlay\"></div>";
 8178: 		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;\">";
 8179: 		modal += this.content;
 8180: 		modal += "</div>";	
 8181: 
 8182: 		$(this.parent).append(modal);
 8183: 
 8184: 		$(".LCmodal-window").append("<a class=\"LCclose-window\"></a>");
 8185: 		$(".LCclose-window").click(function(){modalWindow.close();});
 8186: 		$(".LCmodal-overlay").click(function(){modalWindow.close();});
 8187: 	}
 8188: };
 8189: 	var openMyModal = function(source,width,height,scrolling,transparency,style)
 8190: 	{
 8191:                 source = source.replace("'","&#39;");
 8192: 		modalWindow.windowId = "myModal";
 8193: 		modalWindow.width = width;
 8194: 		modalWindow.height = height;
 8195: 		modalWindow.content = "<iframe width='"+width+"' height='"+height+"' frameborder='0' scrolling='"+scrolling+"' allowtransparency='"+transparency+"' src='" + source + "' style='"+style+"'></iframe>";
 8196: 		modalWindow.open();
 8197: 	};
 8198: // END LON-CAPA Internal -->
 8199: // ]]>
 8200: </script>
 8201: ENDMODAL
 8202: }
 8203: 
 8204: sub modal_link {
 8205:     my ($link,$linktext,$width,$height,$target,$scrolling,$title,$transparency,$style)=@_;
 8206:     unless ($width) { $width=480; }
 8207:     unless ($height) { $height=400; }
 8208:     unless ($scrolling) { $scrolling='yes'; }
 8209:     unless ($transparency) { $transparency='true'; }
 8210: 
 8211:     my $target_attr;
 8212:     if (defined($target)) {
 8213:         $target_attr = 'target="'.$target.'"';
 8214:     }
 8215:     return <<"ENDLINK";
 8216: <a href="$link" $target_attr title="$title" onclick="javascript:openMyModal('$link',$width,$height,'$scrolling','$transparency','$style'); return false;">
 8217:            $linktext</a>
 8218: ENDLINK
 8219: }
 8220: 
 8221: sub modal_adhoc_script {
 8222:     my ($funcname,$width,$height,$content)=@_;
 8223:     return (<<ENDADHOC);
 8224: <script type="text/javascript">
 8225: // <![CDATA[
 8226:         var $funcname = function()
 8227:         {
 8228:                 modalWindow.windowId = "myModal";
 8229:                 modalWindow.width = $width;
 8230:                 modalWindow.height = $height;
 8231:                 modalWindow.content = '$content';
 8232:                 modalWindow.open();
 8233:         };  
 8234: // ]]>
 8235: </script>
 8236: ENDADHOC
 8237: }
 8238: 
 8239: sub modal_adhoc_inner {
 8240:     my ($funcname,$width,$height,$content)=@_;
 8241:     my $innerwidth=$width-20;
 8242:     $content=&js_ready(
 8243:                &start_page('Dialog',undef,{'only_body'=>1,'bgcolor'=>'#FFFFFF'}).
 8244:                  &start_scrollbox($width.'px',$innerwidth.'px',$height.'px','myModal','#FFFFFF',undef,1).
 8245:                  $content.
 8246:                  &end_scrollbox().
 8247:                  &end_page()
 8248:              );
 8249:     return &modal_adhoc_script($funcname,$width,$height,$content);
 8250: }
 8251: 
 8252: sub modal_adhoc_window {
 8253:     my ($funcname,$width,$height,$content,$linktext)=@_;
 8254:     return &modal_adhoc_inner($funcname,$width,$height,$content).
 8255:            "<a href=\"javascript:$funcname();void(0);\">".$linktext."</a>";
 8256: }
 8257: 
 8258: sub modal_adhoc_launch {
 8259:     my ($funcname,$width,$height,$content)=@_;
 8260:     return &modal_adhoc_inner($funcname,$width,$height,$content).(<<ENDLAUNCH);
 8261: <script type="text/javascript">
 8262: // <![CDATA[
 8263: $funcname();
 8264: // ]]>
 8265: </script>
 8266: ENDLAUNCH
 8267: }
 8268: 
 8269: sub modal_adhoc_close {
 8270:     return (<<ENDCLOSE);
 8271: <script type="text/javascript">
 8272: // <![CDATA[
 8273: modalWindow.close();
 8274: // ]]>
 8275: </script>
 8276: ENDCLOSE
 8277: }
 8278: 
 8279: sub togglebox_script {
 8280:    return(<<ENDTOGGLE);
 8281: <script type="text/javascript"> 
 8282: // <![CDATA[
 8283: function LCtoggleDisplay(id,hidetext,showtext) {
 8284:    link = document.getElementById(id + "link").childNodes[0];
 8285:    with (document.getElementById(id).style) {
 8286:       if (display == "none" ) {
 8287:           display = "inline";
 8288:           link.nodeValue = hidetext;
 8289:         } else {
 8290:           display = "none";
 8291:           link.nodeValue = showtext;
 8292:        }
 8293:    }
 8294: }
 8295: // ]]>
 8296: </script>
 8297: ENDTOGGLE
 8298: }
 8299: 
 8300: sub start_togglebox {
 8301:     my ($id,$heading,$headerbg,$hidetext,$showtext)=@_;
 8302:     unless ($heading) { $heading=''; } else { $heading.=' '; }
 8303:     unless ($showtext) { $showtext=&mt('show'); }
 8304:     unless ($hidetext) { $hidetext=&mt('hide'); }
 8305:     unless ($headerbg) { $headerbg='#FFFFFF'; }
 8306:     return &start_data_table().
 8307:            &start_data_table_header_row().
 8308:            '<td bgcolor="'.$headerbg.'">'.$heading.
 8309:            '[<a id="'.$id.'link" href="javascript:LCtoggleDisplay(\''.$id.'\',\''.$hidetext.'\',\''.
 8310:            $showtext.'\')">'.$showtext.'</a>]</td>'.
 8311:            &end_data_table_header_row().
 8312:            '<tr id="'.$id.'" style="display:none""><td>';
 8313: }
 8314: 
 8315: sub end_togglebox {
 8316:     return '</td></tr>'.&end_data_table();
 8317: }
 8318: 
 8319: sub LCprogressbar_script {
 8320:    my ($id)=@_;
 8321:    return(<<ENDPROGRESS);
 8322: <script type="text/javascript">
 8323: // <![CDATA[
 8324: \$('#progressbar$id').progressbar({
 8325:   value: 0,
 8326:   change: function(event, ui) {
 8327:     var newVal = \$(this).progressbar('option', 'value');
 8328:     \$('.pblabel', this).text(LCprogressTxt);
 8329:   }
 8330: });
 8331: // ]]>
 8332: </script>
 8333: ENDPROGRESS
 8334: }
 8335: 
 8336: sub LCprogressbarUpdate_script {
 8337:    return(<<ENDPROGRESSUPDATE);
 8338: <style type="text/css">
 8339: .ui-progressbar { position:relative; }
 8340: .pblabel { position: absolute; width: 100%; text-align: center; line-height: 1.9em; }
 8341: </style>
 8342: <script type="text/javascript">
 8343: // <![CDATA[
 8344: var LCprogressTxt='---';
 8345: 
 8346: function LCupdateProgress(percent,progresstext,id) {
 8347:    LCprogressTxt=progresstext;
 8348:    \$('#progressbar'+id).progressbar('value',percent);
 8349: }
 8350: // ]]>
 8351: </script>
 8352: ENDPROGRESSUPDATE
 8353: }
 8354: 
 8355: my $LClastpercent;
 8356: my $LCidcnt;
 8357: my $LCcurrentid;
 8358: 
 8359: sub LCprogressbar {
 8360:     my ($r)=(@_);
 8361:     $LClastpercent=0;
 8362:     $LCidcnt++;
 8363:     $LCcurrentid=$$.'_'.$LCidcnt;
 8364:     my $starting=&mt('Starting');
 8365:     my $content=(<<ENDPROGBAR);
 8366:   <div id="progressbar$LCcurrentid">
 8367:     <span class="pblabel">$starting</span>
 8368:   </div>
 8369: ENDPROGBAR
 8370:     &r_print($r,$content.&LCprogressbar_script($LCcurrentid));
 8371: }
 8372: 
 8373: sub LCprogressbarUpdate {
 8374:     my ($r,$val,$text)=@_;
 8375:     unless ($val) { 
 8376:        if ($LClastpercent) {
 8377:            $val=$LClastpercent;
 8378:        } else {
 8379:            $val=0;
 8380:        }
 8381:     }
 8382:     if ($val<0) { $val=0; }
 8383:     if ($val>100) { $val=0; }
 8384:     $LClastpercent=$val;
 8385:     unless ($text) { $text=$val.'%'; }
 8386:     $text=&js_ready($text);
 8387:     &r_print($r,<<ENDUPDATE);
 8388: <script type="text/javascript">
 8389: // <![CDATA[
 8390: LCupdateProgress($val,'$text','$LCcurrentid');
 8391: // ]]>
 8392: </script>
 8393: ENDUPDATE
 8394: }
 8395: 
 8396: sub LCprogressbarClose {
 8397:     my ($r)=@_;
 8398:     $LClastpercent=0;
 8399:     &r_print($r,<<ENDCLOSE);
 8400: <script type="text/javascript">
 8401: // <![CDATA[
 8402: \$("#progressbar$LCcurrentid").hide('slow'); 
 8403: // ]]>
 8404: </script>
 8405: ENDCLOSE
 8406: }
 8407: 
 8408: sub r_print {
 8409:     my ($r,$to_print)=@_;
 8410:     if ($r) {
 8411:       $r->print($to_print);
 8412:       $r->rflush();
 8413:     } else {
 8414:       print($to_print);
 8415:     }
 8416: }
 8417: 
 8418: sub html_encode {
 8419:     my ($result) = @_;
 8420: 
 8421:     $result = &HTML::Entities::encode($result,'<>&"');
 8422:     
 8423:     return $result;
 8424: }
 8425: 
 8426: sub js_ready {
 8427:     my ($result) = @_;
 8428: 
 8429:     $result =~ s/[\n\r]/ /xmsg;
 8430:     $result =~ s/\\/\\\\/xmsg;
 8431:     $result =~ s/'/\\'/xmsg;
 8432:     $result =~ s{</}{<\\/}xmsg;
 8433:     
 8434:     return $result;
 8435: }
 8436: 
 8437: sub validate_page {
 8438:     if (  exists($env{'internal.start_page'})
 8439: 	  &&     $env{'internal.start_page'} > 1) {
 8440: 	&Apache::lonnet::logthis('start_page called multiple times '.
 8441: 				 $env{'internal.start_page'}.' '.
 8442: 				 $ENV{'request.filename'});
 8443:     }
 8444:     if (  exists($env{'internal.end_page'})
 8445: 	  &&     $env{'internal.end_page'} > 1) {
 8446: 	&Apache::lonnet::logthis('end_page called multiple times '.
 8447: 				 $env{'internal.end_page'}.' '.
 8448: 				 $env{'request.filename'});
 8449:     }
 8450:     if (     exists($env{'internal.start_page'})
 8451: 	&& ! exists($env{'internal.end_page'})) {
 8452: 	&Apache::lonnet::logthis('start_page called without end_page '.
 8453: 				 $env{'request.filename'});
 8454:     }
 8455:     if (   ! exists($env{'internal.start_page'})
 8456: 	&&   exists($env{'internal.end_page'})) {
 8457: 	&Apache::lonnet::logthis('end_page called without start_page'.
 8458: 				 $env{'request.filename'});
 8459:     }
 8460: }
 8461: 
 8462: 
 8463: sub start_scrollbox {
 8464:     my ($outerwidth,$width,$height,$id,$bgcolor,$cursor,$needjsready) = @_;
 8465:     unless ($outerwidth) { $outerwidth='520px'; }
 8466:     unless ($width) { $width='500px'; }
 8467:     unless ($height) { $height='200px'; }
 8468:     my ($table_id,$div_id,$tdcol);
 8469:     if ($id ne '') {
 8470:         $table_id = ' id="table_'.$id.'"';
 8471:         $div_id = ' id="div_'.$id.'"';
 8472:     }
 8473:     if ($bgcolor ne '') {
 8474:         $tdcol = "background-color: $bgcolor;";
 8475:     }
 8476:     my $nicescroll_js;
 8477:     if ($env{'browser.mobile'}) {
 8478:         $nicescroll_js = &nicescroll_javascript('div_'.$id,$cursor,$needjsready);
 8479:     }
 8480:     return <<"END";
 8481: $nicescroll_js
 8482: 
 8483: <table style="width: $outerwidth; border: 1px solid none;"$table_id><tr><td style="width: $width;$tdcol">
 8484: <div style="overflow:auto; width:$width; height:$height;"$div_id>
 8485: END
 8486: }
 8487: 
 8488: sub end_scrollbox {
 8489:     return '</div></td></tr></table>';
 8490: }
 8491: 
 8492: sub nicescroll_javascript {
 8493:     my ($id,$cursor,$needjsready,$framecheck,$location) = @_;
 8494:     my %options;
 8495:     if (ref($cursor) eq 'HASH') {
 8496:         %options = %{$cursor};
 8497:     }
 8498:     unless ($options{'railalign'} =~ /^left|right$/) {
 8499:         $options{'railalign'} = 'left';
 8500:     }
 8501:     unless ($options{'cursorcolor'} =~ /^\#\w+$/) {
 8502:         my $function  = &get_users_function();
 8503:         $options{'cursorcolor'} = &designparm($function.'.sidebg',$env{'request.role.domain'});
 8504:         unless ($options{'cursorcolor'} =~ /^\#\w+$/) {
 8505:             $options{'cursorcolor'} = '#00F';
 8506:         }
 8507:     }
 8508:     if ($options{'cursoropacity'} =~ /^[\d.]+$/) {
 8509:         unless ($options{'cursoropacity'} >= 0.0 && $options{'cursoropacity'} <=1.0) {
 8510:             $options{'cursoropacity'}='1.0';
 8511:         }
 8512:     } else {
 8513:         $options{'cursoropacity'}='1.0';
 8514:     }
 8515:     if ($options{'cursorfixedheight'} eq 'none') {
 8516:         delete($options{'cursorfixedheight'});
 8517:     } else {
 8518:         unless ($options{'cursorfixedheight'} =~ /^\d+$/) { $options{'cursorfixedheight'}='50'; }
 8519:     }
 8520:     unless ($options{'railoffset'} =~ /^{[\w\:\d\-,]+}$/) {
 8521:         delete($options{'railoffset'});
 8522:     }
 8523:     my @niceoptions;
 8524:     while (my($key,$value) = each(%options)) {
 8525:         if ($value =~ /^\{.+\}$/) {
 8526:             push(@niceoptions,$key.':'.$value);
 8527:         } else {
 8528:             push(@niceoptions,$key.':"'.$value.'"');
 8529:         }
 8530:     }
 8531:     my $nicescroll_js = '
 8532: $(document).ready(
 8533:       function() {
 8534:           $("#'.$id.'").niceScroll({'.join(',',@niceoptions).'});
 8535:       }
 8536: );
 8537: ';
 8538:     if ($framecheck) {
 8539:         $nicescroll_js .= '
 8540: function expand_div(caller) {
 8541:     if (top === self) {
 8542:         document.getElementById("'.$id.'").style.width = "auto";
 8543:         document.getElementById("'.$id.'").style.height = "auto";
 8544:     } else {
 8545:         try {
 8546:             if (parent.frames) {
 8547:                 if (parent.frames.length > 1) {
 8548:                     var framesrc = parent.frames[1].location.href;
 8549:                     var currsrc = framesrc.replace(/\#.*$/,"");
 8550:                     if ((caller == "search") || (currsrc == "'.$location.'")) {
 8551:                         document.getElementById("'.$id.'").style.width = "auto";
 8552:                         document.getElementById("'.$id.'").style.height = "auto";
 8553:                     }
 8554:                 }
 8555:             }
 8556:         } catch (e) {
 8557:             return;
 8558:         }
 8559:     }
 8560:     return;
 8561: }
 8562: ';
 8563:     }
 8564:     if ($needjsready) {
 8565:         $nicescroll_js = '
 8566: <script type="text/javascript">'."\n".$nicescroll_js."\n</script>\n";
 8567:     } else {
 8568:         $nicescroll_js = &Apache::lonhtmlcommon::scripttag($nicescroll_js);
 8569:     }
 8570:     return $nicescroll_js;
 8571: }
 8572: 
 8573: sub simple_error_page {
 8574:     my ($r,$title,$msg,$args) = @_;
 8575:     if (ref($args) eq 'HASH') {
 8576:         if (!$args->{'no_auto_mt_msg'}) { $msg = &mt($msg); }
 8577:     } else {
 8578:         $msg = &mt($msg);
 8579:     }
 8580: 
 8581:     my $page =
 8582: 	&Apache::loncommon::start_page($title).
 8583: 	'<p class="LC_error">'.$msg.'</p>'.
 8584: 	&Apache::loncommon::end_page();
 8585:     if (ref($r)) {
 8586: 	$r->print($page);
 8587: 	return;
 8588:     }
 8589:     return $page;
 8590: }
 8591: 
 8592: {
 8593:     my @row_count;
 8594: 
 8595:     sub start_data_table_count {
 8596:         unshift(@row_count, 0);
 8597:         return;
 8598:     }
 8599: 
 8600:     sub end_data_table_count {
 8601:         shift(@row_count);
 8602:         return;
 8603:     }
 8604: 
 8605:     sub start_data_table {
 8606: 	my ($add_class,$id) = @_;
 8607: 	my $css_class = (join(' ','LC_data_table',$add_class));
 8608:         my $table_id;
 8609:         if (defined($id)) {
 8610:             $table_id = ' id="'.$id.'"';
 8611:         }
 8612: 	&start_data_table_count();
 8613: 	return '<table class="'.$css_class.'"'.$table_id.'>'."\n";
 8614:     }
 8615: 
 8616:     sub end_data_table {
 8617: 	&end_data_table_count();
 8618: 	return '</table>'."\n";;
 8619:     }
 8620: 
 8621:     sub start_data_table_row {
 8622: 	my ($add_class, $id) = @_;
 8623: 	$row_count[0]++;
 8624: 	my $css_class = ($row_count[0] % 2)?'LC_odd_row':'LC_even_row';
 8625: 	$css_class = (join(' ',$css_class,$add_class)) unless ($add_class eq '');
 8626:         $id = (' id="'.$id.'"') unless ($id eq '');
 8627:         return  '<tr class="'.$css_class.'"'.$id.'>'."\n";
 8628:     }
 8629:     
 8630:     sub continue_data_table_row {
 8631: 	my ($add_class, $id) = @_;
 8632: 	my $css_class = ($row_count[0] % 2)?'LC_odd_row':'LC_even_row';
 8633: 	$css_class = (join(' ',$css_class,$add_class)) unless ($add_class eq '');
 8634:         $id = (' id="'.$id.'"') unless ($id eq '');
 8635:         return  '<tr class="'.$css_class.'"'.$id.'>'."\n";
 8636:     }
 8637: 
 8638:     sub end_data_table_row {
 8639: 	return '</tr>'."\n";;
 8640:     }
 8641: 
 8642:     sub start_data_table_empty_row {
 8643: #	$row_count[0]++;
 8644: 	return  '<tr class="LC_empty_row" >'."\n";;
 8645:     }
 8646: 
 8647:     sub end_data_table_empty_row {
 8648: 	return '</tr>'."\n";;
 8649:     }
 8650: 
 8651:     sub start_data_table_header_row {
 8652: 	return  '<tr class="LC_header_row">'."\n";;
 8653:     }
 8654: 
 8655:     sub end_data_table_header_row {
 8656: 	return '</tr>'."\n";;
 8657:     }
 8658: 
 8659:     sub data_table_caption {
 8660:         my $caption = shift;
 8661:         return "<caption class=\"LC_caption\">$caption</caption>";
 8662:     }
 8663: }
 8664: 
 8665: =pod
 8666: 
 8667: =item * &inhibit_menu_check($arg)
 8668: 
 8669: Checks for a inhibitmenu state and generates output to preserve it
 8670: 
 8671: Inputs:         $arg - can be any of
 8672:                      - undef - in which case the return value is a string 
 8673:                                to add  into arguments list of a uri
 8674:                      - 'input' - in which case the return value is a HTML
 8675:                                  <form> <input> field of type hidden to
 8676:                                  preserve the value
 8677:                      - a url - in which case the return value is the url with
 8678:                                the neccesary cgi args added to preserve the
 8679:                                inhibitmenu state
 8680:                      - a ref to a url - no return value, but the string is
 8681:                                         updated to include the neccessary cgi
 8682:                                         args to preserve the inhibitmenu state
 8683: 
 8684: =cut
 8685: 
 8686: sub inhibit_menu_check {
 8687:     my ($arg) = @_;
 8688:     &get_unprocessed_cgi($ENV{'QUERY_STRING'}, ['inhibitmenu']);
 8689:     if ($arg eq 'input') {
 8690: 	if ($env{'form.inhibitmenu'}) {
 8691: 	    return '<input type="hidden" name="inhibitmenu" value="'.$env{'form.inhibitmenu'}.'" />';
 8692: 	} else {
 8693: 	    return
 8694: 	}
 8695:     }
 8696:     if ($env{'form.inhibitmenu'}) {
 8697: 	if (ref($arg)) {
 8698: 	    $$arg .= '?inhibitmenu='.$env{'form.inhibitmenu'};
 8699: 	} elsif ($arg eq '') {
 8700: 	    $arg .= 'inhibitmenu='.$env{'form.inhibitmenu'};
 8701: 	} else {
 8702: 	    $arg .= '?inhibitmenu='.$env{'form.inhibitmenu'};
 8703: 	}
 8704:     }
 8705:     if (!ref($arg)) {
 8706: 	return $arg;
 8707:     }
 8708: }
 8709: 
 8710: ###############################################
 8711: 
 8712: =pod
 8713: 
 8714: =back
 8715: 
 8716: =head1 User Information Routines
 8717: 
 8718: =over 4
 8719: 
 8720: =item * &get_users_function()
 8721: 
 8722: Used by &bodytag to determine the current users primary role.
 8723: Returns either 'student','coordinator','admin', or 'author'.
 8724: 
 8725: =cut
 8726: 
 8727: ###############################################
 8728: sub get_users_function {
 8729:     my $function = 'norole';
 8730:     if ($env{'request.role'}=~/^(st)/) {
 8731:         $function='student';
 8732:     }
 8733:     if ($env{'request.role'}=~/^(cc|co|in|ta|ep)/) {
 8734:         $function='coordinator';
 8735:     }
 8736:     if ($env{'request.role'}=~/^(su|dc|ad|li)/) {
 8737:         $function='admin';
 8738:     }
 8739:     if (($env{'request.role'}=~/^(au|ca|aa)/) ||
 8740:         ($ENV{'REQUEST_URI'}=~ m{/^(/priv)})) {
 8741:         $function='author';
 8742:     }
 8743:     return $function;
 8744: }
 8745: 
 8746: ###############################################
 8747: 
 8748: =pod
 8749: 
 8750: =item * &show_course()
 8751: 
 8752: Used by lonmenu.pm and lonroles.pm to determine whether to use the word
 8753: 'Courses' or 'Roles' in inline navigation and on screen displaying user's roles.
 8754: 
 8755: Inputs:
 8756: None
 8757: 
 8758: Outputs:
 8759: Scalar: 1 if 'Course' to be used, 0 otherwise.
 8760: 
 8761: =cut
 8762: 
 8763: ###############################################
 8764: sub show_course {
 8765:     my $course = !$env{'user.adv'};
 8766:     if (!$env{'user.adv'}) {
 8767:         foreach my $env (keys(%env)) {
 8768:             next if ($env !~ m/^user\.priv\./);
 8769:             if ($env !~ m/^user\.priv\.(?:st|cm)/) {
 8770:                 $course = 0;
 8771:                 last;
 8772:             }
 8773:         }
 8774:     }
 8775:     return $course;
 8776: }
 8777: 
 8778: ###############################################
 8779: 
 8780: =pod
 8781: 
 8782: =item * &check_user_status()
 8783: 
 8784: Determines current status of supplied role for a
 8785: specific user. Roles can be active, previous or future.
 8786: 
 8787: Inputs: 
 8788: user's domain, user's username, course's domain,
 8789: course's number, optional section ID.
 8790: 
 8791: Outputs:
 8792: role status: active, previous or future. 
 8793: 
 8794: =cut
 8795: 
 8796: sub check_user_status {
 8797:     my ($udom,$uname,$cdom,$crs,$role,$sec) = @_;
 8798:     my %userinfo = &Apache::lonnet::dump('roles',$udom,$uname);
 8799:     my @uroles = keys(%userinfo);
 8800:     my $srchstr;
 8801:     my $active_chk = 'none';
 8802:     my $now = time;
 8803:     if (@uroles > 0) {
 8804:         if (($role eq 'cc') || ($role eq 'co') || ($sec eq '') || (!defined($sec))) {
 8805:             $srchstr = '/'.$cdom.'/'.$crs.'_'.$role;
 8806:         } else {
 8807:             $srchstr = '/'.$cdom.'/'.$crs.'/'.$sec.'_'.$role;
 8808:         }
 8809:         if (grep/^\Q$srchstr\E$/,@uroles) {
 8810:             my $role_end = 0;
 8811:             my $role_start = 0;
 8812:             $active_chk = 'active';
 8813:             if ($userinfo{$srchstr} =~ m/^\Q$role\E_(\d+)/) {
 8814:                 $role_end = $1;
 8815:                 if ($userinfo{$srchstr} =~ m/^\Q$role\E_\Q$role_end\E_(\d+)$/) {
 8816:                     $role_start = $1;
 8817:                 }
 8818:             }
 8819:             if ($role_start > 0) {
 8820:                 if ($now < $role_start) {
 8821:                     $active_chk = 'future';
 8822:                 }
 8823:             }
 8824:             if ($role_end > 0) {
 8825:                 if ($now > $role_end) {
 8826:                     $active_chk = 'previous';
 8827:                 }
 8828:             }
 8829:         }
 8830:     }
 8831:     return $active_chk;
 8832: }
 8833: 
 8834: ###############################################
 8835: 
 8836: =pod
 8837: 
 8838: =item * &get_sections()
 8839: 
 8840: Determines all the sections for a course including
 8841: sections with students and sections containing other roles.
 8842: Incoming parameters: 
 8843: 
 8844: 1. domain
 8845: 2. course number 
 8846: 3. reference to array containing roles for which sections should 
 8847: be gathered (optional).
 8848: 4. reference to array containing status types for which sections 
 8849: should be gathered (optional).
 8850: 
 8851: If the third argument is undefined, sections are gathered for any role. 
 8852: If the fourth argument is undefined, sections are gathered for any status.
 8853: Permissible values are 'active' or 'future' or 'previous'.
 8854:  
 8855: Returns section hash (keys are section IDs, values are
 8856: number of users in each section), subject to the
 8857: optional roles filter, optional status filter 
 8858: 
 8859: =cut
 8860: 
 8861: ###############################################
 8862: sub get_sections {
 8863:     my ($cdom,$cnum,$possible_roles,$possible_status) = @_;
 8864:     if (!defined($cdom) || !defined($cnum)) {
 8865:         my $cid =  $env{'request.course.id'};
 8866: 
 8867: 	return if (!defined($cid));
 8868: 
 8869:         $cdom = $env{'course.'.$cid.'.domain'};
 8870:         $cnum = $env{'course.'.$cid.'.num'};
 8871:     }
 8872: 
 8873:     my %sectioncount;
 8874:     my $now = time;
 8875: 
 8876:     my $check_students = 1;
 8877:     my $only_students = 0;
 8878:     if (ref($possible_roles) eq 'ARRAY') {
 8879:         if (grep(/^st$/,@{$possible_roles})) {
 8880:             if (@{$possible_roles} == 1) {
 8881:                 $only_students = 1;
 8882:             }
 8883:         } else {
 8884:             $check_students = 0;
 8885:         }
 8886:     }
 8887: 
 8888:     if ($check_students) {
 8889: 	my ($classlist) = &Apache::loncoursedata::get_classlist($cdom,$cnum);
 8890: 	my $sec_index = &Apache::loncoursedata::CL_SECTION();
 8891: 	my $status_index = &Apache::loncoursedata::CL_STATUS();
 8892:         my $start_index = &Apache::loncoursedata::CL_START();
 8893:         my $end_index = &Apache::loncoursedata::CL_END();
 8894:         my $status;
 8895: 	while (my ($student,$data) = each(%$classlist)) {
 8896: 	    my ($section,$stu_status,$start,$end) = ($data->[$sec_index],
 8897: 				                     $data->[$status_index],
 8898:                                                      $data->[$start_index],
 8899:                                                      $data->[$end_index]);
 8900:             if ($stu_status eq 'Active') {
 8901:                 $status = 'active';
 8902:             } elsif ($end < $now) {
 8903:                 $status = 'previous';
 8904:             } elsif ($start > $now) {
 8905:                 $status = 'future';
 8906:             } 
 8907: 	    if ($section ne '-1' && $section !~ /^\s*$/) {
 8908:                 if ((!defined($possible_status)) || (($status ne '') && 
 8909:                     (grep/^\Q$status\E$/,@{$possible_status}))) { 
 8910: 		    $sectioncount{$section}++;
 8911:                 }
 8912: 	    }
 8913: 	}
 8914:     }
 8915:     if ($only_students) {
 8916:         return %sectioncount;
 8917:     }
 8918:     my %courseroles = &Apache::lonnet::dump('nohist_userroles',$cdom,$cnum);
 8919:     foreach my $user (sort(keys(%courseroles))) {
 8920: 	if ($user !~ /^(\w{2})/) { next; }
 8921: 	my ($role) = ($user =~ /^(\w{2})/);
 8922: 	if ($possible_roles && !(grep(/^$role$/,@$possible_roles))) { next; }
 8923: 	my ($section,$status);
 8924: 	if ($role eq 'cr' &&
 8925: 	    $user =~ m-^$role/[^/]*/[^/]*/[^/]*:[^:]*:[^:]*:(\w+)-) {
 8926: 	    $section=$1;
 8927: 	}
 8928: 	if ($user =~ /^$role:[^:]*:[^:]*:(\w+)/) { $section=$1; }
 8929: 	if (!defined($section) || $section eq '-1') { next; }
 8930:         my ($end,$start) = ($courseroles{$user} =~ /^([^:]*):([^:]*)$/);
 8931:         if ($end == -1 && $start == -1) {
 8932:             next; #deleted role
 8933:         }
 8934:         if (!defined($possible_status)) { 
 8935:             $sectioncount{$section}++;
 8936:         } else {
 8937:             if ((!$end || $end >= $now) && (!$start || $start <= $now)) {
 8938:                 $status = 'active';
 8939:             } elsif ($end < $now) {
 8940:                 $status = 'future';
 8941:             } elsif ($start > $now) {
 8942:                 $status = 'previous';
 8943:             }
 8944:             if (($status ne '') && (grep/^\Q$status\E$/,@{$possible_status})) {
 8945:                 $sectioncount{$section}++;
 8946:             }
 8947:         }
 8948:     }
 8949:     return %sectioncount;
 8950: }
 8951: 
 8952: ###############################################
 8953: 
 8954: =pod
 8955: 
 8956: =item * &get_course_users()
 8957: 
 8958: Retrieves usernames:domains for users in the specified course
 8959: with specific role(s), and access status. 
 8960: 
 8961: Incoming parameters:
 8962: 1. course domain
 8963: 2. course number
 8964: 3. access status: users must have - either active, 
 8965: previous, future, or all.
 8966: 4. reference to array of permissible roles
 8967: 5. reference to array of section restrictions (optional)
 8968: 6. reference to results object (hash of hashes).
 8969: 7. reference to optional userdata hash
 8970: 8. reference to optional statushash
 8971: 9. flag if privileged users (except those set to unhide in
 8972:    course settings) should be excluded    
 8973: Keys of top level results hash are roles.
 8974: Keys of inner hashes are username:domain, with 
 8975: values set to access type.
 8976: Optional userdata hash returns an array with arguments in the 
 8977: same order as loncoursedata::get_classlist() for student data.
 8978: 
 8979: Optional statushash returns
 8980: 
 8981: Entries for end, start, section and status are blank because
 8982: of the possibility of multiple values for non-student roles.
 8983: 
 8984: =cut
 8985: 
 8986: ###############################################
 8987: 
 8988: sub get_course_users {
 8989:     my ($cdom,$cnum,$types,$roles,$sections,$users,$userdata,$statushash,$hidepriv) = @_;
 8990:     my %idx = ();
 8991:     my %seclists;
 8992: 
 8993:     $idx{udom} = &Apache::loncoursedata::CL_SDOM();
 8994:     $idx{uname} =  &Apache::loncoursedata::CL_SNAME();
 8995:     $idx{end} = &Apache::loncoursedata::CL_END();
 8996:     $idx{start} = &Apache::loncoursedata::CL_START();
 8997:     $idx{id} = &Apache::loncoursedata::CL_ID();
 8998:     $idx{section} = &Apache::loncoursedata::CL_SECTION();
 8999:     $idx{fullname} = &Apache::loncoursedata::CL_FULLNAME();
 9000:     $idx{status} = &Apache::loncoursedata::CL_STATUS();
 9001: 
 9002:     if (grep(/^st$/,@{$roles})) {
 9003:         my ($classlist,$keylist)=&Apache::loncoursedata::get_classlist($cdom,$cnum);
 9004:         my $now = time;
 9005:         foreach my $student (keys(%{$classlist})) {
 9006:             my $match = 0;
 9007:             my $secmatch = 0;
 9008:             my $section = $$classlist{$student}[$idx{section}];
 9009:             my $status = $$classlist{$student}[$idx{status}];
 9010:             if ($section eq '') {
 9011:                 $section = 'none';
 9012:             }
 9013:             if ((ref($sections) eq 'ARRAY') && (@{$sections} > 0)) {
 9014:                 if (grep(/^all$/,@{$sections})) {
 9015:                     $secmatch = 1;
 9016:                 } elsif ($$classlist{$student}[$idx{section}] eq '') {
 9017:                     if (grep(/^none$/,@{$sections})) {
 9018:                         $secmatch = 1;
 9019:                     }
 9020:                 } else {  
 9021: 		    if (grep(/^\Q$section\E$/,@{$sections})) {
 9022: 		        $secmatch = 1;
 9023:                     }
 9024: 		}
 9025:                 if (!$secmatch) {
 9026:                     next;
 9027:                 }
 9028:             }
 9029:             if (defined($$types{'active'})) {
 9030:                 if ($$classlist{$student}[$idx{status}] eq 'Active') {
 9031:                     push(@{$$users{st}{$student}},'active');
 9032:                     $match = 1;
 9033:                 }
 9034:             }
 9035:             if (defined($$types{'previous'})) {
 9036:                 if ($$classlist{$student}[$idx{status}] eq 'Expired') {
 9037:                     push(@{$$users{st}{$student}},'previous');
 9038:                     $match = 1;
 9039:                 }
 9040:             }
 9041:             if (defined($$types{'future'})) {
 9042:                 if ($$classlist{$student}[$idx{status}] eq 'Future') {
 9043:                     push(@{$$users{st}{$student}},'future');
 9044:                     $match = 1;
 9045:                 }
 9046:             }
 9047:             if ($match) {
 9048:                 push(@{$seclists{$student}},$section);
 9049:                 if (ref($userdata) eq 'HASH') {
 9050:                     $$userdata{$student} = $$classlist{$student};
 9051:                 }
 9052:                 if (ref($statushash) eq 'HASH') {
 9053:                     $statushash->{$student}{'st'}{$section} = $status;
 9054:                 }
 9055:             }
 9056:         }
 9057:     }
 9058:     if ((@{$roles} > 1) || ((@{$roles} == 1) && ($$roles[0] ne "st"))) {
 9059:         my %coursepersonnel = &Apache::lonnet::dump('nohist_userroles',$cdom,$cnum);
 9060:         my $now = time;
 9061:         my %displaystatus = ( previous => 'Expired',
 9062:                               active   => 'Active',
 9063:                               future   => 'Future',
 9064:                             );
 9065:         my (%nothide,@possdoms);
 9066:         if ($hidepriv) {
 9067:             my %coursehash=&Apache::lonnet::coursedescription($cdom.'_'.$cnum);
 9068:             foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
 9069:                 if ($user !~ /:/) {
 9070:                     $nothide{join(':',split(/[\@]/,$user))}=1;
 9071:                 } else {
 9072:                     $nothide{$user} = 1;
 9073:                 }
 9074:             }
 9075:             my @possdoms = ($cdom);
 9076:             if ($coursehash{'checkforpriv'}) {
 9077:                 push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
 9078:             }
 9079:         }
 9080:         foreach my $person (sort(keys(%coursepersonnel))) {
 9081:             my $match = 0;
 9082:             my $secmatch = 0;
 9083:             my $status;
 9084:             my ($role,$user,$usec) = ($person =~ /^([^:]*):([^:]+:[^:]+):([^:]*)/);
 9085:             $user =~ s/:$//;
 9086:             my ($end,$start) = split(/:/,$coursepersonnel{$person});
 9087:             if ($end == -1 || $start == -1) {
 9088:                 next;
 9089:             }
 9090:             if (($role) && ((grep(/^\Q$role\E$/,@{$roles})) ||
 9091:                 (grep(/^cr$/,@{$roles}) && $role =~ /^cr\//))) {
 9092:                 my ($uname,$udom) = split(/:/,$user);
 9093:                 if ((ref($sections) eq 'ARRAY') && (@{$sections} > 0)) {
 9094:                     if (grep(/^all$/,@{$sections})) {
 9095:                         $secmatch = 1;
 9096:                     } elsif ($usec eq '') {
 9097:                         if (grep(/^none$/,@{$sections})) {
 9098:                             $secmatch = 1;
 9099:                         }
 9100:                     } else {
 9101:                         if (grep(/^\Q$usec\E$/,@{$sections})) {
 9102:                             $secmatch = 1;
 9103:                         }
 9104:                     }
 9105:                     if (!$secmatch) {
 9106:                         next;
 9107:                     }
 9108:                 }
 9109:                 if ($usec eq '') {
 9110:                     $usec = 'none';
 9111:                 }
 9112:                 if ($uname ne '' && $udom ne '') {
 9113:                     if ($hidepriv) {
 9114:                         if ((&Apache::lonnet::privileged($uname,$udom,\@possdoms)) &&
 9115:                             (!$nothide{$uname.':'.$udom})) {
 9116:                             next;
 9117:                         }
 9118:                     }
 9119:                     if ($end > 0 && $end < $now) {
 9120:                         $status = 'previous';
 9121:                     } elsif ($start > $now) {
 9122:                         $status = 'future';
 9123:                     } else {
 9124:                         $status = 'active';
 9125:                     }
 9126:                     foreach my $type (keys(%{$types})) { 
 9127:                         if ($status eq $type) {
 9128:                             if (!grep(/^\Q$type\E$/,@{$$users{$role}{$user}})) {
 9129:                                 push(@{$$users{$role}{$user}},$type);
 9130:                             }
 9131:                             $match = 1;
 9132:                         }
 9133:                     }
 9134:                     if (($match) && (ref($userdata) eq 'HASH')) {
 9135:                         if (!exists($$userdata{$uname.':'.$udom})) {
 9136: 			    &get_user_info($udom,$uname,\%idx,$userdata);
 9137:                         }
 9138:                         if (!grep(/^\Q$usec\E$/,@{$seclists{$uname.':'.$udom}})) {
 9139:                             push(@{$seclists{$uname.':'.$udom}},$usec);
 9140:                         }
 9141:                         if (ref($statushash) eq 'HASH') {
 9142:                             $statushash->{$uname.':'.$udom}{$role}{$usec} = $displaystatus{$status};
 9143:                         }
 9144:                     }
 9145:                 }
 9146:             }
 9147:         }
 9148:         if (grep(/^ow$/,@{$roles})) {
 9149:             if ((defined($cdom)) && (defined($cnum))) {
 9150:                 my %csettings = &Apache::lonnet::get('environment',['internal.courseowner'],$cdom,$cnum);
 9151:                 if ( defined($csettings{'internal.courseowner'}) ) {
 9152:                     my $owner = $csettings{'internal.courseowner'};
 9153:                     next if ($owner eq '');
 9154:                     my ($ownername,$ownerdom);
 9155:                     if ($owner =~ /^([^:]+):([^:]+)$/) {
 9156:                         $ownername = $1;
 9157:                         $ownerdom = $2;
 9158:                     } else {
 9159:                         $ownername = $owner;
 9160:                         $ownerdom = $cdom;
 9161:                         $owner = $ownername.':'.$ownerdom;
 9162:                     }
 9163:                     @{$$users{'ow'}{$owner}} = 'any';
 9164:                     if (defined($userdata) && 
 9165: 			!exists($$userdata{$owner})) {
 9166: 			&get_user_info($ownerdom,$ownername,\%idx,$userdata);
 9167:                         if (!grep(/^none$/,@{$seclists{$owner}})) {
 9168:                             push(@{$seclists{$owner}},'none');
 9169:                         }
 9170:                         if (ref($statushash) eq 'HASH') {
 9171:                             $statushash->{$owner}{'ow'}{'none'} = 'Any';
 9172:                         }
 9173: 		    }
 9174:                 }
 9175:             }
 9176:         }
 9177:         foreach my $user (keys(%seclists)) {
 9178:             @{$seclists{$user}} = (sort {$a <=> $b} @{$seclists{$user}});
 9179:             $$userdata{$user}[$idx{section}] = join(',',@{$seclists{$user}});
 9180:         }
 9181:     }
 9182:     return;
 9183: }
 9184: 
 9185: sub get_user_info {
 9186:     my ($udom,$uname,$idx,$userdata) = @_;
 9187:     $$userdata{$uname.':'.$udom}[$$idx{fullname}] = 
 9188: 	&plainname($uname,$udom,'lastname');
 9189:     $$userdata{$uname.':'.$udom}[$$idx{uname}] = $uname;
 9190:     $$userdata{$uname.':'.$udom}[$$idx{udom}] = $udom;
 9191:     my %idhash =  &Apache::lonnet::idrget($udom,($uname));
 9192:     $$userdata{$uname.':'.$udom}[$$idx{id}] = $idhash{$uname}; 
 9193:     return;
 9194: }
 9195: 
 9196: ###############################################
 9197: 
 9198: =pod
 9199: 
 9200: =item * &get_user_quota()
 9201: 
 9202: Retrieves quota assigned for storage of user files.
 9203: Default is to report quota for portfolio files.
 9204: 
 9205: Incoming parameters:
 9206: 1. user's username
 9207: 2. user's domain
 9208: 3. quota name - portfolio, author, or course
 9209:    (if no quota name provided, defaults to portfolio).
 9210: 4. crstype - official, unofficial, textbook or community, if quota name is
 9211:    course
 9212: 
 9213: Returns:
 9214: 1. Disk quota (in MB) assigned to student.
 9215: 2. (Optional) Type of setting: custom or default
 9216:    (individually assigned or default for user's 
 9217:    institutional status).
 9218: 3. (Optional) - User's institutional status (e.g., faculty, staff
 9219:    or student - types as defined in localenroll::inst_usertypes 
 9220:    for user's domain, which determines default quota for user.
 9221: 4. (Optional) - Default quota which would apply to the user.
 9222: 
 9223: If a value has been stored in the user's environment, 
 9224: it will return that, otherwise it returns the maximal default
 9225: defined for the user's institutional status(es) in the domain.
 9226: 
 9227: =cut
 9228: 
 9229: ###############################################
 9230: 
 9231: 
 9232: sub get_user_quota {
 9233:     my ($uname,$udom,$quotaname,$crstype) = @_;
 9234:     my ($quota,$quotatype,$settingstatus,$defquota);
 9235:     if (!defined($udom)) {
 9236:         $udom = $env{'user.domain'};
 9237:     }
 9238:     if (!defined($uname)) {
 9239:         $uname = $env{'user.name'};
 9240:     }
 9241:     if (($udom eq '' || $uname eq '') ||
 9242:         ($udom eq 'public') && ($uname eq 'public')) {
 9243:         $quota = 0;
 9244:         $quotatype = 'default';
 9245:         $defquota = 0; 
 9246:     } else {
 9247:         my $inststatus;
 9248:         if ($quotaname eq 'course') {
 9249:             if (($env{'course.'.$udom.'_'.$uname.'.num'} eq $uname) &&
 9250:                 ($env{'course.'.$udom.'_'.$uname.'.domain'} eq $udom)) {
 9251:                 $quota = $env{'course.'.$udom.'_'.$uname.'.internal.uploadquota'};
 9252:             } else {
 9253:                 my %cenv = &Apache::lonnet::coursedescription("$udom/$uname");
 9254:                 $quota = $cenv{'internal.uploadquota'};
 9255:             }
 9256:         } else {
 9257:             if ($udom eq $env{'user.domain'} && $uname eq $env{'user.name'}) {
 9258:                 if ($quotaname eq 'author') {
 9259:                     $quota = $env{'environment.authorquota'};
 9260:                 } else {
 9261:                     $quota = $env{'environment.portfolioquota'};
 9262:                 }
 9263:                 $inststatus = $env{'environment.inststatus'};
 9264:             } else {
 9265:                 my %userenv = 
 9266:                     &Apache::lonnet::get('environment',['portfolioquota',
 9267:                                          'authorquota','inststatus'],$udom,$uname);
 9268:                 my ($tmp) = keys(%userenv);
 9269:                 if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
 9270:                     if ($quotaname eq 'author') {
 9271:                         $quota = $userenv{'authorquota'};
 9272:                     } else {
 9273:                         $quota = $userenv{'portfolioquota'};
 9274:                     }
 9275:                     $inststatus = $userenv{'inststatus'};
 9276:                 } else {
 9277:                     undef(%userenv);
 9278:                 }
 9279:             }
 9280:         }
 9281:         if ($quota eq '' || wantarray) {
 9282:             if ($quotaname eq 'course') {
 9283:                 my %domdefs = &Apache::lonnet::get_domain_defaults($udom);
 9284:                 if (($crstype eq 'official') || ($crstype eq 'unofficial') ||
 9285:                     ($crstype eq 'community') || ($crstype eq 'textbook')) {
 9286:                     $defquota = $domdefs{$crstype.'quota'};
 9287:                 }
 9288:                 if ($defquota eq '') {
 9289:                     $defquota = 500;
 9290:                 }
 9291:             } else {
 9292:                 ($defquota,$settingstatus) = &default_quota($udom,$inststatus,$quotaname);
 9293:             }
 9294:             if ($quota eq '') {
 9295:                 $quota = $defquota;
 9296:                 $quotatype = 'default';
 9297:             } else {
 9298:                 $quotatype = 'custom';
 9299:             }
 9300:         }
 9301:     }
 9302:     if (wantarray) {
 9303:         return ($quota,$quotatype,$settingstatus,$defquota);
 9304:     } else {
 9305:         return $quota;
 9306:     }
 9307: }
 9308: 
 9309: ###############################################
 9310: 
 9311: =pod
 9312: 
 9313: =item * &default_quota()
 9314: 
 9315: Retrieves default quota assigned for storage of user portfolio files,
 9316: given an (optional) user's institutional status.
 9317: 
 9318: Incoming parameters:
 9319: 
 9320: 1. domain
 9321: 2. (Optional) institutional status(es).  This is a : separated list of 
 9322:    status types (e.g., faculty, staff, student etc.)
 9323:    which apply to the user for whom the default is being retrieved.
 9324:    If the institutional status string in undefined, the domain
 9325:    default quota will be returned.
 9326: 3.  quota name - portfolio, author, or course
 9327:    (if no quota name provided, defaults to portfolio).
 9328: 
 9329: Returns:
 9330: 
 9331: 1. Default disk quota (in MB) for user portfolios in the domain.
 9332: 2. (Optional) institutional type which determined the value of the
 9333:    default quota.
 9334: 
 9335: If a value has been stored in the domain's configuration db,
 9336: it will return that, otherwise it returns 20 (for backwards 
 9337: compatibility with domains which have not set up a configuration
 9338: db file; the original statically defined portfolio quota was 20 MB). 
 9339: 
 9340: If the user's status includes multiple types (e.g., staff and student),
 9341: the largest default quota which applies to the user determines the
 9342: default quota returned.
 9343: 
 9344: =cut
 9345: 
 9346: ###############################################
 9347: 
 9348: 
 9349: sub default_quota {
 9350:     my ($udom,$inststatus,$quotaname) = @_;
 9351:     my ($defquota,$settingstatus);
 9352:     my %quotahash = &Apache::lonnet::get_dom('configuration',
 9353:                                             ['quotas'],$udom);
 9354:     my $key = 'defaultquota';
 9355:     if ($quotaname eq 'author') {
 9356:         $key = 'authorquota';
 9357:     }
 9358:     if (ref($quotahash{'quotas'}) eq 'HASH') {
 9359:         if ($inststatus ne '') {
 9360:             my @statuses = map { &unescape($_); } split(/:/,$inststatus);
 9361:             foreach my $item (@statuses) {
 9362:                 if (ref($quotahash{'quotas'}{$key}) eq 'HASH') {
 9363:                     if ($quotahash{'quotas'}{$key}{$item} ne '') {
 9364:                         if ($defquota eq '') {
 9365:                             $defquota = $quotahash{'quotas'}{$key}{$item};
 9366:                             $settingstatus = $item;
 9367:                         } elsif ($quotahash{'quotas'}{$key}{$item} > $defquota) {
 9368:                             $defquota = $quotahash{'quotas'}{$key}{$item};
 9369:                             $settingstatus = $item;
 9370:                         }
 9371:                     }
 9372:                 } elsif ($key eq 'defaultquota') {
 9373:                     if ($quotahash{'quotas'}{$item} ne '') {
 9374:                         if ($defquota eq '') {
 9375:                             $defquota = $quotahash{'quotas'}{$item};
 9376:                             $settingstatus = $item;
 9377:                         } elsif ($quotahash{'quotas'}{$item} > $defquota) {
 9378:                             $defquota = $quotahash{'quotas'}{$item};
 9379:                             $settingstatus = $item;
 9380:                         }
 9381:                     }
 9382:                 }
 9383:             }
 9384:         }
 9385:         if ($defquota eq '') {
 9386:             if (ref($quotahash{'quotas'}{$key}) eq 'HASH') {
 9387:                 $defquota = $quotahash{'quotas'}{$key}{'default'};
 9388:             } elsif ($key eq 'defaultquota') {
 9389:                 $defquota = $quotahash{'quotas'}{'default'};
 9390:             }
 9391:             $settingstatus = 'default';
 9392:             if ($defquota eq '') {
 9393:                 if ($quotaname eq 'author') {
 9394:                     $defquota = 500;
 9395:                 }
 9396:             }
 9397:         }
 9398:     } else {
 9399:         $settingstatus = 'default';
 9400:         if ($quotaname eq 'author') {
 9401:             $defquota = 500;
 9402:         } else {
 9403:             $defquota = 20;
 9404:         }
 9405:     }
 9406:     if (wantarray) {
 9407:         return ($defquota,$settingstatus);
 9408:     } else {
 9409:         return $defquota;
 9410:     }
 9411: }
 9412: 
 9413: ###############################################
 9414: 
 9415: =pod
 9416: 
 9417: =item * &excess_filesize_warning()
 9418: 
 9419: Returns warning message if upload of file to authoring space, or copying
 9420: of existing file within authoring space will cause quota for the authoring
 9421: space to be exceeded.
 9422: 
 9423: Same, if upload of a file directly to a course/community via Course Editor
 9424: will cause quota for uploaded content for the course to be exceeded.
 9425: 
 9426: Inputs: 7 
 9427: 1. username or coursenum
 9428: 2. domain
 9429: 3. context ('author' or 'course')
 9430: 4. filename of file for which action is being requested
 9431: 5. filesize (kB) of file
 9432: 6. action being taken: copy or upload.
 9433: 7. quotatype (in course context -- official, unofficial, community or textbook).
 9434: 
 9435: Returns: 1 scalar: HTML to display containing warning if quota would be exceeded,
 9436:          otherwise return null.
 9437: 
 9438: =back
 9439: 
 9440: =cut
 9441: 
 9442: sub excess_filesize_warning {
 9443:     my ($uname,$udom,$context,$filename,$filesize,$action,$quotatype) = @_;
 9444:     my $current_disk_usage = 0;
 9445:     my $disk_quota = &get_user_quota($uname,$udom,$context,$quotatype); #expressed in MB
 9446:     if ($context eq 'author') {
 9447:         my $authorspace = $Apache::lonnet::perlvar{'lonDocRoot'}."/priv/$udom/$uname";
 9448:         $current_disk_usage = &Apache::lonnet::diskusage($udom,$uname,$authorspace);
 9449:     } else {
 9450:         foreach my $subdir ('docs','supplemental') {
 9451:             $current_disk_usage += &Apache::lonnet::diskusage($udom,$uname,"userfiles/$subdir",1);
 9452:         }
 9453:     }
 9454:     $disk_quota = int($disk_quota * 1000);
 9455:     if (($current_disk_usage + $filesize) > $disk_quota) {
 9456:         return '<p class="LC_warning">'.
 9457:                 &mt("Unable to $action [_1]. (size = [_2] kilobytes). Disk quota will be exceeded.",
 9458:                     '<span class="LC_filename">'.$filename.'</span>',$filesize).'</p>'.
 9459:                '<p>'.&mt('Disk quota is [_1] kilobytes. Your current disk usage is [_2] kilobytes.',
 9460:                             $disk_quota,$current_disk_usage).
 9461:                '</p>';
 9462:     }
 9463:     return;
 9464: }
 9465: 
 9466: ###############################################
 9467: 
 9468: 
 9469: sub get_secgrprole_info {
 9470:     my ($cdom,$cnum,$needroles,$type)  = @_;
 9471:     my %sections_count = &get_sections($cdom,$cnum);
 9472:     my @sections =  (sort {$a <=> $b} keys(%sections_count));
 9473:     my %curr_groups = &Apache::longroup::coursegroups($cdom,$cnum);
 9474:     my @groups = sort(keys(%curr_groups));
 9475:     my $allroles = [];
 9476:     my $rolehash;
 9477:     my $accesshash = {
 9478:                      active => 'Currently has access',
 9479:                      future => 'Will have future access',
 9480:                      previous => 'Previously had access',
 9481:                   };
 9482:     if ($needroles) {
 9483:         $rolehash = {'all' => 'all'};
 9484:         my %user_roles = &Apache::lonnet::dump('nohist_userroles',$cdom,$cnum);
 9485: 	if (&Apache::lonnet::error(%user_roles)) {
 9486: 	    undef(%user_roles);
 9487: 	}
 9488:         foreach my $item (keys(%user_roles)) {
 9489:             my ($role)=split(/\:/,$item,2);
 9490:             if ($role eq 'cr') { next; }
 9491:             if ($role =~ /^cr/) {
 9492:                 $$rolehash{$role} = (split('/',$role))[3];
 9493:             } else {
 9494:                 $$rolehash{$role} = &Apache::lonnet::plaintext($role,$type);
 9495:             }
 9496:         }
 9497:         foreach my $key (sort(keys(%{$rolehash}))) {
 9498:             push(@{$allroles},$key);
 9499:         }
 9500:         push (@{$allroles},'st');
 9501:         $$rolehash{'st'} = &Apache::lonnet::plaintext('st',$type);
 9502:     }
 9503:     return (\@sections,\@groups,$allroles,$rolehash,$accesshash);
 9504: }
 9505: 
 9506: sub user_picker {
 9507:     my ($dom,$srch,$forcenewuser,$caller,$cancreate,$usertype,$context) = @_;
 9508:     my $currdom = $dom;
 9509:     my @alldoms = &Apache::lonnet::all_domains();
 9510:     if (@alldoms == 1) {
 9511:         my %domsrch = &Apache::lonnet::get_dom('configuration',
 9512:                                                ['directorysrch'],$alldoms[0]);
 9513:         my $domdesc = &Apache::lonnet::domain($alldoms[0],'description');
 9514:         my $showdom = $domdesc;
 9515:         if ($showdom eq '') {
 9516:             $showdom = $dom;
 9517:         }
 9518:         if (ref($domsrch{'directorysrch'}) eq 'HASH') {
 9519:             if ((!$domsrch{'directorysrch'}{'available'}) &&
 9520:                 ($domsrch{'directorysrch'}{'lcavailable'} eq '0')) {
 9521:                 return (&mt('LON-CAPA directory search is not available in domain: [_1]',$showdom),0);
 9522:             }
 9523:         }
 9524:     }
 9525:     my %curr_selected = (
 9526:                         srchin => 'dom',
 9527:                         srchby => 'lastname',
 9528:                       );
 9529:     my $srchterm;
 9530:     if ((ref($srch) eq 'HASH') && ($env{'form.origform'} ne 'crtusername')) {
 9531:         if ($srch->{'srchby'} ne '') {
 9532:             $curr_selected{'srchby'} = $srch->{'srchby'};
 9533:         }
 9534:         if ($srch->{'srchin'} ne '') {
 9535:             $curr_selected{'srchin'} = $srch->{'srchin'};
 9536:         }
 9537:         if ($srch->{'srchtype'} ne '') {
 9538:             $curr_selected{'srchtype'} = $srch->{'srchtype'};
 9539:         }
 9540:         if ($srch->{'srchdomain'} ne '') {
 9541:             $currdom = $srch->{'srchdomain'};
 9542:         }
 9543:         $srchterm = $srch->{'srchterm'};
 9544:     }
 9545:     my %html_lt=&Apache::lonlocal::texthash(
 9546:                     'usr'       => 'Search criteria',
 9547:                     'doma'      => 'Domain/institution to search',
 9548:                     'uname'     => 'username',
 9549:                     'lastname'  => 'last name',
 9550:                     'lastfirst' => 'last name, first name',
 9551:                     'crs'       => 'in this course',
 9552:                     'dom'       => 'in selected LON-CAPA domain', 
 9553:                     'alc'       => 'all LON-CAPA',
 9554:                     'instd'     => 'in institutional directory for selected domain',
 9555:                     'exact'     => 'is',
 9556:                     'contains'  => 'contains',
 9557:                     'begins'    => 'begins with',
 9558:                                        );
 9559:     my %js_lt=&Apache::lonlocal::texthash(
 9560:                     'youm'      => "You must include some text to search for.",
 9561:                     'thte'      => "The text you are searching for must contain at least two characters when using a 'begins' type search.",
 9562:                     'thet'      => "The text you are searching for must contain at least three characters when using a 'contains' type search.",
 9563:                     'yomc'      => "You must choose a domain when using an institutional directory search.",
 9564:                     'ymcd'      => "You must choose a domain when using a domain search.",
 9565:                     'whus'      => "When using searching by last,first you must include a comma as separator between last name and first name.",
 9566:                     'whse'      => "When searching by last,first you must include at least one character in the first name.",
 9567:                      'thfo'     => "The following need to be corrected before the search can be run:",
 9568:                                        );
 9569:     &html_escape(\%html_lt);
 9570:     &js_escape(\%js_lt);
 9571:     my $domform = &select_dom_form($currdom,'srchdomain',1,1);
 9572:     my $srchinsel = ' <select name="srchin">';
 9573: 
 9574:     my @srchins = ('crs','dom','alc','instd');
 9575: 
 9576:     foreach my $option (@srchins) {
 9577:         # FIXME 'alc' option unavailable until 
 9578:         #       loncreateuser::print_user_query_page()
 9579:         #       has been completed.
 9580:         next if ($option eq 'alc');
 9581:         next if (($option eq 'crs') && ($env{'form.form'} eq 'requestcrs'));  
 9582:         next if ($option eq 'crs' && !$env{'request.course.id'});
 9583:         if ($curr_selected{'srchin'} eq $option) {
 9584:             $srchinsel .= ' 
 9585:    <option value="'.$option.'" selected="selected">'.$html_lt{$option}.'</option>';
 9586:         } else {
 9587:             $srchinsel .= '
 9588:    <option value="'.$option.'">'.$html_lt{$option}.'</option>';
 9589:         }
 9590:     }
 9591:     $srchinsel .= "\n  </select>\n";
 9592: 
 9593:     my $srchbysel =  ' <select name="srchby">';
 9594:     foreach my $option ('lastname','lastfirst','uname') {
 9595:         if ($curr_selected{'srchby'} eq $option) {
 9596:             $srchbysel .= '
 9597:    <option value="'.$option.'" selected="selected">'.$html_lt{$option}.'</option>';
 9598:         } else {
 9599:             $srchbysel .= '
 9600:    <option value="'.$option.'">'.$html_lt{$option}.'</option>';
 9601:          }
 9602:     }
 9603:     $srchbysel .= "\n  </select>\n";
 9604: 
 9605:     my $srchtypesel = ' <select name="srchtype">';
 9606:     foreach my $option ('begins','contains','exact') {
 9607:         if ($curr_selected{'srchtype'} eq $option) {
 9608:             $srchtypesel .= '
 9609:    <option value="'.$option.'" selected="selected">'.$html_lt{$option}.'</option>';
 9610:         } else {
 9611:             $srchtypesel .= '
 9612:    <option value="'.$option.'">'.$html_lt{$option}.'</option>';
 9613:         }
 9614:     }
 9615:     $srchtypesel .= "\n  </select>\n";
 9616: 
 9617:     my ($newuserscript,$new_user_create);
 9618:     my $context_dom = $env{'request.role.domain'};
 9619:     if ($context eq 'requestcrs') {
 9620:         if ($env{'form.coursedom'} ne '') { 
 9621:             $context_dom = $env{'form.coursedom'};
 9622:         }
 9623:     }
 9624:     if ($forcenewuser) {
 9625:         if (ref($srch) eq 'HASH') {
 9626:             if ($srch->{'srchby'} eq 'uname' && $srch->{'srchtype'} eq 'exact' && $srch->{'srchin'} eq 'dom' && $srch->{'srchdomain'} eq $context_dom) {
 9627:                 if ($cancreate) {
 9628:                     $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>';
 9629:                 } else {
 9630:                     my $helplink = 'javascript:helpMenu('."'display'".')';
 9631:                     my %usertypetext = (
 9632:                         official   => 'institutional',
 9633:                         unofficial => 'non-institutional',
 9634:                     );
 9635:                     $new_user_create = '<p class="LC_warning">'
 9636:                                       .&mt("You are not authorized to create new $usertypetext{$usertype} users in this domain.")
 9637:                                       .' '
 9638:                                       .&mt('Please contact the [_1]helpdesk[_2] for assistance.'
 9639:                                           ,'<a href="'.$helplink.'">','</a>')
 9640:                                       .'</p><br />';
 9641:                 }
 9642:             }
 9643:         }
 9644: 
 9645:         $newuserscript = <<"ENDSCRIPT";
 9646: 
 9647: function setSearch(createnew,callingForm) {
 9648:     if (createnew == 1) {
 9649:         for (var i=0; i<callingForm.srchby.length; i++) {
 9650:             if (callingForm.srchby.options[i].value == 'uname') {
 9651:                 callingForm.srchby.selectedIndex = i;
 9652:             }
 9653:         }
 9654:         for (var i=0; i<callingForm.srchin.length; i++) {
 9655:             if ( callingForm.srchin.options[i].value == 'dom') {
 9656: 		callingForm.srchin.selectedIndex = i;
 9657:             }
 9658:         }
 9659:         for (var i=0; i<callingForm.srchtype.length; i++) {
 9660:             if (callingForm.srchtype.options[i].value == 'exact') {
 9661:                 callingForm.srchtype.selectedIndex = i;
 9662:             }
 9663:         }
 9664:         for (var i=0; i<callingForm.srchdomain.length; i++) {
 9665:             if (callingForm.srchdomain.options[i].value == '$context_dom') {
 9666:                 callingForm.srchdomain.selectedIndex = i;
 9667:             }
 9668:         }
 9669:     }
 9670: }
 9671: ENDSCRIPT
 9672: 
 9673:     }
 9674: 
 9675:     my $output = <<"END_BLOCK";
 9676: <script type="text/javascript">
 9677: // <![CDATA[
 9678: function validateEntry(callingForm) {
 9679: 
 9680:     var checkok = 1;
 9681:     var srchin;
 9682:     for (var i=0; i<callingForm.srchin.length; i++) {
 9683: 	if ( callingForm.srchin[i].checked ) {
 9684: 	    srchin = callingForm.srchin[i].value;
 9685: 	}
 9686:     }
 9687: 
 9688:     var srchtype = callingForm.srchtype.options[callingForm.srchtype.selectedIndex].value;
 9689:     var srchby = callingForm.srchby.options[callingForm.srchby.selectedIndex].value;
 9690:     var srchdomain = callingForm.srchdomain.options[callingForm.srchdomain.selectedIndex].value;
 9691:     var srchterm =  callingForm.srchterm.value;
 9692:     var srchin = callingForm.srchin.options[callingForm.srchin.selectedIndex].value;
 9693:     var msg = "";
 9694: 
 9695:     if (srchterm == "") {
 9696:         checkok = 0;
 9697:         msg += "$js_lt{'youm'}\\n";
 9698:     }
 9699: 
 9700:     if (srchtype== 'begins') {
 9701:         if (srchterm.length < 2) {
 9702:             checkok = 0;
 9703:             msg += "$js_lt{'thte'}\\n";
 9704:         }
 9705:     }
 9706: 
 9707:     if (srchtype== 'contains') {
 9708:         if (srchterm.length < 3) {
 9709:             checkok = 0;
 9710:             msg += "$js_lt{'thet'}\\n";
 9711:         }
 9712:     }
 9713:     if (srchin == 'instd') {
 9714:         if (srchdomain == '') {
 9715:             checkok = 0;
 9716:             msg += "$js_lt{'yomc'}\\n";
 9717:         }
 9718:     }
 9719:     if (srchin == 'dom') {
 9720:         if (srchdomain == '') {
 9721:             checkok = 0;
 9722:             msg += "$js_lt{'ymcd'}\\n";
 9723:         }
 9724:     }
 9725:     if (srchby == 'lastfirst') {
 9726:         if (srchterm.indexOf(",") == -1) {
 9727:             checkok = 0;
 9728:             msg += "$js_lt{'whus'}\\n";
 9729:         }
 9730:         if (srchterm.indexOf(",") == srchterm.length -1) {
 9731:             checkok = 0;
 9732:             msg += "$js_lt{'whse'}\\n";
 9733:         }
 9734:     }
 9735:     if (checkok == 0) {
 9736:         alert("$js_lt{'thfo'}\\n"+msg);
 9737:         return;
 9738:     }
 9739:     if (checkok == 1) {
 9740:         callingForm.submit();
 9741:     }
 9742: }
 9743: 
 9744: $newuserscript
 9745: 
 9746: // ]]>
 9747: </script>
 9748: 
 9749: $new_user_create
 9750: 
 9751: END_BLOCK
 9752: 
 9753:     $output .= &Apache::lonhtmlcommon::start_pick_box().
 9754:                &Apache::lonhtmlcommon::row_title($html_lt{'doma'}).
 9755:                $domform.
 9756:                &Apache::lonhtmlcommon::row_closure().
 9757:                &Apache::lonhtmlcommon::row_title($html_lt{'usr'}).
 9758:                $srchbysel.
 9759:                $srchtypesel. 
 9760:                '<input type="text" size="15" name="srchterm" value="'.$srchterm.'" />'.
 9761:                $srchinsel.
 9762:                &Apache::lonhtmlcommon::row_closure(1). 
 9763:                &Apache::lonhtmlcommon::end_pick_box().
 9764:                '<br />';
 9765:     return ($output,1);
 9766: }
 9767: 
 9768: sub user_rule_check {
 9769:     my ($usershash,$checks,$alerts,$rulematch,$inst_results,$curr_rules,$got_rules) = @_;
 9770:     my ($response,%inst_response);
 9771:     if (ref($usershash) eq 'HASH') {
 9772:         if (keys(%{$usershash}) > 1) {
 9773:             my (%by_username,%by_id,%userdoms);
 9774:             my $checkid;
 9775:             if (ref($checks) eq 'HASH') {
 9776:                 if ((!defined($checks->{'username'})) && (defined($checks->{'id'}))) {
 9777:                     $checkid = 1;
 9778:                 }
 9779:             }
 9780:             foreach my $user (keys(%{$usershash})) {
 9781:                 my ($uname,$udom) = split(/:/,$user);
 9782:                 if ($checkid) {
 9783:                     if (ref($usershash->{$user}) eq 'HASH') {
 9784:                         if ($usershash->{$user}->{'id'} ne '') {
 9785:                             $by_id{$udom}{$usershash->{$user}->{'id'}} = $uname;
 9786:                             $userdoms{$udom} = 1;
 9787:                             if (ref($inst_results) eq 'HASH') {
 9788:                                 $inst_results->{$uname.':'.$udom} = {};
 9789:                             }
 9790:                         }
 9791:                     }
 9792:                 } else {
 9793:                     $by_username{$udom}{$uname} = 1;
 9794:                     $userdoms{$udom} = 1;
 9795:                     if (ref($inst_results) eq 'HASH') {
 9796:                         $inst_results->{$uname.':'.$udom} = {};
 9797:                     }
 9798:                 }
 9799:             }
 9800:             foreach my $udom (keys(%userdoms)) {
 9801:                 if (!$got_rules->{$udom}) {
 9802:                     my %domconfig = &Apache::lonnet::get_dom('configuration',
 9803:                                                              ['usercreation'],$udom);
 9804:                     if (ref($domconfig{'usercreation'}) eq 'HASH') {
 9805:                         foreach my $item ('username','id') {
 9806:                             if (ref($domconfig{'usercreation'}{$item.'_rule'}) eq 'ARRAY') {
 9807:                                 $$curr_rules{$udom}{$item} =
 9808:                                     $domconfig{'usercreation'}{$item.'_rule'};
 9809:                             }
 9810:                         }
 9811:                     }
 9812:                     $got_rules->{$udom} = 1;
 9813:                 }
 9814:             }
 9815:             if ($checkid) {
 9816:                 foreach my $udom (keys(%by_id)) {
 9817:                     my ($outcome,$results) = &Apache::lonnet::get_multiple_instusers($udom,$by_id{$udom},'id');
 9818:                     if ($outcome eq 'ok') {
 9819:                         foreach my $id (keys(%{$by_id{$udom}})) {
 9820:                             my $uname = $by_id{$udom}{$id};
 9821:                             $inst_response{$uname.':'.$udom} = $outcome;
 9822:                         }
 9823:                         if (ref($results) eq 'HASH') {
 9824:                             foreach my $uname (keys(%{$results})) {
 9825:                                 if (exists($inst_response{$uname.':'.$udom})) {
 9826:                                     $inst_response{$uname.':'.$udom} = $outcome;
 9827:                                     $inst_results->{$uname.':'.$udom} = $results->{$uname};
 9828:                                 }
 9829:                             }
 9830:                         }
 9831:                     }
 9832:                 }
 9833:             } else {
 9834:                 foreach my $udom (keys(%by_username)) {
 9835:                     my ($outcome,$results) = &Apache::lonnet::get_multiple_instusers($udom,$by_username{$udom});
 9836:                     if ($outcome eq 'ok') {
 9837:                         foreach my $uname (keys(%{$by_username{$udom}})) {
 9838:                             $inst_response{$uname.':'.$udom} = $outcome;
 9839:                         }
 9840:                         if (ref($results) eq 'HASH') {
 9841:                             foreach my $uname (keys(%{$results})) {
 9842:                                 $inst_results->{$uname.':'.$udom} = $results->{$uname};
 9843:                             }
 9844:                         }
 9845:                     }
 9846:                 }
 9847:             }
 9848:         } elsif (keys(%{$usershash}) == 1) {
 9849:             my $user = (keys(%{$usershash}))[0];
 9850:             my ($uname,$udom) = split(/:/,$user);
 9851:             if (($udom ne '') && ($uname ne '')) {
 9852:                 if (ref($usershash->{$user}) eq 'HASH') {
 9853:                     if (ref($checks) eq 'HASH') {
 9854:                         if (defined($checks->{'username'})) {
 9855:                             ($inst_response{$user},%{$inst_results->{$user}}) =
 9856:                                 &Apache::lonnet::get_instuser($udom,$uname);
 9857:                         } elsif (defined($checks->{'id'})) {
 9858:                             if ($usershash->{$user}->{'id'} ne '') {
 9859:                                 ($inst_response{$user},%{$inst_results->{$user}}) =
 9860:                                     &Apache::lonnet::get_instuser($udom,undef,
 9861:                                                                   $usershash->{$user}->{'id'});
 9862:                             } else {
 9863:                                 ($inst_response{$user},%{$inst_results->{$user}}) =
 9864:                                     &Apache::lonnet::get_instuser($udom,$uname);
 9865:                             }
 9866:                         }
 9867:                     } else {
 9868:                        ($inst_response{$user},%{$inst_results->{$user}}) =
 9869:                             &Apache::lonnet::get_instuser($udom,$uname);
 9870:                        return;
 9871:                     }
 9872:                     if (!$got_rules->{$udom}) {
 9873:                         my %domconfig = &Apache::lonnet::get_dom('configuration',
 9874:                                                                  ['usercreation'],$udom);
 9875:                         if (ref($domconfig{'usercreation'}) eq 'HASH') {
 9876:                             foreach my $item ('username','id') {
 9877:                                 if (ref($domconfig{'usercreation'}{$item.'_rule'}) eq 'ARRAY') {
 9878:                                    $$curr_rules{$udom}{$item} =
 9879:                                        $domconfig{'usercreation'}{$item.'_rule'};
 9880:                                 }
 9881:                             }
 9882:                         }
 9883:                         $got_rules->{$udom} = 1;
 9884:                     }
 9885:                 }
 9886:             } else {
 9887:                 return;
 9888:             }
 9889:         } else {
 9890:             return;
 9891:         }
 9892:         foreach my $user (keys(%{$usershash})) {
 9893:             my ($uname,$udom) = split(/:/,$user);
 9894:             next if (($udom eq '') || ($uname eq ''));
 9895:             my $id;
 9896:             if (ref($inst_results) eq 'HASH') {
 9897:                 if (ref($inst_results->{$user}) eq 'HASH') {
 9898:                     $id = $inst_results->{$user}->{'id'};
 9899:                 }
 9900:             }
 9901:             if ($id eq '') {
 9902:                 if (ref($usershash->{$user})) {
 9903:                     $id = $usershash->{$user}->{'id'};
 9904:                 }
 9905:             }
 9906:             foreach my $item (keys(%{$checks})) {
 9907:                 if (ref($$curr_rules{$udom}) eq 'HASH') {
 9908:                     if (ref($$curr_rules{$udom}{$item}) eq 'ARRAY') {
 9909:                         if (@{$$curr_rules{$udom}{$item}} > 0) {
 9910:                             my %rule_check = &Apache::lonnet::inst_rulecheck($udom,$uname,$id,$item,
 9911:                                                                              $$curr_rules{$udom}{$item});
 9912:                             foreach my $rule (@{$$curr_rules{$udom}{$item}}) {
 9913:                                 if ($rule_check{$rule}) {
 9914:                                     $$rulematch{$user}{$item} = $rule;
 9915:                                     if ($inst_response{$user} eq 'ok') {
 9916:                                         if (ref($inst_results) eq 'HASH') {
 9917:                                             if (ref($inst_results->{$user}) eq 'HASH') {
 9918:                                                 if (keys(%{$inst_results->{$user}}) == 0) {
 9919:                                                     $$alerts{$item}{$udom}{$uname} = 1;
 9920:                                                 } elsif ($item eq 'id') {
 9921:                                                     if ($inst_results->{$user}->{'id'} eq '') {
 9922:                                                         $$alerts{$item}{$udom}{$uname} = 1;
 9923:                                                     }
 9924:                                                 }
 9925:                                             }
 9926:                                         }
 9927:                                     }
 9928:                                     last;
 9929:                                 }
 9930:                             }
 9931:                         }
 9932:                     }
 9933:                 }
 9934:             }
 9935:         }
 9936:     }
 9937:     return;
 9938: }
 9939: 
 9940: sub user_rule_formats {
 9941:     my ($domain,$domdesc,$curr_rules,$check) = @_;
 9942:     my %text = ( 
 9943:                  'username' => 'Usernames',
 9944:                  'id'       => 'IDs',
 9945:                );
 9946:     my $output;
 9947:     my ($rules,$ruleorder) = &Apache::lonnet::inst_userrules($domain,$check);
 9948:     if ((ref($rules) eq 'HASH') && (ref($ruleorder) eq 'ARRAY')) {
 9949:         if (@{$ruleorder} > 0) {
 9950:             $output = '<br />'.
 9951:                       &mt($text{$check}.' with the following format(s) may [_1]only[_2] be used for verified users at [_3]:',
 9952:                           '<span class="LC_cusr_emph">','</span>',$domdesc).
 9953:                       ' <ul>';
 9954:             foreach my $rule (@{$ruleorder}) {
 9955:                 if (ref($curr_rules) eq 'ARRAY') {
 9956:                     if (grep(/^\Q$rule\E$/,@{$curr_rules})) {
 9957:                         if (ref($rules->{$rule}) eq 'HASH') {
 9958:                             $output .= '<li>'.$rules->{$rule}{'name'}.': '.
 9959:                                         $rules->{$rule}{'desc'}.'</li>';
 9960:                         }
 9961:                     }
 9962:                 }
 9963:             }
 9964:             $output .= '</ul>';
 9965:         }
 9966:     }
 9967:     return $output;
 9968: }
 9969: 
 9970: sub instrule_disallow_msg {
 9971:     my ($checkitem,$domdesc,$count,$mode) = @_;
 9972:     my $response;
 9973:     my %text = (
 9974:                   item   => 'username',
 9975:                   items  => 'usernames',
 9976:                   match  => 'matches',
 9977:                   do     => 'does',
 9978:                   action => 'a username',
 9979:                   one    => 'one',
 9980:                );
 9981:     if ($count > 1) {
 9982:         $text{'item'} = 'usernames';
 9983:         $text{'match'} ='match';
 9984:         $text{'do'} = 'do';
 9985:         $text{'action'} = 'usernames',
 9986:         $text{'one'} = 'ones';
 9987:     }
 9988:     if ($checkitem eq 'id') {
 9989:         $text{'items'} = 'IDs';
 9990:         $text{'item'} = 'ID';
 9991:         $text{'action'} = 'an ID';
 9992:         if ($count > 1) {
 9993:             $text{'item'} = 'IDs';
 9994:             $text{'action'} = 'IDs';
 9995:         }
 9996:     }
 9997:     $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 />';
 9998:     if ($mode eq 'upload') {
 9999:         if ($checkitem eq 'username') {
10000:             $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'}.");
10001:         } elsif ($checkitem eq 'id') {
10002:             $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.");
10003:         }
10004:     } elsif ($mode eq 'selfcreate') {
10005:         if ($checkitem eq 'id') {
10006:             $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.");
10007:         }
10008:     } else {
10009:         if ($checkitem eq 'username') {
10010:             $response .= &mt("You must choose $text{'action'} with a different format --  $text{'one'} that will not conflict with 'official' institutional $text{'items'}.");
10011:         } elsif ($checkitem eq 'id') {
10012:             $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.");
10013:         }
10014:     }
10015:     return $response;
10016: }
10017: 
10018: sub personal_data_fieldtitles {
10019:     my %fieldtitles = &Apache::lonlocal::texthash (
10020:                         id => 'Student/Employee ID',
10021:                         permanentemail => 'E-mail address',
10022:                         lastname => 'Last Name',
10023:                         firstname => 'First Name',
10024:                         middlename => 'Middle Name',
10025:                         generation => 'Generation',
10026:                         gen => 'Generation',
10027:                         inststatus => 'Affiliation',
10028:                    );
10029:     return %fieldtitles;
10030: }
10031: 
10032: sub sorted_inst_types {
10033:     my ($dom) = @_;
10034:     my ($usertypes,$order);
10035:     my %domdefaults = &Apache::lonnet::get_domain_defaults($dom);
10036:     if (ref($domdefaults{'inststatus'}) eq 'HASH') {
10037:         $usertypes = $domdefaults{'inststatus'}{'inststatustypes'};
10038:         $order = $domdefaults{'inststatus'}{'inststatusorder'};
10039:     } else {
10040:         ($usertypes,$order) = &Apache::lonnet::retrieve_inst_usertypes($dom);
10041:     }
10042:     my $othertitle = &mt('All users');
10043:     if ($env{'request.course.id'}) {
10044:         $othertitle  = &mt('Any users');
10045:     }
10046:     my @types;
10047:     if (ref($order) eq 'ARRAY') {
10048:         @types = @{$order};
10049:     }
10050:     if (@types == 0) {
10051:         if (ref($usertypes) eq 'HASH') {
10052:             @types = sort(keys(%{$usertypes}));
10053:         }
10054:     }
10055:     if (keys(%{$usertypes}) > 0) {
10056:         $othertitle = &mt('Other users');
10057:     }
10058:     return ($othertitle,$usertypes,\@types);
10059: }
10060: 
10061: sub get_institutional_codes {
10062:     my ($settings,$allcourses,$LC_code) = @_;
10063: # Get complete list of course sections to update
10064:     my @currsections = ();
10065:     my @currxlists = ();
10066:     my $coursecode = $$settings{'internal.coursecode'};
10067: 
10068:     if ($$settings{'internal.sectionnums'} ne '') {
10069:         @currsections = split(/,/,$$settings{'internal.sectionnums'});
10070:     }
10071: 
10072:     if ($$settings{'internal.crosslistings'} ne '') {
10073:         @currxlists = split(/,/,$$settings{'internal.crosslistings'});
10074:     }
10075: 
10076:     if (@currxlists > 0) {
10077:         foreach (@currxlists) {
10078:             if (m/^([^:]+):(\w*)$/) {
10079:                 unless (grep/^$1$/,@{$allcourses}) {
10080:                     push @{$allcourses},$1;
10081:                     $$LC_code{$1} = $2;
10082:                 }
10083:             }
10084:         }
10085:     }
10086:  
10087:     if (@currsections > 0) {
10088:         foreach (@currsections) {
10089:             if (m/^(\w+):(\w*)$/) {
10090:                 my $sec = $coursecode.$1;
10091:                 my $lc_sec = $2;
10092:                 unless (grep/^$sec$/,@{$allcourses}) {
10093:                     push @{$allcourses},$sec;
10094:                     $$LC_code{$sec} = $lc_sec;
10095:                 }
10096:             }
10097:         }
10098:     }
10099:     return;
10100: }
10101: 
10102: sub get_standard_codeitems {
10103:     return ('Year','Semester','Department','Number','Section');
10104: }
10105: 
10106: =pod
10107: 
10108: =head1 Slot Helpers
10109: 
10110: =over 4
10111: 
10112: =item * sorted_slots()
10113: 
10114: Sorts an array of slot names in order of an optional sort key,
10115: default sort is by slot start time (earliest first). 
10116: 
10117: Inputs:
10118: 
10119: =over 4
10120: 
10121: slotsarr  - Reference to array of unsorted slot names.
10122: 
10123: slots     - Reference to hash of hash, where outer hash keys are slot names.
10124: 
10125: sortkey   - Name of key in inner hash to be sorted on (e.g., starttime).
10126: 
10127: =back
10128: 
10129: Returns:
10130: 
10131: =over 4
10132: 
10133: sorted   - An array of slot names sorted by a specified sort key 
10134:            (default sort key is start time of the slot).
10135: 
10136: =back
10137: 
10138: =cut
10139: 
10140: 
10141: sub sorted_slots {
10142:     my ($slotsarr,$slots,$sortkey) = @_;
10143:     if ($sortkey eq '') {
10144:         $sortkey = 'starttime';
10145:     }
10146:     my @sorted;
10147:     if ((ref($slotsarr) eq 'ARRAY') && (ref($slots) eq 'HASH')) {
10148:         @sorted =
10149:             sort {
10150:                      if (ref($slots->{$a}) && ref($slots->{$b})) {
10151:                          return $slots->{$a}{$sortkey} <=> $slots->{$b}{$sortkey}
10152:                      }
10153:                      if (ref($slots->{$a})) { return -1;}
10154:                      if (ref($slots->{$b})) { return 1;}
10155:                      return 0;
10156:                  } @{$slotsarr};
10157:     }
10158:     return @sorted;
10159: }
10160: 
10161: =pod
10162: 
10163: =item * get_future_slots()
10164: 
10165: Inputs:
10166: 
10167: =over 4
10168: 
10169: cnum - course number
10170: 
10171: cdom - course domain
10172: 
10173: now - current UNIX time
10174: 
10175: symb - optional symb
10176: 
10177: =back
10178: 
10179: Returns:
10180: 
10181: =over 4
10182: 
10183: sorted_reservable - ref to array of student_schedulable slots currently 
10184:                     reservable, ordered by end date of reservation period.
10185: 
10186: reservable_now - ref to hash of student_schedulable slots currently
10187:                  reservable.
10188: 
10189:     Keys in inner hash are:
10190:     (a) symb: either blank or symb to which slot use is restricted.
10191:     (b) endreserve: end date of reservation period.
10192:     (c) uniqueperiod: start,end dates when slot is to be uniquely
10193:         selected.
10194: 
10195: sorted_future - ref to array of student_schedulable slots reservable in
10196:                 the future, ordered by start date of reservation period.
10197: 
10198: future_reservable - ref to hash of student_schedulable slots reservable
10199:                     in the future.
10200: 
10201:     Keys in inner hash are:
10202:     (a) symb: either blank or symb to which slot use is restricted.
10203:     (b) startreserve:  start date of reservation period.
10204:     (c) uniqueperiod: start,end dates when slot is to be uniquely
10205:         selected.
10206: 
10207: =back
10208: 
10209: =cut
10210: 
10211: sub get_future_slots {
10212:     my ($cnum,$cdom,$now,$symb) = @_;
10213:     my (%reservable_now,%future_reservable,@sorted_reservable,@sorted_future);
10214:     my %slots = &Apache::lonnet::get_course_slots($cnum,$cdom);
10215:     foreach my $slot (keys(%slots)) {
10216:         next unless($slots{$slot}->{'type'} eq 'schedulable_student');
10217:         if ($symb) {
10218:             next if (($slots{$slot}->{'symb'} ne '') && 
10219:                      ($slots{$slot}->{'symb'} ne $symb));
10220:         }
10221:         if (($slots{$slot}->{'starttime'} > $now) &&
10222:             ($slots{$slot}->{'endtime'} > $now)) {
10223:             if (($slots{$slot}->{'allowedsections'}) || ($slots{$slot}->{'allowedusers'})) {
10224:                 my $userallowed = 0;
10225:                 if ($slots{$slot}->{'allowedsections'}) {
10226:                     my @allowed_sec = split(',',$slots{$slot}->{'allowedsections'});
10227:                     if (!defined($env{'request.role.sec'})
10228:                         && grep(/^No section assigned$/,@allowed_sec)) {
10229:                         $userallowed=1;
10230:                     } else {
10231:                         if (grep(/^\Q$env{'request.role.sec'}\E$/,@allowed_sec)) {
10232:                             $userallowed=1;
10233:                         }
10234:                     }
10235:                     unless ($userallowed) {
10236:                         if (defined($env{'request.course.groups'})) {
10237:                             my @groups = split(/:/,$env{'request.course.groups'});
10238:                             foreach my $group (@groups) {
10239:                                 if (grep(/^\Q$group\E$/,@allowed_sec)) {
10240:                                     $userallowed=1;
10241:                                     last;
10242:                                 }
10243:                             }
10244:                         }
10245:                     }
10246:                 }
10247:                 if ($slots{$slot}->{'allowedusers'}) {
10248:                     my @allowed_users = split(',',$slots{$slot}->{'allowedusers'});
10249:                     my $user = $env{'user.name'}.':'.$env{'user.domain'};
10250:                     if (grep(/^\Q$user\E$/,@allowed_users)) {
10251:                         $userallowed = 1;
10252:                     }
10253:                 }
10254:                 next unless($userallowed);
10255:             }
10256:             my $startreserve = $slots{$slot}->{'startreserve'};
10257:             my $endreserve = $slots{$slot}->{'endreserve'};
10258:             my $symb = $slots{$slot}->{'symb'};
10259:             my $uniqueperiod;
10260:             if (ref($slots{$slot}->{'uniqueperiod'}) eq 'ARRAY') {
10261:                 $uniqueperiod = join(',',@{$slots{$slot}->{'uniqueperiod'}});
10262:             }
10263:             if (($startreserve < $now) &&
10264:                 (!$endreserve || $endreserve > $now)) {
10265:                 my $lastres = $endreserve;
10266:                 if (!$lastres) {
10267:                     $lastres = $slots{$slot}->{'starttime'};
10268:                 }
10269:                 $reservable_now{$slot} = {
10270:                                            symb       => $symb,
10271:                                            endreserve => $lastres,
10272:                                            uniqueperiod => $uniqueperiod,   
10273:                                          };
10274:             } elsif (($startreserve > $now) &&
10275:                      (!$endreserve || $endreserve > $startreserve)) {
10276:                 $future_reservable{$slot} = {
10277:                                               symb         => $symb,
10278:                                               startreserve => $startreserve,
10279:                                               uniqueperiod => $uniqueperiod,
10280:                                             };
10281:             }
10282:         }
10283:     }
10284:     my @unsorted_reservable = keys(%reservable_now);
10285:     if (@unsorted_reservable > 0) {
10286:         @sorted_reservable = 
10287:             &sorted_slots(\@unsorted_reservable,\%reservable_now,'endreserve');
10288:     }
10289:     my @unsorted_future = keys(%future_reservable);
10290:     if (@unsorted_future > 0) {
10291:         @sorted_future =
10292:             &sorted_slots(\@unsorted_future,\%future_reservable,'startreserve');
10293:     }
10294:     return (\@sorted_reservable,\%reservable_now,\@sorted_future,\%future_reservable);
10295: }
10296: 
10297: =pod
10298: 
10299: =back
10300: 
10301: =head1 HTTP Helpers
10302: 
10303: =over 4
10304: 
10305: =item * &get_unprocessed_cgi($query,$possible_names)
10306: 
10307: Modify the %env hash to contain unprocessed CGI form parameters held in
10308: $query.  The parameters listed in $possible_names (an array reference),
10309: will be set in $env{'form.name'} if they do not already exist.
10310: 
10311: Typically called with $ENV{'QUERY_STRING'} as the first parameter.  
10312: $possible_names is an ref to an array of form element names.  As an example:
10313: get_unprocessed_cgi($ENV{'QUERY_STRING'},['uname','udom']);
10314: will result in $env{'form.uname'} and $env{'form.udom'} being set.
10315: 
10316: =cut
10317: 
10318: sub get_unprocessed_cgi {
10319:   my ($query,$possible_names)= @_;
10320:   # $Apache::lonxml::debug=1;
10321:   foreach my $pair (split(/&/,$query)) {
10322:     my ($name, $value) = split(/=/,$pair);
10323:     $name = &unescape($name);
10324:     if (!defined($possible_names) || (grep {$_ eq $name} @$possible_names)) {
10325:       $value =~ tr/+/ /;
10326:       $value =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack("C",hex($1))/eg;
10327:       unless (defined($env{'form.'.$name})) { &add_to_env('form.'.$name,$value) };
10328:     }
10329:   }
10330: }
10331: 
10332: =pod
10333: 
10334: =item * &cacheheader() 
10335: 
10336: returns cache-controlling header code
10337: 
10338: =cut
10339: 
10340: sub cacheheader {
10341:     unless ($env{'request.method'} eq 'GET') { return ''; }
10342:     my $date=strftime("%a, %d %b %Y %H:%M:%S GMT",gmtime);
10343:     my $output .='<meta HTTP-EQUIV="Expires" CONTENT="'.$date.'" />
10344:                 <meta HTTP-EQUIV="Cache-control" CONTENT="no-cache" />
10345:                 <meta HTTP-EQUIV="Pragma" CONTENT="no-cache" />';
10346:     return $output;
10347: }
10348: 
10349: =pod
10350: 
10351: =item * &no_cache($r) 
10352: 
10353: specifies header code to not have cache
10354: 
10355: =cut
10356: 
10357: sub no_cache {
10358:     my ($r) = @_;
10359:     if ($ENV{'REQUEST_METHOD'} ne 'GET' &&
10360: 	$env{'request.method'} ne 'GET') { return ''; }
10361:     my $date=strftime("%a, %d %b %Y %H:%M:%S GMT",gmtime(time));
10362:     $r->no_cache(1);
10363:     $r->header_out("Expires" => $date);
10364:     $r->header_out("Pragma" => "no-cache");
10365: }
10366: 
10367: sub content_type {
10368:     my ($r,$type,$charset) = @_;
10369:     if ($r) {
10370: 	#  Note that printout.pl calls this with undef for $r.
10371: 	&no_cache($r);
10372:     }
10373:     if ($env{'browser.mathml'} && $type eq 'text/html') { $type='text/xml'; }
10374:     unless ($charset) {
10375: 	$charset=&Apache::lonlocal::current_encoding;
10376:     }
10377:     if ($charset) { $type.='; charset='.$charset; }
10378:     if ($r) {
10379: 	$r->content_type($type);
10380:     } else {
10381: 	print("Content-type: $type\n\n");
10382:     }
10383: }
10384: 
10385: =pod
10386: 
10387: =item * &add_to_env($name,$value) 
10388: 
10389: adds $name to the %env hash with value
10390: $value, if $name already exists, the entry is converted to an array
10391: reference and $value is added to the array.
10392: 
10393: =cut
10394: 
10395: sub add_to_env {
10396:   my ($name,$value)=@_;
10397:   if (defined($env{$name})) {
10398:     if (ref($env{$name})) {
10399:       #already have multiple values
10400:       push(@{ $env{$name} },$value);
10401:     } else {
10402:       #first time seeing multiple values, convert hash entry to an arrayref
10403:       my $first=$env{$name};
10404:       undef($env{$name});
10405:       push(@{ $env{$name} },$first,$value);
10406:     }
10407:   } else {
10408:     $env{$name}=$value;
10409:   }
10410: }
10411: 
10412: =pod
10413: 
10414: =item * &get_env_multiple($name) 
10415: 
10416: gets $name from the %env hash, it seemlessly handles the cases where multiple
10417: values may be defined and end up as an array ref.
10418: 
10419: returns an array of values
10420: 
10421: =cut
10422: 
10423: sub get_env_multiple {
10424:     my ($name) = @_;
10425:     my @values;
10426:     if (defined($env{$name})) {
10427:         # exists is it an array
10428:         if (ref($env{$name})) {
10429:             @values=@{ $env{$name} };
10430:         } else {
10431:             $values[0]=$env{$name};
10432:         }
10433:     }
10434:     return(@values);
10435: }
10436: 
10437: sub ask_for_embedded_content {
10438:     my ($actionurl,$state,$allfiles,$codebase,$args)=@_;
10439:     my (%subdependencies,%dependencies,%mapping,%existing,%newfiles,%pathchanges,
10440:         %currsubfile,%unused,$rem);
10441:     my $counter = 0;
10442:     my $numnew = 0;
10443:     my $numremref = 0;
10444:     my $numinvalid = 0;
10445:     my $numpathchg = 0;
10446:     my $numexisting = 0;
10447:     my $numunused = 0;
10448:     my ($output,$upload_output,$toplevel,$url,$udom,$uname,$getpropath,$cdom,$cnum,
10449:         $fileloc,$filename,$delete_output,$modify_output,$title,$symb,$path,$navmap);
10450:     my $heading = &mt('Upload embedded files');
10451:     my $buttontext = &mt('Upload');
10452: 
10453:     if ($env{'request.course.id'}) {
10454:         if ($actionurl eq '/adm/dependencies') {
10455:             $navmap = Apache::lonnavmaps::navmap->new();
10456:         }
10457:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
10458:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
10459:     }
10460:     if (($actionurl eq '/adm/portfolio') ||
10461:         ($actionurl eq '/adm/coursegrp_portfolio')) {
10462:         my $current_path='/';
10463:         if ($env{'form.currentpath'}) {
10464:             $current_path = $env{'form.currentpath'};
10465:         }
10466:         if ($actionurl eq '/adm/coursegrp_portfolio') {
10467:             $udom = $cdom;
10468:             $uname = $cnum;
10469:             $url = '/userfiles/groups/'.$env{'form.group'}.'/portfolio';
10470:         } else {
10471:             $udom = $env{'user.domain'};
10472:             $uname = $env{'user.name'};
10473:             $url = '/userfiles/portfolio';
10474:         }
10475:         $toplevel = $url.'/';
10476:         $url .= $current_path;
10477:         $getpropath = 1;
10478:     } elsif (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank') ||
10479:              ($actionurl eq '/adm/imsimport')) { 
10480:         my ($udom,$uname,$rest) = ($args->{'current_path'} =~ m{/priv/($match_domain)/($match_username)/?(.*)$});
10481:         $url = $Apache::lonnet::perlvar{'lonDocRoot'}."/priv/$udom/$uname/";
10482:         $toplevel = $url;
10483:         if ($rest ne '') {
10484:             $url .= $rest;
10485:         }
10486:     } elsif ($actionurl eq '/adm/coursedocs') {
10487:         if (ref($args) eq 'HASH') {
10488:             $url = $args->{'docs_url'};
10489:             $toplevel = $url;
10490:             if ($args->{'context'} eq 'paste') {
10491:                 ($cdom,$cnum) = ($url =~ m{^\Q/uploaded/\E($match_domain)/($match_courseid)/});
10492:                 ($path) =
10493:                     ($toplevel =~ m{^(\Q/uploaded/$cdom/$cnum/\E(?:docs|supplemental)/(?:default|\d+)/\d+)/});
10494:                 $fileloc = &Apache::lonnet::filelocation('',$toplevel);
10495:                 $fileloc =~ s{^/}{};
10496:             }
10497:         }
10498:     } elsif ($actionurl eq '/adm/dependencies') {
10499:         if ($env{'request.course.id'} ne '') {
10500:             if (ref($args) eq 'HASH') {
10501:                 $url = $args->{'docs_url'};
10502:                 $title = $args->{'docs_title'};
10503:                 $toplevel = $url;
10504:                 unless ($toplevel =~ m{^/}) {
10505:                     $toplevel = "/$url";
10506:                 }
10507:                 ($rem) = ($toplevel =~ m{^(.+/)[^/]+$});
10508:                 if ($toplevel =~ m{^(\Q/uploaded/$cdom/$cnum/portfolio/syllabus\E)}) {
10509:                     $path = $1;
10510:                 } else {
10511:                     ($path) =
10512:                         ($toplevel =~ m{^(\Q/uploaded/$cdom/$cnum/\E(?:docs|supplemental)/(?:default|\d+)/\d+)/});
10513:                 }
10514:                 if ($toplevel=~/^\/*(uploaded|editupload)/) {
10515:                     $fileloc = $toplevel;
10516:                     $fileloc=~ s/^\s*(\S+)\s*$/$1/;
10517:                     my ($udom,$uname,$fname) =
10518:                         ($fileloc=~ m{^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$});
10519:                     $fileloc = propath($udom,$uname).'/userfiles/'.$fname;
10520:                 } else {
10521:                     $fileloc = &Apache::lonnet::filelocation('',$toplevel);
10522:                 }
10523:                 $fileloc =~ s{^/}{};
10524:                 ($filename) = ($fileloc =~ m{.+/([^/]+)$});
10525:                 $heading = &mt('Status of dependencies in [_1]',"$title ($filename)");
10526:             }
10527:         }
10528:     } elsif ($actionurl eq "/public/$cdom/$cnum/syllabus") {
10529:         $udom = $cdom;
10530:         $uname = $cnum;
10531:         $url = "/uploaded/$cdom/$cnum/portfolio/syllabus";
10532:         $toplevel = $url;
10533:         $path = $url;
10534:         $fileloc = &Apache::lonnet::filelocation('',$toplevel).'/';
10535:         $fileloc =~ s{^/}{};
10536:     }
10537:     foreach my $file (keys(%{$allfiles})) {
10538:         my $embed_file;
10539:         if (($path eq "/uploaded/$cdom/$cnum/portfolio/syllabus") && ($file =~ m{^\Q$path/\E(.+)$})) {
10540:             $embed_file = $1;
10541:         } else {
10542:             $embed_file = $file;
10543:         }
10544:         my ($absolutepath,$cleaned_file);
10545:         if ($embed_file =~ m{^\w+://}) {
10546:             $cleaned_file = $embed_file;
10547:             $newfiles{$cleaned_file} = 1;
10548:             $mapping{$cleaned_file} = $embed_file;
10549:         } else {
10550:             $cleaned_file = &clean_path($embed_file);
10551:             if ($embed_file =~ m{^/}) {
10552:                 $absolutepath = $embed_file;
10553:             }
10554:             if ($cleaned_file =~ m{/}) {
10555:                 my ($path,$fname) = ($cleaned_file =~ m{^(.+)/([^/]*)$});
10556:                 $path = &check_for_traversal($path,$url,$toplevel);
10557:                 my $item = $fname;
10558:                 if ($path ne '') {
10559:                     $item = $path.'/'.$fname;
10560:                     $subdependencies{$path}{$fname} = 1;
10561:                 } else {
10562:                     $dependencies{$item} = 1;
10563:                 }
10564:                 if ($absolutepath) {
10565:                     $mapping{$item} = $absolutepath;
10566:                 } else {
10567:                     $mapping{$item} = $embed_file;
10568:                 }
10569:             } else {
10570:                 $dependencies{$embed_file} = 1;
10571:                 if ($absolutepath) {
10572:                     $mapping{$cleaned_file} = $absolutepath;
10573:                 } else {
10574:                     $mapping{$cleaned_file} = $embed_file;
10575:                 }
10576:             }
10577:         }
10578:     }
10579:     my $dirptr = 16384;
10580:     foreach my $path (keys(%subdependencies)) {
10581:         $currsubfile{$path} = {};
10582:         if (($actionurl eq '/adm/portfolio') ||
10583:             ($actionurl eq '/adm/coursegrp_portfolio')) { 
10584:             my ($sublistref,$listerror) =
10585:                 &Apache::lonnet::dirlist($url.$path,$udom,$uname,$getpropath);
10586:             if (ref($sublistref) eq 'ARRAY') {
10587:                 foreach my $line (@{$sublistref}) {
10588:                     my ($file_name,$rest) = split(/\&/,$line,2);
10589:                     $currsubfile{$path}{$file_name} = 1;
10590:                 }
10591:             }
10592:         } elsif (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank')) {
10593:             if (opendir(my $dir,$url.'/'.$path)) {
10594:                 my @subdir_list = grep(!/^\./,readdir($dir));
10595:                 map {$currsubfile{$path}{$_} = 1;} @subdir_list;
10596:             }
10597:         } elsif (($actionurl eq '/adm/dependencies') ||
10598:                  (($actionurl eq '/adm/coursedocs') && (ref($args) eq 'HASH') &&
10599:                   ($args->{'context'} eq 'paste')) ||
10600:                  ($actionurl eq "/public/$cdom/$cnum/syllabus")) {
10601:             if ($env{'request.course.id'} ne '') {
10602:                 my $dir;
10603:                 if ($actionurl eq "/public/$cdom/$cnum/syllabus") {
10604:                     $dir = $fileloc;
10605:                 } else {
10606:                     ($dir) = ($fileloc =~ m{^(.+/)[^/]+$});
10607:                 }
10608:                 if ($dir ne '') {
10609:                     my ($sublistref,$listerror) =
10610:                         &Apache::lonnet::dirlist($dir.$path,$cdom,$cnum,$getpropath,undef,'/');
10611:                     if (ref($sublistref) eq 'ARRAY') {
10612:                         foreach my $line (@{$sublistref}) {
10613:                             my ($file_name,$dom,undef,$testdir,undef,undef,undef,undef,$size,
10614:                                 undef,$mtime)=split(/\&/,$line,12);
10615:                             unless (($testdir&$dirptr) ||
10616:                                     ($file_name =~ /^\.\.?$/)) {
10617:                                 $currsubfile{$path}{$file_name} = [$size,$mtime];
10618:                             }
10619:                         }
10620:                     }
10621:                 }
10622:             }
10623:         }
10624:         foreach my $file (keys(%{$subdependencies{$path}})) {
10625:             if (exists($currsubfile{$path}{$file})) {
10626:                 my $item = $path.'/'.$file;
10627:                 unless ($mapping{$item} eq $item) {
10628:                     $pathchanges{$item} = 1;
10629:                 }
10630:                 $existing{$item} = 1;
10631:                 $numexisting ++;
10632:             } else {
10633:                 $newfiles{$path.'/'.$file} = 1;
10634:             }
10635:         }
10636:         if ($actionurl eq '/adm/dependencies') {
10637:             foreach my $path (keys(%currsubfile)) {
10638:                 if (ref($currsubfile{$path}) eq 'HASH') {
10639:                     foreach my $file (keys(%{$currsubfile{$path}})) {
10640:                          unless ($subdependencies{$path}{$file}) {
10641:                              next if (($rem ne '') &&
10642:                                       (($env{"httpref.$rem"."$path/$file"} ne '') ||
10643:                                        (ref($navmap) &&
10644:                                        (($navmap->getResourceByUrl($rem."$path/$file") ne '') ||
10645:                                         (($file =~ /^(.*\.s?html?)\.bak$/i) &&
10646:                                          ($navmap->getResourceByUrl($rem."$path/$1")))))));
10647:                              $unused{$path.'/'.$file} = 1; 
10648:                          }
10649:                     }
10650:                 }
10651:             }
10652:         }
10653:     }
10654:     my %currfile;
10655:     if (($actionurl eq '/adm/portfolio') ||
10656:         ($actionurl eq '/adm/coursegrp_portfolio')) {
10657:         my ($dirlistref,$listerror) =
10658:             &Apache::lonnet::dirlist($url,$udom,$uname,$getpropath);
10659:         if (ref($dirlistref) eq 'ARRAY') {
10660:             foreach my $line (@{$dirlistref}) {
10661:                 my ($file_name,$rest) = split(/\&/,$line,2);
10662:                 $currfile{$file_name} = 1;
10663:             }
10664:         }
10665:     } elsif (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank')) {
10666:         if (opendir(my $dir,$url)) {
10667:             my @dir_list = grep(!/^\./,readdir($dir));
10668:             map {$currfile{$_} = 1;} @dir_list;
10669:         }
10670:     } elsif (($actionurl eq '/adm/dependencies') ||
10671:              (($actionurl eq '/adm/coursedocs') && (ref($args) eq 'HASH') &&
10672:               ($args->{'context'} eq 'paste')) ||
10673:              ($actionurl eq "/public/$cdom/$cnum/syllabus")) {
10674:         if ($env{'request.course.id'} ne '') {
10675:             my ($dir) = ($fileloc =~ m{^(.+/)[^/]+$});
10676:             if ($dir ne '') {
10677:                 my ($dirlistref,$listerror) =
10678:                     &Apache::lonnet::dirlist($dir,$cdom,$cnum,$getpropath,undef,'/');
10679:                 if (ref($dirlistref) eq 'ARRAY') {
10680:                     foreach my $line (@{$dirlistref}) {
10681:                         my ($file_name,$dom,undef,$testdir,undef,undef,undef,undef,
10682:                             $size,undef,$mtime)=split(/\&/,$line,12);
10683:                         unless (($testdir&$dirptr) ||
10684:                                 ($file_name =~ /^\.\.?$/)) {
10685:                             $currfile{$file_name} = [$size,$mtime];
10686:                         }
10687:                     }
10688:                 }
10689:             }
10690:         }
10691:     }
10692:     foreach my $file (keys(%dependencies)) {
10693:         if (exists($currfile{$file})) {
10694:             unless ($mapping{$file} eq $file) {
10695:                 $pathchanges{$file} = 1;
10696:             }
10697:             $existing{$file} = 1;
10698:             $numexisting ++;
10699:         } else {
10700:             $newfiles{$file} = 1;
10701:         }
10702:     }
10703:     foreach my $file (keys(%currfile)) {
10704:         unless (($file eq $filename) ||
10705:                 ($file eq $filename.'.bak') ||
10706:                 ($dependencies{$file})) {
10707:             if ($actionurl eq '/adm/dependencies') {
10708:                 unless ($toplevel =~ m{^\Q/uploaded/$cdom/$cnum/portfolio/syllabus\E}) {
10709:                     next if (($rem ne '') &&
10710:                              (($env{"httpref.$rem".$file} ne '') ||
10711:                               (ref($navmap) &&
10712:                               (($navmap->getResourceByUrl($rem.$file) ne '') ||
10713:                                (($file =~ /^(.*\.s?html?)\.bak$/i) &&
10714:                                 ($navmap->getResourceByUrl($rem.$1)))))));
10715:                 }
10716:             }
10717:             $unused{$file} = 1;
10718:         }
10719:     }
10720:     if (($actionurl eq '/adm/coursedocs') && (ref($args) eq 'HASH') &&
10721:         ($args->{'context'} eq 'paste')) {
10722:         $counter = scalar(keys(%existing));
10723:         $numpathchg = scalar(keys(%pathchanges));
10724:         return ($output,$counter,$numpathchg,\%existing);
10725:     } elsif (($actionurl eq "/public/$cdom/$cnum/syllabus") &&
10726:              (ref($args) eq 'HASH') && ($args->{'context'} eq 'rewrites')) {
10727:         $counter = scalar(keys(%existing));
10728:         $numpathchg = scalar(keys(%pathchanges));
10729:         return ($output,$counter,$numpathchg,\%existing,\%mapping);
10730:     }
10731:     foreach my $embed_file (sort {lc($a) cmp lc($b)} keys(%newfiles)) {
10732:         if ($actionurl eq '/adm/dependencies') {
10733:             next if ($embed_file =~ m{^\w+://});
10734:         }
10735:         $upload_output .= &start_data_table_row().
10736:                           '<td valign="top"><img src="'.&icon($embed_file).'" />&nbsp;'.
10737:                           '<span class="LC_filename">'.$embed_file.'</span>';
10738:         unless ($mapping{$embed_file} eq $embed_file) {
10739:             $upload_output .= '<br /><span class="LC_info" style="font-size:smaller;">'.
10740:                               &mt('changed from: [_1]',$mapping{$embed_file}).'</span>';
10741:         }
10742:         $upload_output .= '</td>';
10743:         if ($args->{'ignore_remote_references'} && $embed_file =~ m{^\w+://}) { 
10744:             $upload_output.='<td align="right">'.
10745:                             '<span class="LC_info LC_fontsize_medium">'.
10746:                             &mt("URL points to web address").'</span>';
10747:             $numremref++;
10748:         } elsif ($args->{'error_on_invalid_names'}
10749:             && $embed_file ne &Apache::lonnet::clean_filename($embed_file,{'keep_path' => 1,})) {
10750:             $upload_output.='<td align="right"><span class="LC_warning">'.
10751:                             &mt('Invalid characters').'</span>';
10752:             $numinvalid++;
10753:         } else {
10754:             $upload_output .= '<td>'.
10755:                               &embedded_file_element('upload_embedded',$counter,
10756:                                                      $embed_file,\%mapping,
10757:                                                      $allfiles,$codebase,'upload');
10758:             $counter ++;
10759:             $numnew ++;
10760:         }
10761:         $upload_output .= '</td>'.&Apache::loncommon::end_data_table_row()."\n";
10762:     }
10763:     foreach my $embed_file (sort {lc($a) cmp lc($b)} keys(%existing)) {
10764:         if ($actionurl eq '/adm/dependencies') {
10765:             my ($size,$mtime) = &get_dependency_details(\%currfile,\%currsubfile,$embed_file);
10766:             $modify_output .= &start_data_table_row().
10767:                               '<td><a href="'.$path.'/'.$embed_file.'" style="text-decoration:none;">'.
10768:                               '<img src="'.&icon($embed_file).'" border="0" />'.
10769:                               '&nbsp;<span class="LC_filename">'.$embed_file.'</span></a></td>'.
10770:                               '<td>'.$size.'</td>'.
10771:                               '<td>'.$mtime.'</td>'.
10772:                               '<td><label><input type="checkbox" name="mod_upload_dep" '.
10773:                               'onclick="toggleBrowse('."'$counter'".')" id="mod_upload_dep_'.
10774:                               $counter.'" value="'.$counter.'" />'.&mt('Yes').'</label>'.
10775:                               '<div id="moduploaddep_'.$counter.'" style="display:none;">'.
10776:                               &embedded_file_element('upload_embedded',$counter,
10777:                                                      $embed_file,\%mapping,
10778:                                                      $allfiles,$codebase,'modify').
10779:                               '</div></td>'.
10780:                               &end_data_table_row()."\n";
10781:             $counter ++;
10782:         } else {
10783:             $upload_output .= &start_data_table_row().
10784:                               '<td valign="top"><img src="'.&icon($embed_file).'" />&nbsp;'.
10785:                               '<span class="LC_filename">'.$embed_file.'</span></td>'.
10786:                               '<td align="right"><span class="LC_info LC_fontsize_medium">'.&mt('Already exists').'</span></td>'.
10787:                               &Apache::loncommon::end_data_table_row()."\n";
10788:         }
10789:     }
10790:     my $delidx = $counter;
10791:     foreach my $oldfile (sort {lc($a) cmp lc($b)} keys(%unused)) {
10792:         my ($size,$mtime) = &get_dependency_details(\%currfile,\%currsubfile,$oldfile);
10793:         $delete_output .= &start_data_table_row().
10794:                           '<td><img src="'.&icon($oldfile).'" />'.
10795:                           '&nbsp;<span class="LC_filename">'.$oldfile.'</span></td>'.
10796:                           '<td>'.$size.'</td>'.
10797:                           '<td>'.$mtime.'</td>'.
10798:                           '<td><label><input type="checkbox" name="del_upload_dep" '.
10799:                           ' value="'.$delidx.'" />'.&mt('Yes').'</label>'.
10800:                           &embedded_file_element('upload_embedded',$delidx,
10801:                                                  $oldfile,\%mapping,$allfiles,
10802:                                                  $codebase,'delete').'</td>'.
10803:                           &end_data_table_row()."\n"; 
10804:         $numunused ++;
10805:         $delidx ++;
10806:     }
10807:     if ($upload_output) {
10808:         $upload_output = &start_data_table().
10809:                          $upload_output.
10810:                          &end_data_table()."\n";
10811:     }
10812:     if ($modify_output) {
10813:         $modify_output = &start_data_table().
10814:                          &start_data_table_header_row().
10815:                          '<th>'.&mt('File').'</th>'.
10816:                          '<th>'.&mt('Size (KB)').'</th>'.
10817:                          '<th>'.&mt('Modified').'</th>'.
10818:                          '<th>'.&mt('Upload replacement?').'</th>'.
10819:                          &end_data_table_header_row().
10820:                          $modify_output.
10821:                          &end_data_table()."\n";
10822:     }
10823:     if ($delete_output) {
10824:         $delete_output = &start_data_table().
10825:                          &start_data_table_header_row().
10826:                          '<th>'.&mt('File').'</th>'.
10827:                          '<th>'.&mt('Size (KB)').'</th>'.
10828:                          '<th>'.&mt('Modified').'</th>'.
10829:                          '<th>'.&mt('Delete?').'</th>'.
10830:                          &end_data_table_header_row().
10831:                          $delete_output.
10832:                          &end_data_table()."\n";
10833:     }
10834:     my $applies = 0;
10835:     if ($numremref) {
10836:         $applies ++;
10837:     }
10838:     if ($numinvalid) {
10839:         $applies ++;
10840:     }
10841:     if ($numexisting) {
10842:         $applies ++;
10843:     }
10844:     if ($counter || $numunused) {
10845:         $output = '<form name="upload_embedded" action="'.$actionurl.'"'.
10846:                   ' method="post" enctype="multipart/form-data">'."\n".
10847:                   $state.'<h3>'.$heading.'</h3>'; 
10848:         if ($actionurl eq '/adm/dependencies') {
10849:             if ($numnew) {
10850:                 $output .= '<h4>'.&mt('Missing dependencies').'</h4>'.
10851:                            '<p>'.&mt('The following files need to be uploaded.').'</p>'."\n".
10852:                            $upload_output.'<br />'."\n";
10853:             }
10854:             if ($numexisting) {
10855:                 $output .= '<h4>'.&mt('Uploaded dependencies (in use)').'</h4>'.
10856:                            '<p>'.&mt('Upload a new file to replace the one currently in use.').'</p>'."\n".
10857:                            $modify_output.'<br />'."\n";
10858:                            $buttontext = &mt('Save changes');
10859:             }
10860:             if ($numunused) {
10861:                 $output .= '<h4>'.&mt('Unused files').'</h4>'.
10862:                            '<p>'.&mt('The following uploaded files are no longer used.').'</p>'."\n".
10863:                            $delete_output.'<br />'."\n";
10864:                            $buttontext = &mt('Save changes');
10865:             }
10866:         } else {
10867:             $output .= $upload_output.'<br />'."\n";
10868:         }
10869:         $output .= '<input type ="hidden" name="number_embedded_items" value="'.
10870:                    $counter.'" />'."\n";
10871:         if ($actionurl eq '/adm/dependencies') { 
10872:             $output .= '<input type ="hidden" name="number_newemb_items" value="'.
10873:                        $numnew.'" />'."\n";
10874:         } elsif ($actionurl eq '') {
10875:             $output .=  '<input type="hidden" name="phase" value="three" />';
10876:         }
10877:     } elsif ($applies) {
10878:         $output = '<b>'.&mt('Referenced files').'</b>:<br />';
10879:         if ($applies > 1) {
10880:             $output .=  
10881:                 &mt('No dependencies need to be uploaded, as one of the following applies to each reference:').'<ul>';
10882:             if ($numremref) {
10883:                 $output .= '<li>'.&mt('reference is to a URL which points to another server').'</li>'."\n";
10884:             }
10885:             if ($numinvalid) {
10886:                 $output .= '<li>'.&mt('reference is to file with a name containing invalid characters').'</li>'."\n";
10887:             }
10888:             if ($numexisting) {
10889:                 $output .= '<li>'.&mt('reference is to an existing file at the specified location').'</li>'."\n";
10890:             }
10891:             $output .= '</ul><br />';
10892:         } elsif ($numremref) {
10893:             $output .= '<p>'.&mt('None to upload, as all references are to URLs pointing to another server.').'</p>';
10894:         } elsif ($numinvalid) {
10895:             $output .= '<p>'.&mt('None to upload, as all references are to files with names containing invalid characters.').'</p>';
10896:         } elsif ($numexisting) {
10897:             $output .= '<p>'.&mt('None to upload, as all references are to existing files.').'</p>';
10898:         }
10899:         $output .= $upload_output.'<br />';
10900:     }
10901:     my ($pathchange_output,$chgcount);
10902:     $chgcount = $counter;
10903:     if (keys(%pathchanges) > 0) {
10904:         foreach my $embed_file (sort {lc($a) cmp lc($b)} keys(%pathchanges)) {
10905:             if ($counter) {
10906:                 $output .= &embedded_file_element('pathchange',$chgcount,
10907:                                                   $embed_file,\%mapping,
10908:                                                   $allfiles,$codebase,'change');
10909:             } else {
10910:                 $pathchange_output .= 
10911:                     &start_data_table_row().
10912:                     '<td><input type ="checkbox" name="namechange" value="'.
10913:                     $chgcount.'" checked="checked" /></td>'.
10914:                     '<td>'.$mapping{$embed_file}.'</td>'.
10915:                     '<td>'.$embed_file.
10916:                     &embedded_file_element('pathchange',$numpathchg,$embed_file,
10917:                                            \%mapping,$allfiles,$codebase,'change').
10918:                     '</td>'.&end_data_table_row();
10919:             }
10920:             $numpathchg ++;
10921:             $chgcount ++;
10922:         }
10923:     }
10924:     if (($counter) || ($numunused)) {
10925:         if ($numpathchg) {
10926:             $output .= '<input type ="hidden" name="number_pathchange_items" value="'.
10927:                        $numpathchg.'" />'."\n";
10928:         }
10929:         if (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank') || 
10930:             ($actionurl eq '/adm/imsimport')) {
10931:             $output .= '<input type="hidden" name="phase" value="three" />'."\n";
10932:         } elsif ($actionurl eq '/adm/portfolio' || $actionurl eq '/adm/coursegrp_portfolio') {
10933:             $output .= '<input type="hidden" name="action" value="upload_embedded" />';
10934:         } elsif ($actionurl eq '/adm/dependencies') {
10935:             $output .= '<input type="hidden" name="action" value="process_changes" />';
10936:         }
10937:         $output .= '<input type ="submit" value="'.$buttontext.'" />'."\n".'</form>'."\n";
10938:     } elsif ($numpathchg) {
10939:         my %pathchange = ();
10940:         $output .= &modify_html_form('pathchange',$actionurl,$state,\%pathchange,$pathchange_output);
10941:         if (($actionurl eq '/adm/portfolio') || ($actionurl eq '/adm/coursegrp_portfolio')) {
10942:             $output .= '<p>'.&mt('or').'</p>'; 
10943:         }
10944:     }
10945:     return ($output,$counter,$numpathchg);
10946: }
10947: 
10948: =pod
10949: 
10950: =item * clean_path($name)
10951: 
10952: Performs clean-up of directories, subdirectories and filename in an
10953: embedded object, referenced in an HTML file which is being uploaded
10954: to a course or portfolio, where
10955: "Upload embedded images/multimedia files if HTML file" checkbox was
10956: checked.
10957: 
10958: Clean-up is similar to replacements in lonnet::clean_filename()
10959: except each / between sub-directory and next level is preserved.
10960: 
10961: =cut
10962: 
10963: sub clean_path {
10964:     my ($embed_file) = @_;
10965:     $embed_file =~s{^/+}{};
10966:     my @contents;
10967:     if ($embed_file =~ m{/}) {
10968:         @contents = split(/\//,$embed_file);
10969:     } else {
10970:         @contents = ($embed_file);
10971:     }
10972:     my $lastidx = scalar(@contents)-1;
10973:     for (my $i=0; $i<=$lastidx; $i++) {
10974:         $contents[$i]=~s{\\}{/}g;
10975:         $contents[$i]=~s/\s+/\_/g;
10976:         $contents[$i]=~s{[^/\w\.\-]}{}g;
10977:         if ($i == $lastidx) {
10978:             $contents[$i]=~s/\.(\d+)(?=\.)/_$1/g;
10979:         }
10980:     }
10981:     if ($lastidx > 0) {
10982:         return join('/',@contents);
10983:     } else {
10984:         return $contents[0];
10985:     }
10986: }
10987: 
10988: sub embedded_file_element {
10989:     my ($context,$num,$embed_file,$mapping,$allfiles,$codebase,$type) = @_;
10990:     return unless ((ref($mapping) eq 'HASH') && (ref($allfiles) eq 'HASH') &&
10991:                    (ref($codebase) eq 'HASH'));
10992:     my $output;
10993:     if (($context eq 'upload_embedded') && ($type ne 'delete')) {
10994:        $output = '<input name="embedded_item_'.$num.'" type="file" value="" />'."\n";
10995:     }
10996:     $output .= '<input name="embedded_orig_'.$num.'" type="hidden" value="'.
10997:                &escape($embed_file).'" />';
10998:     unless (($context eq 'upload_embedded') && 
10999:             ($mapping->{$embed_file} eq $embed_file)) {
11000:         $output .='
11001:         <input name="embedded_ref_'.$num.'" type="hidden" value="'.&escape($mapping->{$embed_file}).'" />';
11002:     }
11003:     my $attrib;
11004:     if (ref($allfiles->{$mapping->{$embed_file}}) eq 'ARRAY') {
11005:         $attrib = &escape(join(':',@{$allfiles->{$mapping->{$embed_file}}}));
11006:     }
11007:     $output .=
11008:         "\n\t\t".
11009:         '<input name="embedded_attrib_'.$num.'" type="hidden" value="'.
11010:         $attrib.'" />';
11011:     if (exists($codebase->{$mapping->{$embed_file}})) {
11012:         $output .=
11013:             "\n\t\t".
11014:             '<input name="codebase_'.$num.'" type="hidden" value="'.
11015:             &escape($codebase->{$mapping->{$embed_file}}).'" />';
11016:     }
11017:     return $output;
11018: }
11019: 
11020: sub get_dependency_details {
11021:     my ($currfile,$currsubfile,$embed_file) = @_;
11022:     my ($size,$mtime,$showsize,$showmtime);
11023:     if ((ref($currfile) eq 'HASH') && (ref($currsubfile))) {
11024:         if ($embed_file =~ m{/}) {
11025:             my ($path,$fname) = split(/\//,$embed_file);
11026:             if (ref($currsubfile->{$path}{$fname}) eq 'ARRAY') {
11027:                 ($size,$mtime) = @{$currsubfile->{$path}{$fname}};
11028:             }
11029:         } else {
11030:             if (ref($currfile->{$embed_file}) eq 'ARRAY') {
11031:                 ($size,$mtime) = @{$currfile->{$embed_file}};
11032:             }
11033:         }
11034:         $showsize = $size/1024.0;
11035:         $showsize = sprintf("%.1f",$showsize);
11036:         if ($mtime > 0) {
11037:             $showmtime = &Apache::lonlocal::locallocaltime($mtime);
11038:         }
11039:     }
11040:     return ($showsize,$showmtime);
11041: }
11042: 
11043: sub ask_embedded_js {
11044:     return <<"END";
11045: <script type="text/javascript"">
11046: // <![CDATA[
11047: function toggleBrowse(counter) {
11048:     var chkboxid = document.getElementById('mod_upload_dep_'+counter);
11049:     var fileid = document.getElementById('embedded_item_'+counter);
11050:     var uploaddivid = document.getElementById('moduploaddep_'+counter);
11051:     if (chkboxid.checked == true) {
11052:         uploaddivid.style.display='block';
11053:     } else {
11054:         uploaddivid.style.display='none';
11055:         fileid.value = '';
11056:     }
11057: }
11058: // ]]>
11059: </script>
11060: 
11061: END
11062: }
11063: 
11064: sub upload_embedded {
11065:     my ($context,$dirpath,$uname,$udom,$dir_root,$url_root,$group,$disk_quota,
11066:         $current_disk_usage,$hiddenstate,$actionurl) = @_;
11067:     my (%pathchange,$output,$modifyform,$footer,$returnflag);
11068:     for (my $i=0; $i<$env{'form.number_embedded_items'}; $i++) {
11069:         next if (!exists($env{'form.embedded_item_'.$i.'.filename'}));
11070:         my $orig_uploaded_filename =
11071:             $env{'form.embedded_item_'.$i.'.filename'};
11072:         foreach my $type ('orig','ref','attrib','codebase') {
11073:             if ($env{'form.embedded_'.$type.'_'.$i} ne '') {
11074:                 $env{'form.embedded_'.$type.'_'.$i} =
11075:                     &unescape($env{'form.embedded_'.$type.'_'.$i});
11076:             }
11077:         }
11078:         my ($path,$fname) =
11079:             ($env{'form.embedded_orig_'.$i} =~ m{(.*/)([^/]*)});
11080:         # no path, whole string is fname
11081:         if (!$fname) { $fname = $env{'form.embedded_orig_'.$i} };
11082:         $fname = &Apache::lonnet::clean_filename($fname);
11083:         # See if there is anything left
11084:         next if ($fname eq '');
11085: 
11086:         # Check if file already exists as a file or directory.
11087:         my ($state,$msg);
11088:         if ($context eq 'portfolio') {
11089:             my $port_path = $dirpath;
11090:             if ($group ne '') {
11091:                 $port_path = "groups/$group/$port_path";
11092:             }
11093:             ($state,$msg) = &check_for_upload($env{'form.currentpath'}.$path,
11094:                                               $fname,$group,'embedded_item_'.$i,
11095:                                               $dir_root,$port_path,$disk_quota,
11096:                                               $current_disk_usage,$uname,$udom);
11097:             if ($state eq 'will_exceed_quota'
11098:                 || $state eq 'file_locked') {
11099:                 $output .= $msg;
11100:                 next;
11101:             }
11102:         } elsif (($context eq 'author') || ($context eq 'testbank')) {
11103:             ($state,$msg) = &check_for_existing($path,$fname,'embedded_item_'.$i);
11104:             if ($state eq 'exists') {
11105:                 $output .= $msg;
11106:                 next;
11107:             }
11108:         }
11109:         # Check if extension is valid
11110:         if (($fname =~ /\.(\w+)$/) &&
11111:             (&Apache::loncommon::fileembstyle($1) eq 'hdn')) {
11112:             $output .= &mt('Invalid file extension ([_1]) - reserved for internal use.',$1)
11113:                       .' '.&mt('Rename the file with a different extension and re-upload.').'<br />';
11114:             next;
11115:         } elsif (($fname =~ /\.(\w+)$/) &&
11116:                  (!defined(&Apache::loncommon::fileembstyle($1)))) {
11117:             $output .= &mt('Unrecognized file extension ([_1]) - rename the file with a proper extension and re-upload.',$1).'<br />';
11118:             next;
11119:         } elsif ($fname=~/\.(\d+)\.(\w+)$/) {
11120:             $output .= &mt('Filename not allowed - rename the file to remove the number immediately before the file extension([_1]) and re-upload.',$2).'<br />';
11121:             next;
11122:         }
11123:         $env{'form.embedded_item_'.$i.'.filename'}=$fname;
11124:         my $subdir = $path;
11125:         $subdir =~ s{/+$}{};
11126:         if ($context eq 'portfolio') {
11127:             my $result;
11128:             if ($state eq 'existingfile') {
11129:                 $result=
11130:                     &Apache::lonnet::userfileupload('embedded_item_'.$i,'existingfile',
11131:                                                     $dirpath.$env{'form.currentpath'}.$subdir);
11132:             } else {
11133:                 $result=
11134:                     &Apache::lonnet::userfileupload('embedded_item_'.$i,'',
11135:                                                     $dirpath.
11136:                                                     $env{'form.currentpath'}.$subdir);
11137:                 if ($result !~ m|^/uploaded/|) {
11138:                     $output .= '<span class="LC_error">'
11139:                                .&mt('An error occurred ([_1]) while trying to upload [_2] for embedded element [_3].'
11140:                                ,$result,$orig_uploaded_filename,$env{'form.embedded_orig_'.$i})
11141:                                .'</span><br />';
11142:                     next;
11143:                 } else {
11144:                     $output .= &mt('Uploaded [_1]','<span class="LC_filename">'.
11145:                                $path.$fname.'</span>').'<br />';     
11146:                 }
11147:             }
11148:         } elsif (($context eq 'coursedoc') || ($context eq 'syllabus')) {
11149:             my $extendedsubdir = $dirpath.'/'.$subdir;
11150:             $extendedsubdir =~ s{/+$}{};
11151:             my $result =
11152:                 &Apache::lonnet::userfileupload('embedded_item_'.$i,$context,$extendedsubdir);
11153:             if ($result !~ m|^/uploaded/|) {
11154:                 $output .= '<span class="LC_error">'
11155:                            .&mt('An error occurred ([_1]) while trying to upload [_2] for embedded element [_3].'
11156:                            ,$result,$orig_uploaded_filename,$env{'form.embedded_orig_'.$i})
11157:                            .'</span><br />';
11158:                     next;
11159:             } else {
11160:                 $output .= &mt('Uploaded [_1]','<span class="LC_filename">'.
11161:                            $path.$fname.'</span>').'<br />';
11162:                 if ($context eq 'syllabus') {
11163:                     &Apache::lonnet::make_public_indefinitely($result);
11164:                 }
11165:             }
11166:         } else {
11167: # Save the file
11168:             my $target = $env{'form.embedded_item_'.$i};
11169:             my $fullpath = $dir_root.$dirpath.'/'.$path;
11170:             my $dest = $fullpath.$fname;
11171:             my $url = $url_root.$dirpath.'/'.$path.$fname;
11172:             my @parts=split(/\//,"$dirpath/$path");
11173:             my $count;
11174:             my $filepath = $dir_root;
11175:             foreach my $subdir (@parts) {
11176:                 $filepath .= "/$subdir";
11177:                 if (!-e $filepath) {
11178:                     mkdir($filepath,0770);
11179:                 }
11180:             }
11181:             my $fh;
11182:             if (!open($fh,'>'.$dest)) {
11183:                 &Apache::lonnet::logthis('Failed to create '.$dest);
11184:                 $output .= '<span class="LC_error">'.
11185:                            &mt('An error occurred while trying to upload [_1] for embedded element [_2].',
11186:                                $orig_uploaded_filename,$env{'form.embedded_orig_'.$i}).
11187:                            '</span><br />';
11188:             } else {
11189:                 if (!print $fh $env{'form.embedded_item_'.$i}) {
11190:                     &Apache::lonnet::logthis('Failed to write to '.$dest);
11191:                     $output .= '<span class="LC_error">'.
11192:                               &mt('An error occurred while writing the file [_1] for embedded element [_2].',
11193:                                   $orig_uploaded_filename,$env{'form.embedded_orig_'.$i}).
11194:                               '</span><br />';
11195:                 } else {
11196:                     $output .= &mt('Uploaded [_1]','<span class="LC_filename">'.
11197:                                $url.'</span>').'<br />';
11198:                     unless ($context eq 'testbank') {
11199:                         $footer .= &mt('View embedded file: [_1]',
11200:                                        '<a href="'.$url.'">'.$fname.'</a>').'<br />';
11201:                     }
11202:                 }
11203:                 close($fh);
11204:             }
11205:         }
11206:         if ($env{'form.embedded_ref_'.$i}) {
11207:             $pathchange{$i} = 1;
11208:         }
11209:     }
11210:     if ($output) {
11211:         $output = '<p>'.$output.'</p>';
11212:     }
11213:     $output .= &modify_html_form('upload_embedded',$actionurl,$hiddenstate,\%pathchange);
11214:     $returnflag = 'ok';
11215:     my $numpathchgs = scalar(keys(%pathchange));
11216:     if ($numpathchgs > 0) {
11217:         if ($context eq 'portfolio') {
11218:             $output .= '<p>'.&mt('or').'</p>';
11219:         } elsif ($context eq 'testbank') {
11220:             $output .=  '<p>'.&mt('Or [_1]continue[_2] the testbank import without modifying the reference(s).',
11221:                                   '<a href="javascript:document.testbankForm.submit();">','</a>').'</p>';
11222:             $returnflag = 'modify_orightml';
11223:         }
11224:     }
11225:     return ($output.$footer,$returnflag,$numpathchgs);
11226: }
11227: 
11228: sub modify_html_form {
11229:     my ($context,$actionurl,$hiddenstate,$pathchange,$pathchgtable) = @_;
11230:     my $end = 0;
11231:     my $modifyform;
11232:     if ($context eq 'upload_embedded') {
11233:         return unless (ref($pathchange) eq 'HASH');
11234:         if ($env{'form.number_embedded_items'}) {
11235:             $end += $env{'form.number_embedded_items'};
11236:         }
11237:         if ($env{'form.number_pathchange_items'}) {
11238:             $end += $env{'form.number_pathchange_items'};
11239:         }
11240:         if ($end) {
11241:             for (my $i=0; $i<$end; $i++) {
11242:                 if ($i < $env{'form.number_embedded_items'}) {
11243:                     next unless($pathchange->{$i});
11244:                 }
11245:                 $modifyform .=
11246:                     &start_data_table_row().
11247:                     '<td><input type ="checkbox" name="namechange" value="'.$i.'" '.
11248:                     'checked="checked" /></td>'.
11249:                     '<td>'.$env{'form.embedded_ref_'.$i}.
11250:                     '<input type="hidden" name="embedded_ref_'.$i.'" value="'.
11251:                     &escape($env{'form.embedded_ref_'.$i}).'" />'.
11252:                     '<input type="hidden" name="embedded_codebase_'.$i.'" value="'.
11253:                     &escape($env{'form.embedded_codebase_'.$i}).'" />'.
11254:                     '<input type="hidden" name="embedded_attrib_'.$i.'" value="'.
11255:                     &escape($env{'form.embedded_attrib_'.$i}).'" /></td>'.
11256:                     '<td>'.$env{'form.embedded_orig_'.$i}.
11257:                     '<input type="hidden" name="embedded_orig_'.$i.'" value="'.
11258:                     &escape($env{'form.embedded_orig_'.$i}).'" /></td>'.
11259:                     &end_data_table_row();
11260:             }
11261:         }
11262:     } else {
11263:         $modifyform = $pathchgtable;
11264:         if (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank')) {
11265:             $hiddenstate .= '<input type="hidden" name="phase" value="four" />';
11266:         } elsif (($actionurl eq '/adm/portfolio') || ($actionurl eq '/adm/coursegrp_portfolio')) {
11267:             $hiddenstate .= '<input type="hidden" name="action" value="modify_orightml" />';
11268:         }
11269:     }
11270:     if ($modifyform) {
11271:         if ($actionurl eq '/adm/dependencies') {
11272:             $hiddenstate .= '<input type="hidden" name="action" value="modifyhrefs" />';
11273:         }
11274:         return '<h3>'.&mt('Changes in content of HTML file required').'</h3>'."\n".
11275:                '<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".
11276:                '<li>'.&mt('For consistency between the reference(s) and the location of the corresponding stored file within LON-CAPA.').'</li>'."\n".
11277:                '<li>'.&mt('To change absolute paths to relative paths, or replace directory traversal via "../" within the original reference.').'</li>'."\n".
11278:                '</ol></p>'."\n".'<p>'.
11279:                &mt('LON-CAPA can make the required changes to your HTML file.').'</p>'."\n".
11280:                '<form method="post" name="refchanger" action="'.$actionurl.'">'.
11281:                &start_data_table()."\n".
11282:                &start_data_table_header_row().
11283:                '<th>'.&mt('Change?').'</th>'.
11284:                '<th>'.&mt('Current reference').'</th>'.
11285:                '<th>'.&mt('Required reference').'</th>'.
11286:                &end_data_table_header_row()."\n".
11287:                $modifyform.
11288:                &end_data_table().'<br />'."\n".$hiddenstate.
11289:                '<input type="submit" name="pathchanges" value="'.&mt('Modify HTML file').'" />'.
11290:                '</form>'."\n";
11291:     }
11292:     return;
11293: }
11294: 
11295: sub modify_html_refs {
11296:     my ($context,$dirpath,$uname,$udom,$dir_root,$url) = @_;
11297:     my $container;
11298:     if ($context eq 'portfolio') {
11299:         $container = $env{'form.container'};
11300:     } elsif ($context eq 'coursedoc') {
11301:         $container = $env{'form.primaryurl'};
11302:     } elsif ($context eq 'manage_dependencies') {
11303:         (undef,undef,$container) = &Apache::lonnet::decode_symb($env{'form.symb'});
11304:         $container = "/$container";
11305:     } elsif ($context eq 'syllabus') {
11306:         $container = $url;
11307:     } else {
11308:         $container = $Apache::lonnet::perlvar{'lonDocRoot'}.$env{'form.filename'};
11309:     }
11310:     my (%allfiles,%codebase,$output,$content);
11311:     my @changes = &get_env_multiple('form.namechange');
11312:     unless ((@changes > 0)  || ($context eq 'syllabus')) {
11313:         if (wantarray) {
11314:             return ('',0,0); 
11315:         } else {
11316:             return;
11317:         }
11318:     }
11319:     if (($context eq 'portfolio') || ($context eq 'coursedoc') || 
11320:         ($context eq 'manage_dependencies') || ($context eq 'syllabus')) {
11321:         unless ($container =~ m{^/uploaded/\Q$udom\E/\Q$uname\E/}) {
11322:             if (wantarray) {
11323:                 return ('',0,0);
11324:             } else {
11325:                 return;
11326:             }
11327:         } 
11328:         $content = &Apache::lonnet::getfile($container);
11329:         if ($content eq '-1') {
11330:             if (wantarray) {
11331:                 return ('',0,0);
11332:             } else {
11333:                 return;
11334:             }
11335:         }
11336:     } else {
11337:         unless ($container =~ /^\Q$dir_root\E/) {
11338:             if (wantarray) {
11339:                 return ('',0,0);
11340:             } else {
11341:                 return;
11342:             }
11343:         } 
11344:         if (open(my $fh,"<$container")) {
11345:             $content = join('', <$fh>);
11346:             close($fh);
11347:         } else {
11348:             if (wantarray) {
11349:                 return ('',0,0);
11350:             } else {
11351:                 return;
11352:             }
11353:         }
11354:     }
11355:     my ($count,$codebasecount) = (0,0);
11356:     my $mm = new File::MMagic;
11357:     my $mime_type = $mm->checktype_contents($content);
11358:     if ($mime_type eq 'text/html') {
11359:         my $parse_result = 
11360:             &Apache::lonnet::extract_embedded_items($container,\%allfiles,
11361:                                                     \%codebase,\$content);
11362:         if ($parse_result eq 'ok') {
11363:             foreach my $i (@changes) {
11364:                 my $orig = &unescape($env{'form.embedded_orig_'.$i});
11365:                 my $ref = &unescape($env{'form.embedded_ref_'.$i});
11366:                 if ($allfiles{$ref}) {
11367:                     my $newname =  $orig;
11368:                     my ($attrib_regexp,$codebase);
11369:                     $attrib_regexp = &unescape($env{'form.embedded_attrib_'.$i});
11370:                     if ($attrib_regexp =~ /:/) {
11371:                         $attrib_regexp =~ s/\:/|/g;
11372:                     }
11373:                     if ($content =~ m{($attrib_regexp\s*=\s*['"]?)\Q$ref\E(['"]?)}) {
11374:                         my $numchg = ($content =~ s{($attrib_regexp\s*=\s*['"]?)\Q$ref\E(['"]?)}{$1$newname$2}gi);
11375:                         $count += $numchg;
11376:                         $allfiles{$newname} = $allfiles{$ref};
11377:                         delete($allfiles{$ref});
11378:                     }
11379:                     if ($env{'form.embedded_codebase_'.$i} ne '') {
11380:                         $codebase = &unescape($env{'form.embedded_codebase_'.$i});
11381:                         my $numchg = ($content =~ s/(codebase\s*=\s*["']?)\Q$codebase\E(["']?)/$1.$2/i); #' stupid emacs
11382:                         $codebasecount ++;
11383:                     }
11384:                 }
11385:             }
11386:             my $skiprewrites;
11387:             if ($count || $codebasecount) {
11388:                 my $saveresult;
11389:                 if (($context eq 'portfolio') || ($context eq 'coursedoc') || 
11390:                     ($context eq 'manage_dependencies') || ($context eq 'syllabus')) {
11391:                     my $url = &Apache::lonnet::store_edited_file($container,$content,$udom,$uname,\$saveresult);
11392:                     if ($url eq $container) {
11393:                         my ($fname) = ($container =~ m{/([^/]+)$});
11394:                         $output = '<p>'.&mt('Updated [quant,_1,reference] in [_2].',
11395:                                             $count,'<span class="LC_filename">'.
11396:                                             $fname.'</span>').'</p>';
11397:                     } else {
11398:                          $output = '<p class="LC_error">'.
11399:                                    &mt('Error: update failed for: [_1].',
11400:                                    '<span class="LC_filename">'.
11401:                                    $container.'</span>').'</p>';
11402:                     }
11403:                     if ($context eq 'syllabus') {
11404:                         unless ($saveresult eq 'ok') {
11405:                             $skiprewrites = 1;
11406:                         }
11407:                     }
11408:                 } else {
11409:                     if (open(my $fh,">$container")) {
11410:                         print $fh $content;
11411:                         close($fh);
11412:                         $output = '<p>'.&mt('Updated [quant,_1,reference] in [_2].',
11413:                                   $count,'<span class="LC_filename">'.
11414:                                   $container.'</span>').'</p>';
11415:                     } else {
11416:                          $output = '<p class="LC_error">'.
11417:                                    &mt('Error: could not update [_1].',
11418:                                    '<span class="LC_filename">'.
11419:                                    $container.'</span>').'</p>';
11420:                     }
11421:                 }
11422:             }
11423:             if (($context eq 'syllabus') && (!$skiprewrites)) {
11424:                 my ($actionurl,$state);
11425:                 $actionurl = "/public/$udom/$uname/syllabus";
11426:                 my ($ignore,$num,$numpathchanges,$existing,$mapping) =
11427:                     &ask_for_embedded_content($actionurl,$state,\%allfiles,
11428:                                               \%codebase,
11429:                                               {'context' => 'rewrites',
11430:                                                'ignore_remote_references' => 1,});
11431:                 if (ref($mapping) eq 'HASH') {
11432:                     my $rewrites = 0;
11433:                     foreach my $key (keys(%{$mapping})) {
11434:                         next if ($key =~ m{^https?://});
11435:                         my $ref = $mapping->{$key};
11436:                         my $newname = "/uploaded/$udom/$uname/portfolio/syllabus/$key";
11437:                         my $attrib;
11438:                         if (ref($allfiles{$mapping->{$key}}) eq 'ARRAY') {
11439:                             $attrib = join('|',@{$allfiles{$mapping->{$key}}});
11440:                         }
11441:                         if ($content =~ m{($attrib\s*=\s*['"]?)\Q$ref\E(['"]?)}) {
11442:                             my $numchg = ($content =~ s{($attrib\s*=\s*['"]?)\Q$ref\E(['"]?)}{$1$newname$2}gi);
11443:                             $rewrites += $numchg;
11444:                         }
11445:                     }
11446:                     if ($rewrites) {
11447:                         my $saveresult;
11448:                         my $url = &Apache::lonnet::store_edited_file($container,$content,$udom,$uname,\$saveresult);
11449:                         if ($url eq $container) {
11450:                             my ($fname) = ($container =~ m{/([^/]+)$});
11451:                             $output .= '<p>'.&mt('Rewrote [quant,_1,link] as [quant,_1,absolute link] in [_2].',
11452:                                             $count,'<span class="LC_filename">'.
11453:                                             $fname.'</span>').'</p>';
11454:                         } else {
11455:                             $output .= '<p class="LC_error">'.
11456:                                        &mt('Error: could not update links in [_1].',
11457:                                        '<span class="LC_filename">'.
11458:                                        $container.'</span>').'</p>';
11459: 
11460:                         }
11461:                     }
11462:                 }
11463:             }
11464:         } else {
11465:             &logthis('Failed to parse '.$container.
11466:                      ' to modify references: '.$parse_result);
11467:         }
11468:     }
11469:     if (wantarray) {
11470:         return ($output,$count,$codebasecount);
11471:     } else {
11472:         return $output;
11473:     }
11474: }
11475: 
11476: sub check_for_existing {
11477:     my ($path,$fname,$element) = @_;
11478:     my ($state,$msg);
11479:     if (-d $path.'/'.$fname) {
11480:         $state = 'exists';
11481:         $msg = &mt('Unable to upload [_1]. A directory by that name was found in [_2].','<span class="LC_filename">'.$fname.'</span>',$path);
11482:     } elsif (-e $path.'/'.$fname) {
11483:         $state = 'exists';
11484:         $msg = &mt('Unable to upload [_1]. A file by that name was found in [_2].','<span class="LC_filename">'.$fname.'</span>',$path);
11485:     }
11486:     if ($state eq 'exists') {
11487:         $msg = '<span class="LC_error">'.$msg.'</span><br />';
11488:     }
11489:     return ($state,$msg);
11490: }
11491: 
11492: sub check_for_upload {
11493:     my ($path,$fname,$group,$element,$portfolio_root,$port_path,
11494:         $disk_quota,$current_disk_usage,$uname,$udom) = @_;
11495:     my $filesize = length($env{'form.'.$element});
11496:     if (!$filesize) {
11497:         my $msg = '<span class="LC_error">'.
11498:                   &mt('Unable to upload [_1]. (size = [_2] bytes)', 
11499:                       '<span class="LC_filename">'.$fname.'</span>',
11500:                       $filesize).'<br />'.
11501:                   &mt('Either the file you attempted to upload was empty, or your web browser was unable to read its contents.').'<br />'.
11502:                   '</span>';
11503:         return ('zero_bytes',$msg);
11504:     }
11505:     $filesize =  $filesize/1000; #express in k (1024?)
11506:     my $getpropath = 1;
11507:     my ($dirlistref,$listerror) =
11508:          &Apache::lonnet::dirlist($portfolio_root.$path,$udom,$uname,$getpropath);
11509:     my $found_file = 0;
11510:     my $locked_file = 0;
11511:     my @lockers;
11512:     my $navmap;
11513:     if ($env{'request.course.id'}) {
11514:         $navmap = Apache::lonnavmaps::navmap->new();
11515:     }
11516:     if (ref($dirlistref) eq 'ARRAY') {
11517:         foreach my $line (@{$dirlistref}) {
11518:             my ($file_name,$rest)=split(/\&/,$line,2);
11519:             if ($file_name eq $fname){
11520:                 $file_name = $path.$file_name;
11521:                 if ($group ne '') {
11522:                     $file_name = $group.$file_name;
11523:                 }
11524:                 $found_file = 1;
11525:                 if (&Apache::lonnet::is_locked($file_name,$udom,$uname,\@lockers) eq 'true') {
11526:                     foreach my $lock (@lockers) {
11527:                         if (ref($lock) eq 'ARRAY') {
11528:                             my ($symb,$crsid) = @{$lock};
11529:                             if ($crsid eq $env{'request.course.id'}) {
11530:                                 if (ref($navmap)) {
11531:                                     my $res = $navmap->getBySymb($symb);
11532:                                     foreach my $part (@{$res->parts()}) { 
11533:                                         my ($slot_status,$slot_time,$slot_name)=$res->check_for_slot($part);
11534:                                         unless (($slot_status == $res->RESERVED) ||
11535:                                                 ($slot_status == $res->RESERVED_LOCATION)) {
11536:                                             $locked_file = 1;
11537:                                         }
11538:                                     }
11539:                                 } else {
11540:                                     $locked_file = 1;
11541:                                 }
11542:                             } else {
11543:                                 $locked_file = 1;
11544:                             }
11545:                         }
11546:                    }
11547:                 } else {
11548:                     my @info = split(/\&/,$rest);
11549:                     my $currsize = $info[6]/1000;
11550:                     if ($currsize < $filesize) {
11551:                         my $extra = $filesize - $currsize;
11552:                         if (($current_disk_usage + $extra) > $disk_quota) {
11553:                             my $msg = '<p class="LC_warning">'.
11554:                                       &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.',
11555:                                           '<span class="LC_filename">'.$fname.'</span>',$filesize,$currsize).'</p>'.
11556:                                       '<p>'.&mt('Disk quota is [_1] kilobytes. Your current disk usage is [_2] kilobytes.',
11557:                                                    $disk_quota,$current_disk_usage).'</p>';
11558:                             return ('will_exceed_quota',$msg);
11559:                         }
11560:                     }
11561:                 }
11562:             }
11563:         }
11564:     }
11565:     if (($current_disk_usage + $filesize) > $disk_quota){
11566:         my $msg = '<p class="LC_warning">'.
11567:                 &mt('Unable to upload [_1]. (size = [_2] kilobytes). Disk quota will be exceeded.','<span class="LC_filename">'.$fname.'</span>',$filesize).'</p>'.
11568:                   '<p>'.&mt('Disk quota is [_1] kilobytes. Your current disk usage is [_2] kilobytes.',$disk_quota,$current_disk_usage).'</p>';
11569:         return ('will_exceed_quota',$msg);
11570:     } elsif ($found_file) {
11571:         if ($locked_file) {
11572:             my $msg = '<p class="LC_warning">';
11573:             $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>');
11574:             $msg .= '</p>';
11575:             $msg .= &mt('You will be able to rename or delete existing [_1] after a grade has been assigned.','<span class="LC_filename">'.$fname.'</span>');
11576:             return ('file_locked',$msg);
11577:         } else {
11578:             my $msg = '<p class="LC_error">';
11579:             $msg .= &mt(' A file by that name: [_1] was found in [_2].','<span class="LC_filename">'.$fname.'</span>',$port_path.$env{'form.currentpath'});
11580:             $msg .= '</p>';
11581:             return ('existingfile',$msg);
11582:         }
11583:     }
11584: }
11585: 
11586: sub check_for_traversal {
11587:     my ($path,$url,$toplevel) = @_;
11588:     my @parts=split(/\//,$path);
11589:     my $cleanpath;
11590:     my $fullpath = $url;
11591:     for (my $i=0;$i<@parts;$i++) {
11592:         next if ($parts[$i] eq '.');
11593:         if ($parts[$i] eq '..') {
11594:             $fullpath =~ s{([^/]+/)$}{};
11595:         } else {
11596:             $fullpath .= $parts[$i].'/';
11597:         }
11598:     }
11599:     if ($fullpath =~ /^\Q$url\E(.*)$/) {
11600:         $cleanpath = $1;
11601:     } elsif ($fullpath =~ /^\Q$toplevel\E(.*)$/) {
11602:         my $curr_toprel = $1;
11603:         my @parts = split(/\//,$curr_toprel);
11604:         my ($url_toprel) = ($url =~ /^\Q$toplevel\E(.*)$/);
11605:         my @urlparts = split(/\//,$url_toprel);
11606:         my $doubledots;
11607:         my $startdiff = -1;
11608:         for (my $i=0; $i<@urlparts; $i++) {
11609:             if ($startdiff == -1) {
11610:                 unless ($urlparts[$i] eq $parts[$i]) {
11611:                     $startdiff = $i;
11612:                     $doubledots .= '../';
11613:                 }
11614:             } else {
11615:                 $doubledots .= '../';
11616:             }
11617:         }
11618:         if ($startdiff > -1) {
11619:             $cleanpath = $doubledots;
11620:             for (my $i=$startdiff; $i<@parts; $i++) {
11621:                 $cleanpath .= $parts[$i].'/';
11622:             }
11623:         }
11624:     }
11625:     $cleanpath =~ s{(/)$}{};
11626:     return $cleanpath;
11627: }
11628: 
11629: sub is_archive_file {
11630:     my ($mimetype) = @_;
11631:     if (($mimetype eq 'application/octet-stream') ||
11632:         ($mimetype eq 'application/x-stuffit') ||
11633:         ($mimetype =~ m{^application/(x\-)?(compressed|tar|zip|tgz|gz|gtar|gzip|gunzip|bz|bz2|bzip2)})) {
11634:         return 1;
11635:     }
11636:     return;
11637: }
11638: 
11639: sub decompress_form {
11640:     my ($mimetype,$archiveurl,$action,$noextract,$hiddenelements,$dirlist) = @_;
11641:     my %lt = &Apache::lonlocal::texthash (
11642:         this => 'This file is an archive file.',
11643:         camt => 'This file is a Camtasia archive file.',
11644:         itsc => 'Its contents are as follows:',
11645:         youm => 'You may wish to extract its contents.',
11646:         extr => 'Extract contents',
11647:         auto => 'LON-CAPA can process the files automatically, or you can decide how each should be handled.',
11648:         proa => 'Process automatically?',
11649:         yes  => 'Yes',
11650:         no   => 'No',
11651:         fold => 'Title for folder containing movie',
11652:         movi => 'Title for page containing embedded movie', 
11653:     );
11654:     my $fileloc = &Apache::lonnet::filelocation(undef,$archiveurl);
11655:     my ($is_camtasia,$topdir,%toplevel,@paths);
11656:     my $info = &list_archive_contents($fileloc,\@paths);
11657:     if (@paths) {
11658:         foreach my $path (@paths) {
11659:             $path =~ s{^/}{};
11660:             if ($path =~ m{^([^/]+)/$}) {
11661:                 $topdir = $1;
11662:             }
11663:             if ($path =~ m{^([^/]+)/}) {
11664:                 $toplevel{$1} = $path;
11665:             } else {
11666:                 $toplevel{$path} = $path;
11667:             }
11668:         }
11669:     }
11670:     if ($mimetype =~ m{^application/(x\-)?(compressed|zip)}) {
11671:         my @camtasia6 = ("$topdir/","$topdir/index.html",
11672:                         "$topdir/media/",
11673:                         "$topdir/media/$topdir.mp4",
11674:                         "$topdir/media/FirstFrame.png",
11675:                         "$topdir/media/player.swf",
11676:                         "$topdir/media/swfobject.js",
11677:                         "$topdir/media/expressInstall.swf");
11678:         my @camtasia8_1 = ("$topdir/","$topdir/$topdir.html",
11679:                          "$topdir/$topdir.mp4",
11680:                          "$topdir/$topdir\_config.xml",
11681:                          "$topdir/$topdir\_controller.swf",
11682:                          "$topdir/$topdir\_embed.css",
11683:                          "$topdir/$topdir\_First_Frame.png",
11684:                          "$topdir/$topdir\_player.html",
11685:                          "$topdir/$topdir\_Thumbnails.png",
11686:                          "$topdir/playerProductInstall.swf",
11687:                          "$topdir/scripts/",
11688:                          "$topdir/scripts/config_xml.js",
11689:                          "$topdir/scripts/handlebars.js",
11690:                          "$topdir/scripts/jquery-1.7.1.min.js",
11691:                          "$topdir/scripts/jquery-ui-1.8.15.custom.min.js",
11692:                          "$topdir/scripts/modernizr.js",
11693:                          "$topdir/scripts/player-min.js",
11694:                          "$topdir/scripts/swfobject.js",
11695:                          "$topdir/skins/",
11696:                          "$topdir/skins/configuration_express.xml",
11697:                          "$topdir/skins/express_show/",
11698:                          "$topdir/skins/express_show/player-min.css",
11699:                          "$topdir/skins/express_show/spritesheet.png");
11700:         my @camtasia8_4 = ("$topdir/","$topdir/$topdir.html",
11701:                          "$topdir/$topdir.mp4",
11702:                          "$topdir/$topdir\_config.xml",
11703:                          "$topdir/$topdir\_controller.swf",
11704:                          "$topdir/$topdir\_embed.css",
11705:                          "$topdir/$topdir\_First_Frame.png",
11706:                          "$topdir/$topdir\_player.html",
11707:                          "$topdir/$topdir\_Thumbnails.png",
11708:                          "$topdir/playerProductInstall.swf",
11709:                          "$topdir/scripts/",
11710:                          "$topdir/scripts/config_xml.js",
11711:                          "$topdir/scripts/techsmith-smart-player.min.js",
11712:                          "$topdir/skins/",
11713:                          "$topdir/skins/configuration_express.xml",
11714:                          "$topdir/skins/express_show/",
11715:                          "$topdir/skins/express_show/spritesheet.min.css",
11716:                          "$topdir/skins/express_show/spritesheet.png",
11717:                          "$topdir/skins/express_show/techsmith-smart-player.min.css");
11718:         my @diffs = &compare_arrays(\@paths,\@camtasia6);
11719:         if (@diffs == 0) {
11720:             $is_camtasia = 6;
11721:         } else {
11722:             @diffs = &compare_arrays(\@paths,\@camtasia8_1);
11723:             if (@diffs == 0) {
11724:                 $is_camtasia = 8;
11725:             } else {
11726:                 @diffs = &compare_arrays(\@paths,\@camtasia8_4);
11727:                 if (@diffs == 0) {
11728:                     $is_camtasia = 8;
11729:                 }
11730:             }
11731:         }
11732:     }
11733:     my $output;
11734:     if ($is_camtasia) {
11735:         $output = <<"ENDCAM";
11736: <script type="text/javascript" language="Javascript">
11737: // <![CDATA[
11738: 
11739: function camtasiaToggle() {
11740:     for (var i=0; i<document.uploaded_decompress.autoextract_camtasia.length; i++) {
11741:         if (document.uploaded_decompress.autoextract_camtasia[i].checked) {
11742:             if (document.uploaded_decompress.autoextract_camtasia[i].value == $is_camtasia) {
11743:                 document.getElementById('camtasia_titles').style.display='block';
11744:             } else {
11745:                 document.getElementById('camtasia_titles').style.display='none';
11746:             }
11747:         }
11748:     }
11749:     return;
11750: }
11751: 
11752: // ]]>
11753: </script>
11754: <p>$lt{'camt'}</p>
11755: ENDCAM
11756:     } else {
11757:         $output = '<p>'.$lt{'this'};
11758:         if ($info eq '') {
11759:             $output .= ' '.$lt{'youm'}.'</p>'."\n";
11760:         } else {
11761:             $output .= ' '.$lt{'itsc'}.'</p>'."\n".
11762:                        '<div><pre>'.$info.'</pre></div>';
11763:         }
11764:     }
11765:     $output .= '<form name="uploaded_decompress" action="'.$action.'" method="post">'."\n";
11766:     my $duplicates;
11767:     my $num = 0;
11768:     if (ref($dirlist) eq 'ARRAY') {
11769:         foreach my $item (@{$dirlist}) {
11770:             if (ref($item) eq 'ARRAY') {
11771:                 if (exists($toplevel{$item->[0]})) {
11772:                     $duplicates .= 
11773:                         &start_data_table_row().
11774:                         '<td><label><input type="radio" name="archive_overwrite_'.$num.'" '.
11775:                         'value="0" checked="checked" />'.&mt('No').'</label>'.
11776:                         '&nbsp;<label><input type="radio" name="archive_overwrite_'.$num.'" '.
11777:                         'value="1" />'.&mt('Yes').'</label>'.
11778:                         '<input type="hidden" name="archive_overwrite_name_'.$num.'" value="'.$item->[0].'" /></td>'."\n".
11779:                         '<td>'.$item->[0].'</td>';
11780:                     if ($item->[2]) {
11781:                         $duplicates .= '<td>'.&mt('Directory').'</td>';
11782:                     } else {
11783:                         $duplicates .= '<td>'.&mt('File').'</td>';
11784:                     }
11785:                     $duplicates .= '<td>'.$item->[3].'</td>'.
11786:                                    '<td>'.
11787:                                    &Apache::lonlocal::locallocaltime($item->[4]).
11788:                                    '</td>'.
11789:                                    &end_data_table_row();
11790:                     $num ++;
11791:                 }
11792:             }
11793:         }
11794:     }
11795:     my $itemcount;
11796:     if (@paths > 0) {
11797:         $itemcount = scalar(@paths);
11798:     } else {
11799:         $itemcount = 1;
11800:     }
11801:     if ($is_camtasia) {
11802:         $output .= $lt{'auto'}.'<br />'.
11803:                    '<span class="LC_nobreak">'.$lt{'proa'}.'<label>'.
11804:                    '<input type="radio" name="autoextract_camtasia" value="'.$is_camtasia.'" onclick="javascript:camtasiaToggle();" checked="checked" />'.
11805:                    $lt{'yes'}.'</label>&nbsp;<label>'.
11806:                    '<input type="radio" name="autoextract_camtasia" value="0" onclick="javascript:camtasiaToggle();" />'.
11807:                    $lt{'no'}.'</label></span><br />'.
11808:                    '<div id="camtasia_titles" style="display:block">'.
11809:                    &Apache::lonhtmlcommon::start_pick_box().
11810:                    &Apache::lonhtmlcommon::row_title($lt{'fold'}).
11811:                    '<input type="textbox" name="camtasia_foldername" value="'.$env{'form.comment'}.'" />'."\n".
11812:                    &Apache::lonhtmlcommon::row_closure().
11813:                    &Apache::lonhtmlcommon::row_title($lt{'movi'}).
11814:                    '<input type="textbox" name="camtasia_moviename" value="" />'."\n".
11815:                    &Apache::lonhtmlcommon::row_closure(1).
11816:                    &Apache::lonhtmlcommon::end_pick_box().
11817:                    '</div>';
11818:     }
11819:     $output .= 
11820:         '<input type="hidden" name="archive_overwrite_total" value="'.$num.'" />'.
11821:         '<input type="hidden" name="archive_itemcount" value="'.$itemcount.'" />'.
11822:         "\n";
11823:     if ($duplicates ne '') {
11824:         $output .= '<p><span class="LC_warning">'.
11825:                    &mt('Warning: decompression of the archive will overwrite the following items which already exist:').'</span><br />'.  
11826:                    &start_data_table().
11827:                    &start_data_table_header_row().
11828:                    '<th>'.&mt('Overwrite?').'</th>'.
11829:                    '<th>'.&mt('Name').'</th>'.
11830:                    '<th>'.&mt('Type').'</th>'.
11831:                    '<th>'.&mt('Size').'</th>'.
11832:                    '<th>'.&mt('Last modified').'</th>'.
11833:                    &end_data_table_header_row().
11834:                    $duplicates.
11835:                    &end_data_table().
11836:                    '</p>';
11837:     }
11838:     $output .= '<input type="hidden" name="archiveurl" value="'.$archiveurl.'" />'."\n";
11839:     if (ref($hiddenelements) eq 'HASH') {
11840:         foreach my $hidden (sort(keys(%{$hiddenelements}))) {
11841:             $output .= '<input type="hidden" name="'.$hidden.'" value="'.$hiddenelements->{$hidden}.'" />'."\n";
11842:         }
11843:     }
11844:     $output .= <<"END";
11845: <br />
11846: <input type="submit" name="decompress" value="$lt{'extr'}" />
11847: </form>
11848: $noextract
11849: END
11850:     return $output;
11851: }
11852: 
11853: sub decompression_utility {
11854:     my ($program) = @_;
11855:     my @utilities = ('tar','gunzip','bunzip2','unzip'); 
11856:     my $location;
11857:     if (grep(/^\Q$program\E$/,@utilities)) { 
11858:         foreach my $dir ('/bin/','/usr/bin/','/usr/local/bin/','/sbin/',
11859:                          '/usr/sbin/') {
11860:             if (-x $dir.$program) {
11861:                 $location = $dir.$program;
11862:                 last;
11863:             }
11864:         }
11865:     }
11866:     return $location;
11867: }
11868: 
11869: sub list_archive_contents {
11870:     my ($file,$pathsref) = @_;
11871:     my (@cmd,$output);
11872:     my $needsregexp;
11873:     if ($file =~ /\.zip$/) {
11874:         @cmd = (&decompression_utility('unzip'),"-l");
11875:         $needsregexp = 1;
11876:     } elsif (($file =~ m/\.tar\.gz$/) ||
11877:              ($file =~ /\.tgz$/)) {
11878:         @cmd = (&decompression_utility('tar'),"-ztf");
11879:     } elsif ($file =~ /\.tar\.bz2$/) {
11880:         @cmd = (&decompression_utility('tar'),"-jtf");
11881:     } elsif ($file =~ m|\.tar$|) {
11882:         @cmd = (&decompression_utility('tar'),"-tf");
11883:     }
11884:     if (@cmd) {
11885:         undef($!);
11886:         undef($@);
11887:         if (open(my $fh,"-|", @cmd, $file)) {
11888:             while (my $line = <$fh>) {
11889:                 $output .= $line;
11890:                 chomp($line);
11891:                 my $item;
11892:                 if ($needsregexp) {
11893:                     ($item) = ($line =~ /^\s*\d+\s+[\d\-]+\s+[\d:]+\s*(.+)$/); 
11894:                 } else {
11895:                     $item = $line;
11896:                 }
11897:                 if ($item ne '') {
11898:                     unless (grep(/^\Q$item\E$/,@{$pathsref})) {
11899:                         push(@{$pathsref},$item);
11900:                     } 
11901:                 }
11902:             }
11903:             close($fh);
11904:         }
11905:     }
11906:     return $output;
11907: }
11908: 
11909: sub decompress_uploaded_file {
11910:     my ($file,$dir) = @_;
11911:     &Apache::lonnet::appenv({'cgi.file' => $file});
11912:     &Apache::lonnet::appenv({'cgi.dir' => $dir});
11913:     my $result = &Apache::lonnet::ssi_body('/cgi-bin/decompress.pl');
11914:     my ($handle) = ($env{'user.environment'} =~m{/([^/]+)\.id$});
11915:     my $lonidsdir = $Apache::lonnet::perlvar{'lonIDsDir'};
11916:     &Apache::lonnet::transfer_profile_to_env($lonidsdir,$handle,1);
11917:     my $decompressed = $env{'cgi.decompressed'};
11918:     &Apache::lonnet::delenv('cgi.file');
11919:     &Apache::lonnet::delenv('cgi.dir');
11920:     &Apache::lonnet::delenv('cgi.decompressed');
11921:     return ($decompressed,$result);
11922: }
11923: 
11924: sub process_decompression {
11925:     my ($docudom,$docuname,$file,$destination,$dir_root,$hiddenelem) = @_;
11926:     my ($dir,$error,$warning,$output);
11927:     if ($file !~ /\.(zip|tar|bz2|gz|tar.gz|tar.bz2|tgz)$/i) {
11928:         $error = &mt('Filename not a supported archive file type.').
11929:                  '<br />'.&mt('Filename should end with one of: [_1].',
11930:                               '.zip, .tar, .bz2, .gz, .tar.gz, .tar.bz2, .tgz');
11931:     } else {
11932:         my $docuhome = &Apache::lonnet::homeserver($docuname,$docudom);
11933:         if ($docuhome eq 'no_host') {
11934:             $error = &mt('Could not determine home server for course.');
11935:         } else {
11936:             my @ids=&Apache::lonnet::current_machine_ids();
11937:             my $currdir = "$dir_root/$destination";
11938:             if (grep(/^\Q$docuhome\E$/,@ids)) {
11939:                 $dir = &LONCAPA::propath($docudom,$docuname).
11940:                        "$dir_root/$destination";
11941:             } else {
11942:                 $dir = $Apache::lonnet::perlvar{'lonDocRoot'}.
11943:                        "$dir_root/$docudom/$docuname/$destination";
11944:                 unless (&Apache::lonnet::repcopy_userfile("$dir/$file") eq 'ok') {
11945:                     $error = &mt('Archive file not found.');
11946:                 }
11947:             }
11948:             my (@to_overwrite,@to_skip);
11949:             if ($env{'form.archive_overwrite_total'} > 0) {
11950:                 my $total = $env{'form.archive_overwrite_total'};
11951:                 for (my $i=0; $i<$total; $i++) {
11952:                     if ($env{'form.archive_overwrite_'.$i} == 1) {
11953:                         push(@to_overwrite,$env{'form.archive_overwrite_name_'.$i});
11954:                     } elsif ($env{'form.archive_overwrite_'.$i} == 0) {
11955:                         push(@to_skip,$env{'form.archive_overwrite_name_'.$i});
11956:                     }
11957:                 }
11958:             }
11959:             my $numskip = scalar(@to_skip);
11960:             if (($numskip > 0) && 
11961:                 ($numskip == $env{'form.archive_itemcount'})) {
11962:                 $warning = &mt('All items in the archive file already exist, and no overwriting of existing files has been requested.');         
11963:             } elsif ($dir eq '') {
11964:                 $error = &mt('Directory containing archive file unavailable.');
11965:             } elsif (!$error) {
11966:                 my ($decompressed,$display);
11967:                 if ($numskip > 0) {
11968:                     my $tempdir = time.'_'.$$.int(rand(10000));
11969:                     mkdir("$dir/$tempdir",0755);
11970:                     system("mv $dir/$file $dir/$tempdir/$file");
11971:                     ($decompressed,$display) = 
11972:                         &decompress_uploaded_file($file,"$dir/$tempdir");
11973:                     foreach my $item (@to_skip) {
11974:                         if (($item ne '') && ($item !~ /\.\./)) {
11975:                             if (-f "$dir/$tempdir/$item") { 
11976:                                 unlink("$dir/$tempdir/$item");
11977:                             } elsif (-d "$dir/$tempdir/$item") {
11978:                                 system("rm -rf $dir/$tempdir/$item");
11979:                             }
11980:                         }
11981:                     }
11982:                     system("mv $dir/$tempdir/* $dir");
11983:                     rmdir("$dir/$tempdir");   
11984:                 } else {
11985:                     ($decompressed,$display) = 
11986:                         &decompress_uploaded_file($file,$dir);
11987:                 }
11988:                 if ($decompressed eq 'ok') {
11989:                     $output = '<p class="LC_info">'.
11990:                               &mt('Files extracted successfully from archive.').
11991:                               '</p>'."\n";
11992:                     my ($warning,$result,@contents);
11993:                     my ($newdirlistref,$newlisterror) =
11994:                         &Apache::lonnet::dirlist($currdir,$docudom,
11995:                                                  $docuname,1);
11996:                     my (%is_dir,%changes,@newitems);
11997:                     my $dirptr = 16384;
11998:                     if (ref($newdirlistref) eq 'ARRAY') {
11999:                         foreach my $dir_line (@{$newdirlistref}) {
12000:                             my ($item,undef,undef,$testdir)=split(/\&/,$dir_line,5);
12001:                             unless (($item =~ /^\.+$/) || ($item eq $file) || 
12002:                                     ((@to_skip > 0) && (grep(/^\Q$item\E$/,@to_skip)))) {
12003:                                 push(@newitems,$item);
12004:                                 if ($dirptr&$testdir) {
12005:                                     $is_dir{$item} = 1;
12006:                                 }
12007:                                 $changes{$item} = 1;
12008:                             }
12009:                         }
12010:                     }
12011:                     if (keys(%changes) > 0) {
12012:                         foreach my $item (sort(@newitems)) {
12013:                             if ($changes{$item}) {
12014:                                 push(@contents,$item);
12015:                             }
12016:                         }
12017:                     }
12018:                     if (@contents > 0) {
12019:                         my $wantform;
12020:                         unless ($env{'form.autoextract_camtasia'}) {
12021:                             $wantform = 1;
12022:                         }
12023:                         my (%children,%parent,%dirorder,%titles);
12024:                         my ($count,$datatable) = &get_extracted($docudom,$docuname,
12025:                                                                 $currdir,\%is_dir,
12026:                                                                 \%children,\%parent,
12027:                                                                 \@contents,\%dirorder,
12028:                                                                 \%titles,$wantform);
12029:                         if ($datatable ne '') {
12030:                             $output .= &archive_options_form('decompressed',$datatable,
12031:                                                              $count,$hiddenelem);
12032:                             my $startcount = 6;
12033:                             $output .= &archive_javascript($startcount,$count,
12034:                                                            \%titles,\%children);
12035:                         }
12036:                         if ($env{'form.autoextract_camtasia'}) {
12037:                             my $version = $env{'form.autoextract_camtasia'};
12038:                             my %displayed;
12039:                             my $total = 1;
12040:                             $env{'form.archive_directory'} = [];
12041:                             foreach my $i (sort { $a <=> $b } keys(%dirorder)) {
12042:                                 my $path = join('/',map { $titles{$_}; } @{$dirorder{$i}});
12043:                                 $path =~ s{/$}{};
12044:                                 my $item;
12045:                                 if ($path ne '') {
12046:                                     $item = "$path/$titles{$i}";
12047:                                 } else {
12048:                                     $item = $titles{$i};
12049:                                 }
12050:                                 $env{'form.archive_content_'.$i} = "$dir_root/$destination/$item";
12051:                                 if ($item eq $contents[0]) {
12052:                                     push(@{$env{'form.archive_directory'}},$i);
12053:                                     $env{'form.archive_'.$i} = 'display';
12054:                                     $env{'form.archive_title_'.$i} = $env{'form.camtasia_foldername'};
12055:                                     $displayed{'folder'} = $i;
12056:                                 } elsif ((($item eq "$contents[0]/index.html") && ($version == 6)) ||
12057:                                          (($item eq "$contents[0]/$contents[0]".'.html') && ($version == 8))) {
12058:                                     $env{'form.archive_'.$i} = 'display';
12059:                                     $env{'form.archive_title_'.$i} = $env{'form.camtasia_moviename'};
12060:                                     $displayed{'web'} = $i;
12061:                                 } else {
12062:                                     if ((($item eq "$contents[0]/media") && ($version == 6)) ||
12063:                                         ((($item eq "$contents[0]/scripts") || ($item eq "$contents[0]/skins") ||
12064:                                              ($item eq "$contents[0]/skins/express_show")) && ($version == 8))) {
12065:                                         push(@{$env{'form.archive_directory'}},$i);
12066:                                     }
12067:                                     $env{'form.archive_'.$i} = 'dependency';
12068:                                 }
12069:                                 $total ++;
12070:                             }
12071:                             for (my $i=1; $i<$total; $i++) {
12072:                                 next if ($i == $displayed{'web'});
12073:                                 next if ($i == $displayed{'folder'});
12074:                                 $env{'form.archive_dependent_on_'.$i} = $displayed{'web'};
12075:                             }
12076:                             $env{'form.phase'} = 'decompress_cleanup';
12077:                             $env{'form.archivedelete'} = 1;
12078:                             $env{'form.archive_count'} = $total-1;
12079:                             $output .=
12080:                                 &process_extracted_files('coursedocs',$docudom,
12081:                                                          $docuname,$destination,
12082:                                                          $dir_root,$hiddenelem);
12083:                         }
12084:                     } else {
12085:                         $warning = &mt('No new items extracted from archive file.');
12086:                     }
12087:                 } else {
12088:                     $output = $display;
12089:                     $error = &mt('An error occurred during extraction from the archive file.');
12090:                 }
12091:             }
12092:         }
12093:     }
12094:     if ($error) {
12095:         $output .= '<p class="LC_error">'.&mt('Not extracted.').'<br />'.
12096:                    $error.'</p>'."\n";
12097:     }
12098:     if ($warning) {
12099:         $output .= '<p class="LC_warning">'.$warning.'</p>'."\n";
12100:     }
12101:     return $output;
12102: }
12103: 
12104: sub get_extracted {
12105:     my ($docudom,$docuname,$currdir,$is_dir,$children,$parent,$contents,$dirorder,
12106:         $titles,$wantform) = @_;
12107:     my $count = 0;
12108:     my $depth = 0;
12109:     my $datatable;
12110:     my @hierarchy;
12111:     return unless ((ref($is_dir) eq 'HASH') && (ref($children) eq 'HASH') &&
12112:                    (ref($parent) eq 'HASH') && (ref($contents) eq 'ARRAY') &&
12113:                    (ref($dirorder) eq 'HASH') && (ref($titles) eq 'HASH'));
12114:     foreach my $item (@{$contents}) {
12115:         $count ++;
12116:         @{$dirorder->{$count}} = @hierarchy;
12117:         $titles->{$count} = $item;
12118:         &archive_hierarchy($depth,$count,$parent,$children);
12119:         if ($wantform) {
12120:             $datatable .= &archive_row($is_dir->{$item},$item,
12121:                                        $currdir,$depth,$count);
12122:         }
12123:         if ($is_dir->{$item}) {
12124:             $depth ++;
12125:             push(@hierarchy,$count);
12126:             $parent->{$depth} = $count;
12127:             $datatable .=
12128:                 &recurse_extracted_archive("$currdir/$item",$docudom,$docuname,
12129:                                            \$depth,\$count,\@hierarchy,$dirorder,
12130:                                            $children,$parent,$titles,$wantform);
12131:             $depth --;
12132:             pop(@hierarchy);
12133:         }
12134:     }
12135:     return ($count,$datatable);
12136: }
12137: 
12138: sub recurse_extracted_archive {
12139:     my ($currdir,$docudom,$docuname,$depth,$count,$hierarchy,$dirorder,
12140:         $children,$parent,$titles,$wantform) = @_;
12141:     my $result='';
12142:     unless ((ref($depth)) && (ref($count)) && (ref($hierarchy) eq 'ARRAY') &&
12143:             (ref($children) eq 'HASH') && (ref($parent) eq 'HASH') &&
12144:             (ref($dirorder) eq 'HASH')) {
12145:         return $result;
12146:     }
12147:     my $dirptr = 16384;
12148:     my ($newdirlistref,$newlisterror) =
12149:         &Apache::lonnet::dirlist($currdir,$docudom,$docuname,1);
12150:     if (ref($newdirlistref) eq 'ARRAY') {
12151:         foreach my $dir_line (@{$newdirlistref}) {
12152:             my ($item,undef,undef,$testdir)=split(/\&/,$dir_line,5);
12153:             unless ($item =~ /^\.+$/) {
12154:                 $$count ++;
12155:                 @{$dirorder->{$$count}} = @{$hierarchy};
12156:                 $titles->{$$count} = $item;
12157:                 &archive_hierarchy($$depth,$$count,$parent,$children);
12158: 
12159:                 my $is_dir;
12160:                 if ($dirptr&$testdir) {
12161:                     $is_dir = 1;
12162:                 }
12163:                 if ($wantform) {
12164:                     $result .= &archive_row($is_dir,$item,$currdir,$$depth,$$count);
12165:                 }
12166:                 if ($is_dir) {
12167:                     $$depth ++;
12168:                     push(@{$hierarchy},$$count);
12169:                     $parent->{$$depth} = $$count;
12170:                     $result .=
12171:                         &recurse_extracted_archive("$currdir/$item",$docudom,
12172:                                                    $docuname,$depth,$count,
12173:                                                    $hierarchy,$dirorder,$children,
12174:                                                    $parent,$titles,$wantform);
12175:                     $$depth --;
12176:                     pop(@{$hierarchy});
12177:                 }
12178:             }
12179:         }
12180:     }
12181:     return $result;
12182: }
12183: 
12184: sub archive_hierarchy {
12185:     my ($depth,$count,$parent,$children) =@_;
12186:     if ((ref($parent) eq 'HASH') && (ref($children) eq 'HASH')) {
12187:         if (exists($parent->{$depth})) {
12188:              $children->{$parent->{$depth}} .= $count.':';
12189:         }
12190:     }
12191:     return;
12192: }
12193: 
12194: sub archive_row {
12195:     my ($is_dir,$item,$currdir,$depth,$count) = @_;
12196:     my ($name) = ($item =~ m{([^/]+)$});
12197:     my %choices = &Apache::lonlocal::texthash (
12198:                                        'display'    => 'Add as file',
12199:                                        'dependency' => 'Include as dependency',
12200:                                        'discard'    => 'Discard',
12201:                                       );
12202:     if ($is_dir) {
12203:         $choices{'display'} = &mt('Add as folder'); 
12204:     }
12205:     my $output = &start_data_table_row().'<td align="right">'.$count.'</td>'."\n";
12206:     my $offset = 0;
12207:     foreach my $action ('display','dependency','discard') {
12208:         $offset ++;
12209:         if ($action ne 'display') {
12210:             $offset ++;
12211:         }  
12212:         $output .= '<td><span class="LC_nobreak">'.
12213:                    '<label><input type="radio" name="archive_'.$count.
12214:                    '" id="archive_'.$action.'_'.$count.'" value="'.$action.'"';
12215:         my $text = $choices{$action};
12216:         if ($is_dir) {
12217:             $output .= ' onclick="javascript:propagateCheck(this.form,'."'$count'".');"';
12218:             if ($action eq 'display') {
12219:                 $text = &mt('Add as folder');
12220:             }
12221:         } else {
12222:             $output .= ' onclick="javascript:dependencyCheck(this.form,'."$count,$offset".');"';
12223: 
12224:         }
12225:         $output .= ' />&nbsp;'.$choices{$action}.'</label></span>';
12226:         if ($action eq 'dependency') {
12227:             $output .= '<div id="arc_depon_'.$count.'" style="display:none;">'."\n".
12228:                        &mt('Used by:').'&nbsp;<select name="archive_dependent_on_'.$count.'" '.
12229:                        'onchange="propagateSelect(this.form,'."$count,$offset".')">'."\n".
12230:                        '<option value=""></option>'."\n".
12231:                        '</select>'."\n".
12232:                        '</div>';
12233:         } elsif ($action eq 'display') {
12234:             $output .= '<div id="arc_title_'.$count.'" style="display:none;">'."\n".
12235:                        &mt('Title:').'&nbsp;<input type="text" name="archive_title_'.$count.'" id="archive_title_'.$count.'" />'."\n".
12236:                        '</div>';
12237:         }
12238:         $output .= '</td>';
12239:     }
12240:     $output .= '<td><input type="hidden" name="archive_content_'.$count.'" value="'.
12241:                &HTML::Entities::encode("$currdir/$item",'"<>&').'" />'.('&nbsp;' x 2);
12242:     for (my $i=0; $i<$depth; $i++) {
12243:         $output .= ('<img src="/adm/lonIcons/whitespace1.gif" class="LC_docs_spacer" alt="" />' x2)."\n";
12244:     }
12245:     if ($is_dir) {
12246:         $output .= '<img src="/adm/lonIcons/navmap.folder.open.gif" alt="" />&nbsp;'."\n".
12247:                    '<input type="hidden" name="archive_directory" value="'.$count.'" />'."\n";
12248:     } else {
12249:         $output .= '<input type="hidden" name="archive_file" value="'.$count.'" />'."\n";
12250:     }
12251:     $output .= '&nbsp;'.$name.'</td>'."\n".
12252:                &end_data_table_row();
12253:     return $output;
12254: }
12255: 
12256: sub archive_options_form {
12257:     my ($form,$display,$count,$hiddenelem) = @_;
12258:     my %lt = &Apache::lonlocal::texthash(
12259:                perm => 'Permanently remove archive file?',
12260:                hows => 'How should each extracted item be incorporated in the course?',
12261:                cont => 'Content actions for all',
12262:                addf => 'Add as folder/file',
12263:                incd => 'Include as dependency for a displayed file',
12264:                disc => 'Discard',
12265:                no   => 'No',
12266:                yes  => 'Yes',
12267:                save => 'Save',
12268:     );
12269:     my $output = <<"END";
12270: <form name="$form" method="post" action="">
12271: <p><span class="LC_nobreak">$lt{'perm'}&nbsp;
12272: <label>
12273:   <input type="radio" name="archivedelete" value="0" checked="checked" />$lt{'no'}
12274: </label>
12275: &nbsp;
12276: <label>
12277:   <input type="radio" name="archivedelete" value="1" />$lt{'yes'}</label>
12278: </span>
12279: </p>
12280: <input type="hidden" name="phase" value="decompress_cleanup" />
12281: <br />$lt{'hows'}
12282: <div class="LC_columnSection">
12283:   <fieldset>
12284:     <legend>$lt{'cont'}</legend>
12285:     <input type="button" value="$lt{'addf'}" onclick="javascript:checkAll(document.$form,'display');" /> 
12286:     &nbsp;&nbsp;<input type="button" value="$lt{'incd'}" onclick="javascript:checkAll(document.$form,'dependency');" />
12287:     &nbsp;&nbsp;<input type="button" value="$lt{'disc'}" onclick="javascript:checkAll(document.$form,'discard');" />
12288:   </fieldset>
12289: </div>
12290: END
12291:     return $output.
12292:            &start_data_table()."\n".
12293:            $display."\n".
12294:            &end_data_table()."\n".
12295:            '<input type="hidden" name="archive_count" value="'.$count.'" />'.
12296:            $hiddenelem.
12297:            '<br /><input type="submit" name="archive_submit" value="'.$lt{'save'}.'" />'.
12298:            '</form>';
12299: }
12300: 
12301: sub archive_javascript {
12302:     my ($startcount,$numitems,$titles,$children) = @_;
12303:     return unless ((ref($titles) eq 'HASH') && (ref($children) eq 'HASH'));
12304:     my $maintitle = $env{'form.comment'};
12305:     my $scripttag = <<START;
12306: <script type="text/javascript">
12307: // <![CDATA[
12308: 
12309: function checkAll(form,prefix) {
12310:     var idstr =  new RegExp("^archive_"+prefix+"_\\\\d+\$");
12311:     for (var i=0; i < form.elements.length; i++) {
12312:         var id = form.elements[i].id;
12313:         if ((id != '') && (id != undefined)) {
12314:             if (idstr.test(id)) {
12315:                 if (form.elements[i].type == 'radio') {
12316:                     form.elements[i].checked = true;
12317:                     var nostart = i-$startcount;
12318:                     var offset = nostart%7;
12319:                     var count = (nostart-offset)/7;    
12320:                     dependencyCheck(form,count,offset);
12321:                 }
12322:             }
12323:         }
12324:     }
12325: }
12326: 
12327: function propagateCheck(form,count) {
12328:     if (count > 0) {
12329:         var startelement = $startcount + ((count-1) * 7);
12330:         for (var j=1; j<6; j++) {
12331:             if ((j != 2) && (j != 4)) {
12332:                 var item = startelement + j; 
12333:                 if (form.elements[item].type == 'radio') {
12334:                     if (form.elements[item].checked) {
12335:                         containerCheck(form,count,j);
12336:                         break;
12337:                     }
12338:                 }
12339:             }
12340:         }
12341:     }
12342: }
12343: 
12344: numitems = $numitems
12345: var titles = new Array(numitems);
12346: var parents = new Array(numitems);
12347: for (var i=0; i<numitems; i++) {
12348:     parents[i] = new Array;
12349: }
12350: var maintitle = '$maintitle';
12351: 
12352: START
12353: 
12354:     foreach my $container (sort { $a <=> $b } (keys(%{$children}))) {
12355:         my @contents = split(/:/,$children->{$container});
12356:         for (my $i=0; $i<@contents; $i ++) {
12357:             $scripttag .= 'parents['.$container.']['.$i.'] = '.$contents[$i]."\n";
12358:         }
12359:     }
12360: 
12361:     foreach my $key (sort { $a <=> $b } (keys(%{$titles}))) {
12362:         $scripttag .= "titles[$key] = '".$titles->{$key}."';\n";
12363:     }
12364: 
12365:     $scripttag .= <<END;
12366: 
12367: function containerCheck(form,count,offset) {
12368:     if (count > 0) {
12369:         dependencyCheck(form,count,offset);
12370:         var item = (offset+$startcount)+7*(count-1);
12371:         form.elements[item].checked = true;
12372:         if(Object.prototype.toString.call(parents[count]) === '[object Array]') {
12373:             if (parents[count].length > 0) {
12374:                 for (var j=0; j<parents[count].length; j++) {
12375:                     containerCheck(form,parents[count][j],offset);
12376:                 }
12377:             }
12378:         }
12379:     }
12380: }
12381: 
12382: function dependencyCheck(form,count,offset) {
12383:     if (count > 0) {
12384:         var chosen = (offset+$startcount)+7*(count-1);
12385:         var depitem = $startcount + ((count-1) * 7) + 4;
12386:         var currtype = form.elements[depitem].type;
12387:         if (form.elements[chosen].value == 'dependency') {
12388:             document.getElementById('arc_depon_'+count).style.display='block'; 
12389:             form.elements[depitem].options.length = 0;
12390:             form.elements[depitem].options[0] = new Option('Select','',true,true);
12391:             for (var i=1; i<=numitems; i++) {
12392:                 if (i == count) {
12393:                     continue;
12394:                 }
12395:                 var startelement = $startcount + (i-1) * 7;
12396:                 for (var j=1; j<6; j++) {
12397:                     if ((j != 2) && (j!= 4)) {
12398:                         var item = startelement + j;
12399:                         if (form.elements[item].type == 'radio') {
12400:                             if (form.elements[item].checked) {
12401:                                 if (form.elements[item].value == 'display') {
12402:                                     var n = form.elements[depitem].options.length;
12403:                                     form.elements[depitem].options[n] = new Option(titles[i],i,false,false);
12404:                                 }
12405:                             }
12406:                         }
12407:                     }
12408:                 }
12409:             }
12410:         } else {
12411:             document.getElementById('arc_depon_'+count).style.display='none';
12412:             form.elements[depitem].options.length = 0;
12413:             form.elements[depitem].options[0] = new Option('Select','',true,true);
12414:         }
12415:         titleCheck(form,count,offset);
12416:     }
12417: }
12418: 
12419: function propagateSelect(form,count,offset) {
12420:     if (count > 0) {
12421:         var item = (1+offset+$startcount)+7*(count-1);
12422:         var picked = form.elements[item].options[form.elements[item].selectedIndex].value; 
12423:         if (Object.prototype.toString.call(parents[count]) === '[object Array]') {
12424:             if (parents[count].length > 0) {
12425:                 for (var j=0; j<parents[count].length; j++) {
12426:                     containerSelect(form,parents[count][j],offset,picked);
12427:                 }
12428:             }
12429:         }
12430:     }
12431: }
12432: 
12433: function containerSelect(form,count,offset,picked) {
12434:     if (count > 0) {
12435:         var item = (offset+$startcount)+7*(count-1);
12436:         if (form.elements[item].type == 'radio') {
12437:             if (form.elements[item].value == 'dependency') {
12438:                 if (form.elements[item+1].type == 'select-one') {
12439:                     for (var i=0; i<form.elements[item+1].options.length; i++) {
12440:                         if (form.elements[item+1].options[i].value == picked) {
12441:                             form.elements[item+1].selectedIndex = i;
12442:                             break;
12443:                         }
12444:                     }
12445:                 }
12446:                 if (Object.prototype.toString.call(parents[count]) === '[object Array]') {
12447:                     if (parents[count].length > 0) {
12448:                         for (var j=0; j<parents[count].length; j++) {
12449:                             containerSelect(form,parents[count][j],offset,picked);
12450:                         }
12451:                     }
12452:                 }
12453:             }
12454:         }
12455:     }
12456: }
12457: 
12458: function titleCheck(form,count,offset) {
12459:     if (count > 0) {
12460:         var chosen = (offset+$startcount)+7*(count-1);
12461:         var depitem = $startcount + ((count-1) * 7) + 2;
12462:         var currtype = form.elements[depitem].type;
12463:         if (form.elements[chosen].value == 'display') {
12464:             document.getElementById('arc_title_'+count).style.display='block';
12465:             if ((count==1) && ((parents[count].length > 0) || (numitems == 1))) {
12466:                 document.getElementById('archive_title_'+count).value=maintitle;
12467:             }
12468:         } else {
12469:             document.getElementById('arc_title_'+count).style.display='none';
12470:             if (currtype == 'text') { 
12471:                 document.getElementById('archive_title_'+count).value='';
12472:             }
12473:         }
12474:     }
12475:     return;
12476: }
12477: 
12478: // ]]>
12479: </script>
12480: END
12481:     return $scripttag;
12482: }
12483: 
12484: sub process_extracted_files {
12485:     my ($context,$docudom,$docuname,$destination,$dir_root,$hiddenelem) = @_;
12486:     my $numitems = $env{'form.archive_count'};
12487:     return unless ($numitems);
12488:     my @ids=&Apache::lonnet::current_machine_ids();
12489:     my ($prefix,$pathtocheck,$dir,$ishome,$error,$warning,%toplevelitems,%is_dir,
12490:         %folders,%containers,%mapinner,%prompttofetch);
12491:     my $docuhome = &Apache::lonnet::homeserver($docuname,$docudom);
12492:     if (grep(/^\Q$docuhome\E$/,@ids)) {
12493:         $prefix = &LONCAPA::propath($docudom,$docuname);
12494:         $pathtocheck = "$dir_root/$destination";
12495:         $dir = $dir_root;
12496:         $ishome = 1;
12497:     } else {
12498:         $prefix = $Apache::lonnet::perlvar{'lonDocRoot'};
12499:         $pathtocheck = "$dir_root/$docudom/$docuname/$destination";
12500:         $dir = "$dir_root/$docudom/$docuname";    
12501:     }
12502:     my $currdir = "$dir_root/$destination";
12503:     (my $docstype,$mapinner{'0'}) = ($destination =~ m{^(docs|supplemental)/(\w+)/});
12504:     if ($env{'form.folderpath'}) {
12505:         my @items = split('&',$env{'form.folderpath'});
12506:         $folders{'0'} = $items[-2];
12507:         if ($env{'form.folderpath'} =~ /\:1$/) {
12508:             $containers{'0'}='page';
12509:         } else {
12510:             $containers{'0'}='sequence';
12511:         }
12512:     }
12513:     my @archdirs = &get_env_multiple('form.archive_directory');
12514:     if ($numitems) {
12515:         for (my $i=1; $i<=$numitems; $i++) {
12516:             my $path = $env{'form.archive_content_'.$i};
12517:             if ($path =~ m{^\Q$pathtocheck\E/([^/]+)$}) {
12518:                 my $item = $1;
12519:                 $toplevelitems{$item} = $i;
12520:                 if (grep(/^\Q$i\E$/,@archdirs)) {
12521:                     $is_dir{$item} = 1;
12522:                 }
12523:             }
12524:         }
12525:     }
12526:     my ($output,%children,%parent,%titles,%dirorder,$result);
12527:     if (keys(%toplevelitems) > 0) {
12528:         my @contents = sort(keys(%toplevelitems));
12529:         (my $count,undef) = &get_extracted($docudom,$docuname,$currdir,\%is_dir,\%children,
12530:                                            \%parent,\@contents,\%dirorder,\%titles);
12531:     }
12532:     my (%referrer,%orphaned,%todelete,%todeletedir,%newdest,%newseqid);
12533:     if ($numitems) {
12534:         for (my $i=1; $i<=$numitems; $i++) {
12535:             next if ($env{'form.archive_'.$i} eq 'dependency');
12536:             my $path = $env{'form.archive_content_'.$i};
12537:             if ($path =~ /^\Q$pathtocheck\E/) {
12538:                 if ($env{'form.archive_'.$i} eq 'discard') {
12539:                     if ($prefix ne '' && $path ne '') {
12540:                         if (-e $prefix.$path) {
12541:                             if ((@archdirs > 0) && 
12542:                                 (grep(/^\Q$i\E$/,@archdirs))) {
12543:                                 $todeletedir{$prefix.$path} = 1;
12544:                             } else {
12545:                                 $todelete{$prefix.$path} = 1;
12546:                             }
12547:                         }
12548:                     }
12549:                 } elsif ($env{'form.archive_'.$i} eq 'display') {
12550:                     my ($docstitle,$title,$url,$outer);
12551:                     ($title) = ($path =~ m{/([^/]+)$});
12552:                     $docstitle = $env{'form.archive_title_'.$i};
12553:                     if ($docstitle eq '') {
12554:                         $docstitle = $title;
12555:                     }
12556:                     $outer = 0;
12557:                     if (ref($dirorder{$i}) eq 'ARRAY') {
12558:                         if (@{$dirorder{$i}} > 0) {
12559:                             foreach my $item (reverse(@{$dirorder{$i}})) {
12560:                                 if ($env{'form.archive_'.$item} eq 'display') {
12561:                                     $outer = $item;
12562:                                     last;
12563:                                 }
12564:                             }
12565:                         }
12566:                     }
12567:                     my ($errtext,$fatal) = 
12568:                         &LONCAPA::map::mapread('/uploaded/'.$docudom.'/'.$docuname.
12569:                                                '/'.$folders{$outer}.'.'.
12570:                                                $containers{$outer});
12571:                     next if ($fatal);
12572:                     if ((@archdirs > 0) && (grep(/^\Q$i\E$/,@archdirs))) {
12573:                         if ($context eq 'coursedocs') {
12574:                             $mapinner{$i} = time;
12575:                             $folders{$i} = 'default_'.$mapinner{$i};
12576:                             $containers{$i} = 'sequence';
12577:                             my $url = '/uploaded/'.$docudom.'/'.$docuname.'/'.
12578:                                       $folders{$i}.'.'.$containers{$i};
12579:                             my $newidx = &LONCAPA::map::getresidx();
12580:                             $LONCAPA::map::resources[$newidx]=
12581:                                 $docstitle.':'.$url.':false:normal:res';
12582:                             push(@LONCAPA::map::order,$newidx);
12583:                             my ($outtext,$errtext) =
12584:                                 &LONCAPA::map::storemap('/uploaded/'.$docudom.'/'.
12585:                                                         $docuname.'/'.$folders{$outer}.
12586:                                                         '.'.$containers{$outer},1,1);
12587:                             $newseqid{$i} = $newidx;
12588:                             unless ($errtext) {
12589:                                 $result .=  '<li>'.&mt('Folder: [_1] added to course',$docstitle).'</li>'."\n";
12590:                             }
12591:                         }
12592:                     } else {
12593:                         if ($context eq 'coursedocs') {
12594:                             my $newidx=&LONCAPA::map::getresidx();
12595:                             my $url = '/uploaded/'.$docudom.'/'.$docuname.'/'.
12596:                                       $docstype.'/'.$mapinner{$outer}.'/'.$newidx.'/'.
12597:                                       $title;
12598:                             if (!-e "$prefix$dir/$docstype/$mapinner{$outer}") {
12599:                                 mkdir("$prefix$dir/$docstype/$mapinner{$outer}",0755);
12600:                             }
12601:                             if (!-e "$prefix$dir/$docstype/$mapinner{$outer}/$newidx") {
12602:                                 mkdir("$prefix$dir/$docstype/$mapinner{$outer}/$newidx");
12603:                             }
12604:                             if (-e "$prefix$dir/$docstype/$mapinner{$outer}/$newidx") {
12605:                                 system("mv $prefix$path $prefix$dir/$docstype/$mapinner{$outer}/$newidx/$title");
12606:                                 $newdest{$i} = "$prefix$dir/$docstype/$mapinner{$outer}/$newidx";
12607:                                 unless ($ishome) {
12608:                                     my $fetch = "$newdest{$i}/$title";
12609:                                     $fetch =~ s/^\Q$prefix$dir\E//;
12610:                                     $prompttofetch{$fetch} = 1;
12611:                                 }
12612:                             }
12613:                             $LONCAPA::map::resources[$newidx]=
12614:                                 $docstitle.':'.$url.':false:normal:res';
12615:                             push(@LONCAPA::map::order, $newidx);
12616:                             my ($outtext,$errtext)=
12617:                                 &LONCAPA::map::storemap('/uploaded/'.$docudom.'/'.
12618:                                                         $docuname.'/'.$folders{$outer}.
12619:                                                         '.'.$containers{$outer},1,1);
12620:                             unless ($errtext) {
12621:                                 if (-e "$prefix$dir/$docstype/$mapinner{$outer}/$newidx/$title") {
12622:                                     $result .= '<li>'.&mt('File: [_1] added to course',$docstitle).'</li>'."\n";
12623:                                 }
12624:                             }
12625:                         }
12626:                     }
12627:                 }
12628:             } else {
12629:                 $warning .= &mt('Item extracted from archive: [_1] has unexpected path.',$path).'<br />';
12630:             }
12631:         }
12632:         for (my $i=1; $i<=$numitems; $i++) {
12633:             next unless ($env{'form.archive_'.$i} eq 'dependency');
12634:             my $path = $env{'form.archive_content_'.$i};
12635:             if ($path =~ /^\Q$pathtocheck\E/) {
12636:                 my ($title) = ($path =~ m{/([^/]+)$});
12637:                 $referrer{$i} = $env{'form.archive_dependent_on_'.$i};
12638:                 if ($env{'form.archive_'.$referrer{$i}} eq 'display') {
12639:                     if (ref($dirorder{$i}) eq 'ARRAY') {
12640:                         my ($itemidx,$fullpath,$relpath);
12641:                         if (ref($dirorder{$referrer{$i}}) eq 'ARRAY') {
12642:                             my $container = $dirorder{$referrer{$i}}->[-1];
12643:                             for (my $j=0; $j<@{$dirorder{$i}}; $j++) {
12644:                                 if ($dirorder{$i}->[$j] eq $container) {
12645:                                     $itemidx = $j;
12646:                                 }
12647:                             }
12648:                         }
12649:                         if ($itemidx eq '') {
12650:                             $itemidx =  0;
12651:                         }
12652:                         if (grep(/^\Q$referrer{$i}\E$/,@archdirs)) {
12653:                             if ($mapinner{$referrer{$i}}) {
12654:                                 $fullpath = "$prefix$dir/$docstype/$mapinner{$referrer{$i}}";
12655:                                 for (my $j=$itemidx; $j<@{$dirorder{$i}}; $j++) {
12656:                                     if (grep(/^\Q$dirorder{$i}->[$j]\E$/,@archdirs)) {
12657:                                         unless (defined($newseqid{$dirorder{$i}->[$j]})) {
12658:                                             $fullpath .= '/'.$titles{$dirorder{$i}->[$j]};
12659:                                             $relpath .= '/'.$titles{$dirorder{$i}->[$j]};
12660:                                             if (!-e $fullpath) {
12661:                                                 mkdir($fullpath,0755);
12662:                                             }
12663:                                         }
12664:                                     } else {
12665:                                         last;
12666:                                     }
12667:                                 }
12668:                             }
12669:                         } elsif ($newdest{$referrer{$i}}) {
12670:                             $fullpath = $newdest{$referrer{$i}};
12671:                             for (my $j=$itemidx; $j<@{$dirorder{$i}}; $j++) {
12672:                                 if ($env{'form.archive_'.$dirorder{$i}->[$j]} eq 'discard') {
12673:                                     $orphaned{$i} = $env{'form.archive_'.$dirorder{$i}->[$j]};
12674:                                     last;
12675:                                 } elsif (grep(/^\Q$dirorder{$i}->[$j]\E$/,@archdirs)) {
12676:                                     unless (defined($newseqid{$dirorder{$i}->[$j]})) {
12677:                                         $fullpath .= '/'.$titles{$dirorder{$i}->[$j]};
12678:                                         $relpath .= '/'.$titles{$dirorder{$i}->[$j]};
12679:                                         if (!-e $fullpath) {
12680:                                             mkdir($fullpath,0755);
12681:                                         }
12682:                                     }
12683:                                 } else {
12684:                                     last;
12685:                                 }
12686:                             }
12687:                         }
12688:                         if ($fullpath ne '') {
12689:                             if (-e "$prefix$path") {
12690:                                 system("mv $prefix$path $fullpath/$title");
12691:                             }
12692:                             if (-e "$fullpath/$title") {
12693:                                 my $showpath;
12694:                                 if ($relpath ne '') {
12695:                                     $showpath = "$relpath/$title";
12696:                                 } else {
12697:                                     $showpath = "/$title";
12698:                                 }
12699:                                 $result .= '<li>'.&mt('[_1] included as a dependency',$showpath).'</li>'."\n";
12700:                             }
12701:                             unless ($ishome) {
12702:                                 my $fetch = "$fullpath/$title";
12703:                                 $fetch =~ s/^\Q$prefix$dir\E//;
12704:                                 $prompttofetch{$fetch} = 1;
12705:                             }
12706:                         }
12707:                     }
12708:                 } elsif ($env{'form.archive_'.$referrer{$i}} eq 'discard') {
12709:                     $warning .= &mt('[_1] is a dependency of [_2], which was discarded.',
12710:                                     $path,$env{'form.archive_content_'.$referrer{$i}}).'<br />';
12711:                 }
12712:             } else {
12713:                 $warning .= &mt('Item extracted from archive: [_1] has unexpected path.',$path).'<br />';
12714:             }
12715:         }
12716:         if (keys(%todelete)) {
12717:             foreach my $key (keys(%todelete)) {
12718:                 unlink($key);
12719:             }
12720:         }
12721:         if (keys(%todeletedir)) {
12722:             foreach my $key (keys(%todeletedir)) {
12723:                 rmdir($key);
12724:             }
12725:         }
12726:         foreach my $dir (sort(keys(%is_dir))) {
12727:             if (($pathtocheck ne '') && ($dir ne ''))  {
12728:                 &cleanup_empty_dirs($prefix."$pathtocheck/$dir");
12729:             }
12730:         }
12731:         if ($result ne '') {
12732:             $output .= '<ul>'."\n".
12733:                        $result."\n".
12734:                        '</ul>';
12735:         }
12736:         unless ($ishome) {
12737:             my $replicationfail;
12738:             foreach my $item (keys(%prompttofetch)) {
12739:                 my $fetchresult= &Apache::lonnet::reply('fetchuserfile:'.$item,$docuhome);
12740:                 unless ($fetchresult eq 'ok') {
12741:                     $replicationfail .= '<li>'.$item.'</li>'."\n";
12742:                 }
12743:             }
12744:             if ($replicationfail) {
12745:                 $output .= '<p class="LC_error">'.
12746:                            &mt('Course home server failed to retrieve:').'<ul>'.
12747:                            $replicationfail.
12748:                            '</ul></p>';
12749:             }
12750:         }
12751:     } else {
12752:         $warning = &mt('No items found in archive.');
12753:     }
12754:     if ($error) {
12755:         $output .= '<p class="LC_error">'.&mt('Not extracted.').'<br />'.
12756:                    $error.'</p>'."\n";
12757:     }
12758:     if ($warning) {
12759:         $output .= '<p class="LC_warning">'.$warning.'</p>'."\n";
12760:     }
12761:     return $output;
12762: }
12763: 
12764: sub cleanup_empty_dirs {
12765:     my ($path) = @_;
12766:     if (($path ne '') && (-d $path)) {
12767:         if (opendir(my $dirh,$path)) {
12768:             my @dircontents = grep(!/^\./,readdir($dirh));
12769:             my $numitems = 0;
12770:             foreach my $item (@dircontents) {
12771:                 if (-d "$path/$item") {
12772:                     &cleanup_empty_dirs("$path/$item");
12773:                     if (-e "$path/$item") {
12774:                         $numitems ++;
12775:                     }
12776:                 } else {
12777:                     $numitems ++;
12778:                 }
12779:             }
12780:             if ($numitems == 0) {
12781:                 rmdir($path);
12782:             }
12783:             closedir($dirh);
12784:         }
12785:     }
12786:     return;
12787: }
12788: 
12789: =pod
12790: 
12791: =item * &get_folder_hierarchy()
12792: 
12793: Provides hierarchy of names of folders/sub-folders containing the current
12794: item,
12795: 
12796: Inputs: 3
12797:      - $navmap - navmaps object
12798: 
12799:      - $map - url for map (either the trigger itself, or map containing
12800:                            the resource, which is the trigger).
12801: 
12802:      - $showitem - 1 => show title for map itself; 0 => do not show.
12803: 
12804: Outputs: 1 @pathitems - array of folder/subfolder names.
12805: 
12806: =cut
12807: 
12808: sub get_folder_hierarchy {
12809:     my ($navmap,$map,$showitem) = @_;
12810:     my @pathitems;
12811:     if (ref($navmap)) {
12812:         my $mapres = $navmap->getResourceByUrl($map);
12813:         if (ref($mapres)) {
12814:             my $pcslist = $mapres->map_hierarchy();
12815:             if ($pcslist ne '') {
12816:                 my @pcs = split(/,/,$pcslist);
12817:                 foreach my $pc (@pcs) {
12818:                     if ($pc == 1) {
12819:                         push(@pathitems,&mt('Main Content'));
12820:                     } else {
12821:                         my $res = $navmap->getByMapPc($pc);
12822:                         if (ref($res)) {
12823:                             my $title = $res->compTitle();
12824:                             $title =~ s/\W+/_/g;
12825:                             if ($title ne '') {
12826:                                 push(@pathitems,$title);
12827:                             }
12828:                         }
12829:                     }
12830:                 }
12831:             }
12832:             if ($showitem) {
12833:                 if ($mapres->{ID} eq '0.0') {
12834:                     push(@pathitems,&mt('Main Content'));
12835:                 } else {
12836:                     my $maptitle = $mapres->compTitle();
12837:                     $maptitle =~ s/\W+/_/g;
12838:                     if ($maptitle ne '') {
12839:                         push(@pathitems,$maptitle);
12840:                     }
12841:                 }
12842:             }
12843:         }
12844:     }
12845:     return @pathitems;
12846: }
12847: 
12848: =pod
12849: 
12850: =item * &get_turnedin_filepath()
12851: 
12852: Determines path in a user's portfolio file for storage of files uploaded
12853: to a specific essayresponse or dropbox item.
12854: 
12855: Inputs: 3 required + 1 optional.
12856: $symb is symb for resource, $uname and $udom are for current user (required).
12857: $caller is optional (can be "submission", if routine is called when storing
12858: an upoaded file when "Submit Answer" button was pressed).
12859: 
12860: Returns array containing $path and $multiresp. 
12861: $path is path in portfolio.  $multiresp is 1 if this resource contains more
12862: than one file upload item.  Callers of routine should append partid as a 
12863: subdirectory to $path in cases where $multiresp is 1.
12864: 
12865: Called by: homework/essayresponse.pm and homework/structuretags.pm
12866: 
12867: =cut
12868: 
12869: sub get_turnedin_filepath {
12870:     my ($symb,$uname,$udom,$caller) = @_;
12871:     my ($map,$resid,$resurl)=&Apache::lonnet::decode_symb($symb);
12872:     my $turnindir;
12873:     my %userhash = &Apache::lonnet::userenvironment($udom,$uname,'turnindir');
12874:     $turnindir = $userhash{'turnindir'};
12875:     my ($path,$multiresp);
12876:     if ($turnindir eq '') {
12877:         if ($caller eq 'submission') {
12878:             $turnindir = &mt('turned in');
12879:             $turnindir =~ s/\W+/_/g;
12880:             my %newhash = (
12881:                             'turnindir' => $turnindir,
12882:                           );
12883:             &Apache::lonnet::put('environment',\%newhash,$udom,$uname);
12884:         }
12885:     }
12886:     if ($turnindir ne '') {
12887:         $path = '/'.$turnindir.'/';
12888:         my ($multipart,$turnin,@pathitems);
12889:         my $navmap = Apache::lonnavmaps::navmap->new();
12890:         if (defined($navmap)) {
12891:             my $mapres = $navmap->getResourceByUrl($map);
12892:             if (ref($mapres)) {
12893:                 my $pcslist = $mapres->map_hierarchy();
12894:                 if ($pcslist ne '') {
12895:                     foreach my $pc (split(/,/,$pcslist)) {
12896:                         my $res = $navmap->getByMapPc($pc);
12897:                         if (ref($res)) {
12898:                             my $title = $res->compTitle();
12899:                             $title =~ s/\W+/_/g;
12900:                             if ($title ne '') {
12901:                                 if (($pc > 1) && (length($title) > 12)) {
12902:                                     $title = substr($title,0,12);
12903:                                 }
12904:                                 push(@pathitems,$title);
12905:                             }
12906:                         }
12907:                     }
12908:                 }
12909:                 my $maptitle = $mapres->compTitle();
12910:                 $maptitle =~ s/\W+/_/g;
12911:                 if ($maptitle ne '') {
12912:                     if (length($maptitle) > 12) {
12913:                         $maptitle = substr($maptitle,0,12);
12914:                     }
12915:                     push(@pathitems,$maptitle);
12916:                 }
12917:                 unless ($env{'request.state'} eq 'construct') {
12918:                     my $res = $navmap->getBySymb($symb);
12919:                     if (ref($res)) {
12920:                         my $partlist = $res->parts();
12921:                         my $totaluploads = 0;
12922:                         if (ref($partlist) eq 'ARRAY') {
12923:                             foreach my $part (@{$partlist}) {
12924:                                 my @types = $res->responseType($part);
12925:                                 my @ids = $res->responseIds($part);
12926:                                 for (my $i=0; $i < scalar(@ids); $i++) {
12927:                                     if ($types[$i] eq 'essay') {
12928:                                         my $partid = $part.'_'.$ids[$i];
12929:                                         if (&Apache::lonnet::EXT("resource.$partid.uploadedfiletypes") ne '') {
12930:                                             $totaluploads ++;
12931:                                         }
12932:                                     }
12933:                                 }
12934:                             }
12935:                             if ($totaluploads > 1) {
12936:                                 $multiresp = 1;
12937:                             }
12938:                         }
12939:                     }
12940:                 }
12941:             } else {
12942:                 return;
12943:             }
12944:         } else {
12945:             return;
12946:         }
12947:         my $restitle=&Apache::lonnet::gettitle($symb);
12948:         $restitle =~ s/\W+/_/g;
12949:         if ($restitle eq '') {
12950:             $restitle = ($resurl =~ m{/[^/]+$});
12951:             if ($restitle eq '') {
12952:                 $restitle = time;
12953:             }
12954:         }
12955:         if (length($restitle) > 12) {
12956:             $restitle = substr($restitle,0,12);
12957:         }
12958:         push(@pathitems,$restitle);
12959:         $path .= join('/',@pathitems);
12960:     }
12961:     return ($path,$multiresp);
12962: }
12963: 
12964: =pod
12965: 
12966: =back
12967: 
12968: =head1 CSV Upload/Handling functions
12969: 
12970: =over 4
12971: 
12972: =item * &upfile_store($r)
12973: 
12974: Store uploaded file, $r should be the HTTP Request object,
12975: needs $env{'form.upfile'}
12976: returns $datatoken to be put into hidden field
12977: 
12978: =cut
12979: 
12980: sub upfile_store {
12981:     my $r=shift;
12982:     $env{'form.upfile'}=~s/\r/\n/gs;
12983:     $env{'form.upfile'}=~s/\f/\n/gs;
12984:     $env{'form.upfile'}=~s/\n+/\n/gs;
12985:     $env{'form.upfile'}=~s/\n+$//gs;
12986: 
12987:     my $datatoken=$env{'user.name'}.'_'.$env{'user.domain'}.
12988: 	'_enroll_'.$env{'request.course.id'}.'_'.time.'_'.$$;
12989:     {
12990:         my $datafile = $r->dir_config('lonDaemons').
12991:                            '/tmp/'.$datatoken.'.tmp';
12992:         if ( open(my $fh,">$datafile") ) {
12993:             print $fh $env{'form.upfile'};
12994:             close($fh);
12995:         }
12996:     }
12997:     return $datatoken;
12998: }
12999: 
13000: =pod
13001: 
13002: =item * &load_tmp_file($r)
13003: 
13004: Load uploaded file from tmp, $r should be the HTTP Request object,
13005: needs $env{'form.datatoken'},
13006: sets $env{'form.upfile'} to the contents of the file
13007: 
13008: =cut
13009: 
13010: sub load_tmp_file {
13011:     my $r=shift;
13012:     my @studentdata=();
13013:     {
13014:         my $studentfile = $r->dir_config('lonDaemons').
13015:                               '/tmp/'.$env{'form.datatoken'}.'.tmp';
13016:         if ( open(my $fh,"<$studentfile") ) {
13017:             @studentdata=<$fh>;
13018:             close($fh);
13019:         }
13020:     }
13021:     $env{'form.upfile'}=join('',@studentdata);
13022: }
13023: 
13024: =pod
13025: 
13026: =item * &upfile_record_sep()
13027: 
13028: Separate uploaded file into records
13029: returns array of records,
13030: needs $env{'form.upfile'} and $env{'form.upfiletype'}
13031: 
13032: =cut
13033: 
13034: sub upfile_record_sep {
13035:     if ($env{'form.upfiletype'} eq 'xml') {
13036:     } else {
13037: 	my @records;
13038: 	foreach my $line (split(/\n/,$env{'form.upfile'})) {
13039: 	    if ($line=~/^\s*$/) { next; }
13040: 	    push(@records,$line);
13041: 	}
13042: 	return @records;
13043:     }
13044: }
13045: 
13046: =pod
13047: 
13048: =item * &record_sep($record)
13049: 
13050: Separate a record into fields $record should be an item from the upfile_record_sep(), needs $env{'form.upfiletype'}
13051: 
13052: =cut
13053: 
13054: sub takeleft {
13055:     my $index=shift;
13056:     return substr('0000'.$index,-4,4);
13057: }
13058: 
13059: sub record_sep {
13060:     my $record=shift;
13061:     my %components=();
13062:     if ($env{'form.upfiletype'} eq 'xml') {
13063:     } elsif ($env{'form.upfiletype'} eq 'space') {
13064:         my $i=0;
13065:         foreach my $field (split(/\s+/,$record)) {
13066:             $field=~s/^(\"|\')//;
13067:             $field=~s/(\"|\')$//;
13068:             $components{&takeleft($i)}=$field;
13069:             $i++;
13070:         }
13071:     } elsif ($env{'form.upfiletype'} eq 'tab') {
13072:         my $i=0;
13073:         foreach my $field (split(/\t/,$record)) {
13074:             $field=~s/^(\"|\')//;
13075:             $field=~s/(\"|\')$//;
13076:             $components{&takeleft($i)}=$field;
13077:             $i++;
13078:         }
13079:     } else {
13080:         my $separator=',';
13081:         if ($env{'form.upfiletype'} eq 'semisv') {
13082:             $separator=';';
13083:         }
13084:         my $i=0;
13085: # the character we are looking for to indicate the end of a quote or a record 
13086:         my $looking_for=$separator;
13087: # do not add the characters to the fields
13088:         my $ignore=0;
13089: # we just encountered a separator (or the beginning of the record)
13090:         my $just_found_separator=1;
13091: # store the field we are working on here
13092:         my $field='';
13093: # work our way through all characters in record
13094:         foreach my $character ($record=~/(.)/g) {
13095:             if ($character eq $looking_for) {
13096:                if ($character ne $separator) {
13097: # Found the end of a quote, again looking for separator
13098:                   $looking_for=$separator;
13099:                   $ignore=1;
13100:                } else {
13101: # Found a separator, store away what we got
13102:                   $components{&takeleft($i)}=$field;
13103: 	          $i++;
13104:                   $just_found_separator=1;
13105:                   $ignore=0;
13106:                   $field='';
13107:                }
13108:                next;
13109:             }
13110: # single or double quotation marks after a separator indicate beginning of a quote
13111: # we are now looking for the end of the quote and need to ignore separators
13112:             if ((($character eq '"') || ($character eq "'")) && ($just_found_separator))  {
13113:                $looking_for=$character;
13114:                next;
13115:             }
13116: # ignore would be true after we reached the end of a quote
13117:             if ($ignore) { next; }
13118:             if (($just_found_separator) && ($character=~/\s/)) { next; }
13119:             $field.=$character;
13120:             $just_found_separator=0; 
13121:         }
13122: # catch the very last entry, since we never encountered the separator
13123:         $components{&takeleft($i)}=$field;
13124:     }
13125:     return %components;
13126: }
13127: 
13128: ######################################################
13129: ######################################################
13130: 
13131: =pod
13132: 
13133: =item * &upfile_select_html()
13134: 
13135: Return HTML code to select a file from the users machine and specify 
13136: the file type.
13137: 
13138: =cut
13139: 
13140: ######################################################
13141: ######################################################
13142: sub upfile_select_html {
13143:     my %Types = (
13144:                  csv   => &mt('CSV (comma separated values, spreadsheet)'),
13145:                  semisv => &mt('Semicolon separated values'),
13146:                  space => &mt('Space separated'),
13147:                  tab   => &mt('Tabulator separated'),
13148: #                 xml   => &mt('HTML/XML'),
13149:                  );
13150:     my $Str = '<input type="file" name="upfile" size="50" />'.
13151:         '<br />'.&mt('Type').': <select name="upfiletype">';
13152:     foreach my $type (sort(keys(%Types))) {
13153:         $Str .= '<option value="'.$type.'" >'.$Types{$type}."</option>\n";
13154:     }
13155:     $Str .= "</select>\n";
13156:     return $Str;
13157: }
13158: 
13159: sub get_samples {
13160:     my ($records,$toget) = @_;
13161:     my @samples=({});
13162:     my $got=0;
13163:     foreach my $rec (@$records) {
13164: 	my %temp = &record_sep($rec);
13165: 	if (! grep(/\S/, values(%temp))) { next; }
13166: 	if (%temp) {
13167: 	    $samples[$got]=\%temp;
13168: 	    $got++;
13169: 	    if ($got == $toget) { last; }
13170: 	}
13171:     }
13172:     return \@samples;
13173: }
13174: 
13175: ######################################################
13176: ######################################################
13177: 
13178: =pod
13179: 
13180: =item * &csv_print_samples($r,$records)
13181: 
13182: Prints a table of sample values from each column uploaded $r is an
13183: Apache Request ref, $records is an arrayref from
13184: &Apache::loncommon::upfile_record_sep
13185: 
13186: =cut
13187: 
13188: ######################################################
13189: ######################################################
13190: sub csv_print_samples {
13191:     my ($r,$records) = @_;
13192:     my $samples = &get_samples($records,5);
13193: 
13194:     $r->print(&mt('Samples').'<br />'.&start_data_table().
13195:               &start_data_table_header_row());
13196:     foreach my $sample (sort({$a <=> $b} keys(%{ $samples->[0] }))) { 
13197:         $r->print('<th>'.&mt('Column [_1]',($sample+1)).'</th>'); }
13198:     $r->print(&end_data_table_header_row());
13199:     foreach my $hash (@$samples) {
13200: 	$r->print(&start_data_table_row());
13201: 	foreach my $sample (sort({$a <=> $b} keys(%{ $samples->[0] }))) {
13202: 	    $r->print('<td>');
13203: 	    if (defined($$hash{$sample})) { $r->print($$hash{$sample}); }
13204: 	    $r->print('</td>');
13205: 	}
13206: 	$r->print(&end_data_table_row());
13207:     }
13208:     $r->print(&end_data_table().'<br />'."\n");
13209: }
13210: 
13211: ######################################################
13212: ######################################################
13213: 
13214: =pod
13215: 
13216: =item * &csv_print_select_table($r,$records,$d)
13217: 
13218: Prints a table to create associations between values and table columns.
13219: 
13220: $r is an Apache Request ref,
13221: $records is an arrayref from &Apache::loncommon::upfile_record_sep,
13222: $d is an array of 2 element arrays (internal name, displayed name,defaultcol)
13223: 
13224: =cut
13225: 
13226: ######################################################
13227: ######################################################
13228: sub csv_print_select_table {
13229:     my ($r,$records,$d) = @_;
13230:     my $i=0;
13231:     my $samples = &get_samples($records,1);
13232:     $r->print(&mt('Associate columns with student attributes.')."\n".
13233: 	      &start_data_table().&start_data_table_header_row().
13234:               '<th>'.&mt('Attribute').'</th>'.
13235:               '<th>'.&mt('Column').'</th>'.
13236:               &end_data_table_header_row()."\n");
13237:     foreach my $array_ref (@$d) {
13238: 	my ($value,$display,$defaultcol)=@{ $array_ref };
13239: 	$r->print(&start_data_table_row().'<td>'.$display.'</td>');
13240: 
13241: 	$r->print('<td><select name="f'.$i.'"'.
13242: 		  ' onchange="javascript:flip(this.form,'.$i.');">');
13243: 	$r->print('<option value="none"></option>');
13244: 	foreach my $sample (sort({$a <=> $b} keys(%{ $samples->[0] }))) {
13245: 	    $r->print('<option value="'.$sample.'"'.
13246:                       ($sample eq $defaultcol ? ' selected="selected" ' : '').
13247:                       '>'.&mt('Column [_1]',($sample+1)).'</option>');
13248: 	}
13249: 	$r->print('</select></td>'.&end_data_table_row()."\n");
13250: 	$i++;
13251:     }
13252:     $r->print(&end_data_table());
13253:     $i--;
13254:     return $i;
13255: }
13256: 
13257: ######################################################
13258: ######################################################
13259: 
13260: =pod
13261: 
13262: =item * &csv_samples_select_table($r,$records,$d)
13263: 
13264: Prints a table of sample values from the upload and can make associate samples to internal names.
13265: 
13266: $r is an Apache Request ref,
13267: $records is an arrayref from &Apache::loncommon::upfile_record_sep,
13268: $d is an array of 2 element arrays (internal name, displayed name)
13269: 
13270: =cut
13271: 
13272: ######################################################
13273: ######################################################
13274: sub csv_samples_select_table {
13275:     my ($r,$records,$d) = @_;
13276:     my $i=0;
13277:     #
13278:     my $max_samples = 5;
13279:     my $samples = &get_samples($records,$max_samples);
13280:     $r->print(&start_data_table().
13281:               &start_data_table_header_row().'<th>'.
13282:               &mt('Field').'</th><th>'.&mt('Samples').'</th>'.
13283:               &end_data_table_header_row());
13284: 
13285:     foreach my $key (sort(keys(%{ $samples->[0] }))) {
13286: 	$r->print(&start_data_table_row().'<td><select name="f'.$i.'"'.
13287: 		  ' onchange="javascript:flip(this.form,'.$i.');">');
13288: 	foreach my $option (@$d) {
13289: 	    my ($value,$display,$defaultcol)=@{ $option };
13290: 	    $r->print('<option value="'.$value.'"'.
13291:                       ($i eq $defaultcol ? ' selected="selected" ':'').'>'.
13292:                       $display.'</option>');
13293: 	}
13294: 	$r->print('</select></td><td>');
13295: 	foreach my $line (0..($max_samples-1)) {
13296: 	    if (defined($samples->[$line]{$key})) { 
13297: 		$r->print($samples->[$line]{$key}."<br />\n"); 
13298: 	    }
13299: 	}
13300: 	$r->print('</td>'.&end_data_table_row());
13301: 	$i++;
13302:     }
13303:     $r->print(&end_data_table());
13304:     $i--;
13305:     return($i);
13306: }
13307: 
13308: ######################################################
13309: ######################################################
13310: 
13311: =pod
13312: 
13313: =item * &clean_excel_name($name)
13314: 
13315: Returns a replacement for $name which does not contain any illegal characters.
13316: 
13317: =cut
13318: 
13319: ######################################################
13320: ######################################################
13321: sub clean_excel_name {
13322:     my ($name) = @_;
13323:     $name =~ s/[:\*\?\/\\]//g;
13324:     if (length($name) > 31) {
13325:         $name = substr($name,0,31);
13326:     }
13327:     return $name;
13328: }
13329: 
13330: =pod
13331: 
13332: =item * &check_if_partid_hidden($id,$symb,$udom,$uname)
13333: 
13334: Returns either 1 or undef
13335: 
13336: 1 if the part is to be hidden, undef if it is to be shown
13337: 
13338: Arguments are:
13339: 
13340: $id the id of the part to be checked
13341: $symb, optional the symb of the resource to check
13342: $udom, optional the domain of the user to check for
13343: $uname, optional the username of the user to check for
13344: 
13345: =cut
13346: 
13347: sub check_if_partid_hidden {
13348:     my ($id,$symb,$udom,$uname) = @_;
13349:     my $hiddenparts=&Apache::lonnet::EXT('resource.0.hiddenparts',
13350: 					 $symb,$udom,$uname);
13351:     my $truth=1;
13352:     #if the string starts with !, then the list is the list to show not hide
13353:     if ($hiddenparts=~s/^\s*!//) { $truth=undef; }
13354:     my @hiddenlist=split(/,/,$hiddenparts);
13355:     foreach my $checkid (@hiddenlist) {
13356: 	if ($checkid =~ /^\s*\Q$id\E\s*$/) { return $truth; }
13357:     }
13358:     return !$truth;
13359: }
13360: 
13361: 
13362: ############################################################
13363: ############################################################
13364: 
13365: =pod
13366: 
13367: =back 
13368: 
13369: =head1 cgi-bin script and graphing routines
13370: 
13371: =over 4
13372: 
13373: =item * &get_cgi_id()
13374: 
13375: Inputs: none
13376: 
13377: Returns an id which can be used to pass environment variables
13378: to various cgi-bin scripts.  These environment variables will
13379: be removed from the users environment after a given time by
13380: the routine &Apache::lonnet::transfer_profile_to_env.
13381: 
13382: =cut
13383: 
13384: ############################################################
13385: ############################################################
13386: my $uniq=0;
13387: sub get_cgi_id {
13388:     $uniq=($uniq+1)%100000;
13389:     return (time.'_'.$$.'_'.$uniq);
13390: }
13391: 
13392: ############################################################
13393: ############################################################
13394: 
13395: =pod
13396: 
13397: =item * &DrawBarGraph()
13398: 
13399: Facilitates the plotting of data in a (stacked) bar graph.
13400: Puts plot definition data into the users environment in order for 
13401: graph.png to plot it.  Returns an <img> tag for the plot.
13402: The bars on the plot are labeled '1','2',...,'n'.
13403: 
13404: Inputs:
13405: 
13406: =over 4
13407: 
13408: =item $Title: string, the title of the plot
13409: 
13410: =item $xlabel: string, text describing the X-axis of the plot
13411: 
13412: =item $ylabel: string, text describing the Y-axis of the plot
13413: 
13414: =item $Max: scalar, the maximum Y value to use in the plot
13415: If $Max is < any data point, the graph will not be rendered.
13416: 
13417: =item $colors: array ref holding the colors to be used for the data sets when
13418: they are plotted.  If undefined, default values will be used.
13419: 
13420: =item $labels: array ref holding the labels to use on the x-axis for the bars.
13421: 
13422: =item @Values: An array of array references.  Each array reference holds data
13423: to be plotted in a stacked bar chart.
13424: 
13425: =item If the final element of @Values is a hash reference the key/value
13426: pairs will be added to the graph definition.
13427: 
13428: =back
13429: 
13430: Returns:
13431: 
13432: An <img> tag which references graph.png and the appropriate identifying
13433: information for the plot.
13434: 
13435: =cut
13436: 
13437: ############################################################
13438: ############################################################
13439: sub DrawBarGraph {
13440:     my ($Title,$xlabel,$ylabel,$Max,$colors,$labels,@Values)=@_;
13441:     #
13442:     if (! defined($colors)) {
13443:         $colors = ['#33ff00', 
13444:                   '#0033cc', '#990000', '#aaaa66', '#663399', '#ff9933',
13445:                   '#66ccff', '#ff9999', '#cccc33', '#660000', '#33cc66',
13446:                   ]; 
13447:     }
13448:     my $extra_settings = {};
13449:     if (ref($Values[-1]) eq 'HASH') {
13450:         $extra_settings = pop(@Values);
13451:     }
13452:     #
13453:     my $identifier = &get_cgi_id();
13454:     my $id = 'cgi.'.$identifier;        
13455:     if (! @Values || ref($Values[0]) ne 'ARRAY') {
13456:         return '';
13457:     }
13458:     #
13459:     my @Labels;
13460:     if (defined($labels)) {
13461:         @Labels = @$labels;
13462:     } else {
13463:         for (my $i=0;$i<@{$Values[0]};$i++) {
13464:             push (@Labels,$i+1);
13465:         }
13466:     }
13467:     #
13468:     my $NumBars = scalar(@{$Values[0]});
13469:     if ($NumBars < scalar(@Labels)) { $NumBars = scalar(@Labels); }
13470:     my %ValuesHash;
13471:     my $NumSets=1;
13472:     foreach my $array (@Values) {
13473:         next if (! ref($array));
13474:         $ValuesHash{$id.'.data.'.$NumSets++} = 
13475:             join(',',@$array);
13476:     }
13477:     #
13478:     my ($height,$width,$xskip,$bar_width) = (200,120,1,15);
13479:     if ($NumBars < 3) {
13480:         $width = 120+$NumBars*32;
13481:         $xskip = 1;
13482:         $bar_width = 30;
13483:     } elsif ($NumBars < 5) {
13484:         $width = 120+$NumBars*20;
13485:         $xskip = 1;
13486:         $bar_width = 20;
13487:     } elsif ($NumBars < 10) {
13488:         $width = 120+$NumBars*15;
13489:         $xskip = 1;
13490:         $bar_width = 15;
13491:     } elsif ($NumBars <= 25) {
13492:         $width = 120+$NumBars*11;
13493:         $xskip = 5;
13494:         $bar_width = 8;
13495:     } elsif ($NumBars <= 50) {
13496:         $width = 120+$NumBars*8;
13497:         $xskip = 5;
13498:         $bar_width = 4;
13499:     } else {
13500:         $width = 120+$NumBars*8;
13501:         $xskip = 5;
13502:         $bar_width = 4;
13503:     }
13504:     #
13505:     $Max = 1 if ($Max < 1);
13506:     if ( int($Max) < $Max ) {
13507:         $Max++;
13508:         $Max = int($Max);
13509:     }
13510:     $Title  = '' if (! defined($Title));
13511:     $xlabel = '' if (! defined($xlabel));
13512:     $ylabel = '' if (! defined($ylabel));
13513:     $ValuesHash{$id.'.title'}    = &escape($Title);
13514:     $ValuesHash{$id.'.xlabel'}   = &escape($xlabel);
13515:     $ValuesHash{$id.'.ylabel'}   = &escape($ylabel);
13516:     $ValuesHash{$id.'.y_max_value'} = $Max;
13517:     $ValuesHash{$id.'.NumBars'}  = $NumBars;
13518:     $ValuesHash{$id.'.NumSets'}  = $NumSets;
13519:     $ValuesHash{$id.'.PlotType'} = 'bar';
13520:     $ValuesHash{$id.'.Colors'}   = join(',',@{$colors});
13521:     $ValuesHash{$id.'.height'}   = $height;
13522:     $ValuesHash{$id.'.width'}    = $width;
13523:     $ValuesHash{$id.'.xskip'}    = $xskip;
13524:     $ValuesHash{$id.'.bar_width'} = $bar_width;
13525:     $ValuesHash{$id.'.labels'} = join(',',@Labels);
13526:     #
13527:     # Deal with other parameters
13528:     while (my ($key,$value) = each(%$extra_settings)) {
13529:         $ValuesHash{$id.'.'.$key} = $value;
13530:     }
13531:     #
13532:     &Apache::lonnet::appenv(\%ValuesHash);
13533:     return '<img src="/cgi-bin/graph.png?'.$identifier.'" border="1" />';
13534: }
13535: 
13536: ############################################################
13537: ############################################################
13538: 
13539: =pod
13540: 
13541: =item * &DrawXYGraph()
13542: 
13543: Facilitates the plotting of data in an XY graph.
13544: Puts plot definition data into the users environment in order for 
13545: graph.png to plot it.  Returns an <img> tag for the plot.
13546: 
13547: Inputs:
13548: 
13549: =over 4
13550: 
13551: =item $Title: string, the title of the plot
13552: 
13553: =item $xlabel: string, text describing the X-axis of the plot
13554: 
13555: =item $ylabel: string, text describing the Y-axis of the plot
13556: 
13557: =item $Max: scalar, the maximum Y value to use in the plot
13558: If $Max is < any data point, the graph will not be rendered.
13559: 
13560: =item $colors: Array ref containing the hex color codes for the data to be 
13561: plotted in.  If undefined, default values will be used.
13562: 
13563: =item $Xlabels: Array ref containing the labels to be used for the X-axis.
13564: 
13565: =item $Ydata: Array ref containing Array refs.  
13566: Each of the contained arrays will be plotted as a separate curve.
13567: 
13568: =item %Values: hash indicating or overriding any default values which are 
13569: passed to graph.png.  
13570: Possible values are: width, xskip, x_ticks, x_tick_offset, among others.
13571: 
13572: =back
13573: 
13574: Returns:
13575: 
13576: An <img> tag which references graph.png and the appropriate identifying
13577: information for the plot.
13578: 
13579: =cut
13580: 
13581: ############################################################
13582: ############################################################
13583: sub DrawXYGraph {
13584:     my ($Title,$xlabel,$ylabel,$Max,$colors,$Xlabels,$Ydata,%Values)=@_;
13585:     #
13586:     # Create the identifier for the graph
13587:     my $identifier = &get_cgi_id();
13588:     my $id = 'cgi.'.$identifier;
13589:     #
13590:     $Title  = '' if (! defined($Title));
13591:     $xlabel = '' if (! defined($xlabel));
13592:     $ylabel = '' if (! defined($ylabel));
13593:     my %ValuesHash = 
13594:         (
13595:          $id.'.title'  => &escape($Title),
13596:          $id.'.xlabel' => &escape($xlabel),
13597:          $id.'.ylabel' => &escape($ylabel),
13598:          $id.'.y_max_value'=> $Max,
13599:          $id.'.labels'     => join(',',@$Xlabels),
13600:          $id.'.PlotType'   => 'XY',
13601:          );
13602:     #
13603:     if (defined($colors) && ref($colors) eq 'ARRAY') {
13604:         $ValuesHash{$id.'.Colors'}   = join(',',@{$colors});
13605:     }
13606:     #
13607:     if (! ref($Ydata) || ref($Ydata) ne 'ARRAY') {
13608:         return '';
13609:     }
13610:     my $NumSets=1;
13611:     foreach my $array (@{$Ydata}){
13612:         next if (! ref($array));
13613:         $ValuesHash{$id.'.data.'.$NumSets++} = join(',',@$array);
13614:     }
13615:     $ValuesHash{$id.'.NumSets'} = $NumSets-1;
13616:     #
13617:     # Deal with other parameters
13618:     while (my ($key,$value) = each(%Values)) {
13619:         $ValuesHash{$id.'.'.$key} = $value;
13620:     }
13621:     #
13622:     &Apache::lonnet::appenv(\%ValuesHash);
13623:     return '<img src="/cgi-bin/graph.png?'.$identifier.'" border="1" />';
13624: }
13625: 
13626: ############################################################
13627: ############################################################
13628: 
13629: =pod
13630: 
13631: =item * &DrawXYYGraph()
13632: 
13633: Facilitates the plotting of data in an XY graph with two Y axes.
13634: Puts plot definition data into the users environment in order for 
13635: graph.png to plot it.  Returns an <img> tag for the plot.
13636: 
13637: Inputs:
13638: 
13639: =over 4
13640: 
13641: =item $Title: string, the title of the plot
13642: 
13643: =item $xlabel: string, text describing the X-axis of the plot
13644: 
13645: =item $ylabel: string, text describing the Y-axis of the plot
13646: 
13647: =item $colors: Array ref containing the hex color codes for the data to be 
13648: plotted in.  If undefined, default values will be used.
13649: 
13650: =item $Xlabels: Array ref containing the labels to be used for the X-axis.
13651: 
13652: =item $Ydata1: The first data set
13653: 
13654: =item $Min1: The minimum value of the left Y-axis
13655: 
13656: =item $Max1: The maximum value of the left Y-axis
13657: 
13658: =item $Ydata2: The second data set
13659: 
13660: =item $Min2: The minimum value of the right Y-axis
13661: 
13662: =item $Max2: The maximum value of the left Y-axis
13663: 
13664: =item %Values: hash indicating or overriding any default values which are 
13665: passed to graph.png.  
13666: Possible values are: width, xskip, x_ticks, x_tick_offset, among others.
13667: 
13668: =back
13669: 
13670: Returns:
13671: 
13672: An <img> tag which references graph.png and the appropriate identifying
13673: information for the plot.
13674: 
13675: =cut
13676: 
13677: ############################################################
13678: ############################################################
13679: sub DrawXYYGraph {
13680:     my ($Title,$xlabel,$ylabel,$colors,$Xlabels,$Ydata1,$Min1,$Max1,
13681:                                         $Ydata2,$Min2,$Max2,%Values)=@_;
13682:     #
13683:     # Create the identifier for the graph
13684:     my $identifier = &get_cgi_id();
13685:     my $id = 'cgi.'.$identifier;
13686:     #
13687:     $Title  = '' if (! defined($Title));
13688:     $xlabel = '' if (! defined($xlabel));
13689:     $ylabel = '' if (! defined($ylabel));
13690:     my %ValuesHash = 
13691:         (
13692:          $id.'.title'  => &escape($Title),
13693:          $id.'.xlabel' => &escape($xlabel),
13694:          $id.'.ylabel' => &escape($ylabel),
13695:          $id.'.labels' => join(',',@$Xlabels),
13696:          $id.'.PlotType' => 'XY',
13697:          $id.'.NumSets' => 2,
13698:          $id.'.two_axes' => 1,
13699:          $id.'.y1_max_value' => $Max1,
13700:          $id.'.y1_min_value' => $Min1,
13701:          $id.'.y2_max_value' => $Max2,
13702:          $id.'.y2_min_value' => $Min2,
13703:          );
13704:     #
13705:     if (defined($colors) && ref($colors) eq 'ARRAY') {
13706:         $ValuesHash{$id.'.Colors'}   = join(',',@{$colors});
13707:     }
13708:     #
13709:     if (! ref($Ydata1) || ref($Ydata1) ne 'ARRAY' ||
13710:         ! ref($Ydata2) || ref($Ydata2) ne 'ARRAY'){
13711:         return '';
13712:     }
13713:     my $NumSets=1;
13714:     foreach my $array ($Ydata1,$Ydata2){
13715:         next if (! ref($array));
13716:         $ValuesHash{$id.'.data.'.$NumSets++} = join(',',@$array);
13717:     }
13718:     #
13719:     # Deal with other parameters
13720:     while (my ($key,$value) = each(%Values)) {
13721:         $ValuesHash{$id.'.'.$key} = $value;
13722:     }
13723:     #
13724:     &Apache::lonnet::appenv(\%ValuesHash);
13725:     return '<img src="/cgi-bin/graph.png?'.$identifier.'" border="1" />';
13726: }
13727: 
13728: ############################################################
13729: ############################################################
13730: 
13731: =pod
13732: 
13733: =back 
13734: 
13735: =head1 Statistics helper routines?  
13736: 
13737: Bad place for them but what the hell.
13738: 
13739: =over 4
13740: 
13741: =item * &chartlink()
13742: 
13743: Returns a link to the chart for a specific student.  
13744: 
13745: Inputs:
13746: 
13747: =over 4
13748: 
13749: =item $linktext: The text of the link
13750: 
13751: =item $sname: The students username
13752: 
13753: =item $sdomain: The students domain
13754: 
13755: =back
13756: 
13757: =back
13758: 
13759: =cut
13760: 
13761: ############################################################
13762: ############################################################
13763: sub chartlink {
13764:     my ($linktext, $sname, $sdomain) = @_;
13765:     my $link = '<a href="/adm/statistics?reportSelected=student_assessment'.
13766:         '&amp;SelectedStudent='.&escape($sname.':'.$sdomain).
13767:         '&amp;chartoutputmode='.HTML::Entities::encode('html, with all links').
13768:        '">'.$linktext.'</a>';
13769: }
13770: 
13771: #######################################################
13772: #######################################################
13773: 
13774: =pod
13775: 
13776: =head1 Course Environment Routines
13777: 
13778: =over 4
13779: 
13780: =item * &restore_course_settings()
13781: 
13782: =item * &store_course_settings()
13783: 
13784: Restores/Store indicated form parameters from the course environment.
13785: Will not overwrite existing values of the form parameters.
13786: 
13787: Inputs: 
13788: a scalar describing the data (e.g. 'chart', 'problem_analysis')
13789: 
13790: a hash ref describing the data to be stored.  For example:
13791:    
13792: %Save_Parameters = ('Status' => 'scalar',
13793:     'chartoutputmode' => 'scalar',
13794:     'chartoutputdata' => 'scalar',
13795:     'Section' => 'array',
13796:     'Group' => 'array',
13797:     'StudentData' => 'array',
13798:     'Maps' => 'array');
13799: 
13800: Returns: both routines return nothing
13801: 
13802: =back
13803: 
13804: =cut
13805: 
13806: #######################################################
13807: #######################################################
13808: sub store_course_settings {
13809:     return &store_settings($env{'request.course.id'},@_);
13810: }
13811: 
13812: sub store_settings {
13813:     # save to the environment
13814:     # appenv the same items, just to be safe
13815:     my $udom  = $env{'user.domain'};
13816:     my $uname = $env{'user.name'};
13817:     my ($context,$prefix,$Settings) = @_;
13818:     my %SaveHash;
13819:     my %AppHash;
13820:     while (my ($setting,$type) = each(%$Settings)) {
13821:         my $basename = join('.','internal',$context,$prefix,$setting);
13822:         my $envname = 'environment.'.$basename;
13823:         if (exists($env{'form.'.$setting})) {
13824:             # Save this value away
13825:             if ($type eq 'scalar' &&
13826:                 (! exists($env{$envname}) || 
13827:                  $env{$envname} ne $env{'form.'.$setting})) {
13828:                 $SaveHash{$basename} = $env{'form.'.$setting};
13829:                 $AppHash{$envname}   = $env{'form.'.$setting};
13830:             } elsif ($type eq 'array') {
13831:                 my $stored_form;
13832:                 if (ref($env{'form.'.$setting})) {
13833:                     $stored_form = join(',',
13834:                                         map {
13835:                                             &escape($_);
13836:                                         } sort(@{$env{'form.'.$setting}}));
13837:                 } else {
13838:                     $stored_form = 
13839:                         &escape($env{'form.'.$setting});
13840:                 }
13841:                 # Determine if the array contents are the same.
13842:                 if ($stored_form ne $env{$envname}) {
13843:                     $SaveHash{$basename} = $stored_form;
13844:                     $AppHash{$envname}   = $stored_form;
13845:                 }
13846:             }
13847:         }
13848:     }
13849:     my $put_result = &Apache::lonnet::put('environment',\%SaveHash,
13850:                                           $udom,$uname);
13851:     if ($put_result !~ /^(ok|delayed)/) {
13852:         &Apache::lonnet::logthis('unable to save form parameters, '.
13853:                                  'got error:'.$put_result);
13854:     }
13855:     # Make sure these settings stick around in this session, too
13856:     &Apache::lonnet::appenv(\%AppHash);
13857:     return;
13858: }
13859: 
13860: sub restore_course_settings {
13861:     return &restore_settings($env{'request.course.id'},@_);
13862: }
13863: 
13864: sub restore_settings {
13865:     my ($context,$prefix,$Settings) = @_;
13866:     while (my ($setting,$type) = each(%$Settings)) {
13867:         next if (exists($env{'form.'.$setting}));
13868:         my $envname = 'environment.internal.'.$context.'.'.$prefix.
13869:             '.'.$setting;
13870:         if (exists($env{$envname})) {
13871:             if ($type eq 'scalar') {
13872:                 $env{'form.'.$setting} = $env{$envname};
13873:             } elsif ($type eq 'array') {
13874:                 $env{'form.'.$setting} = [ 
13875:                                            map { 
13876:                                                &unescape($_); 
13877:                                            } split(',',$env{$envname})
13878:                                            ];
13879:             }
13880:         }
13881:     }
13882: }
13883: 
13884: #######################################################
13885: #######################################################
13886: 
13887: =pod
13888: 
13889: =head1 Domain E-mail Routines  
13890: 
13891: =over 4
13892: 
13893: =item * &build_recipient_list()
13894: 
13895: Build recipient lists for following types of e-mail:
13896: (a) Error Reports, (b) Package Updates, (c) lonstatus warnings/errors
13897: (d) Help requests, (e) Course requests needing approval, (f) loncapa
13898: module change checking, student/employee ID conflict checks, as
13899: generated by lonerrorhandler.pm, CHECKRPMS, loncron,
13900: lonsupportreq.pm, loncoursequeueadmin.pm, searchcat.pl respectively.
13901: 
13902: Inputs:
13903: defmail (scalar - email address of default recipient),
13904: mailing type (scalar: errormail, packagesmail, helpdeskmail,
13905: requestsmail, updatesmail, or idconflictsmail).
13906: 
13907: defdom (domain for which to retrieve configuration settings),
13908: 
13909: origmail (scalar - email address of recipient from loncapa.conf,
13910: i.e., predates configuration by DC via domainprefs.pm
13911: 
13912: Returns: comma separated list of addresses to which to send e-mail.
13913: 
13914: =back
13915: 
13916: =cut
13917: 
13918: ############################################################
13919: ############################################################
13920: sub build_recipient_list {
13921:     my ($defmail,$mailing,$defdom,$origmail) = @_;
13922:     my @recipients;
13923:     my $otheremails;
13924:     my %domconfig =
13925:          &Apache::lonnet::get_dom('configuration',['contacts'],$defdom);
13926:     if (ref($domconfig{'contacts'}) eq 'HASH') {
13927:         if (exists($domconfig{'contacts'}{$mailing})) {
13928:             if (ref($domconfig{'contacts'}{$mailing}) eq 'HASH') {
13929:                 my @contacts = ('adminemail','supportemail');
13930:                 foreach my $item (@contacts) {
13931:                     if ($domconfig{'contacts'}{$mailing}{$item}) {
13932:                         my $addr = $domconfig{'contacts'}{$item}; 
13933:                         if (!grep(/^\Q$addr\E$/,@recipients)) {
13934:                             push(@recipients,$addr);
13935:                         }
13936:                     }
13937:                     $otheremails = $domconfig{'contacts'}{$mailing}{'others'};
13938:                 }
13939:             }
13940:         } elsif ($origmail ne '') {
13941:             push(@recipients,$origmail);
13942:         }
13943:     } elsif ($origmail ne '') {
13944:         push(@recipients,$origmail);
13945:     }
13946:     if (defined($defmail)) {
13947:         if ($defmail ne '') {
13948:             push(@recipients,$defmail);
13949:         }
13950:     }
13951:     if ($otheremails) {
13952:         my @others;
13953:         if ($otheremails =~ /,/) {
13954:             @others = split(/,/,$otheremails);
13955:         } else {
13956:             push(@others,$otheremails);
13957:         }
13958:         foreach my $addr (@others) {
13959:             if (!grep(/^\Q$addr\E$/,@recipients)) {
13960:                 push(@recipients,$addr);
13961:             }
13962:         }
13963:     }
13964:     my $recipientlist = join(',',@recipients); 
13965:     return $recipientlist;
13966: }
13967: 
13968: ############################################################
13969: ############################################################
13970: 
13971: =pod
13972: 
13973: =head1 Course Catalog Routines
13974: 
13975: =over 4
13976: 
13977: =item * &gather_categories()
13978: 
13979: Converts category definitions - keys of categories hash stored in  
13980: coursecategories in configuration.db on the primary library server in a 
13981: domain - to an array.  Also generates javascript and idx hash used to 
13982: generate Domain Coordinator interface for editing Course Categories.
13983: 
13984: Inputs:
13985: 
13986: categories (reference to hash of category definitions).
13987: 
13988: cats (reference to array of arrays/hashes which encapsulates hierarchy of
13989:       categories and subcategories).
13990: 
13991: idx (reference to hash of counters used in Domain Coordinator interface for 
13992:       editing Course Categories).
13993: 
13994: jsarray (reference to array of categories used to create Javascript arrays for
13995:          Domain Coordinator interface for editing Course Categories).
13996: 
13997: Returns: nothing
13998: 
13999: Side effects: populates cats, idx and jsarray. 
14000: 
14001: =cut
14002: 
14003: sub gather_categories {
14004:     my ($categories,$cats,$idx,$jsarray) = @_;
14005:     my %counters;
14006:     my $num = 0;
14007:     foreach my $item (keys(%{$categories})) {
14008:         my ($cat,$container,$depth) = map { &unescape($_); } split(/:/,$item);
14009:         if ($container eq '' && $depth == 0) {
14010:             $cats->[$depth][$categories->{$item}] = $cat;
14011:         } else {
14012:             $cats->[$depth]{$container}[$categories->{$item}] = $cat;
14013:         }
14014:         my ($escitem,$tail) = split(/:/,$item,2);
14015:         if ($counters{$tail} eq '') {
14016:             $counters{$tail} = $num;
14017:             $num ++;
14018:         }
14019:         if (ref($idx) eq 'HASH') {
14020:             $idx->{$item} = $counters{$tail};
14021:         }
14022:         if (ref($jsarray) eq 'ARRAY') {
14023:             push(@{$jsarray->[$counters{$tail}]},$item);
14024:         }
14025:     }
14026:     return;
14027: }
14028: 
14029: =pod
14030: 
14031: =item * &extract_categories()
14032: 
14033: Used to generate breadcrumb trails for course categories.
14034: 
14035: Inputs:
14036: 
14037: categories (reference to hash of category definitions).
14038: 
14039: cats (reference to array of arrays/hashes which encapsulates hierarchy of
14040:       categories and subcategories).
14041: 
14042: trails (reference to array of breacrumb trails for each category).
14043: 
14044: allitems (reference to hash - key is category key 
14045:          (format: escaped(name):escaped(parent category):depth in hierarchy).
14046: 
14047: idx (reference to hash of counters used in Domain Coordinator interface for
14048:       editing Course Categories).
14049: 
14050: jsarray (reference to array of categories used to create Javascript arrays for
14051:          Domain Coordinator interface for editing Course Categories).
14052: 
14053: subcats (reference to hash of arrays containing all subcategories within each 
14054:          category, -recursive)
14055: 
14056: Returns: nothing
14057: 
14058: Side effects: populates trails and allitems hash references.
14059: 
14060: =cut
14061: 
14062: sub extract_categories {
14063:     my ($categories,$cats,$trails,$allitems,$idx,$jsarray,$subcats) = @_;
14064:     if (ref($categories) eq 'HASH') {
14065:         &gather_categories($categories,$cats,$idx,$jsarray);
14066:         if (ref($cats->[0]) eq 'ARRAY') {
14067:             for (my $i=0; $i<@{$cats->[0]}; $i++) {
14068:                 my $name = $cats->[0][$i];
14069:                 my $item = &escape($name).'::0';
14070:                 my $trailstr;
14071:                 if ($name eq 'instcode') {
14072:                     $trailstr = &mt('Official courses (with institutional codes)');
14073:                 } elsif ($name eq 'communities') {
14074:                     $trailstr = &mt('Communities');
14075:                 } else {
14076:                     $trailstr = $name;
14077:                 }
14078:                 if ($allitems->{$item} eq '') {
14079:                     push(@{$trails},$trailstr);
14080:                     $allitems->{$item} = scalar(@{$trails})-1;
14081:                 }
14082:                 my @parents = ($name);
14083:                 if (ref($cats->[1]{$name}) eq 'ARRAY') {
14084:                     for (my $j=0; $j<@{$cats->[1]{$name}}; $j++) {
14085:                         my $category = $cats->[1]{$name}[$j];
14086:                         if (ref($subcats) eq 'HASH') {
14087:                             push(@{$subcats->{$item}},&escape($category).':'.&escape($name).':1');
14088:                         }
14089:                         &recurse_categories($cats,2,$category,$trails,$allitems,\@parents,$subcats);
14090:                     }
14091:                 } else {
14092:                     if (ref($subcats) eq 'HASH') {
14093:                         $subcats->{$item} = [];
14094:                     }
14095:                 }
14096:             }
14097:         }
14098:     }
14099:     return;
14100: }
14101: 
14102: =pod
14103: 
14104: =item * &recurse_categories()
14105: 
14106: Recursively used to generate breadcrumb trails for course categories.
14107: 
14108: Inputs:
14109: 
14110: cats (reference to array of arrays/hashes which encapsulates hierarchy of
14111:       categories and subcategories).
14112: 
14113: depth (current depth in hierarchy of categories and sub-categories - 0 indexed).
14114: 
14115: category (current course category, for which breadcrumb trail is being generated).
14116: 
14117: trails (reference to array of breadcrumb trails for each category).
14118: 
14119: allitems (reference to hash - key is category key
14120:          (format: escaped(name):escaped(parent category):depth in hierarchy).
14121: 
14122: parents (array containing containers directories for current category, 
14123:          back to top level). 
14124: 
14125: Returns: nothing
14126: 
14127: Side effects: populates trails and allitems hash references
14128: 
14129: =cut
14130: 
14131: sub recurse_categories {
14132:     my ($cats,$depth,$category,$trails,$allitems,$parents,$subcats) = @_;
14133:     my $shallower = $depth - 1;
14134:     if (ref($cats->[$depth]{$category}) eq 'ARRAY') {
14135:         for (my $k=0; $k<@{$cats->[$depth]{$category}}; $k++) {
14136:             my $name = $cats->[$depth]{$category}[$k];
14137:             my $item = &escape($category).':'.&escape($parents->[-1]).':'.$shallower;
14138:             my $trailstr = join(' -&gt; ',(@{$parents},$category));
14139:             if ($allitems->{$item} eq '') {
14140:                 push(@{$trails},$trailstr);
14141:                 $allitems->{$item} = scalar(@{$trails})-1;
14142:             }
14143:             my $deeper = $depth+1;
14144:             push(@{$parents},$category);
14145:             if (ref($subcats) eq 'HASH') {
14146:                 my $subcat = &escape($name).':'.$category.':'.$depth;
14147:                 for (my $j=@{$parents}; $j>=0; $j--) {
14148:                     my $higher;
14149:                     if ($j > 0) {
14150:                         $higher = &escape($parents->[$j]).':'.
14151:                                   &escape($parents->[$j-1]).':'.$j;
14152:                     } else {
14153:                         $higher = &escape($parents->[$j]).'::'.$j;
14154:                     }
14155:                     push(@{$subcats->{$higher}},$subcat);
14156:                 }
14157:             }
14158:             &recurse_categories($cats,$deeper,$name,$trails,$allitems,$parents,
14159:                                 $subcats);
14160:             pop(@{$parents});
14161:         }
14162:     } else {
14163:         my $item = &escape($category).':'.&escape($parents->[-1]).':'.$shallower;
14164:         my $trailstr = join(' -&gt; ',(@{$parents},$category));
14165:         if ($allitems->{$item} eq '') {
14166:             push(@{$trails},$trailstr);
14167:             $allitems->{$item} = scalar(@{$trails})-1;
14168:         }
14169:     }
14170:     return;
14171: }
14172: 
14173: =pod
14174: 
14175: =item * &assign_categories_table()
14176: 
14177: Create a datatable for display of hierarchical categories in a domain,
14178: with checkboxes to allow a course to be categorized. 
14179: 
14180: Inputs:
14181: 
14182: cathash - reference to hash of categories defined for the domain (from
14183:           configuration.db)
14184: 
14185: currcat - scalar with an & separated list of categories assigned to a course. 
14186: 
14187: type    - scalar contains course type (Course or Community).
14188: 
14189: Returns: $output (markup to be displayed) 
14190: 
14191: =cut
14192: 
14193: sub assign_categories_table {
14194:     my ($cathash,$currcat,$type) = @_;
14195:     my $output;
14196:     if (ref($cathash) eq 'HASH') {
14197:         my (@cats,@trails,%allitems,%idx,@jsarray,@path,$maxdepth);
14198:         &extract_categories($cathash,\@cats,\@trails,\%allitems,\%idx,\@jsarray);
14199:         $maxdepth = scalar(@cats);
14200:         if (@cats > 0) {
14201:             my $itemcount = 0;
14202:             if (ref($cats[0]) eq 'ARRAY') {
14203:                 my @currcategories;
14204:                 if ($currcat ne '') {
14205:                     @currcategories = split('&',$currcat);
14206:                 }
14207:                 my $table;
14208:                 for (my $i=0; $i<@{$cats[0]}; $i++) {
14209:                     my $parent = $cats[0][$i];
14210:                     next if ($parent eq 'instcode');
14211:                     if ($type eq 'Community') {
14212:                         next unless ($parent eq 'communities');
14213:                     } else {
14214:                         next if ($parent eq 'communities');
14215:                     }
14216:                     my $css_class = $itemcount%2?' class="LC_odd_row"':'';
14217:                     my $item = &escape($parent).'::0';
14218:                     my $checked = '';
14219:                     if (@currcategories > 0) {
14220:                         if (grep(/^\Q$item\E$/,@currcategories)) {
14221:                             $checked = ' checked="checked"';
14222:                         }
14223:                     }
14224:                     my $parent_title = $parent;
14225:                     if ($parent eq 'communities') {
14226:                         $parent_title = &mt('Communities');
14227:                     }
14228:                     $table .= '<tr '.$css_class.'><td><span class="LC_nobreak">'.
14229:                               '<input type="checkbox" name="usecategory" value="'.
14230:                               $item.'"'.$checked.' />'.$parent_title.'</span>'.
14231:                               '<input type="hidden" name="catname" value="'.$parent.'" /></td>';
14232:                     my $depth = 1;
14233:                     push(@path,$parent);
14234:                     $table .= &assign_category_rows($itemcount,\@cats,$depth,$parent,\@path,\@currcategories);
14235:                     pop(@path);
14236:                     $table .= '</tr><tr><td colspan="'.$maxdepth.'" class="LC_row_separator"></td></tr>';
14237:                     $itemcount ++;
14238:                 }
14239:                 if ($itemcount) {
14240:                     $output = &Apache::loncommon::start_data_table().
14241:                               $table.
14242:                               &Apache::loncommon::end_data_table();
14243:                 }
14244:             }
14245:         }
14246:     }
14247:     return $output;
14248: }
14249: 
14250: =pod
14251: 
14252: =item * &assign_category_rows()
14253: 
14254: Create a datatable row for display of nested categories in a domain,
14255: with checkboxes to allow a course to be categorized,called recursively.
14256: 
14257: Inputs:
14258: 
14259: itemcount - track row number for alternating colors
14260: 
14261: cats - reference to array of arrays/hashes which encapsulates hierarchy of
14262:       categories and subcategories.
14263: 
14264: depth - current depth in hierarchy of categories and sub-categories - 0 indexed.
14265: 
14266: parent - parent of current category item
14267: 
14268: path - Array containing all categories back up through the hierarchy from the
14269:        current category to the top level.
14270: 
14271: currcategories - reference to array of current categories assigned to the course
14272: 
14273: Returns: $output (markup to be displayed).
14274: 
14275: =cut
14276: 
14277: sub assign_category_rows {
14278:     my ($itemcount,$cats,$depth,$parent,$path,$currcategories) = @_;
14279:     my ($text,$name,$item,$chgstr);
14280:     if (ref($cats) eq 'ARRAY') {
14281:         my $maxdepth = scalar(@{$cats});
14282:         if (ref($cats->[$depth]) eq 'HASH') {
14283:             if (ref($cats->[$depth]{$parent}) eq 'ARRAY') {
14284:                 my $numchildren = @{$cats->[$depth]{$parent}};
14285:                 my $css_class = $itemcount%2?' class="LC_odd_row"':'';
14286:                 $text .= '<td><table class="LC_data_table">';
14287:                 for (my $j=0; $j<$numchildren; $j++) {
14288:                     $name = $cats->[$depth]{$parent}[$j];
14289:                     $item = &escape($name).':'.&escape($parent).':'.$depth;
14290:                     my $deeper = $depth+1;
14291:                     my $checked = '';
14292:                     if (ref($currcategories) eq 'ARRAY') {
14293:                         if (@{$currcategories} > 0) {
14294:                             if (grep(/^\Q$item\E$/,@{$currcategories})) {
14295:                                 $checked = ' checked="checked"';
14296:                             }
14297:                         }
14298:                     }
14299:                     $text .= '<tr><td><span class="LC_nobreak"><label>'.
14300:                              '<input type="checkbox" name="usecategory" value="'.
14301:                              $item.'"'.$checked.' />'.$name.'</label></span>'.
14302:                              '<input type="hidden" name="catname" value="'.$name.'" />'.
14303:                              '</td><td>';
14304:                     if (ref($path) eq 'ARRAY') {
14305:                         push(@{$path},$name);
14306:                         $text .= &assign_category_rows($itemcount,$cats,$deeper,$name,$path,$currcategories);
14307:                         pop(@{$path});
14308:                     }
14309:                     $text .= '</td></tr>';
14310:                 }
14311:                 $text .= '</table></td>';
14312:             }
14313:         }
14314:     }
14315:     return $text;
14316: }
14317: 
14318: =pod
14319: 
14320: =back
14321: 
14322: =cut
14323: 
14324: ############################################################
14325: ############################################################
14326: 
14327: 
14328: sub commit_customrole {
14329:     my ($udom,$uname,$url,$three,$four,$five,$start,$end,$context) = @_;
14330:     my $output = &mt('Assigning custom role').' "'.$five.'" by '.$four.':'.$three.' in '.$url.
14331:                          ($start?', '.&mt('starting').' '.localtime($start):'').
14332:                          ($end?', ending '.localtime($end):'').': <b>'.
14333:               &Apache::lonnet::assigncustomrole(
14334:                  $udom,$uname,$url,$three,$four,$five,$end,$start,undef,undef,$context).
14335:                  '</b><br />';
14336:     return $output;
14337: }
14338: 
14339: sub commit_standardrole {
14340:     my ($udom,$uname,$url,$three,$start,$end,$one,$two,$sec,$context,$credits) = @_;
14341:     my ($output,$logmsg,$linefeed);
14342:     if ($context eq 'auto') {
14343:         $linefeed = "\n";
14344:     } else {
14345:         $linefeed = "<br />\n";
14346:     }  
14347:     if ($three eq 'st') {
14348:         my $result = &commit_studentrole(\$logmsg,$udom,$uname,$url,$three,$start,$end,
14349:                                          $one,$two,$sec,$context,$credits);
14350:         if (($result =~ /^error/) || ($result eq 'not_in_class') || 
14351:             ($result eq 'unknown_course') || ($result eq 'refused')) {
14352:             $output = $logmsg.' '.&mt('Error: ').$result."\n"; 
14353:         } else {
14354:             $output = $logmsg.$linefeed.&mt('Assigning').' '.$three.' in '.$url.
14355:                ($start?', '.&mt('starting').' '.localtime($start):'').
14356:                ($end?', '.&mt('ending').' '.localtime($end):'').': ';
14357:             if ($context eq 'auto') {
14358:                 $output .= $result.$linefeed.&mt('Add to classlist').': ok';
14359:             } else {
14360:                $output .= '<b>'.$result.'</b>'.$linefeed.
14361:                &mt('Add to classlist').': <b>ok</b>';
14362:             }
14363:             $output .= $linefeed;
14364:         }
14365:     } else {
14366:         $output = &mt('Assigning').' '.$three.' in '.$url.
14367:                ($start?', '.&mt('starting').' '.localtime($start):'').
14368:                ($end?', '.&mt('ending').' '.localtime($end):'').': ';
14369:         my $result = &Apache::lonnet::assignrole($udom,$uname,$url,$three,$end,$start,'','',$context);
14370:         if ($context eq 'auto') {
14371:             $output .= $result.$linefeed;
14372:         } else {
14373:             $output .= '<b>'.$result.'</b>'.$linefeed;
14374:         }
14375:     }
14376:     return $output;
14377: }
14378: 
14379: sub commit_studentrole {
14380:     my ($logmsg,$udom,$uname,$url,$three,$start,$end,$one,$two,$sec,$context,
14381:         $credits) = @_;
14382:     my ($result,$linefeed,$oldsecurl,$newsecurl);
14383:     if ($context eq 'auto') {
14384:         $linefeed = "\n";
14385:     } else {
14386:         $linefeed = '<br />'."\n";
14387:     }
14388:     if (defined($one) && defined($two)) {
14389:         my $cid=$one.'_'.$two;
14390:         my $oldsec=&Apache::lonnet::getsection($udom,$uname,$cid);
14391:         my $secchange = 0;
14392:         my $expire_role_result;
14393:         my $modify_section_result;
14394:         if ($oldsec ne '-1') { 
14395:             if ($oldsec ne $sec) {
14396:                 $secchange = 1;
14397:                 my $now = time;
14398:                 my $uurl='/'.$cid;
14399:                 $uurl=~s/\_/\//g;
14400:                 if ($oldsec) {
14401:                     $uurl.='/'.$oldsec;
14402:                 }
14403:                 $oldsecurl = $uurl;
14404:                 $expire_role_result = 
14405:                     &Apache::lonnet::assignrole($udom,$uname,$uurl,'st',$now,'','',$context);
14406:                 if ($env{'request.course.sec'} ne '') { 
14407:                     if ($expire_role_result eq 'refused') {
14408:                         my @roles = ('st');
14409:                         my @statuses = ('previous');
14410:                         my @roledoms = ($one);
14411:                         my $withsec = 1;
14412:                         my %roleshash = 
14413:                             &Apache::lonnet::get_my_roles($uname,$udom,'userroles',
14414:                                               \@statuses,\@roles,\@roledoms,$withsec);
14415:                         if (defined ($roleshash{$two.':'.$one.':st:'.$oldsec})) {
14416:                             my ($oldstart,$oldend) = 
14417:                                 split(':',$roleshash{$two.':'.$one.':st:'.$oldsec});
14418:                             if ($oldend > 0 && $oldend <= $now) {
14419:                                 $expire_role_result = 'ok';
14420:                             }
14421:                         }
14422:                     }
14423:                 }
14424:                 $result = $expire_role_result;
14425:             }
14426:         }
14427:         if (($expire_role_result eq 'ok') || ($secchange == 0)) {
14428:             $modify_section_result = 
14429:                 &Apache::lonnet::modify_student_enrollment($udom,$uname,undef,undef,
14430:                                                            undef,undef,undef,$sec,
14431:                                                            $end,$start,'','',$cid,
14432:                                                            '',$context,$credits);
14433:             if ($modify_section_result =~ /^ok/) {
14434:                 if ($secchange == 1) {
14435:                     if ($sec eq '') {
14436:                         $$logmsg .= &mt('Section for [_1] switched from (possibly expired) old section: [_2] to student role without a section.',$uname,$oldsec).$linefeed;
14437:                     } else {
14438:                         $$logmsg .= &mt('Section for [_1] switched from (possibly expired) old section: [_2] to new section: [_3].',$uname,$oldsec,$sec).$linefeed;
14439:                     }
14440:                 } elsif ($oldsec eq '-1') {
14441:                     if ($sec eq '') {
14442:                         $$logmsg .= &mt('New student role without a section for [_1] in course [_2].',$uname,$cid).$linefeed;
14443:                     } else {
14444:                         $$logmsg .= &mt('New student role for [_1] in section [_2] in course [_3].',$uname,$sec,$cid).$linefeed;
14445:                     }
14446:                 } else {
14447:                     if ($sec eq '') {
14448:                         $$logmsg .= &mt('Student [_1] assigned to course [_2] without a section.',$uname,$cid).$linefeed;
14449:                     } else {
14450:                         $$logmsg .= &mt('Student [_1] assigned to section [_2] in course [_3].',$uname,$sec,$cid).$linefeed;
14451:                     }
14452:                 }
14453:             } else {
14454:                 if ($secchange) {       
14455:                     $$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;
14456:                 } else {
14457:                     $$logmsg .= &mt('Error when attempting to modify role for [_1] for section: "[_2]" in course [_3] -error:',$uname,$sec,$cid).' '.$modify_section_result.$linefeed;
14458:                 }
14459:             }
14460:             $result = $modify_section_result;
14461:         } elsif ($secchange == 1) {
14462:             if ($oldsec eq '') {
14463:                 $$logmsg .= &mt('Error when attempting to expire existing role without a section for [_1] in course [_2] -error: ',$uname,$cid).' '.$expire_role_result.$linefeed;
14464:             } else {
14465:                 $$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;
14466:             }
14467:             if ($expire_role_result eq 'refused') {
14468:                 my $newsecurl = '/'.$cid;
14469:                 $newsecurl =~ s/\_/\//g;
14470:                 if ($sec ne '') {
14471:                     $newsecurl.='/'.$sec;
14472:                 }
14473:                 if (&Apache::lonnet::allowed('cst',$newsecurl) && !(&Apache::lonnet::allowed('cst',$oldsecurl))) {
14474:                     if ($sec eq '') {
14475:                         $$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;
14476:                     } else {
14477:                         $$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;
14478:                     }
14479:                 }
14480:             }
14481:         }
14482:     } else {
14483:         $$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;
14484:         $result = "error: incomplete course id\n";
14485:     }
14486:     return $result;
14487: }
14488: 
14489: sub show_role_extent {
14490:     my ($scope,$context,$role) = @_;
14491:     $scope =~ s{^/}{};
14492:     my @courseroles = &Apache::lonuserutils::roles_by_context('course',1);
14493:     push(@courseroles,'co');
14494:     my @authorroles = &Apache::lonuserutils::roles_by_context('author');
14495:     if (($context eq 'course') || (grep(/^\Q$role\E/,@courseroles))) {
14496:         $scope =~ s{/}{_};
14497:         return '<span class="LC_cusr_emph">'.$env{'course.'.$scope.'.description'}.'</span>';
14498:     } elsif (($context eq 'author') || (grep(/^\Q$role\E/,@authorroles))) {
14499:         my ($audom,$auname) = split(/\//,$scope);
14500:         return &mt('[_1] Author Space','<span class="LC_cusr_emph">'.
14501:                    &Apache::loncommon::plainname($auname,$audom).'</span>');
14502:     } else {
14503:         $scope =~ s{/$}{};
14504:         return &mt('Domain: [_1]','<span class="LC_cusr_emph">'.
14505:                    &Apache::lonnet::domain($scope,'description').'</span>');
14506:     }
14507: }
14508: 
14509: ############################################################
14510: ############################################################
14511: 
14512: sub check_clone {
14513:     my ($args,$linefeed) = @_;
14514:     my $cloneid='/'.$args->{'clonedomain'}.'/'.$args->{'clonecourse'};
14515:     my ($clonecrsudom,$clonecrsunum)= &LONCAPA::split_courseid($cloneid);
14516:     my $clonehome=&Apache::lonnet::homeserver($clonecrsunum,$clonecrsudom);
14517:     my $clonemsg;
14518:     my $can_clone = 0;
14519:     my $lctype = lc($args->{'crstype'});
14520:     if ($lctype ne 'community') {
14521:         $lctype = 'course';
14522:     }
14523:     if ($clonehome eq 'no_host') {
14524:         if ($args->{'crstype'} eq 'Community') {
14525:             $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'});
14526:         } else {
14527:             $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'});
14528:         }     
14529:     } else {
14530: 	my %clonedesc = &Apache::lonnet::coursedescription($cloneid,{'one_time' => 1});
14531:         if ($args->{'crstype'} eq 'Community') {
14532:             if ($clonedesc{'type'} ne 'Community') {
14533:                  $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'});
14534:                 return ($can_clone, $clonemsg, $cloneid, $clonehome);
14535:             }
14536:         }
14537: 	if (($env{'request.role.domain'} eq $args->{'clonedomain'}) && 
14538:             (&Apache::lonnet::allowed('ccc',$env{'request.role.domain'}))) {
14539: 	    $can_clone = 1;
14540: 	} else {
14541: 	    my %clonehash = &Apache::lonnet::get('environment',['cloners','internal.coursecode'],
14542: 						 $args->{'clonedomain'},$args->{'clonecourse'});
14543:             if ($clonehash{'cloners'} eq '') {
14544:                 my %domdefs = &Apache::lonnet::get_domain_defaults($args->{'course_domain'});
14545:                 if ($domdefs{'canclone'}) {
14546:                     unless ($domdefs{'canclone'} eq 'none') {
14547:                         if ($domdefs{'canclone'} eq 'domain') {
14548:                             if ($args->{'ccdomain'} eq $args->{'clonedomain'}) {
14549:                                 $can_clone = 1;
14550:                             }
14551:                         } elsif (($clonehash{'internal.coursecode'}) && ($args->{'crscode'}) &&
14552:                                  ($args->{'clonedomain'} eq  $args->{'course_domain'})) {
14553:                             if (&Apache::lonnet::default_instcode_cloning($args->{'clonedomain'},$domdefs{'canclone'},
14554:                                                                           $clonehash{'internal.coursecode'},$args->{'crscode'})) {
14555:                                 $can_clone = 1;
14556:                             }
14557:                         }
14558:                     }
14559:                 }
14560:             } else {
14561: 	        my @cloners = split(/,/,$clonehash{'cloners'});
14562:                 if (grep(/^\*$/,@cloners)) {
14563:                     $can_clone = 1;
14564:                 } elsif (grep(/^\*\:\Q$args->{'ccdomain'}\E$/,@cloners)) {
14565:                     $can_clone = 1;
14566:                 } elsif (grep(/^\Q$args->{'ccuname'}\E:\Q$args->{'ccdomain'}\E$/,@cloners)) {
14567:                     $can_clone = 1;
14568:                 }
14569:                 unless ($can_clone) {
14570:                     if (($clonehash{'internal.coursecode'}) && ($args->{'crscode'}) &&
14571:                         ($args->{'clonedomain'} eq  $args->{'course_domain'})) {
14572:                         my (%gotdomdefaults,%gotcodedefaults);
14573:                         foreach my $cloner (@cloners) {
14574:                             if (($cloner ne '*') && ($cloner !~ /^\*\:$match_domain$/) &&
14575:                                 ($cloner !~ /^$match_username\:$match_domain$/) && ($cloner ne '')) {
14576:                                 my (%codedefaults,@code_order);
14577:                                 if (ref($gotcodedefaults{$args->{'clonedomain'}}) eq 'HASH') {
14578:                                     if (ref($gotcodedefaults{$args->{'clonedomain'}}{'defaults'}) eq 'HASH') {
14579:                                         %codedefaults = %{$gotcodedefaults{$args->{'clonedomain'}}{'defaults'}};
14580:                                     }
14581:                                     if (ref($gotcodedefaults{$args->{'clonedomain'}}{'order'}) eq 'ARRAY') {
14582:                                         @code_order = @{$gotcodedefaults{$args->{'clonedomain'}}{'order'}};
14583:                                     }
14584:                                 } else {
14585:                                     &Apache::lonnet::auto_instcode_defaults($args->{'clonedomain'},
14586:                                                                             \%codedefaults,
14587:                                                                             \@code_order);
14588:                                     $gotcodedefaults{$args->{'clonedomain'}}{'defaults'} = \%codedefaults;
14589:                                     $gotcodedefaults{$args->{'clonedomain'}}{'order'} = \@code_order;
14590:                                 }
14591:                                 if (@code_order > 0) {
14592:                                     if (&Apache::lonnet::check_instcode_cloning(\%codedefaults,\@code_order,
14593:                                                                                 $cloner,$clonehash{'internal.coursecode'},
14594:                                                                                 $args->{'crscode'})) {
14595:                                         $can_clone = 1;
14596:                                         last;
14597:                                     }
14598:                                 }
14599:                             }
14600:                         }
14601:                     }
14602:                 }
14603:             }
14604:             unless ($can_clone) {
14605:                 my $ccrole = 'cc';
14606:                 if ($args->{'crstype'} eq 'Community') {
14607:                     $ccrole = 'co';
14608:                 }
14609:                 my %roleshash =
14610:                     &Apache::lonnet::get_my_roles($args->{'ccuname'},
14611:                                                   $args->{'ccdomain'},
14612:                                                   'userroles',['active'],[$ccrole],
14613:                                                   [$args->{'clonedomain'}]);
14614:                 if ($roleshash{$args->{'clonecourse'}.':'.$args->{'clonedomain'}.':'.$ccrole}) {
14615:                     $can_clone = 1;
14616:                 } elsif (&Apache::lonnet::is_course_owner($args->{'clonedomain'},$args->{'clonecourse'},
14617:                                                           $args->{'ccuname'},$args->{'ccdomain'})) {
14618:                     $can_clone = 1;
14619:                 }
14620:             }
14621:             unless ($can_clone) {
14622:                 if ($args->{'crstype'} eq 'Community') {
14623:                     $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'});
14624:                 } else {
14625:                     $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'});
14626: 	        }
14627: 	    }
14628:         }
14629:     }
14630:     return ($can_clone, $clonemsg, $cloneid, $clonehome);
14631: }
14632: 
14633: sub construct_course {
14634:     my ($args,$logmsg,$courseid,$crsudom,$crsunum,$udom,$uname,$context,$cnum,$category,$coderef) = @_;
14635:     my $outcome;
14636:     my $linefeed =  '<br />'."\n";
14637:     if ($context eq 'auto') {
14638:         $linefeed = "\n";
14639:     }
14640: 
14641: #
14642: # Are we cloning?
14643: #
14644:     my ($can_clone, $clonemsg, $cloneid, $clonehome);
14645:     if (($args->{'clonecourse'}) && ($args->{'clonedomain'})) {
14646: 	($can_clone, $clonemsg, $cloneid, $clonehome) = &check_clone($args,$linefeed);
14647: 	if ($context ne 'auto') {
14648:             if ($clonemsg ne '') {
14649: 	        $clonemsg = '<span class="LC_error">'.$clonemsg.'</span>';
14650:             }
14651: 	}
14652: 	$outcome .= $clonemsg.$linefeed;
14653: 
14654:         if (!$can_clone) {
14655: 	    return (0,$outcome);
14656: 	}
14657:     }
14658: 
14659: #
14660: # Open course
14661: #
14662:     my $crstype = lc($args->{'crstype'});
14663:     my %cenv=();
14664:     $$courseid=&Apache::lonnet::createcourse($args->{'course_domain'},
14665:                                              $args->{'cdescr'},
14666:                                              $args->{'curl'},
14667:                                              $args->{'course_home'},
14668:                                              $args->{'nonstandard'},
14669:                                              $args->{'crscode'},
14670:                                              $args->{'ccuname'}.':'.
14671:                                              $args->{'ccdomain'},
14672:                                              $args->{'crstype'},
14673:                                              $cnum,$context,$category);
14674: 
14675:     # Note: The testing routines depend on this being output; see 
14676:     # Utils::Course. This needs to at least be output as a comment
14677:     # if anyone ever decides to not show this, and Utils::Course::new
14678:     # will need to be suitably modified.
14679:     $outcome .= &mt('New LON-CAPA [_1] ID: [_2]',$crstype,$$courseid).$linefeed;
14680:     if ($$courseid =~ /^error:/) {
14681:         return (0,$outcome);
14682:     }
14683: 
14684: #
14685: # Check if created correctly
14686: #
14687:     ($$crsudom,$$crsunum)= &LONCAPA::split_courseid($$courseid);
14688:     my $crsuhome=&Apache::lonnet::homeserver($$crsunum,$$crsudom);
14689:     if ($crsuhome eq 'no_host') {
14690:         $outcome .= &mt('Course creation failed, unrecognized course home server.').$linefeed;
14691:         return (0,$outcome);
14692:     }
14693:     $outcome .= &mt('Created on').': '.$crsuhome.$linefeed;
14694: 
14695: #
14696: # Do the cloning
14697: #   
14698:     if ($can_clone && $cloneid) {
14699: 	$clonemsg = &mt('Cloning [_1] from [_2]',$crstype,$clonehome);
14700: 	if ($context ne 'auto') {
14701: 	    $clonemsg = '<span class="LC_success">'.$clonemsg.'</span>';
14702: 	}
14703: 	$outcome .= $clonemsg.$linefeed;
14704: 	my %oldcenv=&Apache::lonnet::dump('environment',$$crsudom,$$crsunum);
14705: # Copy all files
14706: 	&Apache::lonclonecourse::copycoursefiles($cloneid,$$courseid,$args->{'datemode'},$args->{'dateshift'});
14707: # Restore URL
14708: 	$cenv{'url'}=$oldcenv{'url'};
14709: # Restore title
14710: 	$cenv{'description'}=$oldcenv{'description'};
14711: # Restore creation date, creator and creation context.
14712:         $cenv{'internal.created'}=$oldcenv{'internal.created'};
14713:         $cenv{'internal.creator'}=$oldcenv{'internal.creator'};
14714:         $cenv{'internal.creationcontext'}=$oldcenv{'internal.creationcontext'};
14715: # Mark as cloned
14716: 	$cenv{'clonedfrom'}=$cloneid;
14717: # Need to clone grading mode
14718:         my %newenv=&Apache::lonnet::get('environment',['grading'],$$crsudom,$$crsunum);
14719:         $cenv{'grading'}=$newenv{'grading'};
14720: # Do not clone these environment entries
14721:         &Apache::lonnet::del('environment',
14722:                   ['default_enrollment_start_date',
14723:                    'default_enrollment_end_date',
14724:                    'question.email',
14725:                    'policy.email',
14726:                    'comment.email',
14727:                    'pch.users.denied',
14728:                    'plc.users.denied',
14729:                    'hidefromcat',
14730:                    'checkforpriv',
14731:                    'categories',
14732:                    'internal.uniquecode'],
14733:                    $$crsudom,$$crsunum);
14734:         if ($args->{'textbook'}) {
14735:             $cenv{'internal.textbook'} = $args->{'textbook'};
14736:         }
14737:     }
14738: 
14739: #
14740: # Set environment (will override cloned, if existing)
14741: #
14742:     my @sections = ();
14743:     my @xlists = ();
14744:     if ($args->{'crstype'}) {
14745:         $cenv{'type'}=$args->{'crstype'};
14746:     }
14747:     if ($args->{'crsid'}) {
14748:         $cenv{'courseid'}=$args->{'crsid'};
14749:     }
14750:     if ($args->{'crscode'}) {
14751:         $cenv{'internal.coursecode'}=$args->{'crscode'};
14752:     }
14753:     if ($args->{'crsquota'} ne '') {
14754:         $cenv{'internal.coursequota'}=$args->{'crsquota'};
14755:     } else {
14756:         $cenv{'internal.coursequota'}=$args->{'crsquota'} = 20;
14757:     }
14758:     if ($args->{'ccuname'}) {
14759:         $cenv{'internal.courseowner'} = $args->{'ccuname'}.
14760:                                         ':'.$args->{'ccdomain'};
14761:     } else {
14762:         $cenv{'internal.courseowner'} = $args->{'curruser'};
14763:     }
14764:     if ($args->{'defaultcredits'}) {
14765:         $cenv{'internal.defaultcredits'} = $args->{'defaultcredits'};
14766:     }
14767:     my @badclasses = (); # Used to accumulate sections/crosslistings that did not pass classlist access check for course owner.
14768:     if ($args->{'crssections'}) {
14769:         $cenv{'internal.sectionnums'} = '';
14770:         if ($args->{'crssections'} =~ m/,/) {
14771:             @sections = split/,/,$args->{'crssections'};
14772:         } else {
14773:             $sections[0] = $args->{'crssections'};
14774:         }
14775:         if (@sections > 0) {
14776:             foreach my $item (@sections) {
14777:                 my ($sec,$gp) = split/:/,$item;
14778:                 my $class = $args->{'crscode'}.$sec;
14779:                 my $addcheck = &Apache::lonnet::auto_new_course($$crsunum,$$crsudom,$class,$cenv{'internal.courseowner'});
14780:                 $cenv{'internal.sectionnums'} .= $item.',';
14781:                 unless ($addcheck eq 'ok') {
14782:                     push @badclasses, $class;
14783:                 }
14784:             }
14785:             $cenv{'internal.sectionnums'} =~ s/,$//;
14786:         }
14787:     }
14788: # do not hide course coordinator from staff listing, 
14789: # even if privileged
14790:     $cenv{'nothideprivileged'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
14791: # add course coordinator's domain to domains to check for privileged users
14792: # if different to course domain
14793:     if ($$crsudom ne $args->{'ccdomain'}) {
14794:         $cenv{'checkforpriv'} = $args->{'ccdomain'};
14795:     }
14796: # add crosslistings
14797:     if ($args->{'crsxlist'}) {
14798:         $cenv{'internal.crosslistings'}='';
14799:         if ($args->{'crsxlist'} =~ m/,/) {
14800:             @xlists = split/,/,$args->{'crsxlist'};
14801:         } else {
14802:             $xlists[0] = $args->{'crsxlist'};
14803:         }
14804:         if (@xlists > 0) {
14805:             foreach my $item (@xlists) {
14806:                 my ($xl,$gp) = split/:/,$item;
14807:                 my $addcheck =  &Apache::lonnet::auto_new_course($$crsunum,$$crsudom,$xl,$cenv{'internal.courseowner'});
14808:                 $cenv{'internal.crosslistings'} .= $item.',';
14809:                 unless ($addcheck eq 'ok') {
14810:                     push @badclasses, $xl;
14811:                 }
14812:             }
14813:             $cenv{'internal.crosslistings'} =~ s/,$//;
14814:         }
14815:     }
14816:     if ($args->{'autoadds'}) {
14817:         $cenv{'internal.autoadds'}=$args->{'autoadds'};
14818:     }
14819:     if ($args->{'autodrops'}) {
14820:         $cenv{'internal.autodrops'}=$args->{'autodrops'};
14821:     }
14822: # check for notification of enrollment changes
14823:     my @notified = ();
14824:     if ($args->{'notify_owner'}) {
14825:         if ($args->{'ccuname'} ne '') {
14826:             push(@notified,$args->{'ccuname'}.':'.$args->{'ccdomain'});
14827:         }
14828:     }
14829:     if ($args->{'notify_dc'}) {
14830:         if ($uname ne '') { 
14831:             push(@notified,$uname.':'.$udom);
14832:         }
14833:     }
14834:     if (@notified > 0) {
14835:         my $notifylist;
14836:         if (@notified > 1) {
14837:             $notifylist = join(',',@notified);
14838:         } else {
14839:             $notifylist = $notified[0];
14840:         }
14841:         $cenv{'internal.notifylist'} = $notifylist;
14842:     }
14843:     if (@badclasses > 0) {
14844:         my %lt=&Apache::lonlocal::texthash(
14845:                 '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',
14846:                 'dnhr' => 'does not have rights to access enrollment in these classes',
14847:                 'adby' => 'as determined by the policies of your institution on access to official classlists'
14848:         );
14849:         my $badclass_msg = $cenv{'internal.courseowner'}.') - '.$lt{'dnhr'}.
14850:                            ' ('.$lt{'adby'}.')';
14851:         if ($context eq 'auto') {
14852:             $outcome .= $badclass_msg.$linefeed;
14853:             $outcome .= '<div class="LC_warning">'.$badclass_msg.$linefeed.'<ul>'."\n";
14854:             foreach my $item (@badclasses) {
14855:                 if ($context eq 'auto') {
14856:                     $outcome .= " - $item\n";
14857:                 } else {
14858:                     $outcome .= "<li>$item</li>\n";
14859:                 }
14860:             }
14861:             if ($context eq 'auto') {
14862:                 $outcome .= $linefeed;
14863:             } else {
14864:                 $outcome .= "</ul><br /><br /></div>\n";
14865:             }
14866:         } 
14867:     }
14868:     if ($args->{'no_end_date'}) {
14869:         $args->{'endaccess'} = 0;
14870:     }
14871:     $cenv{'internal.autostart'}=$args->{'enrollstart'};
14872:     $cenv{'internal.autoend'}=$args->{'enrollend'};
14873:     $cenv{'default_enrollment_start_date'}=$args->{'startaccess'};
14874:     $cenv{'default_enrollment_end_date'}=$args->{'endaccess'};
14875:     if ($args->{'showphotos'}) {
14876:       $cenv{'internal.showphotos'}=$args->{'showphotos'};
14877:     }
14878:     $cenv{'internal.authtype'} = $args->{'authtype'};
14879:     $cenv{'internal.autharg'} = $args->{'autharg'}; 
14880:     if ( ($cenv{'internal.authtype'} =~ /^krb/) && ($cenv{'internal.autoadds'} == 1)) {
14881:         if (! defined($cenv{'internal.autharg'}) || $cenv{'internal.autharg'}  eq '') {
14882:             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'); 
14883:             if ($context eq 'auto') {
14884:                 $outcome .= $krb_msg;
14885:             } else {
14886:                 $outcome .= '<span class="LC_error">'.$krb_msg.'</span>';
14887:             }
14888:             $outcome .= $linefeed;
14889:         }
14890:     }
14891:     if (($args->{'ccdomain'}) && ($args->{'ccuname'})) {
14892:        if ($args->{'setpolicy'}) {
14893:            $cenv{'policy.email'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
14894:        }
14895:        if ($args->{'setcontent'}) {
14896:            $cenv{'question.email'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
14897:        }
14898:        if ($args->{'setcomment'}) {
14899:            $cenv{'comment.email'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
14900:        }
14901:     }
14902:     if ($args->{'reshome'}) {
14903: 	$cenv{'reshome'}=$args->{'reshome'}.'/';
14904: 	$cenv{'reshome'}=~s/\/+$/\//;
14905:     }
14906: #
14907: # course has keyed access
14908: #
14909:     if ($args->{'setkeys'}) {
14910:        $cenv{'keyaccess'}='yes';
14911:     }
14912: # if specified, key authority is not course, but user
14913: # only active if keyaccess is yes
14914:     if ($args->{'keyauth'}) {
14915: 	my ($user,$domain) = split(':',$args->{'keyauth'});
14916: 	$user = &LONCAPA::clean_username($user);
14917: 	$domain = &LONCAPA::clean_username($domain);
14918: 	if ($user ne '' && $domain ne '') {
14919: 	    $cenv{'keyauth'}=$user.':'.$domain;
14920: 	}
14921:     }
14922: 
14923: #
14924: #  generate and store uniquecode (available to course requester), if course should have one.
14925: #
14926:     if ($args->{'uniquecode'}) {
14927:         my ($code,$error) = &make_unique_code($$crsudom,$$crsunum);
14928:         if ($code) {
14929:             $cenv{'internal.uniquecode'} = $code;
14930:             my %crsinfo =
14931:                 &Apache::lonnet::courseiddump($$crsudom,'.',1,'.','.',$$crsunum,undef,undef,'.');
14932:             if (ref($crsinfo{$$crsudom.'_'.$$crsunum}) eq 'HASH') {
14933:                 $crsinfo{$$crsudom.'_'.$$crsunum}{'uniquecode'} = $code;
14934:                 my $putres = &Apache::lonnet::courseidput($$crsudom,\%crsinfo,$crsuhome,'notime');
14935:             }
14936:             if (ref($coderef)) {
14937:                 $$coderef = $code;
14938:             }
14939:         }
14940:     }
14941: 
14942:     if ($args->{'disresdis'}) {
14943:         $cenv{'pch.roles.denied'}='st';
14944:     }
14945:     if ($args->{'disablechat'}) {
14946:         $cenv{'plc.roles.denied'}='st';
14947:     }
14948: 
14949:     # Record we've not yet viewed the Course Initialization Helper for this 
14950:     # course
14951:     $cenv{'course.helper.not.run'} = 1;
14952:     #
14953:     # Use new Randomseed
14954:     #
14955:     $cenv{'rndseed'}=&Apache::lonnet::latest_rnd_algorithm_id();;
14956:     $cenv{'receiptalg'}=&Apache::lonnet::latest_receipt_algorithm_id();;
14957:     #
14958:     # The encryption code and receipt prefix for this course
14959:     #
14960:     $cenv{'internal.encseed'}=$Apache::lonnet::perlvar{'lonReceipt'}.$$.time.int(rand(9999));
14961:     $cenv{'internal.encpref'}=100+int(9*rand(99));
14962:     #
14963:     # By default, use standard grading
14964:     if (!defined($cenv{'grading'})) { $cenv{'grading'} = 'standard'; }
14965: 
14966:     $outcome .= $linefeed.&mt('Setting environment').': '.                 
14967:           &Apache::lonnet::put('environment',\%cenv,$$crsudom,$$crsunum).$linefeed;
14968: #
14969: # Open all assignments
14970: #
14971:     if ($args->{'openall'}) {
14972:        my $storeunder=$$crsudom.'_'.$$crsunum.'.0.opendate';
14973:        my %storecontent = ($storeunder         => time,
14974:                            $storeunder.'.type' => 'date_start');
14975:        
14976:        $outcome .= &mt('Opening all assignments').': '.&Apache::lonnet::cput
14977:                  ('resourcedata',\%storecontent,$$crsudom,$$crsunum).$linefeed;
14978:    }
14979: #
14980: # Set first page
14981: #
14982:     unless (($args->{'nonstandard'}) || ($args->{'firstres'} eq 'blank')
14983: 	    || ($cloneid)) {
14984: 	use LONCAPA::map;
14985: 	$outcome .= &mt('Setting first resource').': ';
14986: 
14987: 	my $map = '/uploaded/'.$$crsudom.'/'.$$crsunum.'/default.sequence';
14988:         my ($errtext,$fatal)=&LONCAPA::map::mapread($map);
14989: 
14990:         $outcome .= ($fatal?$errtext:'read ok').' - ';
14991:         my $title; my $url;
14992:         if ($args->{'firstres'} eq 'syl') {
14993: 	    $title=&mt('Syllabus');
14994:             $url='/public/'.$$crsudom.'/'.$$crsunum.'/syllabus';
14995:         } else {
14996:             $title=&mt('Table of Contents');
14997:             $url='/adm/navmaps';
14998:         }
14999: 
15000:         $LONCAPA::map::resources[1]=$title.':'.$url.':false:start:res';
15001: 	(my $outtext,$errtext) = &LONCAPA::map::storemap($map,1);
15002: 
15003: 	if ($errtext) { $fatal=2; }
15004:         $outcome .= ($fatal?$errtext:'write ok').$linefeed;
15005:     }
15006: 
15007:     return (1,$outcome);
15008: }
15009: 
15010: sub make_unique_code {
15011:     my ($cdom,$cnum) = @_;
15012:     # get lock on uniquecodes db
15013:     my $lockhash = {
15014:                       $cnum."\0".'uniquecodes' => $env{'user.name'}.
15015:                                                   ':'.$env{'user.domain'},
15016:                    };
15017:     my $tries = 0;
15018:     my $gotlock = &Apache::lonnet::newput_dom('uniquecodes',$lockhash,$cdom);
15019:     my ($code,$error);
15020: 
15021:     while (($gotlock ne 'ok') && ($tries<3)) {
15022:         $tries ++;
15023:         sleep 1;
15024:         $gotlock = &Apache::lonnet::newput_dom('uniquecodes',$lockhash,$cdom);
15025:     }
15026:     if ($gotlock eq 'ok') {
15027:         my %currcodes = &Apache::lonnet::dump_dom('uniquecodes',$cdom);
15028:         my $gotcode;
15029:         my $attempts = 0;
15030:         while ((!$gotcode) && ($attempts < 100)) {
15031:             $code = &generate_code();
15032:             if (!exists($currcodes{$code})) {
15033:                 $gotcode = 1;
15034:                 unless (&Apache::lonnet::newput_dom('uniquecodes',{ $code => $cnum },$cdom) eq 'ok') {
15035:                     $error = 'nostore';
15036:                 }
15037:             }
15038:             $attempts ++;
15039:         }
15040:         my @del_lock = ($cnum."\0".'uniquecodes');
15041:         my $dellockoutcome = &Apache::lonnet::del_dom('uniquecodes',\@del_lock,$cdom);
15042:     } else {
15043:         $error = 'nolock';
15044:     }
15045:     return ($code,$error);
15046: }
15047: 
15048: sub generate_code {
15049:     my $code;
15050:     my @letts = qw(B C D G H J K M N P Q R S T V W X Z);
15051:     for (my $i=0; $i<6; $i++) {
15052:         my $lettnum = int (rand 2);
15053:         my $item = '';
15054:         if ($lettnum) {
15055:             $item = $letts[int( rand(18) )];
15056:         } else {
15057:             $item = 1+int( rand(8) );
15058:         }
15059:         $code .= $item;
15060:     }
15061:     return $code;
15062: }
15063: 
15064: ############################################################
15065: ############################################################
15066: 
15067: #SD
15068: # only Community and Course, or anything else?
15069: sub course_type {
15070:     my ($cid) = @_;
15071:     if (!defined($cid)) {
15072:         $cid = $env{'request.course.id'};
15073:     }
15074:     if (defined($env{'course.'.$cid.'.type'})) {
15075:         return $env{'course.'.$cid.'.type'};
15076:     } else {
15077:         return 'Course';
15078:     }
15079: }
15080: 
15081: sub group_term {
15082:     my $crstype = &course_type();
15083:     my %names = (
15084:                   'Course' => 'group',
15085:                   'Community' => 'group',
15086:                 );
15087:     return $names{$crstype};
15088: }
15089: 
15090: sub course_types {
15091:     my @types = ('official','unofficial','community','textbook');
15092:     my %typename = (
15093:                          official   => 'Official course',
15094:                          unofficial => 'Unofficial course',
15095:                          community  => 'Community',
15096:                          textbook   => 'Textbook course',
15097:                    );
15098:     return (\@types,\%typename);
15099: }
15100: 
15101: sub icon {
15102:     my ($file)=@_;
15103:     my $curfext = lc((split(/\./,$file))[-1]);
15104:     my $iconname=$Apache::lonnet::perlvar{'lonIconsURL'}.'/unknown.gif';
15105:     my $embstyle = &Apache::loncommon::fileembstyle($curfext);
15106:     if (!(!defined($embstyle) || $embstyle eq 'unk' || $embstyle eq 'hdn')) {
15107: 	if (-e  $Apache::lonnet::perlvar{'lonDocRoot'}.'/'.
15108: 	          $Apache::lonnet::perlvar{'lonIconsURL'}.'/'.
15109: 	            $curfext.".gif") {
15110: 	    $iconname=$Apache::lonnet::perlvar{'lonIconsURL'}.'/'.
15111: 		$curfext.".gif";
15112: 	}
15113:     }
15114:     return &lonhttpdurl($iconname);
15115: } 
15116: 
15117: sub lonhttpdurl {
15118: #
15119: # Had been used for "small fry" static images on separate port 8080.
15120: # Modify here if lightweight http functionality desired again.
15121: # Currently eliminated due to increasing firewall issues.
15122: #
15123:     my ($url)=@_;
15124:     return $url;
15125: }
15126: 
15127: sub connection_aborted {
15128:     my ($r)=@_;
15129:     $r->print(" ");$r->rflush();
15130:     my $c = $r->connection;
15131:     return $c->aborted();
15132: }
15133: 
15134: #    Escapes strings that may have embedded 's that will be put into
15135: #    strings as 'strings'.
15136: sub escape_single {
15137:     my ($input) = @_;
15138:     $input =~ s/\\/\\\\/g;	# Escape the \'s..(must be first)>
15139:     $input =~ s/\'/\\\'/g;	# Esacpe the 's....
15140:     return $input;
15141: }
15142: 
15143: #  Same as escape_single, but escape's "'s  This 
15144: #  can be used for  "strings"
15145: sub escape_double {
15146:     my ($input) = @_;
15147:     $input =~ s/\\/\\\\/g;	# Escape the /'s..(must be first)>
15148:     $input =~ s/\"/\\\"/g;	# Esacpe the "s....
15149:     return $input;
15150: }
15151:  
15152: #   Escapes the last element of a full URL.
15153: sub escape_url {
15154:     my ($url)   = @_;
15155:     my @urlslices = split(/\//, $url,-1);
15156:     my $lastitem = &escape(pop(@urlslices));
15157:     return &HTML::Entities::encode(join('/',@urlslices),"'").'/'.$lastitem;
15158: }
15159: 
15160: sub compare_arrays {
15161:     my ($arrayref1,$arrayref2) = @_;
15162:     my (@difference,%count);
15163:     @difference = ();
15164:     %count = ();
15165:     if ((ref($arrayref1) eq 'ARRAY') && (ref($arrayref2) eq 'ARRAY')) {
15166:         foreach my $element (@{$arrayref1}, @{$arrayref2}) { $count{$element}++; }
15167:         foreach my $element (keys(%count)) {
15168:             if ($count{$element} == 1) {
15169:                 push(@difference,$element);
15170:             }
15171:         }
15172:     }
15173:     return @difference;
15174: }
15175: 
15176: # -------------------------------------------------------- Initialize user login
15177: sub init_user_environment {
15178:     my ($r, $username, $domain, $authhost, $form, $args) = @_;
15179:     my $lonids=$Apache::lonnet::perlvar{'lonIDsDir'};
15180: 
15181:     my $public=($username eq 'public' && $domain eq 'public');
15182: 
15183: # See if old ID present, if so, remove
15184: 
15185:     my ($filename,$cookie,$userroles,$firstaccenv,$timerintenv);
15186:     my $now=time;
15187: 
15188:     if ($public) {
15189: 	my $max_public=100;
15190: 	my $oldest;
15191: 	my $oldest_time=0;
15192: 	for(my $next=1;$next<=$max_public;$next++) {
15193: 	    if (-e $lonids."/publicuser_$next.id") {
15194: 		my $mtime=(stat($lonids."/publicuser_$next.id"))[9];
15195: 		if ($mtime<$oldest_time || !$oldest_time) {
15196: 		    $oldest_time=$mtime;
15197: 		    $oldest=$next;
15198: 		}
15199: 	    } else {
15200: 		$cookie="publicuser_$next";
15201: 		last;
15202: 	    }
15203: 	}
15204: 	if (!$cookie) { $cookie="publicuser_$oldest"; }
15205:     } else {
15206: 	# if this isn't a robot, kill any existing non-robot sessions
15207: 	if (!$args->{'robot'}) {
15208: 	    opendir(DIR,$lonids);
15209: 	    while ($filename=readdir(DIR)) {
15210: 		if ($filename=~/^$username\_\d+\_$domain\_$authhost\.id$/) {
15211: 		    unlink($lonids.'/'.$filename);
15212: 		}
15213: 	    }
15214: 	    closedir(DIR);
15215: # If there is a undeleted lockfile for the user's paste buffer remove it.
15216:             my $namespace = 'nohist_courseeditor';
15217:             my $lockingkey = 'paste'."\0".'locked_num';
15218:             my %lockhash = &Apache::lonnet::get($namespace,[$lockingkey],
15219:                                                 $domain,$username);
15220:             if (exists($lockhash{$lockingkey})) {
15221:                 my $delresult = &Apache::lonnet::del($namespace,[$lockingkey],$domain,$username);
15222:                 unless ($delresult eq 'ok') {
15223:                     &Apache::lonnet::logthis("Failed to delete paste buffer locking key in $namespace for ".$username.":".$domain." Result was: $delresult");
15224:                 }
15225:             }
15226: 	}
15227: # Give them a new cookie
15228: 	my $id = ($args->{'robot'} ? 'robot'.$args->{'robot'}
15229: 		                   : $now.$$.int(rand(10000)));
15230: 	$cookie="$username\_$id\_$domain\_$authhost";
15231:     
15232: # Initialize roles
15233: 
15234: 	($userroles,$firstaccenv,$timerintenv) = 
15235:             &Apache::lonnet::rolesinit($domain,$username,$authhost);
15236:     }
15237: # ------------------------------------ Check browser type and MathML capability
15238: 
15239:     my ($httpbrowser,$clientbrowser,$clientversion,$clientmathml,$clientunicode,
15240:         $clientos,$clientmobile,$clientinfo,$clientosversion) = &decode_user_agent($r);
15241: 
15242: # ------------------------------------------------------------- Get environment
15243: 
15244:     my %userenv = &Apache::lonnet::dump('environment',$domain,$username);
15245:     my ($tmp) = keys(%userenv);
15246:     if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
15247:     } else {
15248: 	undef(%userenv);
15249:     }
15250:     if (($userenv{'interface'}) && (!$form->{'interface'})) {
15251: 	$form->{'interface'}=$userenv{'interface'};
15252:     }
15253:     if ($userenv{'texengine'} eq 'ttm') { $clientmathml=1; }
15254: 
15255: # --------------- Do not trust query string to be put directly into environment
15256:     foreach my $option ('interface','localpath','localres') {
15257:         $form->{$option}=~s/[\n\r\=]//gs;
15258:     }
15259: # --------------------------------------------------------- Write first profile
15260: 
15261:     {
15262: 	my %initial_env = 
15263: 	    ("user.name"          => $username,
15264: 	     "user.domain"        => $domain,
15265: 	     "user.home"          => $authhost,
15266: 	     "browser.type"       => $clientbrowser,
15267: 	     "browser.version"    => $clientversion,
15268: 	     "browser.mathml"     => $clientmathml,
15269: 	     "browser.unicode"    => $clientunicode,
15270: 	     "browser.os"         => $clientos,
15271:              "browser.mobile"     => $clientmobile,
15272:              "browser.info"       => $clientinfo,
15273:              "browser.osversion"  => $clientosversion,
15274: 	     "server.domain"      => $Apache::lonnet::perlvar{'lonDefDomain'},
15275: 	     "request.course.fn"  => '',
15276: 	     "request.course.uri" => '',
15277: 	     "request.course.sec" => '',
15278: 	     "request.role"       => 'cm',
15279: 	     "request.role.adv"   => $env{'user.adv'},
15280: 	     "request.host"       => $ENV{'REMOTE_ADDR'},);
15281: 
15282:         if ($form->{'localpath'}) {
15283: 	    $initial_env{"browser.localpath"}  = $form->{'localpath'};
15284: 	    $initial_env{"browser.localres"}   = $form->{'localres'};
15285:         }
15286: 	
15287: 	if ($form->{'interface'}) {
15288: 	    $form->{'interface'}=~s/\W//gs;
15289: 	    $initial_env{"browser.interface"} = $form->{'interface'};
15290: 	    $env{'browser.interface'}=$form->{'interface'};
15291: 	}
15292: 
15293:         if ($form->{'iptoken'}) {
15294:             my $lonhost = $r->dir_config('lonHostID');
15295:             $initial_env{"user.noloadbalance"} = $lonhost;
15296:             $env{'user.noloadbalance'} = $lonhost;
15297:         }
15298: 
15299:         my %is_adv = ( is_adv => $env{'user.adv'} );
15300:         my %domdef;
15301:         unless ($domain eq 'public') {
15302:             %domdef = &Apache::lonnet::get_domain_defaults($domain);
15303:         }
15304: 
15305:         foreach my $tool ('aboutme','blog','webdav','portfolio') {
15306:             $userenv{'availabletools.'.$tool} = 
15307:                 &Apache::lonnet::usertools_access($username,$domain,$tool,'reload',
15308:                                                   undef,\%userenv,\%domdef,\%is_adv);
15309:         }
15310: 
15311:         foreach my $crstype ('official','unofficial','community','textbook') {
15312:             $userenv{'canrequest.'.$crstype} =
15313:                 &Apache::lonnet::usertools_access($username,$domain,$crstype,
15314:                                                   'reload','requestcourses',
15315:                                                   \%userenv,\%domdef,\%is_adv);
15316:         }
15317: 
15318:         $userenv{'canrequest.author'} =
15319:             &Apache::lonnet::usertools_access($username,$domain,'requestauthor',
15320:                                         'reload','requestauthor',
15321:                                         \%userenv,\%domdef,\%is_adv);
15322:         my %reqauthor = &Apache::lonnet::get('requestauthor',['author_status','author'],
15323:                                              $domain,$username);
15324:         my $reqstatus = $reqauthor{'author_status'};
15325:         if ($reqstatus eq 'approval' || $reqstatus eq 'approved') {
15326:             if (ref($reqauthor{'author'}) eq 'HASH') {
15327:                 $userenv{'requestauthorqueued'} = $reqstatus.':'.
15328:                                                   $reqauthor{'author'}{'timestamp'};
15329:             }
15330:         }
15331: 
15332: 	$env{'user.environment'} = "$lonids/$cookie.id";
15333: 
15334: 	if (tie(my %disk_env,'GDBM_File',"$lonids/$cookie.id",
15335: 		 &GDBM_WRCREAT(),0640)) {
15336: 	    &_add_to_env(\%disk_env,\%initial_env);
15337: 	    &_add_to_env(\%disk_env,\%userenv,'environment.');
15338: 	    &_add_to_env(\%disk_env,$userroles);
15339:             if (ref($firstaccenv) eq 'HASH') {
15340:                 &_add_to_env(\%disk_env,$firstaccenv);
15341:             }
15342:             if (ref($timerintenv) eq 'HASH') {
15343:                 &_add_to_env(\%disk_env,$timerintenv);
15344:             }
15345: 	    if (ref($args->{'extra_env'})) {
15346: 		&_add_to_env(\%disk_env,$args->{'extra_env'});
15347: 	    }
15348: 	    untie(%disk_env);
15349: 	} else {
15350: 	    &Apache::lonnet::logthis("<span style=\"color:blue;\">WARNING: ".
15351: 			   'Could not create environment storage in lonauth: '.$!.'</span>');
15352: 	    return 'error: '.$!;
15353: 	}
15354:     }
15355:     $env{'request.role'}='cm';
15356:     $env{'request.role.adv'}=$env{'user.adv'};
15357:     $env{'browser.type'}=$clientbrowser;
15358: 
15359:     return $cookie;
15360: 
15361: }
15362: 
15363: sub _add_to_env {
15364:     my ($idf,$env_data,$prefix) = @_;
15365:     if (ref($env_data) eq 'HASH') {
15366:         while (my ($key,$value) = each(%$env_data)) {
15367: 	    $idf->{$prefix.$key} = $value;
15368: 	    $env{$prefix.$key}   = $value;
15369:         }
15370:     }
15371: }
15372: 
15373: # --- Get the symbolic name of a problem and the url
15374: sub get_symb {
15375:     my ($request,$silent) = @_;
15376:     (my $url=$env{'form.url'}) =~ s-^https?\://($ENV{'SERVER_NAME'}|$ENV{'HTTP_HOST'})--;
15377:     my $symb=($env{'form.symb'} ne '' ? $env{'form.symb'} : (&Apache::lonnet::symbread($url)));
15378:     if ($symb eq '') {
15379:         if (!$silent) {
15380:             if (ref($request)) { 
15381:                 $request->print("Unable to handle ambiguous references:$url:.");
15382:             }
15383:             return ();
15384:         }
15385:     }
15386:     &Apache::lonenc::check_decrypt(\$symb);
15387:     return ($symb);
15388: }
15389: 
15390: # --------------------------------------------------------------Get annotation
15391: 
15392: sub get_annotation {
15393:     my ($symb,$enc) = @_;
15394: 
15395:     my $key = $symb;
15396:     if (!$enc) {
15397:         $key =
15398:             &Apache::lonnet::clutter((&Apache::lonnet::decode_symb($symb))[2]);
15399:     }
15400:     my %annotation=&Apache::lonnet::get('nohist_annotations',[$key]);
15401:     return $annotation{$key};
15402: }
15403: 
15404: sub clean_symb {
15405:     my ($symb,$delete_enc) = @_;
15406: 
15407:     &Apache::lonenc::check_decrypt(\$symb);
15408:     my $enc = $env{'request.enc'};
15409:     if ($delete_enc) {
15410:         delete($env{'request.enc'});
15411:     }
15412: 
15413:     return ($symb,$enc);
15414: }
15415: 
15416: ############################################################
15417: ############################################################
15418: 
15419: =pod
15420: 
15421: =head1 Routines for building display used to search for courses
15422: 
15423: 
15424: =over 4
15425: 
15426: =item * &build_filters()
15427: 
15428: Create markup for a table used to set filters to use when selecting
15429: courses in a domain.  Used by lonpickcourse.pm, lonmodifycourse.pm
15430: and quotacheck.pl
15431: 
15432: 
15433: Inputs:
15434: 
15435: filterlist - anonymous array of fields to include as potential filters
15436: 
15437: crstype - course type
15438: 
15439: roleelement - fifth arg in selectcourse_link() populates fifth arg in javascript: opencrsbrowser() function, used
15440:               to pop-open a course selector (will contain "extra element").
15441: 
15442: multelement - if multiple course selections will be allowed, this will be a hidden form element: name: multiple; value: 1
15443: 
15444: filter - anonymous hash of criteria and their values
15445: 
15446: action - form action
15447: 
15448: numfiltersref - ref to scalar (count of number of elements in institutional codes -- e.g., 4 for year, semester, department, and number)
15449: 
15450: caller - caller context (e.g., set to 'modifycourse' when routine is called from lonmodifycourse.pm)
15451: 
15452: cloneruname - username of owner of new course who wants to clone
15453: 
15454: clonerudom - domain of owner of new course who wants to clone
15455: 
15456: typeelem - text to use for left column in row containing course type (i.e., Course, Community or Course/Community)
15457: 
15458: codetitlesref - reference to array of titles of components in institutional codes (official courses)
15459: 
15460: codedom - domain
15461: 
15462: formname - value of form element named "form".
15463: 
15464: fixeddom - domain, if fixed.
15465: 
15466: prevphase - value to assign to form element named "phase" when going back to the previous screen
15467: 
15468: cnameelement - name of form element in form on opener page which will receive title of selected course
15469: 
15470: cnumelement - name of form element in form on opener page which will receive courseID  of selected course
15471: 
15472: cdomelement - name of form element in form on opener page which will receive domain of selected course
15473: 
15474: setroles - includes access constraint identifier when setting a roles-based condition for acces to a portfolio file
15475: 
15476: clonetext - hidden form elements containing list of courses cloneable by intended course owner when DC creates a course
15477: 
15478: clonewarning - warning message about missing information for intended course owner when DC creates a course
15479: 
15480: 
15481: Returns: $output - HTML for display of search criteria, and hidden form elements.
15482: 
15483: 
15484: Side Effects: None
15485: 
15486: =cut
15487: 
15488: # ---------------------------------------------- search for courses based on last activity etc.
15489: 
15490: sub build_filters {
15491:     my ($filterlist,$crstype,$roleelement,$multelement,$filter,$action,
15492:         $numtitlesref,$caller,$cloneruname,$clonerudom,$typeelement,
15493:         $codetitlesref,$codedom,$formname,$fixeddom,$prevphase,
15494:         $cnameelement,$cnumelement,$cdomelement,$setroles,
15495:         $clonetext,$clonewarning) = @_;
15496:     my ($list,$jscript);
15497:     my $onchange = 'javascript:updateFilters(this)';
15498:     my ($domainselectform,$sincefilterform,$createdfilterform,
15499:         $ownerdomselectform,$persondomselectform,$instcodeform,
15500:         $typeselectform,$instcodetitle);
15501:     if ($formname eq '') {
15502:         $formname = $caller;
15503:     }
15504:     foreach my $item (@{$filterlist}) {
15505:         unless (($item eq 'descriptfilter') || ($item eq 'instcodefilter') ||
15506:                 ($item eq 'sincefilter') || ($item eq 'createdfilter')) {
15507:             if ($item eq 'domainfilter') {
15508:                 $filter->{$item} = &LONCAPA::clean_domain($filter->{$item});
15509:             } elsif ($item eq 'coursefilter') {
15510:                 $filter->{$item} = &LONCAPA::clean_courseid($filter->{$item});
15511:             } elsif ($item eq 'ownerfilter') {
15512:                 $filter->{$item} = &LONCAPA::clean_username($filter->{$item});
15513:             } elsif ($item eq 'ownerdomfilter') {
15514:                 $filter->{'ownerdomfilter'} =
15515:                     &LONCAPA::clean_domain($filter->{$item});
15516:                 $ownerdomselectform = &select_dom_form($filter->{'ownerdomfilter'},
15517:                                                        'ownerdomfilter',1);
15518:             } elsif ($item eq 'personfilter') {
15519:                 $filter->{$item} = &LONCAPA::clean_username($filter->{$item});
15520:             } elsif ($item eq 'persondomfilter') {
15521:                 $persondomselectform = &select_dom_form($filter->{'persondomfilter'},
15522:                                                         'persondomfilter',1);
15523:             } else {
15524:                 $filter->{$item} =~ s/\W//g;
15525:             }
15526:             if (!$filter->{$item}) {
15527:                 $filter->{$item} = '';
15528:             }
15529:         }
15530:         if ($item eq 'domainfilter') {
15531:             my $allow_blank = 1;
15532:             if ($formname eq 'portform') {
15533:                 $allow_blank=0;
15534:             } elsif ($formname eq 'studentform') {
15535:                 $allow_blank=0;
15536:             }
15537:             if ($fixeddom) {
15538:                 $domainselectform = '<input type="hidden" name="domainfilter"'.
15539:                                     ' value="'.$codedom.'" />'.
15540:                                     &Apache::lonnet::domain($codedom,'description');
15541:             } else {
15542:                 $domainselectform = &select_dom_form($filter->{$item},
15543:                                                      'domainfilter',
15544:                                                       $allow_blank,'',$onchange);
15545:             }
15546:         } else {
15547:             $list->{$item} = &HTML::Entities::encode($filter->{$item},'<>&"');
15548:         }
15549:     }
15550: 
15551:     # last course activity filter and selection
15552:     $sincefilterform = &timebased_select_form('sincefilter',$filter);
15553: 
15554:     # course created filter and selection
15555:     if (exists($filter->{'createdfilter'})) {
15556:         $createdfilterform = &timebased_select_form('createdfilter',$filter);
15557:     }
15558: 
15559:     my %lt = &Apache::lonlocal::texthash(
15560:                 'cac' => "$crstype Activity",
15561:                 'ccr' => "$crstype Created",
15562:                 'cde' => "$crstype Title",
15563:                 'cdo' => "$crstype Domain",
15564:                 'ins' => 'Institutional Code',
15565:                 'inc' => 'Institutional Categorization',
15566:                 'cow' => "$crstype Owner/Co-owner",
15567:                 'cop' => "$crstype Personnel Includes",
15568:                 'cog' => 'Type',
15569:              );
15570: 
15571:     if (($formname eq 'ccrs') || ($formname eq 'requestcrs')) {
15572:         my $typeval = 'Course';
15573:         if ($crstype eq 'Community') {
15574:             $typeval = 'Community';
15575:         }
15576:         $typeselectform = '<input type="hidden" name="type" value="'.$typeval.'" />';
15577:     } else {
15578:         $typeselectform =  '<select name="type" size="1"';
15579:         if ($onchange) {
15580:             $typeselectform .= ' onchange="'.$onchange.'"';
15581:         }
15582:         $typeselectform .= '>'."\n";
15583:         foreach my $posstype ('Course','Community') {
15584:             $typeselectform.='<option value="'.$posstype.'"'.
15585:                 ($posstype eq $crstype ? ' selected="selected" ' : ''). ">".&mt($posstype)."</option>\n";
15586:         }
15587:         $typeselectform.="</select>";
15588:     }
15589: 
15590:     my ($cloneableonlyform,$cloneabletitle);
15591:     if (exists($filter->{'cloneableonly'})) {
15592:         my $cloneableon = '';
15593:         my $cloneableoff = ' checked="checked"';
15594:         if ($filter->{'cloneableonly'}) {
15595:             $cloneableon = $cloneableoff;
15596:             $cloneableoff = '';
15597:         }
15598:         $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>';
15599:         if ($formname eq 'ccrs') {
15600:             $cloneabletitle = &mt('Cloneable for [_1]',$cloneruname.':'.$clonerudom);
15601:         } else {
15602:             $cloneabletitle = &mt('Cloneable by you');
15603:         }
15604:     }
15605:     my $officialjs;
15606:     if ($crstype eq 'Course') {
15607:         if (exists($filter->{'instcodefilter'})) {
15608: #            if (($fixeddom) || ($formname eq 'requestcrs') ||
15609: #                ($formname eq 'modifycourse') || ($formname eq 'filterpicker')) {
15610:             if ($codedom) {
15611:                 $officialjs = 1;
15612:                 ($instcodeform,$jscript,$$numtitlesref) =
15613:                     &Apache::courseclassifier::instcode_selectors($codedom,'filterpicker',
15614:                                                                   $officialjs,$codetitlesref);
15615:                 if ($jscript) {
15616:                     $jscript = '<script type="text/javascript">'."\n".
15617:                                '// <![CDATA['."\n".
15618:                                $jscript."\n".
15619:                                '// ]]>'."\n".
15620:                                '</script>'."\n";
15621:                 }
15622:             }
15623:             if ($instcodeform eq '') {
15624:                 $instcodeform =
15625:                     '<input type="text" name="instcodefilter" size="10" value="'.
15626:                     $list->{'instcodefilter'}.'" />';
15627:                 $instcodetitle = $lt{'ins'};
15628:             } else {
15629:                 $instcodetitle = $lt{'inc'};
15630:             }
15631:             if ($fixeddom) {
15632:                 $instcodetitle .= '<br />('.$codedom.')';
15633:             }
15634:         }
15635:     }
15636:     my $output = qq|
15637: <form method="post" name="filterpicker" action="$action">
15638: <input type="hidden" name="form" value="$formname" />
15639: |;
15640:     if ($formname eq 'modifycourse') {
15641:         $output .= '<input type="hidden" name="phase" value="courselist" />'."\n".
15642:                    '<input type="hidden" name="prevphase" value="'.
15643:                    $prevphase.'" />'."\n";
15644:     } elsif ($formname eq 'quotacheck') {
15645:         $output .= qq|
15646: <input type="hidden" name="sortby" value="" />
15647: <input type="hidden" name="sortorder" value="" />
15648: |;
15649:     } else {
15650:         my $name_input;
15651:         if ($cnameelement ne '') {
15652:             $name_input = '<input type="hidden" name="cnameelement" value="'.
15653:                           $cnameelement.'" />';
15654:         }
15655:         $output .= qq|
15656: <input type="hidden" name="cnumelement" value="$cnumelement" />
15657: <input type="hidden" name="cdomelement" value="$cdomelement" />
15658: $name_input
15659: $roleelement
15660: $multelement
15661: $typeelement
15662: |;
15663:         if ($formname eq 'portform') {
15664:             $output .= '<input type="hidden" name="setroles" value="'.$setroles.'" />'."\n";
15665:         }
15666:     }
15667:     if ($fixeddom) {
15668:         $output .= '<input type="hidden" name="fixeddom" value="'.$fixeddom.'" />'."\n";
15669:     }
15670:     $output .= "<br />\n".&Apache::lonhtmlcommon::start_pick_box();
15671:     if ($sincefilterform) {
15672:         $output .= &Apache::lonhtmlcommon::row_title($lt{'cac'})
15673:                   .$sincefilterform
15674:                   .&Apache::lonhtmlcommon::row_closure();
15675:     }
15676:     if ($createdfilterform) {
15677:         $output .= &Apache::lonhtmlcommon::row_title($lt{'ccr'})
15678:                   .$createdfilterform
15679:                   .&Apache::lonhtmlcommon::row_closure();
15680:     }
15681:     if ($domainselectform) {
15682:         $output .= &Apache::lonhtmlcommon::row_title($lt{'cdo'})
15683:                   .$domainselectform
15684:                   .&Apache::lonhtmlcommon::row_closure();
15685:     }
15686:     if ($typeselectform) {
15687:         if (($formname eq 'ccrs') || ($formname eq 'requestcrs')) {
15688:             $output .= $typeselectform;
15689:         } else {
15690:             $output .= &Apache::lonhtmlcommon::row_title($lt{'cog'})
15691:                       .$typeselectform
15692:                       .&Apache::lonhtmlcommon::row_closure();
15693:         }
15694:     }
15695:     if ($instcodeform) {
15696:         $output .= &Apache::lonhtmlcommon::row_title($instcodetitle)
15697:                   .$instcodeform
15698:                   .&Apache::lonhtmlcommon::row_closure();
15699:     }
15700:     if (exists($filter->{'ownerfilter'})) {
15701:         $output .= &Apache::lonhtmlcommon::row_title($lt{'cow'}).
15702:                    '<table><tr><td>'.&mt('Username').'<br />'.
15703:                    '<input type="text" name="ownerfilter" size="20" value="'.
15704:                    $list->{'ownerfilter'}.'" /></td><td>'.&mt('Domain').'<br />'.
15705:                    $ownerdomselectform.'</td></tr></table>'.
15706:                    &Apache::lonhtmlcommon::row_closure();
15707:     }
15708:     if (exists($filter->{'personfilter'})) {
15709:         $output .= &Apache::lonhtmlcommon::row_title($lt{'cop'}).
15710:                    '<table><tr><td>'.&mt('Username').'<br />'.
15711:                    '<input type="text" name="personfilter" size="20" value="'.
15712:                    $list->{'personfilter'}.'" /></td><td>'.&mt('Domain').'<br />'.
15713:                    $persondomselectform.'</td></tr></table>'.
15714:                    &Apache::lonhtmlcommon::row_closure();
15715:     }
15716:     if (exists($filter->{'coursefilter'})) {
15717:         $output .= &Apache::lonhtmlcommon::row_title(&mt('LON-CAPA course ID'))
15718:                   .'<input type="text" name="coursefilter" size="25" value="'
15719:                   .$list->{'coursefilter'}.'" />'
15720:                   .&Apache::lonhtmlcommon::row_closure();
15721:     }
15722:     if ($cloneableonlyform) {
15723:         $output .= &Apache::lonhtmlcommon::row_title($cloneabletitle).
15724:                    $cloneableonlyform.&Apache::lonhtmlcommon::row_closure();
15725:     }
15726:     if (exists($filter->{'descriptfilter'})) {
15727:         $output .= &Apache::lonhtmlcommon::row_title($lt{'cde'})
15728:                   .'<input type="text" name="descriptfilter" size="40" value="'
15729:                   .$list->{'descriptfilter'}.'" />'
15730:                   .&Apache::lonhtmlcommon::row_closure(1);
15731:     }
15732:     $output .= &Apache::lonhtmlcommon::end_pick_box().'<p>'.$clonetext."\n".
15733:                '<input type="hidden" name="updater" value="" />'."\n".
15734:                '<input type="submit" name="gosearch" value="'.
15735:                &mt('Search').'" /></p>'."\n".'</form>'."\n".'<hr />'."\n";
15736:     return $jscript.$clonewarning.$output;
15737: }
15738: 
15739: =pod
15740: 
15741: =item * &timebased_select_form()
15742: 
15743: Create markup for a dropdown list used to select a time-based
15744: filter e.g., Course Activity, Course Created, when searching for courses
15745: or communities
15746: 
15747: Inputs:
15748: 
15749: item - name of form element (sincefilter or createdfilter)
15750: 
15751: filter - anonymous hash of criteria and their values
15752: 
15753: Returns: HTML for a select box contained a blank, then six time selections,
15754:          with value set in incoming form variables currently selected.
15755: 
15756: Side Effects: None
15757: 
15758: =cut
15759: 
15760: sub timebased_select_form {
15761:     my ($item,$filter) = @_;
15762:     if (ref($filter) eq 'HASH') {
15763:         $filter->{$item} =~ s/[^\d-]//g;
15764:         if (!$filter->{$item}) { $filter->{$item}=-1; }
15765:         return &select_form(
15766:                             $filter->{$item},
15767:                             $item,
15768:                             {      '-1' => '',
15769:                                 '86400' => &mt('today'),
15770:                                '604800' => &mt('last week'),
15771:                               '2592000' => &mt('last month'),
15772:                               '7776000' => &mt('last three months'),
15773:                              '15552000' => &mt('last six months'),
15774:                              '31104000' => &mt('last year'),
15775:                     'select_form_order' =>
15776:                            ['-1','86400','604800','2592000','7776000',
15777:                             '15552000','31104000']});
15778:     }
15779: }
15780: 
15781: =pod
15782: 
15783: =item * &js_changer()
15784: 
15785: Create script tag containing Javascript used to submit course search form
15786: when course type or domain is changed, and also to hide 'Searching ...' on
15787: page load completion for page showing search result.
15788: 
15789: Inputs: None
15790: 
15791: Returns: markup containing updateFilters() and hideSearching() javascript functions.
15792: 
15793: Side Effects: None
15794: 
15795: =cut
15796: 
15797: sub js_changer {
15798:     return <<ENDJS;
15799: <script type="text/javascript">
15800: // <![CDATA[
15801: function updateFilters(caller) {
15802:     if (typeof(caller) != "undefined") {
15803:         document.filterpicker.updater.value = caller.name;
15804:     }
15805:     document.filterpicker.submit();
15806: }
15807: 
15808: function hideSearching() {
15809:     if (document.getElementById('searching')) {
15810:         document.getElementById('searching').style.display = 'none';
15811:     }
15812:     return;
15813: }
15814: 
15815: // ]]>
15816: </script>
15817: 
15818: ENDJS
15819: }
15820: 
15821: =pod
15822: 
15823: =item * &search_courses()
15824: 
15825: Process selected filters form course search form and pass to lonnet::courseiddump
15826: to retrieve a hash for which keys are courseIDs which match the selected filters.
15827: 
15828: Inputs:
15829: 
15830: dom - domain being searched
15831: 
15832: type - course type ('Course' or 'Community' or '.' if any).
15833: 
15834: filter - anonymous hash of criteria and their values
15835: 
15836: numtitles - for institutional codes - number of categories
15837: 
15838: cloneruname - optional username of new course owner
15839: 
15840: clonerudom - optional domain of new course owner
15841: 
15842: domcloner - optional "domcloner" flag; has value=1 if user has ccc priv in domain being filtered by,
15843:             (used when DC is using course creation form)
15844: 
15845: codetitles - reference to array of titles of components in institutional codes (official courses).
15846: 
15847: cc_clone - escaped comma separated list of courses for which course cloner has active CC role
15848:            (and so can clone automatically)
15849: 
15850: reqcrsdom - domain of new course, where search_courses is used to identify potential courses to clone
15851: 
15852: reqinstcode - institutional code of new course, where search_courses is used to identify potential
15853:               courses to clone
15854: 
15855: Returns: %courses - hash of courses satisfying search criteria, keys = course IDs, values are corresponding colon-separated escaped description, institutional code, owner and type.
15856: 
15857: 
15858: Side Effects: None
15859: 
15860: =cut
15861: 
15862: 
15863: sub search_courses {
15864:     my ($dom,$type,$filter,$numtitles,$cloneruname,$clonerudom,$domcloner,$codetitles,
15865:         $cc_clone,$reqcrsdom,$reqinstcode) = @_;
15866:     my (%courses,%showcourses,$cloner);
15867:     if (($filter->{'ownerfilter'} ne '') ||
15868:         ($filter->{'ownerdomfilter'} ne '')) {
15869:         $filter->{'combownerfilter'} = $filter->{'ownerfilter'}.':'.
15870:                                        $filter->{'ownerdomfilter'};
15871:     }
15872:     foreach my $item ('descriptfilter','coursefilter','combownerfilter') {
15873:         if (!$filter->{$item}) {
15874:             $filter->{$item}='.';
15875:         }
15876:     }
15877:     my $now = time;
15878:     my $timefilter =
15879:        ($filter->{'sincefilter'}==-1?1:$now-$filter->{'sincefilter'});
15880:     my ($createdbefore,$createdafter);
15881:     if (($filter->{'createdfilter'} ne '') && ($filter->{'createdfilter'} !=-1)) {
15882:         $createdbefore = $now;
15883:         $createdafter = $now-$filter->{'createdfilter'};
15884:     }
15885:     my ($instcodefilter,$regexpok);
15886:     if ($numtitles) {
15887:         if ($env{'form.official'} eq 'on') {
15888:             $instcodefilter =
15889:                 &Apache::courseclassifier::instcode_search_str($dom,$numtitles,$codetitles);
15890:             $regexpok = 1;
15891:         } elsif ($env{'form.official'} eq 'off') {
15892:             $instcodefilter = &Apache::courseclassifier::instcode_search_str($dom,$numtitles,$codetitles);
15893:             unless ($instcodefilter eq '') {
15894:                 $regexpok = -1;
15895:             }
15896:         }
15897:     } else {
15898:         $instcodefilter = $filter->{'instcodefilter'};
15899:     }
15900:     if ($instcodefilter eq '') { $instcodefilter = '.'; }
15901:     if ($type eq '') { $type = '.'; }
15902: 
15903:     if (($clonerudom ne '') && ($cloneruname ne '')) {
15904:         $cloner = $cloneruname.':'.$clonerudom;
15905:     }
15906:     %courses = &Apache::lonnet::courseiddump($dom,
15907:                                              $filter->{'descriptfilter'},
15908:                                              $timefilter,
15909:                                              $instcodefilter,
15910:                                              $filter->{'combownerfilter'},
15911:                                              $filter->{'coursefilter'},
15912:                                              undef,undef,$type,$regexpok,undef,undef,
15913:                                              undef,undef,$cloner,$cc_clone,
15914:                                              $filter->{'cloneableonly'},
15915:                                              $createdbefore,$createdafter,undef,
15916:                                              $domcloner,undef,$reqcrsdom,$reqinstcode);
15917:     if (($filter->{'personfilter'} ne '') && ($filter->{'persondomfilter'} ne '')) {
15918:         my $ccrole;
15919:         if ($type eq 'Community') {
15920:             $ccrole = 'co';
15921:         } else {
15922:             $ccrole = 'cc';
15923:         }
15924:         my %rolehash = &Apache::lonnet::get_my_roles($filter->{'personfilter'},
15925:                                                      $filter->{'persondomfilter'},
15926:                                                      'userroles',undef,
15927:                                                      [$ccrole,'in','ad','ep','ta','cr'],
15928:                                                      $dom);
15929:         foreach my $role (keys(%rolehash)) {
15930:             my ($cnum,$cdom,$courserole) = split(':',$role);
15931:             my $cid = $cdom.'_'.$cnum;
15932:             if (exists($courses{$cid})) {
15933:                 if (ref($courses{$cid}) eq 'HASH') {
15934:                     if (ref($courses{$cid}{roles}) eq 'ARRAY') {
15935:                         if (!grep(/^\Q$courserole\E$/,@{$courses{$cid}{roles}})) {
15936:                             push (@{$courses{$cid}{roles}},$courserole);
15937:                         }
15938:                     } else {
15939:                         $courses{$cid}{roles} = [$courserole];
15940:                     }
15941:                     $showcourses{$cid} = $courses{$cid};
15942:                 }
15943:             }
15944:         }
15945:         %courses = %showcourses;
15946:     }
15947:     return %courses;
15948: }
15949: 
15950: =pod
15951: 
15952: =back
15953: 
15954: =head1 Routines for version requirements for current course.
15955: 
15956: =over 4
15957: 
15958: =item * &check_release_required()
15959: 
15960: Compares required LON-CAPA version with version on server, and
15961: if required version is newer looks for a server with the required version.
15962: 
15963: Looks first at servers in user's owen domain; if none suitable, looks at
15964: servers in course's domain are permitted to host sessions for user's domain.
15965: 
15966: Inputs:
15967: 
15968: $loncaparev - Version on current server (format: Major.Minor.Subrelease-datestamp)
15969: 
15970: $courseid - Course ID of current course
15971: 
15972: $rolecode - User's current role in course (for switchserver query string).
15973: 
15974: $required - LON-CAPA version needed by course (format: Major.Minor).
15975: 
15976: 
15977: Returns:
15978: 
15979: $switchserver - query string tp append to /adm/switchserver call (if
15980:                 current server's LON-CAPA version is too old.
15981: 
15982: $warning - Message is displayed if no suitable server could be found.
15983: 
15984: =cut
15985: 
15986: sub check_release_required {
15987:     my ($loncaparev,$courseid,$rolecode,$required) = @_;
15988:     my ($switchserver,$warning);
15989:     if ($required ne '') {
15990:         my ($reqdmajor,$reqdminor) = ($required =~ /^(\d+)\.(\d+)$/);
15991:         my ($major,$minor) = ($loncaparev =~ /^\'?(\d+)\.(\d+)\.[\w.\-]+\'?$/);
15992:         if ($reqdmajor ne '' && $reqdminor ne '') {
15993:             my $otherserver;
15994:             if (($major eq '' && $minor eq '') ||
15995:                 (($reqdmajor > $major) || (($reqdmajor == $major) && ($reqdminor > $minor)))) {
15996:                 my ($userdomserver) = &Apache::lonnet::choose_server($env{'user.domain'},undef,$required,1);
15997:                 my $switchlcrev =
15998:                     &Apache::lonnet::get_server_loncaparev($env{'user.domain'},
15999:                                                            $userdomserver);
16000:                 my ($swmajor,$swminor) = ($switchlcrev =~ /^\'?(\d+)\.(\d+)\.[\w.\-]+\'?$/);
16001:                 if (($swmajor eq '' && $swminor eq '') || ($reqdmajor > $swmajor) ||
16002:                     (($reqdmajor == $swmajor) && ($reqdminor > $swminor))) {
16003:                     my $cdom = $env{'course.'.$courseid.'.domain'};
16004:                     if ($cdom ne $env{'user.domain'}) {
16005:                         my ($coursedomserver,$coursehostname) = &Apache::lonnet::choose_server($cdom,undef,$required,1);
16006:                         my $serverhomeID = &Apache::lonnet::get_server_homeID($coursehostname);
16007:                         my $serverhomedom = &Apache::lonnet::host_domain($serverhomeID);
16008:                         my %defdomdefaults = &Apache::lonnet::get_domain_defaults($serverhomedom);
16009:                         my %udomdefaults = &Apache::lonnet::get_domain_defaults($env{'user.domain'});
16010:                         my $remoterev = &Apache::lonnet::get_server_loncaparev($serverhomedom,$coursedomserver);
16011:                         my $canhost =
16012:                             &Apache::lonnet::can_host_session($env{'user.domain'},
16013:                                                               $coursedomserver,
16014:                                                               $remoterev,
16015:                                                               $udomdefaults{'remotesessions'},
16016:                                                               $defdomdefaults{'hostedsessions'});
16017: 
16018:                         if ($canhost) {
16019:                             $otherserver = $coursedomserver;
16020:                         } else {
16021:                             $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.");
16022:                         }
16023:                     } else {
16024:                         $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).");
16025:                     }
16026:                 } else {
16027:                     $otherserver = $userdomserver;
16028:                 }
16029:             }
16030:             if ($otherserver ne '') {
16031:                 $switchserver = 'otherserver='.$otherserver.'&amp;role='.$rolecode;
16032:             }
16033:         }
16034:     }
16035:     return ($switchserver,$warning);
16036: }
16037: 
16038: =pod
16039: 
16040: =item * &check_release_result()
16041: 
16042: Inputs:
16043: 
16044: $switchwarning - Warning message if no suitable server found to host session.
16045: 
16046: $switchserver - query string to append to /adm/switchserver containing lonHostID
16047:                 and current role.
16048: 
16049: Returns: HTML to display with information about requirement to switch server.
16050:          Either displaying warning with link to Roles/Courses screen or
16051:          display link to switchserver.
16052: 
16053: =cut
16054: 
16055: sub check_release_result {
16056:     my ($switchwarning,$switchserver) = @_;
16057:     my $output = &start_page('Selected course unavailable on this server').
16058:                  '<p class="LC_warning">';
16059:     if ($switchwarning) {
16060:         $output .= $switchwarning.'<br /><a href="/adm/roles">';
16061:         if (&show_course()) {
16062:             $output .= &mt('Display courses');
16063:         } else {
16064:             $output .= &mt('Display roles');
16065:         }
16066:         $output .= '</a>';
16067:     } elsif ($switchserver) {
16068:         $output .= &mt('This course requires a newer version of LON-CAPA than is installed on this server.').
16069:                    '<br />'.
16070:                    '<a href="/adm/switchserver?'.$switchserver.'">'.
16071:                    &mt('Switch Server').
16072:                    '</a>';
16073:     }
16074:     $output .= '</p>'.&end_page();
16075:     return $output;
16076: }
16077: 
16078: =pod
16079: 
16080: =item * &needs_coursereinit()
16081: 
16082: Determine if course contents stored for user's session needs to be
16083: refreshed, because content has changed since "Big Hash" last tied.
16084: 
16085: Check for change is made if time last checked is more than 10 minutes ago
16086: (by default).
16087: 
16088: Inputs:
16089: 
16090: $loncaparev - Version on current server (format: Major.Minor.Subrelease-datestamp)
16091: 
16092: $interval (optional) - Time which may elapse (in s) between last check for content
16093:                        change in current course. (default: 600 s).
16094: 
16095: Returns: an array; first element is:
16096: 
16097: =over 4
16098: 
16099: 'switch' - if content updates mean user's session
16100:            needs to be switched to a server running a newer LON-CAPA version
16101: 
16102: 'update' - if course session needs to be refreshed (i.e., Big Hash needs to be reloaded)
16103:            on current server hosting user's session
16104: 
16105: ''       - if no action required.
16106: 
16107: =back
16108: 
16109: If first item element is 'switch':
16110: 
16111: second item is $switchwarning - Warning message if no suitable server found to host session.
16112: 
16113: third item is $switchserver - query string to append to /adm/switchserver containing lonHostID
16114:                               and current role.
16115: 
16116: otherwise: no other elements returned.
16117: 
16118: =back
16119: 
16120: =cut
16121: 
16122: sub needs_coursereinit {
16123:     my ($loncaparev,$interval) = @_;
16124:     return() unless ($env{'request.course.id'} && $env{'request.course.tied'});
16125:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
16126:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
16127:     my $now = time;
16128:     if ($interval eq '') {
16129:         $interval = 600;
16130:     }
16131:     if (($now-$env{'request.course.timechecked'})>$interval) {
16132:         my $lastchange = &Apache::lonnet::get_coursechange($cdom,$cnum);
16133:         &Apache::lonnet::appenv({'request.course.timechecked'=>$now});
16134:         if ($lastchange > $env{'request.course.tied'}) {
16135:             my %curr_reqd_hash = &Apache::lonnet::userenvironment($cdom,$cnum,'internal.releaserequired');
16136:             if ($curr_reqd_hash{'internal.releaserequired'} ne '') {
16137:                 my $required = $env{'course.'.$cdom.'_'.$cnum.'.internal.releaserequired'};
16138:                 if ($curr_reqd_hash{'internal.releaserequired'} ne $required) {
16139:                     &Apache::lonnet::appenv({'course.'.$cdom.'_'.$cnum.'.internal.releaserequired' =>
16140:                                              $curr_reqd_hash{'internal.releaserequired'}});
16141:                     my ($switchserver,$switchwarning) =
16142:                         &check_release_required($loncaparev,$cdom.'_'.$cnum,$env{'request.role'},
16143:                                                 $curr_reqd_hash{'internal.releaserequired'});
16144:                     if ($switchwarning ne '' || $switchserver ne '') {
16145:                         return ('switch',$switchwarning,$switchserver);
16146:                     }
16147:                 }
16148:             }
16149:             return ('update');
16150:         }
16151:     }
16152:     return ();
16153: }
16154: 
16155: sub update_content_constraints {
16156:     my ($cdom,$cnum,$chome,$cid) = @_;
16157:     my %curr_reqd_hash = &Apache::lonnet::userenvironment($cdom,$cnum,'internal.releaserequired');
16158:     my ($reqdmajor,$reqdminor) = split(/\./,$curr_reqd_hash{'internal.releaserequired'});
16159:     my %checkresponsetypes;
16160:     foreach my $key (keys(%Apache::lonnet::needsrelease)) {
16161:         my ($item,$name,$value) = split(/:/,$key);
16162:         if ($item eq 'resourcetag') {
16163:             if ($name eq 'responsetype') {
16164:                 $checkresponsetypes{$value} = $Apache::lonnet::needsrelease{$key}
16165:             }
16166:         }
16167:     }
16168:     my $navmap = Apache::lonnavmaps::navmap->new();
16169:     if (defined($navmap)) {
16170:         my %allresponses;
16171:         foreach my $res ($navmap->retrieveResources(undef,sub { $_[0]->is_problem() },1,0)) {
16172:             my %responses = $res->responseTypes();
16173:             foreach my $key (keys(%responses)) {
16174:                 next unless(exists($checkresponsetypes{$key}));
16175:                 $allresponses{$key} += $responses{$key};
16176:             }
16177:         }
16178:         foreach my $key (keys(%allresponses)) {
16179:             my ($major,$minor) = split(/\./,$checkresponsetypes{$key});
16180:             if (($major > $reqdmajor) || ($major == $reqdmajor && $minor > $reqdminor)) {
16181:                 ($reqdmajor,$reqdminor) = ($major,$minor);
16182:             }
16183:         }
16184:         undef($navmap);
16185:     }
16186:     unless (($reqdmajor eq '') && ($reqdminor eq '')) {
16187:         &Apache::lonnet::update_released_required($reqdmajor.'.'.$reqdminor,$cdom,$cnum,$chome,$cid);
16188:     }
16189:     return;
16190: }
16191: 
16192: sub allmaps_incourse {
16193:     my ($cdom,$cnum,$chome,$cid) = @_;
16194:     if ($cdom eq '' || $cnum eq '' || $chome eq '' || $cid eq '') {
16195:         $cid = $env{'request.course.id'};
16196:         $cdom = $env{'course.'.$cid.'.domain'};
16197:         $cnum = $env{'course.'.$cid.'.num'};
16198:         $chome = $env{'course.'.$cid.'.home'};
16199:     }
16200:     my %allmaps = ();
16201:     my $lastchange =
16202:         &Apache::lonnet::get_coursechange($cdom,$cnum);
16203:     if ($lastchange > $env{'request.course.tied'}) {
16204:         my ($furl,$ferr) = &Apache::lonuserstate::readmap("$cdom/$cnum");
16205:         unless ($ferr) {
16206:             &update_content_constraints($cdom,$cnum,$chome,$cid);
16207:         }
16208:     }
16209:     my $navmap = Apache::lonnavmaps::navmap->new();
16210:     if (defined($navmap)) {
16211:         foreach my $res ($navmap->retrieveResources(undef,sub { $_[0]->is_map() },1,0,1)) {
16212:             $allmaps{$res->src()} = 1;
16213:         }
16214:     }
16215:     return \%allmaps;
16216: }
16217: 
16218: sub parse_supplemental_title {
16219:     my ($title) = @_;
16220: 
16221:     my ($foldertitle,$renametitle);
16222:     if ($title =~ /&amp;&amp;&amp;/) {
16223:         $title = &HTML::Entites::decode($title);
16224:     }
16225:     if ($title =~ m/^(\d+)___&&&___($match_username)___&&&___($match_domain)___&&&___(.*)$/) {
16226:         $renametitle=$4;
16227:         my ($time,$uname,$udom) = ($1,$2,$3);
16228:         $foldertitle=&Apache::lontexconvert::msgtexconverted($4);
16229:         my $name =  &plainname($uname,$udom);
16230:         $name = &HTML::Entities::encode($name,'"<>&\'');
16231:         $renametitle = &HTML::Entities::encode($renametitle,'"<>&\'');
16232:         $title='<i>'.&Apache::lonlocal::locallocaltime($time).'</i> '.
16233:             $name.': <br />'.$foldertitle;
16234:     }
16235:     if (wantarray) {
16236:         return ($title,$foldertitle,$renametitle);
16237:     }
16238:     return $title;
16239: }
16240: 
16241: sub recurse_supplemental {
16242:     my ($cnum,$cdom,$suppmap,$numfiles,$errors) = @_;
16243:     if ($suppmap) {
16244:         my ($errtext,$fatal) = &LONCAPA::map::mapread('/uploaded/'.$cdom.'/'.$cnum.'/'.$suppmap);
16245:         if ($fatal) {
16246:             $errors ++;
16247:         } else {
16248:             if ($#LONCAPA::map::resources > 0) {
16249:                 foreach my $res (@LONCAPA::map::resources) {
16250:                     my ($title,$src,$ext,$type,$status)=split(/\:/,$res);
16251:                     if (($src ne '') && ($status eq 'res')) {
16252:                         if ($src =~ m{^\Q/uploaded/$cdom/$cnum/\E(supplemental_\d+\.sequence)$}) {
16253:                             ($numfiles,$errors) = &recurse_supplemental($cnum,$cdom,$1,$numfiles,$errors);
16254:                         } else {
16255:                             $numfiles ++;
16256:                         }
16257:                     }
16258:                 }
16259:             }
16260:         }
16261:     }
16262:     return ($numfiles,$errors);
16263: }
16264: 
16265: sub symb_to_docspath {
16266:     my ($symb) = @_;
16267:     return unless ($symb);
16268:     my ($mapurl,$id,$resurl) = &Apache::lonnet::decode_symb($symb);
16269:     if ($resurl=~/\.(sequence|page)$/) {
16270:         $mapurl=$resurl;
16271:     } elsif ($resurl eq 'adm/navmaps') {
16272:         $mapurl=$env{'course.'.$env{'request.course.id'}.'.url'};
16273:     }
16274:     my $mapresobj;
16275:     my $navmap = Apache::lonnavmaps::navmap->new();
16276:     if (ref($navmap)) {
16277:         $mapresobj = $navmap->getResourceByUrl($mapurl);
16278:     }
16279:     $mapurl=~s{^.*/([^/]+)\.(\w+)$}{$1};
16280:     my $type=$2;
16281:     my $path;
16282:     if (ref($mapresobj)) {
16283:         my $pcslist = $mapresobj->map_hierarchy();
16284:         if ($pcslist ne '') {
16285:             foreach my $pc (split(/,/,$pcslist)) {
16286:                 next if ($pc <= 1);
16287:                 my $res = $navmap->getByMapPc($pc);
16288:                 if (ref($res)) {
16289:                     my $thisurl = $res->src();
16290:                     $thisurl=~s{^.*/([^/]+)\.\w+$}{$1};
16291:                     my $thistitle = $res->title();
16292:                     $path .= '&'.
16293:                              &Apache::lonhtmlcommon::entity_encode($thisurl).'&'.
16294:                              &escape($thistitle).
16295:                              ':'.$res->randompick().
16296:                              ':'.$res->randomout().
16297:                              ':'.$res->encrypted().
16298:                              ':'.$res->randomorder().
16299:                              ':'.$res->is_page();
16300:                 }
16301:             }
16302:         }
16303:         $path =~ s/^\&//;
16304:         my $maptitle = $mapresobj->title();
16305:         if ($mapurl eq 'default') {
16306:             $maptitle = 'Main Content';
16307:         }
16308:         $path .= (($path ne '')? '&' : '').
16309:                  &Apache::lonhtmlcommon::entity_encode($mapurl).'&'.
16310:                  &escape($maptitle).
16311:                  ':'.$mapresobj->randompick().
16312:                  ':'.$mapresobj->randomout().
16313:                  ':'.$mapresobj->encrypted().
16314:                  ':'.$mapresobj->randomorder().
16315:                  ':'.$mapresobj->is_page();
16316:     } else {
16317:         my $maptitle = &Apache::lonnet::gettitle($mapurl);
16318:         my $ispage = (($type eq 'page')? 1 : '');
16319:         if ($mapurl eq 'default') {
16320:             $maptitle = 'Main Content';
16321:         }
16322:         $path = &Apache::lonhtmlcommon::entity_encode($mapurl).'&'.
16323:                 &escape($maptitle).':::::'.$ispage;
16324:     }
16325:     unless ($mapurl eq 'default') {
16326:         $path = 'default&'.
16327:                 &escape('Main Content').
16328:                 ':::::&'.$path;
16329:     }
16330:     return $path;
16331: }
16332: 
16333: sub captcha_display {
16334:     my ($context,$lonhost) = @_;
16335:     my ($output,$error);
16336:     my ($captcha,$pubkey,$privkey,$version) =
16337:         &get_captcha_config($context,$lonhost);
16338:     if ($captcha eq 'original') {
16339:         $output = &create_captcha();
16340:         unless ($output) {
16341:             $error = 'captcha';
16342:         }
16343:     } elsif ($captcha eq 'recaptcha') {
16344:         $output = &create_recaptcha($pubkey,$version);
16345:         unless ($output) {
16346:             $error = 'recaptcha';
16347:         }
16348:     }
16349:     return ($output,$error,$captcha,$version);
16350: }
16351: 
16352: sub captcha_response {
16353:     my ($context,$lonhost) = @_;
16354:     my ($captcha_chk,$captcha_error);
16355:     my ($captcha,$pubkey,$privkey,$version) = &get_captcha_config($context,$lonhost);
16356:     if ($captcha eq 'original') {
16357:         ($captcha_chk,$captcha_error) = &check_captcha();
16358:     } elsif ($captcha eq 'recaptcha') {
16359:         $captcha_chk = &check_recaptcha($privkey,$version);
16360:     } else {
16361:         $captcha_chk = 1;
16362:     }
16363:     return ($captcha_chk,$captcha_error);
16364: }
16365: 
16366: sub get_captcha_config {
16367:     my ($context,$lonhost) = @_;
16368:     my ($captcha,$pubkey,$privkey,$version,$hashtocheck);
16369:     my $hostname = &Apache::lonnet::hostname($lonhost);
16370:     my $serverhomeID = &Apache::lonnet::get_server_homeID($hostname);
16371:     my $serverhomedom = &Apache::lonnet::host_domain($serverhomeID);
16372:     if ($context eq 'usercreation') {
16373:         my %domconfig = &Apache::lonnet::get_dom('configuration',[$context],$serverhomedom);
16374:         if (ref($domconfig{$context}) eq 'HASH') {
16375:             $hashtocheck = $domconfig{$context}{'cancreate'};
16376:             if (ref($hashtocheck) eq 'HASH') {
16377:                 if ($hashtocheck->{'captcha'} eq 'recaptcha') {
16378:                     if (ref($hashtocheck->{'recaptchakeys'}) eq 'HASH') {
16379:                         $pubkey = $hashtocheck->{'recaptchakeys'}{'public'};
16380:                         $privkey = $hashtocheck->{'recaptchakeys'}{'private'};
16381:                     }
16382:                     if ($privkey && $pubkey) {
16383:                         $captcha = 'recaptcha';
16384:                         $version = $hashtocheck->{'recaptchaversion'};
16385:                         if ($version ne '2') {
16386:                             $version = 1;
16387:                         }
16388:                     } else {
16389:                         $captcha = 'original';
16390:                     }
16391:                 } elsif ($hashtocheck->{'captcha'} ne 'notused') {
16392:                     $captcha = 'original';
16393:                 }
16394:             }
16395:         } else {
16396:             $captcha = 'captcha';
16397:         }
16398:     } elsif ($context eq 'login') {
16399:         my %domconfhash = &Apache::loncommon::get_domainconf($serverhomedom);
16400:         if ($domconfhash{$serverhomedom.'.login.captcha'} eq 'recaptcha') {
16401:             $pubkey = $domconfhash{$serverhomedom.'.login.recaptchakeys_public'};
16402:             $privkey = $domconfhash{$serverhomedom.'.login.recaptchakeys_private'};
16403:             if ($privkey && $pubkey) {
16404:                 $captcha = 'recaptcha';
16405:                 $version = $domconfhash{$serverhomedom.'.login.recaptchaversion'};
16406:                 if ($version ne '2') {
16407:                     $version = 1;
16408:                 }
16409:             } else {
16410:                 $captcha = 'original';
16411:             }
16412:         } elsif ($domconfhash{$serverhomedom.'.login.captcha'} eq 'original') {
16413:             $captcha = 'original';
16414:         }
16415:     }
16416:     return ($captcha,$pubkey,$privkey,$version);
16417: }
16418: 
16419: sub create_captcha {
16420:     my %captcha_params = &captcha_settings();
16421:     my ($output,$maxtries,$tries) = ('',10,0);
16422:     while ($tries < $maxtries) {
16423:         $tries ++;
16424:         my $captcha = Authen::Captcha->new (
16425:                                            output_folder => $captcha_params{'output_dir'},
16426:                                            data_folder   => $captcha_params{'db_dir'},
16427:                                           );
16428:         my $md5sum = $captcha->generate_code($captcha_params{'numchars'});
16429: 
16430:         if (-e $Apache::lonnet::perlvar{'lonCaptchaDir'}.'/'.$md5sum.'.png') {
16431:             $output = '<input type="hidden" name="crypt" value="'.$md5sum.'" />'."\n".
16432:                       &mt('Type in the letters/numbers shown below').'&nbsp;'.
16433:                       '<input type="text" size="5" name="code" value="" autocomplete="off" />'.
16434:                       '<br />'.
16435:                       '<img src="'.$captcha_params{'www_output_dir'}.'/'.$md5sum.'.png" alt="captcha" />';
16436:             last;
16437:         }
16438:     }
16439:     return $output;
16440: }
16441: 
16442: sub captcha_settings {
16443:     my %captcha_params = (
16444:                            output_dir     => $Apache::lonnet::perlvar{'lonCaptchaDir'},
16445:                            www_output_dir => "/captchaspool",
16446:                            db_dir         => $Apache::lonnet::perlvar{'lonCaptchaDb'},
16447:                            numchars       => '5',
16448:                          );
16449:     return %captcha_params;
16450: }
16451: 
16452: sub check_captcha {
16453:     my ($captcha_chk,$captcha_error);
16454:     my $code = $env{'form.code'};
16455:     my $md5sum = $env{'form.crypt'};
16456:     my %captcha_params = &captcha_settings();
16457:     my $captcha = Authen::Captcha->new(
16458:                       output_folder => $captcha_params{'output_dir'},
16459:                       data_folder   => $captcha_params{'db_dir'},
16460:                   );
16461:     $captcha_chk = $captcha->check_code($code,$md5sum);
16462:     my %captcha_hash = (
16463:                         0       => 'Code not checked (file error)',
16464:                        -1      => 'Failed: code expired',
16465:                        -2      => 'Failed: invalid code (not in database)',
16466:                        -3      => 'Failed: invalid code (code does not match crypt)',
16467:     );
16468:     if ($captcha_chk != 1) {
16469:         $captcha_error = $captcha_hash{$captcha_chk}
16470:     }
16471:     return ($captcha_chk,$captcha_error);
16472: }
16473: 
16474: sub create_recaptcha {
16475:     my ($pubkey,$version) = @_;
16476:     if ($version >= 2) {
16477:         return '<div class="g-recaptcha" data-sitekey="'.$pubkey.'"></div>';
16478:     } else {
16479:         my $use_ssl;
16480:         if ($ENV{'SERVER_PORT'} == 443) {
16481:             $use_ssl = 1;
16482:         }
16483:         my $captcha = Captcha::reCAPTCHA->new;
16484:         return $captcha->get_options_setter({theme => 'white'})."\n".
16485:                $captcha->get_html($pubkey,undef,$use_ssl).
16486:                &mt('If the text is hard to read, [_1] will replace them.',
16487:                    '<img src="/res/adm/pages/refresh.gif" alt="reCAPTCHA refresh" />').
16488:                '<br /><br />';
16489:      }
16490: }
16491: 
16492: sub check_recaptcha {
16493:     my ($privkey,$version) = @_;
16494:     my $captcha_chk;
16495:     if ($version >= 2) {
16496:         my $ua = LWP::UserAgent->new;
16497:         $ua->timeout(10);
16498:         my %info = (
16499:                      secret   => $privkey,
16500:                      response => $env{'form.g-recaptcha-response'},
16501:                      remoteip => $ENV{'REMOTE_ADDR'},
16502:                    );
16503:         my $response = $ua->post('https://www.google.com/recaptcha/api/siteverify',\%info);
16504:         if ($response->is_success)  {
16505:             my $data = JSON::DWIW->from_json($response->decoded_content);
16506:             if (ref($data) eq 'HASH') {
16507:                 if ($data->{'success'}) {
16508:                     $captcha_chk = 1;
16509:                 }
16510:             }
16511:         }
16512:     } else {
16513:         my $captcha = Captcha::reCAPTCHA->new;
16514:         my $captcha_result =
16515:             $captcha->check_answer(
16516:                                     $privkey,
16517:                                     $ENV{'REMOTE_ADDR'},
16518:                                     $env{'form.recaptcha_challenge_field'},
16519:                                     $env{'form.recaptcha_response_field'},
16520:                                   );
16521:         if ($captcha_result->{is_valid}) {
16522:             $captcha_chk = 1;
16523:         }
16524:     }
16525:     return $captcha_chk;
16526: }
16527: 
16528: sub emailusername_info {
16529:     my @fields = ('firstname','lastname','institution','web','location','officialemail','id');
16530:     my %titles = &Apache::lonlocal::texthash (
16531:                      lastname      => 'Last Name',
16532:                      firstname     => 'First Name',
16533:                      institution   => 'School/college/university',
16534:                      location      => "School's city, state/province, country",
16535:                      web           => "School's web address",
16536:                      officialemail => 'E-mail address at institution (if different)',
16537:                      id            => 'Student/Employee ID',
16538:                  );
16539:     return (\@fields,\%titles);
16540: }
16541: 
16542: sub cleanup_html {
16543:     my ($incoming) = @_;
16544:     my $outgoing;
16545:     if ($incoming ne '') {
16546:         $outgoing = $incoming;
16547:         $outgoing =~ s/;/&#059;/g;
16548:         $outgoing =~ s/\#/&#035;/g;
16549:         $outgoing =~ s/\&/&#038;/g;
16550:         $outgoing =~ s/</&#060;/g;
16551:         $outgoing =~ s/>/&#062;/g;
16552:         $outgoing =~ s/\(/&#040/g;
16553:         $outgoing =~ s/\)/&#041;/g;
16554:         $outgoing =~ s/"/&#034;/g;
16555:         $outgoing =~ s/'/&#039;/g;
16556:         $outgoing =~ s/\$/&#036;/g;
16557:         $outgoing =~ s{/}{&#047;}g;
16558:         $outgoing =~ s/=/&#061;/g;
16559:         $outgoing =~ s/\\/&#092;/g
16560:     }
16561:     return $outgoing;
16562: }
16563: 
16564: # Checks for critical messages and returns a redirect url if one exists.
16565: # $interval indicates how often to check for messages.
16566: sub critical_redirect {
16567:     my ($interval) = @_;
16568:     if ((time-$env{'user.criticalcheck.time'})>$interval) {
16569:         my @what=&Apache::lonnet::dump('critical', $env{'user.domain'},
16570:                                         $env{'user.name'});
16571:         &Apache::lonnet::appenv({'user.criticalcheck.time'=>time});
16572:         my $redirecturl;
16573:         if ($what[0]) {
16574:             if (($what[0] ne 'con_lost') && ($what[0]!~/^error\:/)) {
16575:                 $redirecturl='/adm/email?critical=display';
16576:                 my $url=&Apache::lonnet::absolute_url().$redirecturl;
16577:                 return (1, $url);
16578:             }
16579:         }
16580:     }
16581:     return ();
16582: }
16583: 
16584: # Use:
16585: #   my $answer=reply("encrypt:passwd:$udom:$uname:$upass",$tryserver);
16586: #
16587: ##################################################
16588: #          password associated functions         #
16589: ##################################################
16590: sub des_keys {
16591:     # Make a new key for DES encryption.
16592:     # Each key has two parts which are returned separately.
16593:     # Please note:  Each key must be passed through the &hex function
16594:     # before it is output to the web browser.  The hex versions cannot
16595:     # be used to decrypt.
16596:     my @hexstr=('0','1','2','3','4','5','6','7',
16597:                 '8','9','a','b','c','d','e','f');
16598:     my $lkey='';
16599:     for (0..7) {
16600:         $lkey.=$hexstr[rand(15)];
16601:     }
16602:     my $ukey='';
16603:     for (0..7) {
16604:         $ukey.=$hexstr[rand(15)];
16605:     }
16606:     return ($lkey,$ukey);
16607: }
16608: 
16609: sub des_decrypt {
16610:     my ($key,$cyphertext) = @_;
16611:     my $keybin=pack("H16",$key);
16612:     my $cypher;
16613:     if ($Crypt::DES::VERSION>=2.03) {
16614:         $cypher=new Crypt::DES $keybin;
16615:     } else {
16616:         $cypher=new DES $keybin;
16617:     }
16618:     my $plaintext='';
16619:     my $cypherlength = length($cyphertext);
16620:     my $numchunks = int($cypherlength/32);
16621:     for (my $j=0; $j<$numchunks; $j++) {
16622:         my $start = $j*32;
16623:         my $cypherblock = substr($cyphertext,$start,32);
16624:         my $chunk =
16625:             $cypher->decrypt(unpack("a8",pack("H16",substr($cypherblock,0,16))));
16626:         $chunk .=
16627:             $cypher->decrypt(unpack("a8",pack("H16",substr($cypherblock,16,16))));
16628:         $chunk=substr($chunk,1,ord(substr($chunk,0,1)) );
16629:         $plaintext .= $chunk;
16630:     }
16631:     return $plaintext;
16632: }
16633: 
16634: 1;
16635: __END__;
16636: 

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