File:  [LON-CAPA] / loncom / interface / loncommon.pm
Revision 1.1251: download - view: text, annotated - select for diffs
Thu Aug 25 22:33:02 2016 UTC (7 years, 9 months ago) by raeburn
Branches: MAIN
CVS tags: HEAD
- Courses created by process a course request will have comment.email set
  to username:domain of requester.
- XML file used for batch course creation can also include <setcomment> tag
  which when set to 1 will have the same result.

    1: # The LearningOnline Network with CAPA
    2: # a pile of common routines
    3: #
    4: # $Id: loncommon.pm,v 1.1251 2016/08/25 22:33:02 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 Text::Aspell;
   78: use Authen::Captcha;
   79: use Captcha::reCAPTCHA;
   80: use JSON::DWIW;
   81: use LWP::UserAgent;
   82: use Crypt::DES;
   83: use DynaLoader; # for Crypt::DES version
   84: use MIME::Lite;
   85: use MIME::Types;
   86: 
   87: # ---------------------------------------------- Designs
   88: use vars qw(%defaultdesign);
   89: 
   90: my $readit;
   91: 
   92: 
   93: ##
   94: ## Global Variables
   95: ##
   96: 
   97: 
   98: # ----------------------------------------------- SSI with retries:
   99: #
  100: 
  101: =pod
  102: 
  103: =head1 Server Side include with retries:
  104: 
  105: =over 4
  106: 
  107: =item * &ssi_with_retries(resource,retries form)
  108: 
  109: Performs an ssi with some number of retries.  Retries continue either
  110: until the result is ok or until the retry count supplied by the
  111: caller is exhausted.  
  112: 
  113: Inputs:
  114: 
  115: =over 4
  116: 
  117: resource   - Identifies the resource to insert.
  118: 
  119: retries    - Count of the number of retries allowed.
  120: 
  121: form       - Hash that identifies the rendering options.
  122: 
  123: =back
  124: 
  125: Returns:
  126: 
  127: =over 4
  128: 
  129: content    - The content of the response.  If retries were exhausted this is empty.
  130: 
  131: response   - The response from the last attempt (which may or may not have been successful.
  132: 
  133: =back
  134: 
  135: =back
  136: 
  137: =cut
  138: 
  139: sub ssi_with_retries {
  140:     my ($resource, $retries, %form) = @_;
  141: 
  142: 
  143:     my $ok = 0;			# True if we got a good response.
  144:     my $content;
  145:     my $response;
  146: 
  147:     # Try to get the ssi done. within the retries count:
  148: 
  149:     do {
  150: 	($content, $response) = &Apache::lonnet::ssi($resource, %form);
  151: 	$ok      = $response->is_success;
  152:         if (!$ok) {
  153:             &Apache::lonnet::logthis("Failed ssi_with_retries on $resource: ".$response->is_success.', '.$response->code.', '.$response->message);
  154:         }
  155: 	$retries--;
  156:     } while (!$ok && ($retries > 0));
  157: 
  158:     if (!$ok) {
  159: 	$content = '';		# On error return an empty content.
  160:     }
  161:     return ($content, $response);
  162: 
  163: }
  164: 
  165: 
  166: 
  167: # ----------------------------------------------- Filetypes/Languages/Copyright
  168: my %language;
  169: my %supported_language;
  170: my %supported_codes;
  171: my %latex_language;		# For choosing hyphenation in <transl..>
  172: my %latex_language_bykey;	# for choosing hyphenation from metadata
  173: my %cprtag;
  174: my %scprtag;
  175: my %fe; my %fd; my %fm;
  176: my %category_extensions;
  177: 
  178: # ---------------------------------------------- Thesaurus variables
  179: #
  180: # %Keywords:
  181: #      A hash used by &keyword to determine if a word is considered a keyword.
  182: # $thesaurus_db_file 
  183: #      Scalar containing the full path to the thesaurus database.
  184: 
  185: my %Keywords;
  186: my $thesaurus_db_file;
  187: 
  188: #
  189: # Initialize values from language.tab, copyright.tab, filetypes.tab,
  190: # thesaurus.tab, and filecategories.tab.
  191: #
  192: BEGIN {
  193:     # Variable initialization
  194:     $thesaurus_db_file = $Apache::lonnet::perlvar{'lonTabDir'}."/thesaurus.db";
  195:     #
  196:     unless ($readit) {
  197: # ------------------------------------------------------------------- languages
  198:     {
  199:         my $langtabfile = $Apache::lonnet::perlvar{'lonTabDir'}.
  200:                                    '/language.tab';
  201:         if ( open(my $fh,"<$langtabfile") ) {
  202:             while (my $line = <$fh>) {
  203:                 next if ($line=~/^\#/);
  204:                 chomp($line);
  205:                 my ($key,$code,$country,$three,$enc,$val,$sup,$latex)=(split(/\t/,$line));
  206:                 $language{$key}=$val.' - '.$enc;
  207:                 if ($sup) {
  208:                     $supported_language{$key}=$sup;
  209: 		    $supported_codes{$key}   = $code;
  210:                 }
  211: 		if ($latex) {
  212: 		    $latex_language_bykey{$key} = $latex;
  213: 		    $latex_language{$code} = $latex;
  214: 		}
  215:             }
  216:             close($fh);
  217:         }
  218:     }
  219: # ------------------------------------------------------------------ copyrights
  220:     {
  221:         my $copyrightfile = $Apache::lonnet::perlvar{'lonIncludes'}.
  222:                                   '/copyright.tab';
  223:         if ( open (my $fh,"<$copyrightfile") ) {
  224:             while (my $line = <$fh>) {
  225:                 next if ($line=~/^\#/);
  226:                 chomp($line);
  227:                 my ($key,$val)=(split(/\s+/,$line,2));
  228:                 $cprtag{$key}=$val;
  229:             }
  230:             close($fh);
  231:         }
  232:     }
  233: # ----------------------------------------------------------- source copyrights
  234:     {
  235:         my $sourcecopyrightfile = $Apache::lonnet::perlvar{'lonIncludes'}.
  236:                                   '/source_copyright.tab';
  237:         if ( open (my $fh,"<$sourcecopyrightfile") ) {
  238:             while (my $line = <$fh>) {
  239:                 next if ($line =~ /^\#/);
  240:                 chomp($line);
  241:                 my ($key,$val)=(split(/\s+/,$line,2));
  242:                 $scprtag{$key}=$val;
  243:             }
  244:             close($fh);
  245:         }
  246:     }
  247: 
  248: # -------------------------------------------------------------- default domain designs
  249:     my $designdir=$Apache::lonnet::perlvar{'lonTabDir'}.'/lonDomColors';
  250:     my $designfile = $designdir.'/default.tab';
  251:     if ( open (my $fh,"<$designfile") ) {
  252:         while (my $line = <$fh>) {
  253:             next if ($line =~ /^\#/);
  254:             chomp($line);
  255:             my ($key,$val)=(split(/\=/,$line));
  256:             if ($val) { $defaultdesign{$key}=$val; }
  257:         }
  258:         close($fh);
  259:     }
  260: 
  261: # ------------------------------------------------------------- file categories
  262:     {
  263:         my $categoryfile = $Apache::lonnet::perlvar{'lonTabDir'}.
  264:                                   '/filecategories.tab';
  265:         if ( open (my $fh,"<$categoryfile") ) {
  266: 	    while (my $line = <$fh>) {
  267: 		next if ($line =~ /^\#/);
  268: 		chomp($line);
  269:                 my ($extension,$category)=(split(/\s+/,$line,2));
  270:                 push @{$category_extensions{lc($category)}},$extension;
  271:             }
  272:             close($fh);
  273:         }
  274: 
  275:     }
  276: # ------------------------------------------------------------------ file types
  277:     {
  278:         my $typesfile = $Apache::lonnet::perlvar{'lonTabDir'}.
  279:                '/filetypes.tab';
  280:         if ( open (my $fh,"<$typesfile") ) {
  281:             while (my $line = <$fh>) {
  282: 		next if ($line =~ /^\#/);
  283: 		chomp($line);
  284:                 my ($ending,$emb,$mime,$descr)=split(/\s+/,$line,4);
  285:                 if ($descr ne '') {
  286:                     $fe{$ending}=lc($emb);
  287:                     $fd{$ending}=$descr;
  288:                     if ($mime ne 'unk') { $fm{$ending}=$mime; }
  289:                 }
  290:             }
  291:             close($fh);
  292:         }
  293:     }
  294:     &Apache::lonnet::logthis(
  295:              "<span style='color:yellow;'>INFO: Read file types</span>");
  296:     $readit=1;
  297:     }  # end of unless($readit) 
  298:     
  299: }
  300: 
  301: ###############################################################
  302: ##           HTML and Javascript Helper Functions            ##
  303: ###############################################################
  304: 
  305: =pod 
  306: 
  307: =head1 HTML and Javascript Functions
  308: 
  309: =over 4
  310: 
  311: =item * &browser_and_searcher_javascript()
  312: 
  313: X<browsing, javascript>X<searching, javascript>Returns a string
  314: containing javascript with two functions, C<openbrowser> and
  315: C<opensearcher>. Returned string does not contain E<lt>scriptE<gt>
  316: tags.
  317: 
  318: =item * &openbrowser(formname,elementname,only,omit) [javascript]
  319: 
  320: inputs: formname, elementname, only, omit
  321: 
  322: formname and elementname indicate the name of the html form and name of
  323: the element that the results of the browsing selection are to be placed in. 
  324: 
  325: Specifying 'only' will restrict the browser to displaying only files
  326: with the given extension.  Can be a comma separated list.
  327: 
  328: Specifying 'omit' will restrict the browser to NOT displaying files
  329: with the given extension.  Can be a comma separated list.
  330: 
  331: =item * &opensearcher(formname,elementname) [javascript]
  332: 
  333: Inputs: formname, elementname
  334: 
  335: formname and elementname specify the name of the html form and the name
  336: of the element the selection from the search results will be placed in.
  337: 
  338: =cut
  339: 
  340: sub browser_and_searcher_javascript {
  341:     my ($mode)=@_;
  342:     if (!defined($mode)) { $mode='edit'; }
  343:     my $resurl=&escape_single(&lastresurl());
  344:     return <<END;
  345: // <!-- BEGIN LON-CAPA Internal
  346:     var editbrowser = null;
  347:     function openbrowser(formname,elementname,only,omit,titleelement) {
  348:         var url = '$resurl/?';
  349:         if (editbrowser == null) {
  350:             url += 'launch=1&';
  351:         }
  352:         url += 'catalogmode=interactive&';
  353:         url += 'mode=$mode&';
  354:         url += 'inhibitmenu=yes&';
  355:         url += 'form=' + formname + '&';
  356:         if (only != null) {
  357:             url += 'only=' + only + '&';
  358:         } else {
  359:             url += 'only=&';
  360: 	}
  361:         if (omit != null) {
  362:             url += 'omit=' + omit + '&';
  363:         } else {
  364:             url += 'omit=&';
  365: 	}
  366:         if (titleelement != null) {
  367:             url += 'titleelement=' + titleelement + '&';
  368:         } else {
  369: 	    url += 'titleelement=&';
  370: 	}
  371:         url += 'element=' + elementname + '';
  372:         var title = 'Browser';
  373:         var options = 'scrollbars=1,resizable=1,menubar=0,toolbar=1,location=1';
  374:         options += ',width=700,height=600';
  375:         editbrowser = open(url,title,options,'1');
  376:         editbrowser.focus();
  377:     }
  378:     var editsearcher;
  379:     function opensearcher(formname,elementname,titleelement) {
  380:         var url = '/adm/searchcat?';
  381:         if (editsearcher == null) {
  382:             url += 'launch=1&';
  383:         }
  384:         url += 'catalogmode=interactive&';
  385:         url += 'mode=$mode&';
  386:         url += 'form=' + formname + '&';
  387:         if (titleelement != null) {
  388:             url += 'titleelement=' + titleelement + '&';
  389:         } else {
  390: 	    url += 'titleelement=&';
  391: 	}
  392:         url += 'element=' + elementname + '';
  393:         var title = 'Search';
  394:         var options = 'scrollbars=1,resizable=1,menubar=0,toolbar=1,location=1';
  395:         options += ',width=700,height=600';
  396:         editsearcher = open(url,title,options,'1');
  397:         editsearcher.focus();
  398:     }
  399: // END LON-CAPA Internal -->
  400: END
  401: }
  402: 
  403: sub lastresurl {
  404:     if ($env{'environment.lastresurl'}) {
  405: 	return $env{'environment.lastresurl'}
  406:     } else {
  407: 	return '/res';
  408:     }
  409: }
  410: 
  411: sub storeresurl {
  412:     my $resurl=&Apache::lonnet::clutter(shift);
  413:     unless ($resurl=~/^\/res/) { return 0; }
  414:     $resurl=~s/\/$//;
  415:     &Apache::lonnet::put('environment',{'lastresurl' => $resurl});
  416:     &Apache::lonnet::appenv({'environment.lastresurl' => $resurl});
  417:     return 1;
  418: }
  419: 
  420: sub studentbrowser_javascript {
  421:    unless (
  422:             (($env{'request.course.id'}) && 
  423:              (&Apache::lonnet::allowed('srm',$env{'request.course.id'})
  424: 	      || &Apache::lonnet::allowed('srm',$env{'request.course.id'}.
  425: 					  '/'.$env{'request.course.sec'})
  426: 	      ))
  427:          || ($env{'request.role'}=~/^(au|dc|su)/)
  428:           ) { return ''; }  
  429:    return (<<'ENDSTDBRW');
  430: <script type="text/javascript" language="Javascript">
  431: // <![CDATA[
  432:     var stdeditbrowser;
  433:     function openstdbrowser(formname,uname,udom,clicker,roleflag,ignorefilter,courseadvonly) {
  434:         var url = '/adm/pickstudent?';
  435:         var filter;
  436: 	if (!ignorefilter) {
  437: 	    eval('filter=document.'+formname+'.'+uname+'.value;');
  438: 	}
  439:         if (filter != null) {
  440:            if (filter != '') {
  441:                url += 'filter='+filter+'&';
  442: 	   }
  443:         }
  444:         url += 'form=' + formname + '&unameelement='+uname+
  445:                                     '&udomelement='+udom+
  446:                                     '&clicker='+clicker;
  447: 	if (roleflag) { url+="&roles=1"; }
  448:         if (courseadvonly) { url+="&courseadvonly=1"; }
  449:         var title = 'Student_Browser';
  450:         var options = 'scrollbars=1,resizable=1,menubar=0';
  451:         options += ',width=700,height=600';
  452:         stdeditbrowser = open(url,title,options,'1');
  453:         stdeditbrowser.focus();
  454:     }
  455: // ]]>
  456: </script>
  457: ENDSTDBRW
  458: }
  459: 
  460: sub resourcebrowser_javascript {
  461:    unless ($env{'request.course.id'}) { return ''; }
  462:    return (<<'ENDRESBRW');
  463: <script type="text/javascript" language="Javascript">
  464: // <![CDATA[
  465:     var reseditbrowser;
  466:     function openresbrowser(formname,reslink) {
  467:         var url = '/adm/pickresource?form='+formname+'&reslink='+reslink;
  468:         var title = 'Resource_Browser';
  469:         var options = 'scrollbars=1,resizable=1,menubar=0';
  470:         options += ',width=700,height=500';
  471:         reseditbrowser = open(url,title,options,'1');
  472:         reseditbrowser.focus();
  473:     }
  474: // ]]>
  475: </script>
  476: ENDRESBRW
  477: }
  478: 
  479: sub selectstudent_link {
  480:    my ($form,$unameele,$udomele,$courseadvonly,$clickerid)=@_;
  481:    my $callargs = "'".&Apache::lonhtmlcommon::entity_encode($form)."','".
  482:                       &Apache::lonhtmlcommon::entity_encode($unameele)."','".
  483:                       &Apache::lonhtmlcommon::entity_encode($udomele)."'";
  484:    if ($env{'request.course.id'}) {  
  485:        if (!&Apache::lonnet::allowed('srm',$env{'request.course.id'})
  486: 	   && !&Apache::lonnet::allowed('srm',$env{'request.course.id'}.
  487: 					'/'.$env{'request.course.sec'})) {
  488: 	   return '';
  489:        }
  490:        $callargs.=",'".&Apache::lonhtmlcommon::entity_encode($clickerid)."'";
  491:        if ($courseadvonly)  {
  492:            $callargs .= ",'',1,1";
  493:        }
  494:        return '<span class="LC_nobreak">'.
  495:               '<a href="javascript:openstdbrowser('.$callargs.');">'.
  496:               &mt('Select User').'</a></span>';
  497:    }
  498:    if ($env{'request.role'}=~/^(au|dc|su)/) {
  499:        $callargs .= ",'',1"; 
  500:        return '<span class="LC_nobreak">'.
  501:               '<a href="javascript:openstdbrowser('.$callargs.');">'.
  502:               &mt('Select User').'</a></span>';
  503:    }
  504:    return '';
  505: }
  506: 
  507: sub selectresource_link {
  508:    my ($form,$reslink,$arg)=@_;
  509:    
  510:    my $callargs = "'".&Apache::lonhtmlcommon::entity_encode($form)."','".
  511:                       &Apache::lonhtmlcommon::entity_encode($reslink)."'";
  512:    unless ($env{'request.course.id'}) { return $arg; }
  513:    return '<span class="LC_nobreak">'.
  514:               '<a href="javascript:openresbrowser('.$callargs.');">'.
  515:               $arg.'</a></span>';
  516: }
  517: 
  518: 
  519: 
  520: sub authorbrowser_javascript {
  521:     return <<"ENDAUTHORBRW";
  522: <script type="text/javascript" language="JavaScript">
  523: // <![CDATA[
  524: var stdeditbrowser;
  525: 
  526: function openauthorbrowser(formname,udom) {
  527:     var url = '/adm/pickauthor?';
  528:     url += 'form='+formname+'&roledom='+udom;
  529:     var title = 'Author_Browser';
  530:     var options = 'scrollbars=1,resizable=1,menubar=0';
  531:     options += ',width=700,height=600';
  532:     stdeditbrowser = open(url,title,options,'1');
  533:     stdeditbrowser.focus();
  534: }
  535: 
  536: // ]]>
  537: </script>
  538: ENDAUTHORBRW
  539: }
  540: 
  541: sub coursebrowser_javascript {
  542:     my ($domainfilter,$sec_element,$formname,$role_element,$crstype,
  543:         $credits_element,$instcode) = @_;
  544:     my $wintitle = 'Course_Browser';
  545:     if ($crstype eq 'Community') {
  546:         $wintitle = 'Community_Browser';
  547:     }
  548:     my $id_functions = &javascript_index_functions();
  549:     my $output = '
  550: <script type="text/javascript" language="JavaScript">
  551: // <![CDATA[
  552:     var stdeditbrowser;'."\n";
  553: 
  554:     $output .= <<"ENDSTDBRW";
  555:     function opencrsbrowser(formname,uname,udom,desc,extra_element,multflag,type,type_elem) {
  556:         var url = '/adm/pickcourse?';
  557:         var formid = getFormIdByName(formname);
  558:         var domainfilter = getDomainFromSelectbox(formname,udom);
  559:         if (domainfilter != null) {
  560:            if (domainfilter != '') {
  561:                url += 'domainfilter='+domainfilter+'&';
  562: 	   }
  563:         }
  564:         url += 'form=' + formname + '&cnumelement='+uname+
  565: 	                            '&cdomelement='+udom+
  566:                                     '&cnameelement='+desc;
  567:         if (extra_element !=null && extra_element != '') {
  568:             if (formname == 'rolechoice' || formname == 'studentform') {
  569:                 url += '&roleelement='+extra_element;
  570:                 if (domainfilter == null || domainfilter == '') {
  571:                     url += '&domainfilter='+extra_element;
  572:                 }
  573:             }
  574:             else {
  575:                 if (formname == 'portform') {
  576:                     url += '&setroles='+extra_element;
  577:                 } else {
  578:                     if (formname == 'rules') {
  579:                         url += '&fixeddom='+extra_element; 
  580:                     }
  581:                 }
  582:             }     
  583:         }
  584:         if (type != null && type != '') {
  585:             url += '&type='+type;
  586:         }
  587:         if (type_elem != null && type_elem != '') {
  588:             url += '&typeelement='+type_elem;
  589:         }
  590:         if (formname == 'ccrs') {
  591:             var ownername = document.forms[formid].ccuname.value;
  592:             var ownerdom =  document.forms[formid].ccdomain.options[document.forms[formid].ccdomain.selectedIndex].value;
  593:             url += '&cloner='+ownername+':'+ownerdom;
  594:             if (type == 'Course') {
  595:                 url += '&crscode='+document.forms[formid].crscode.value;
  596:             }
  597:         }
  598:         if (formname == 'requestcrs') {
  599:             url += '&crsdom=$domainfilter&crscode=$instcode';
  600:         }
  601:         if (multflag !=null && multflag != '') {
  602:             url += '&multiple='+multflag;
  603:         }
  604:         var title = '$wintitle';
  605:         var options = 'scrollbars=1,resizable=1,menubar=0';
  606:         options += ',width=700,height=600';
  607:         stdeditbrowser = open(url,title,options,'1');
  608:         stdeditbrowser.focus();
  609:     }
  610: $id_functions
  611: ENDSTDBRW
  612:     if (($sec_element ne '') || ($role_element ne '') || ($credits_element ne '')) {
  613:         $output .= &setsec_javascript($sec_element,$formname,$role_element,
  614:                                       $credits_element);
  615:     }
  616:     $output .= '
  617: // ]]>
  618: </script>';
  619:     return $output;
  620: }
  621: 
  622: sub javascript_index_functions {
  623:     return <<"ENDJS";
  624: 
  625: function getFormIdByName(formname) {
  626:     for (var i=0;i<document.forms.length;i++) {
  627:         if (document.forms[i].name == formname) {
  628:             return i;
  629:         }
  630:     }
  631:     return -1;
  632: }
  633: 
  634: function getIndexByName(formid,item) {
  635:     for (var i=0;i<document.forms[formid].elements.length;i++) {
  636:         if (document.forms[formid].elements[i].name == item) {
  637:             return i;
  638:         }
  639:     }
  640:     return -1;
  641: }
  642: 
  643: function getDomainFromSelectbox(formname,udom) {
  644:     var userdom;
  645:     var formid = getFormIdByName(formname);
  646:     if (formid > -1) {
  647:         var domid = getIndexByName(formid,udom);
  648:         if (domid > -1) {
  649:             if (document.forms[formid].elements[domid].type == 'select-one') {
  650:                 userdom=document.forms[formid].elements[domid].options[document.forms[formid].elements[domid].selectedIndex].value;
  651:             }
  652:             if (document.forms[formid].elements[domid].type == 'hidden') {
  653:                 userdom=document.forms[formid].elements[domid].value;
  654:             }
  655:         }
  656:     }
  657:     return userdom;
  658: }
  659: 
  660: ENDJS
  661: 
  662: }
  663: 
  664: sub javascript_array_indexof {
  665:     return <<ENDJS;
  666: <script type="text/javascript" language="JavaScript">
  667: // <![CDATA[
  668: 
  669: if (!Array.prototype.indexOf) {
  670:     Array.prototype.indexOf = function (searchElement /*, fromIndex */ ) {
  671:         "use strict";
  672:         if (this === void 0 || this === null) {
  673:             throw new TypeError();
  674:         }
  675:         var t = Object(this);
  676:         var len = t.length >>> 0;
  677:         if (len === 0) {
  678:             return -1;
  679:         }
  680:         var n = 0;
  681:         if (arguments.length > 0) {
  682:             n = Number(arguments[1]);
  683:             if (n !== n) { // shortcut for verifying if it is NaN
  684:                 n = 0;
  685:             } else if (n !== 0 && n !== (1 / 0) && n !== -(1 / 0)) {
  686:                 n = (n > 0 || -1) * Math.floor(Math.abs(n));
  687:             }
  688:         }
  689:         if (n >= len) {
  690:             return -1;
  691:         }
  692:         var k = n >= 0 ? n : Math.max(len - Math.abs(n), 0);
  693:         for (; k < len; k++) {
  694:             if (k in t && t[k] === searchElement) {
  695:                 return k;
  696:             }
  697:         }
  698:         return -1;
  699:     }
  700: }
  701: 
  702: // ]]>
  703: </script>
  704: 
  705: ENDJS
  706: 
  707: }
  708: 
  709: sub userbrowser_javascript {
  710:     my $id_functions = &javascript_index_functions();
  711:     return <<"ENDUSERBRW";
  712: 
  713: function openuserbrowser(formname,uname,udom,ulast,ufirst,uemail,hideudom,crsdom,caller) {
  714:     var url = '/adm/pickuser?';
  715:     var userdom = getDomainFromSelectbox(formname,udom);
  716:     if (userdom != null) {
  717:        if (userdom != '') {
  718:            url += 'srchdom='+userdom+'&';
  719:        }
  720:     }
  721:     url += 'form=' + formname + '&unameelement='+uname+
  722:                                 '&udomelement='+udom+
  723:                                 '&ulastelement='+ulast+
  724:                                 '&ufirstelement='+ufirst+
  725:                                 '&uemailelement='+uemail+
  726:                                 '&hideudomelement='+hideudom+
  727:                                 '&coursedom='+crsdom;
  728:     if ((caller != null) && (caller != undefined)) {
  729:         url += '&caller='+caller;
  730:     }
  731:     var title = 'User_Browser';
  732:     var options = 'scrollbars=1,resizable=1,menubar=0';
  733:     options += ',width=700,height=600';
  734:     var stdeditbrowser = open(url,title,options,'1');
  735:     stdeditbrowser.focus();
  736: }
  737: 
  738: function fix_domain (formname,udom,origdom,uname) {
  739:     var formid = getFormIdByName(formname);
  740:     if (formid > -1) {
  741:         var unameid = getIndexByName(formid,uname);
  742:         var domid = getIndexByName(formid,udom);
  743:         var hidedomid = getIndexByName(formid,origdom);
  744:         if (hidedomid > -1) {
  745:             var fixeddom = document.forms[formid].elements[hidedomid].value;
  746:             var unameval = document.forms[formid].elements[unameid].value;
  747:             if ((fixeddom != '') && (fixeddom != undefined) && (fixeddom != null) && (unameval != '') && (unameval != undefined) && (unameval != null)) {
  748:                 if (domid > -1) {
  749:                     var slct = document.forms[formid].elements[domid];
  750:                     if (slct.type == 'select-one') {
  751:                         var i;
  752:                         for (i=0;i<slct.length;i++) {
  753:                             if (slct.options[i].value==fixeddom) { slct.selectedIndex=i; }
  754:                         }
  755:                     }
  756:                     if (slct.type == 'hidden') {
  757:                         slct.value = fixeddom;
  758:                     }
  759:                 }
  760:             }
  761:         }
  762:     }
  763:     return;
  764: }
  765: 
  766: $id_functions
  767: ENDUSERBRW
  768: }
  769: 
  770: sub setsec_javascript {
  771:     my ($sec_element,$formname,$role_element,$credits_element) = @_;
  772:     my (@courserolenames,@communityrolenames,$rolestr,$courserolestr,
  773:         $communityrolestr);
  774:     if ($role_element ne '') {
  775:         my @allroles = ('st','ta','ep','in','ad');
  776:         foreach my $crstype ('Course','Community') {
  777:             if ($crstype eq 'Community') {
  778:                 foreach my $role (@allroles) {
  779:                     push(@communityrolenames,&Apache::lonnet::plaintext($role,$crstype));
  780:                 }
  781:                 push(@communityrolenames,&Apache::lonnet::plaintext('co'));
  782:             } else {
  783:                 foreach my $role (@allroles) {
  784:                     push(@courserolenames,&Apache::lonnet::plaintext($role,$crstype));
  785:                 }
  786:                 push(@courserolenames,&Apache::lonnet::plaintext('cc'));
  787:             }
  788:         }
  789:         $rolestr = '"'.join('","',@allroles).'"';
  790:         $courserolestr = '"'.join('","',@courserolenames).'"';
  791:         $communityrolestr = '"'.join('","',@communityrolenames).'"';
  792:     }
  793:     my $setsections = qq|
  794: function setSect(sectionlist) {
  795:     var sectionsArray = new Array();
  796:     if ((sectionlist != '') && (typeof sectionlist != "undefined")) {
  797:         sectionsArray = sectionlist.split(",");
  798:     }
  799:     var numSections = sectionsArray.length;
  800:     document.$formname.$sec_element.length = 0;
  801:     if (numSections == 0) {
  802:         document.$formname.$sec_element.multiple=false;
  803:         document.$formname.$sec_element.size=1;
  804:         document.$formname.$sec_element.options[0] = new Option('No existing sections','',false,false)
  805:     } else {
  806:         if (numSections == 1) {
  807:             document.$formname.$sec_element.multiple=false;
  808:             document.$formname.$sec_element.size=1;
  809:             document.$formname.$sec_element.options[0] = new Option('Select','',true,true);
  810:             document.$formname.$sec_element.options[1] = new Option('No section','',false,false)
  811:             document.$formname.$sec_element.options[2] = new Option(sectionsArray[0],sectionsArray[0],false,false);
  812:         } else {
  813:             for (var i=0; i<numSections; i++) {
  814:                 document.$formname.$sec_element.options[i] = new Option(sectionsArray[i],sectionsArray[i],false,false)
  815:             }
  816:             document.$formname.$sec_element.multiple=true
  817:             if (numSections < 3) {
  818:                 document.$formname.$sec_element.size=numSections;
  819:             } else {
  820:                 document.$formname.$sec_element.size=3;
  821:             }
  822:             document.$formname.$sec_element.options[0].selected = false
  823:         }
  824:     }
  825: }
  826: 
  827: function setRole(crstype) {
  828: |;
  829:     if ($role_element eq '') {
  830:         $setsections .= '    return;
  831: }
  832: ';
  833:     } else {
  834:         $setsections .= qq|
  835:     var elementLength = document.$formname.$role_element.length;
  836:     var allroles = Array($rolestr);
  837:     var courserolenames = Array($courserolestr);
  838:     var communityrolenames = Array($communityrolestr);
  839:     if (elementLength != undefined) {
  840:         if (document.$formname.$role_element.options[5].value == 'cc') {
  841:             if (crstype == 'Course') {
  842:                 return;
  843:             } else {
  844:                 allroles[5] = 'co';
  845:                 for (var i=0; i<6; i++) {
  846:                     document.$formname.$role_element.options[i].value = allroles[i];
  847:                     document.$formname.$role_element.options[i].text = communityrolenames[i];
  848:                 }
  849:             }
  850:         } else {
  851:             if (crstype == 'Community') {
  852:                 return;
  853:             } else {
  854:                 allroles[5] = 'cc';
  855:                 for (var i=0; i<6; i++) {
  856:                     document.$formname.$role_element.options[i].value = allroles[i];
  857:                     document.$formname.$role_element.options[i].text = courserolenames[i];
  858:                 }
  859:             }
  860:         }
  861:     }
  862:     return;
  863: }
  864: |;
  865:     }
  866:     if ($credits_element) {
  867:         $setsections .= qq|
  868: function setCredits(defaultcredits) {
  869:     document.$formname.$credits_element.value = defaultcredits;
  870:     return;
  871: }
  872: |;
  873:     }
  874:     return $setsections;
  875: }
  876: 
  877: sub selectcourse_link {
  878:    my ($form,$unameele,$udomele,$desc,$extra_element,$multflag,$selecttype,
  879:        $typeelement) = @_;
  880:    my $type = $selecttype;
  881:    my $linktext = &mt('Select Course');
  882:    if ($selecttype eq 'Community') {
  883:        $linktext = &mt('Select Community');
  884:    } elsif ($selecttype eq 'Placement') {
  885:        $linktext = &mt('Select Placement Test'); 
  886:    } elsif ($selecttype eq 'Course/Community') {
  887:        $linktext = &mt('Select Course/Community');
  888:        $type = '';
  889:    } elsif ($selecttype eq 'Select') {
  890:        $linktext = &mt('Select');
  891:        $type = '';
  892:    }
  893:    return '<span class="LC_nobreak">'
  894:          ."<a href='"
  895:          .'javascript:opencrsbrowser("'.$form.'","'.$unameele
  896:          .'","'.$udomele.'","'.$desc.'","'.$extra_element
  897:          .'","'.$multflag.'","'.$type.'","'.$typeelement.'");'
  898:          ."'>".$linktext.'</a>'
  899:          .'</span>';
  900: }
  901: 
  902: sub selectauthor_link {
  903:    my ($form,$udom)=@_;
  904:    return '<a href="javascript:openauthorbrowser('."'$form','$udom'".');">'.
  905:           &mt('Select Author').'</a>';
  906: }
  907: 
  908: sub selectuser_link {
  909:     my ($form,$unameelem,$domelem,$lastelem,$firstelem,$emailelem,$hdomelem,
  910:         $coursedom,$linktext,$caller) = @_;
  911:     return '<a href="javascript:openuserbrowser('."'$form','$unameelem','$domelem',".
  912:            "'$lastelem','$firstelem','$emailelem','$hdomelem','$coursedom','$caller'".
  913:            ');">'.$linktext.'</a>';
  914: }
  915: 
  916: sub check_uncheck_jscript {
  917:     my $jscript = <<"ENDSCRT";
  918: function checkAll(field) {
  919:     if (field.length > 0) {
  920:         for (i = 0; i < field.length; i++) {
  921:             if (!field[i].disabled) { 
  922:                 field[i].checked = true;
  923:             }
  924:         }
  925:     } else {
  926:         if (!field.disabled) { 
  927:             field.checked = true;
  928:         }
  929:     }
  930: }
  931:  
  932: function uncheckAll(field) {
  933:     if (field.length > 0) {
  934:         for (i = 0; i < field.length; i++) {
  935:             field[i].checked = false ;
  936:         }
  937:     } else {
  938:         field.checked = false ;
  939:     }
  940: }
  941: ENDSCRT
  942:     return $jscript;
  943: }
  944: 
  945: sub select_timezone {
  946:    my ($name,$selected,$onchange,$includeempty)=@_;
  947:    my $output='<select name="'.$name.'" '.$onchange.'>'."\n";
  948:    if ($includeempty) {
  949:        $output .= '<option value=""';
  950:        if (($selected eq '') || ($selected eq 'local')) {
  951:            $output .= ' selected="selected" ';
  952:        }
  953:        $output .= '> </option>';
  954:    }
  955:    my @timezones = DateTime::TimeZone->all_names;
  956:    foreach my $tzone (@timezones) {
  957:        $output.= '<option value="'.$tzone.'"';
  958:        if ($tzone eq $selected) {
  959:            $output.=' selected="selected"';
  960:        }
  961:        $output.=">$tzone</option>\n";
  962:    }
  963:    $output.="</select>";
  964:    return $output;
  965: }
  966: 
  967: sub select_datelocale {
  968:     my ($name,$selected,$onchange,$includeempty)=@_;
  969:     my $output='<select name="'.$name.'" '.$onchange.'>'."\n";
  970:     if ($includeempty) {
  971:         $output .= '<option value=""';
  972:         if ($selected eq '') {
  973:             $output .= ' selected="selected" ';
  974:         }
  975:         $output .= '> </option>';
  976:     }
  977:     my @languages = &Apache::lonlocal::preferred_languages();
  978:     my (@possibles,%locale_names);
  979:     my @locales = DateTime::Locale->ids();
  980:     foreach my $id (@locales) {
  981:         if ($id ne '') {
  982:             my ($en_terr,$native_terr);
  983:             my $loc = DateTime::Locale->load($id);
  984:             if (ref($loc)) {
  985:                 $en_terr = $loc->name();
  986:                 $native_terr = $loc->native_name();
  987:                 if (grep(/^en$/,@languages) || !@languages) {
  988:                     if ($en_terr ne '') {
  989:                         $locale_names{$id} = '('.$en_terr.')';
  990:                     } elsif ($native_terr ne '') {
  991:                         $locale_names{$id} = $native_terr;
  992:                     }
  993:                 } else {
  994:                     if ($native_terr ne '') {
  995:                         $locale_names{$id} = $native_terr.' ';
  996:                     } elsif ($en_terr ne '') {
  997:                         $locale_names{$id} = '('.$en_terr.')';
  998:                     }
  999:                 }
 1000:                 $locale_names{$id} = Encode::encode('UTF-8',$locale_names{$id});
 1001:                 push(@possibles,$id);
 1002:             } 
 1003:         }
 1004:     }
 1005:     foreach my $item (sort(@possibles)) {
 1006:         $output.= '<option value="'.$item.'"';
 1007:         if ($item eq $selected) {
 1008:             $output.=' selected="selected"';
 1009:         }
 1010:         $output.=">$item";
 1011:         if ($locale_names{$item} ne '') {
 1012:             $output.='  '.$locale_names{$item};
 1013:         }
 1014:         $output.="</option>\n";
 1015:     }
 1016:     $output.="</select>";
 1017:     return $output;
 1018: }
 1019: 
 1020: sub select_language {
 1021:     my ($name,$selected,$includeempty) = @_;
 1022:     my %langchoices;
 1023:     if ($includeempty) {
 1024:         %langchoices = ('' => 'No language preference');
 1025:     }
 1026:     foreach my $id (&languageids()) {
 1027:         my $code = &supportedlanguagecode($id);
 1028:         if ($code) {
 1029:             $langchoices{$code} = &plainlanguagedescription($id);
 1030:         }
 1031:     }
 1032:     %langchoices = &Apache::lonlocal::texthash(%langchoices);
 1033:     return &select_form($selected,$name,\%langchoices);
 1034: }
 1035: 
 1036: =pod
 1037: 
 1038: 
 1039: =item * &list_languages()
 1040: 
 1041: Returns an array reference that is suitable for use in language prompters.
 1042: Each array element is itself a two element array.  The first element
 1043: is the language code.  The second element a descsriptiuon of the 
 1044: language itself.  This is suitable for use in e.g.
 1045: &Apache::edit::select_arg (once dereferenced that is).
 1046: 
 1047: =cut 
 1048: 
 1049: sub list_languages {
 1050:     my @lang_choices;
 1051: 
 1052:     foreach my $id (&languageids()) {
 1053: 	my $code = &supportedlanguagecode($id);
 1054: 	if ($code) {
 1055: 	    my $selector    = $supported_codes{$id};
 1056: 	    my $description = &plainlanguagedescription($id);
 1057: 	    push (@lang_choices, [$selector, $description]);
 1058: 	}
 1059:     }
 1060:     return \@lang_choices;
 1061: }
 1062: 
 1063: =pod
 1064: 
 1065: =item * &linked_select_forms(...)
 1066: 
 1067: linked_select_forms returns a string containing a <script></script> block
 1068: and html for two <select> menus.  The select menus will be linked in that
 1069: changing the value of the first menu will result in new values being placed
 1070: in the second menu.  The values in the select menu will appear in alphabetical
 1071: order unless a defined order is provided.
 1072: 
 1073: linked_select_forms takes the following ordered inputs:
 1074: 
 1075: =over 4
 1076: 
 1077: =item * $formname, the name of the <form> tag
 1078: 
 1079: =item * $middletext, the text which appears between the <select> tags
 1080: 
 1081: =item * $firstdefault, the default value for the first menu
 1082: 
 1083: =item * $firstselectname, the name of the first <select> tag
 1084: 
 1085: =item * $secondselectname, the name of the second <select> tag
 1086: 
 1087: =item * $hashref, a reference to a hash containing the data for the menus.
 1088: 
 1089: =item * $menuorder, the order of values in the first menu
 1090: 
 1091: =item * $onchangefirst, additional javascript call to execute for an onchange
 1092:         event for the first <select> tag
 1093: 
 1094: =item * $onchangesecond, additional javascript call to execute for an onchange
 1095:         event for the second <select> tag
 1096: 
 1097: =item * $suffix, to differentiate separate uses of select2data javascript
 1098:         objects in a page.
 1099: 
 1100: =back 
 1101: 
 1102: Below is an example of such a hash.  Only the 'text', 'default', and 
 1103: 'select2' keys must appear as stated.  keys(%menu) are the possible 
 1104: values for the first select menu.  The text that coincides with the 
 1105: first menu value is given in $menu{$choice1}->{'text'}.  The values 
 1106: and text for the second menu are given in the hash pointed to by 
 1107: $menu{$choice1}->{'select2'}.  
 1108: 
 1109:  my %menu = ( A1 => { text =>"Choice A1" ,
 1110:                        default => "B3",
 1111:                        select2 => { 
 1112:                            B1 => "Choice B1",
 1113:                            B2 => "Choice B2",
 1114:                            B3 => "Choice B3",
 1115:                            B4 => "Choice B4"
 1116:                            },
 1117:                        order => ['B4','B3','B1','B2'],
 1118:                    },
 1119:                A2 => { text =>"Choice A2" ,
 1120:                        default => "C2",
 1121:                        select2 => { 
 1122:                            C1 => "Choice C1",
 1123:                            C2 => "Choice C2",
 1124:                            C3 => "Choice C3"
 1125:                            },
 1126:                        order => ['C2','C1','C3'],
 1127:                    },
 1128:                A3 => { text =>"Choice A3" ,
 1129:                        default => "D6",
 1130:                        select2 => { 
 1131:                            D1 => "Choice D1",
 1132:                            D2 => "Choice D2",
 1133:                            D3 => "Choice D3",
 1134:                            D4 => "Choice D4",
 1135:                            D5 => "Choice D5",
 1136:                            D6 => "Choice D6",
 1137:                            D7 => "Choice D7"
 1138:                            },
 1139:                        order => ['D4','D3','D2','D1','D7','D6','D5'],
 1140:                    }
 1141:                );
 1142: 
 1143: =cut
 1144: 
 1145: sub linked_select_forms {
 1146:     my ($formname,
 1147:         $middletext,
 1148:         $firstdefault,
 1149:         $firstselectname,
 1150:         $secondselectname, 
 1151:         $hashref,
 1152:         $menuorder,
 1153:         $onchangefirst,
 1154:         $onchangesecond,
 1155:         $suffix
 1156:         ) = @_;
 1157:     my $second = "document.$formname.$secondselectname";
 1158:     my $first = "document.$formname.$firstselectname";
 1159:     # output the javascript to do the changing
 1160:     my $result = '';
 1161:     $result.='<script type="text/javascript" language="JavaScript">'."\n";
 1162:     $result.="// <![CDATA[\n";
 1163:     $result.="var select2data${suffix} = new Object();\n";
 1164:     $" = '","';
 1165:     my $debug = '';
 1166:     foreach my $s1 (sort(keys(%$hashref))) {
 1167:         $result.="select2data${suffix}['d_$s1'] = new Object();\n";        
 1168:         $result.="select2data${suffix}['d_$s1'].def = new String('".
 1169:             $hashref->{$s1}->{'default'}."');\n";
 1170:         $result.="select2data${suffix}['d_$s1'].values = new Array(";
 1171:         my @s2values = sort(keys( %{ $hashref->{$s1}->{'select2'} } ));
 1172:         if (ref($hashref->{$s1}->{'order'}) eq 'ARRAY') {
 1173:             @s2values = @{$hashref->{$s1}->{'order'}};
 1174:         }
 1175:         $result.="\"@s2values\");\n";
 1176:         $result.="select2data${suffix}['d_$s1'].texts = new Array(";        
 1177:         my @s2texts;
 1178:         foreach my $value (@s2values) {
 1179:             push @s2texts, $hashref->{$s1}->{'select2'}->{$value};
 1180:         }
 1181:         $result.="\"@s2texts\");\n";
 1182:     }
 1183:     $"=' ';
 1184:     $result.= <<"END";
 1185: 
 1186: function select1${suffix}_changed() {
 1187:     // Determine new choice
 1188:     var newvalue = "d_" + $first.options[$first.selectedIndex].value;
 1189:     // update select2
 1190:     var values     = select2data${suffix}[newvalue].values;
 1191:     var texts      = select2data${suffix}[newvalue].texts;
 1192:     var select2def = select2data${suffix}[newvalue].def;
 1193:     var i;
 1194:     // out with the old
 1195:     $second.options.length = 0;
 1196:     // in with the new
 1197:     for (i=0;i<values.length; i++) {
 1198:         $second.options[i] = new Option(values[i]);
 1199:         $second.options[i].value = values[i];
 1200:         $second.options[i].text = texts[i];
 1201:         if (values[i] == select2def) {
 1202:             $second.options[i].selected = true;
 1203:         }
 1204:     }
 1205: }
 1206: // ]]>
 1207: </script>
 1208: END
 1209:     # output the initial values for the selection lists
 1210:     $result .= "<select size=\"1\" name=\"$firstselectname\" onchange=\"select1${suffix}_changed();$onchangefirst\">\n";
 1211:     my @order = sort(keys(%{$hashref}));
 1212:     if (ref($menuorder) eq 'ARRAY') {
 1213:         @order = @{$menuorder};
 1214:     }
 1215:     foreach my $value (@order) {
 1216:         $result.="    <option value=\"$value\" ";
 1217:         $result.=" selected=\"selected\" " if ($value eq $firstdefault);
 1218:         $result.=">".&mt($hashref->{$value}->{'text'})."</option>\n";
 1219:     }
 1220:     $result .= "</select>\n";
 1221:     my %select2 = %{$hashref->{$firstdefault}->{'select2'}};
 1222:     $result .= $middletext;
 1223:     $result .= "<select size=\"1\" name=\"$secondselectname\"";
 1224:     if ($onchangesecond) {
 1225:         $result .= ' onchange="'.$onchangesecond.'"';
 1226:     }
 1227:     $result .= ">\n";
 1228:     my $seconddefault = $hashref->{$firstdefault}->{'default'};
 1229:     
 1230:     my @secondorder = sort(keys(%select2));
 1231:     if (ref($hashref->{$firstdefault}->{'order'}) eq 'ARRAY') {
 1232:         @secondorder = @{$hashref->{$firstdefault}->{'order'}};
 1233:     }
 1234:     foreach my $value (@secondorder) {
 1235:         $result.="    <option value=\"$value\" ";        
 1236:         $result.=" selected=\"selected\" " if ($value eq $seconddefault);
 1237:         $result.=">".&mt($select2{$value})."</option>\n";
 1238:     }
 1239:     $result .= "</select>\n";
 1240:     #    return $debug;
 1241:     return $result;
 1242: }   #  end of sub linked_select_forms {
 1243: 
 1244: =pod
 1245: 
 1246: =item * &help_open_topic($topic,$text,$stayOnPage,$width,$height,$imgid)
 1247: 
 1248: Returns a string corresponding to an HTML link to the given help
 1249: $topic, where $topic corresponds to the name of a .tex file in
 1250: /home/httpd/html/adm/help/tex, with underscores replaced by
 1251: spaces. 
 1252: 
 1253: $text will optionally be linked to the same topic, allowing you to
 1254: link text in addition to the graphic. If you do not want to link
 1255: text, but wish to specify one of the later parameters, pass an
 1256: empty string. 
 1257: 
 1258: $stayOnPage is a value that will be interpreted as a boolean. If true,
 1259: the link will not open a new window. If false, the link will open
 1260: a new window using Javascript. (Default is false.) 
 1261: 
 1262: $width and $height are optional numerical parameters that will
 1263: override the width and height of the popped up window, which may
 1264: be useful for certain help topics with big pictures included.
 1265: 
 1266: $imgid is the id of the img tag used for the help icon. This may be
 1267: used in a javascript call to switch the image src.  See 
 1268: lonhtmlcommon::htmlareaselectactive() for an example.
 1269: 
 1270: =cut
 1271: 
 1272: sub help_open_topic {
 1273:     my ($topic, $text, $stayOnPage, $width, $height, $imgid) = @_;
 1274:     $text = "" if (not defined $text);
 1275:     $stayOnPage = 0 if (not defined $stayOnPage);
 1276:     $width = 500 if (not defined $width);
 1277:     $height = 400 if (not defined $height);
 1278:     my $filename = $topic;
 1279:     $filename =~ s/ /_/g;
 1280: 
 1281:     my $template = "";
 1282:     my $link;
 1283:     
 1284:     $topic=~s/\W/\_/g;
 1285: 
 1286:     if (!$stayOnPage) {
 1287: 	$link = "javascript:openMyModal('/adm/help/${filename}.hlp',$width,$height,'yes');";
 1288:     } elsif ($stayOnPage eq 'popup') {
 1289:         $link = "javascript:void(open('/adm/help/${filename}.hlp', 'Help_for_$topic', 'menubar=0,toolbar=1,scrollbars=1,width=$width,height=$height,resizable=yes'))";
 1290:     } else {
 1291: 	$link = "/adm/help/${filename}.hlp";
 1292:     }
 1293: 
 1294:     # Add the text
 1295:     if ($text ne "") {	
 1296: 	$template.='<span class="LC_help_open_topic">'
 1297:                   .'<a target="_top" href="'.$link.'">'
 1298:                   .$text.'</a>';
 1299:     }
 1300: 
 1301:     # (Always) Add the graphic
 1302:     my $title = &mt('Online Help');
 1303:     my $helpicon=&lonhttpdurl("/adm/help/help.png");
 1304:     if ($imgid ne '') {
 1305:         $imgid = ' id="'.$imgid.'"';
 1306:     }
 1307:     $template.=' <a target="_top" href="'.$link.'" title="'.$title.'">'
 1308:               .'<img src="'.$helpicon.'" border="0"'
 1309:               .' alt="'.&mt('Help: [_1]',$topic).'"'
 1310:               .' title="'.$title.'" style="vertical-align:middle;"'.$imgid 
 1311:               .' /></a>';
 1312:     if ($text ne "") {	
 1313:         $template.='</span>';
 1314:     }
 1315:     return $template;
 1316: 
 1317: }
 1318: 
 1319: # This is a quicky function for Latex cheatsheet editing, since it 
 1320: # appears in at least four places
 1321: sub helpLatexCheatsheet {
 1322:     my ($topic,$text,$not_author,$stayOnPage) = @_;
 1323:     my $out;
 1324:     my $addOther = '';
 1325:     if ($topic) {
 1326: 	$addOther = '<span>'.&help_open_topic($topic,&mt($text),$stayOnPage, undef, 600).'</span> ';
 1327:     }
 1328:     $out = '<span>' # Start cheatsheet
 1329: 	  .$addOther
 1330:           .'<span>'
 1331: 	  .&help_open_topic('Greek_Symbols',&mt('Greek Symbols'),$stayOnPage,undef,600)
 1332: 	  .'</span> <span>'
 1333: 	  .&help_open_topic('Other_Symbols',&mt('Other Symbols'),$stayOnPage,undef,600)
 1334: 	  .'</span>';
 1335:     unless ($not_author) {
 1336:         $out .= '<span>'
 1337:                .&help_open_topic('Authoring_Output_Tags',&mt('Output Tags'),$stayOnPage,undef,600)
 1338:                .'</span> <span>'
 1339:                .&help_open_topic('Authoring_Multilingual_Problems',&mt('How to create problems in different languages'),$stayOnPage,undef,600)
 1340: 	       .'</span>';
 1341:     }
 1342:     $out .= '</span>'; # End cheatsheet
 1343:     return $out;
 1344: }
 1345: 
 1346: sub general_help {
 1347:     my $helptopic='Student_Intro';
 1348:     if ($env{'request.role'}=~/^(ca|au)/) {
 1349: 	$helptopic='Authoring_Intro';
 1350:     } elsif ($env{'request.role'}=~/^(cc|co)/) {
 1351: 	$helptopic='Course_Coordination_Intro';
 1352:     } elsif ($env{'request.role'}=~/^dc/) {
 1353:         $helptopic='Domain_Coordination_Intro';
 1354:     }
 1355:     return $helptopic;
 1356: }
 1357: 
 1358: sub update_help_link {
 1359:     my ($topic,$component_help,$faq,$bug,$stayOnPage) = @_;
 1360:     my $origurl = $ENV{'REQUEST_URI'};
 1361:     $origurl=~s|^/~|/priv/|;
 1362:     my $timestamp = time;
 1363:     foreach my $datum (\$topic,\$component_help,\$faq,\$bug,\$origurl) {
 1364:         $$datum = &escape($$datum);
 1365:     }
 1366: 
 1367:     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";
 1368:     my $output .= <<"ENDOUTPUT";
 1369: <script type="text/javascript">
 1370: // <![CDATA[
 1371: banner_link = '$banner_link';
 1372: // ]]>
 1373: </script>
 1374: ENDOUTPUT
 1375:     return $output;
 1376: }
 1377: 
 1378: # now just updates the help link and generates a blue icon
 1379: sub help_open_menu {
 1380:     my ($topic,$component_help,$faq,$bug,$stayOnPage,$width,$height,$text) 
 1381: 	= @_;    
 1382:     $stayOnPage = 1;
 1383:     my $output;
 1384:     if ($component_help) {
 1385: 	if (!$text) {
 1386: 	    $output=&help_open_topic($component_help,undef,$stayOnPage,
 1387: 				       $width,$height);
 1388: 	} else {
 1389: 	    my $help_text;
 1390: 	    $help_text=&unescape($topic);
 1391: 	    $output='<table><tr><td>'.
 1392: 		&help_open_topic($component_help,$help_text,$stayOnPage,
 1393: 				 $width,$height).'</td></tr></table>';
 1394: 	}
 1395:     }
 1396:     my $banner_link = &update_help_link($topic,$component_help,$faq,$bug,$stayOnPage);
 1397:     return $output.$banner_link;
 1398: }
 1399: 
 1400: sub top_nav_help {
 1401:     my ($text) = @_;
 1402:     $text = &mt($text);
 1403:     my $stay_on_page = 1;
 1404: 
 1405:     my ($link,$banner_link);
 1406:     unless ($env{'request.noversionuri'} =~ m{^/adm/helpmenu}) {
 1407:         $link = ($stay_on_page) ? "javascript:helpMenu('display')"
 1408: 	                         : "javascript:helpMenu('open')";
 1409:         $banner_link = &update_help_link(undef,undef,undef,undef,$stay_on_page);
 1410:     }
 1411:     my $title = &mt('Get help');
 1412:     if ($link) {
 1413:         return <<"END";
 1414: $banner_link
 1415: <a href="$link" title="$title">$text</a>
 1416: END
 1417:     } else {
 1418:         return '&nbsp;'.$text.'&nbsp;';
 1419:     }
 1420: }
 1421: 
 1422: sub help_menu_js {
 1423:     my ($httphost) = @_;
 1424:     my $stayOnPage = 1;
 1425:     my $width = 620;
 1426:     my $height = 600;
 1427:     my $helptopic=&general_help();
 1428:     my $details_link = $httphost.'/adm/help/'.$helptopic.'.hlp';
 1429:     my $nothing=&Apache::lonhtmlcommon::javascript_nothing();
 1430:     my $start_page =
 1431:         &Apache::loncommon::start_page('Help Menu', undef,
 1432: 				       {'frameset'    => 1,
 1433: 					'js_ready'    => 1,
 1434:                                         'use_absolute' => $httphost,
 1435: 					'add_entries' => {
 1436: 					    'border' => '0', 
 1437: 					    'rows'   => "110,*",},});
 1438:     my $end_page =
 1439:         &Apache::loncommon::end_page({'frameset' => 1,
 1440: 				      'js_ready' => 1,});
 1441: 
 1442:     my $template .= <<"ENDTEMPLATE";
 1443: <script type="text/javascript">
 1444: // <![CDATA[
 1445: // <!-- BEGIN LON-CAPA Internal
 1446: var banner_link = '';
 1447: function helpMenu(target) {
 1448:     var caller = this;
 1449:     if (target == 'open') {
 1450:         var newWindow = null;
 1451:         try {
 1452:             newWindow =  window.open($nothing,"helpmenu","HEIGHT=$height,WIDTH=$width,resizable=yes,scrollbars=yes" )
 1453:         }
 1454:         catch(error) {
 1455:             writeHelp(caller);
 1456:             return;
 1457:         }
 1458:         if (newWindow) {
 1459:             caller = newWindow;
 1460:         }
 1461:     }
 1462:     writeHelp(caller);
 1463:     return;
 1464: }
 1465: function writeHelp(caller) {
 1466:     caller.document.writeln('$start_page\\n<frame name="bannerframe" src="'+banner_link+'" marginwidth="0" marginheight="0" frameborder="0">\\n');
 1467:     caller.document.writeln('<frame name="bodyframe" src="$details_link" marginwidth="0" marginheight="0" frameborder="0">\\n$end_page');
 1468:     caller.document.close();
 1469:     caller.focus();
 1470: }
 1471: // END LON-CAPA Internal -->
 1472: // ]]>
 1473: </script>
 1474: ENDTEMPLATE
 1475:     return $template;
 1476: }
 1477: 
 1478: sub help_open_bug {
 1479:     my ($topic, $text, $stayOnPage, $width, $height) = @_;
 1480:     unless ($env{'user.adv'}) { return ''; }
 1481:     unless ($Apache::lonnet::perlvar{'BugzillaHost'}) { return ''; }
 1482:     $text = "" if (not defined $text);
 1483: 	$stayOnPage=1;
 1484:     $width = 600 if (not defined $width);
 1485:     $height = 600 if (not defined $height);
 1486: 
 1487:     $topic=~s/\W+/\+/g;
 1488:     my $link='';
 1489:     my $template='';
 1490:     my $url=$Apache::lonnet::perlvar{'BugzillaHost'}.'enter_bug.cgi?product=LON-CAPA&amp;bug_file_loc='.
 1491: 	&escape($ENV{'REQUEST_URI'}).'&amp;component='.$topic;
 1492:     if (!$stayOnPage)
 1493:     {
 1494: 	$link = "javascript:void(open('$url', 'Bugzilla', 'menubar=0,toolbar=1,scrollbars=1,width=$width,height=$height,resizable=yes'))";
 1495:     }
 1496:     else
 1497:     {
 1498: 	$link = $url;
 1499:     }
 1500:     # Add the text
 1501:     if ($text ne "")
 1502:     {
 1503: 	$template .= 
 1504:   "<table bgcolor='#AA3333' cellspacing='1' cellpadding='1' border='0'><tr>".
 1505:   "<td bgcolor='#FF5555'><a target=\"_top\" href=\"$link\"><span style=\"color:#FFFFFF;font-size:10pt;\">$text</span></a>";
 1506:     }
 1507: 
 1508:     # Add the graphic
 1509:     my $title = &mt('Report a Bug');
 1510:     my $bugicon=&lonhttpdurl("/adm/lonMisc/smallBug.gif");
 1511:     $template .= <<"ENDTEMPLATE";
 1512:  <a target="_top" href="$link" title="$title"><img src="$bugicon" border="0" alt="(Bug: $topic)" /></a>
 1513: ENDTEMPLATE
 1514:     if ($text ne '') { $template.='</td></tr></table>' };
 1515:     return $template;
 1516: 
 1517: }
 1518: 
 1519: sub help_open_faq {
 1520:     my ($topic, $text, $stayOnPage, $width, $height) = @_;
 1521:     unless ($env{'user.adv'}) { return ''; }
 1522:     unless ($Apache::lonnet::perlvar{'FAQHost'}) { return ''; }
 1523:     $text = "" if (not defined $text);
 1524: 	$stayOnPage=1;
 1525:     $width = 350 if (not defined $width);
 1526:     $height = 400 if (not defined $height);
 1527: 
 1528:     $topic=~s/\W+/\+/g;
 1529:     my $link='';
 1530:     my $template='';
 1531:     my $url=$Apache::lonnet::perlvar{'FAQHost'}.'/fom/cache/'.$topic.'.html';
 1532:     if (!$stayOnPage)
 1533:     {
 1534: 	$link = "javascript:void(open('$url', 'FAQ-O-Matic', 'menubar=0,toolbar=1,scrollbars=1,width=$width,height=$height,resizable=yes'))";
 1535:     }
 1536:     else
 1537:     {
 1538: 	$link = $url;
 1539:     }
 1540: 
 1541:     # Add the text
 1542:     if ($text ne "")
 1543:     {
 1544: 	$template .= 
 1545:   "<table bgcolor='#337733' cellspacing='1' cellpadding='1' border='0'><tr>".
 1546:   "<td bgcolor='#448844'><a target=\"_top\" href=\"$link\"><span style=\"color:#FFFFFF; font-size:10pt;\">$text</span></a>";
 1547:     }
 1548: 
 1549:     # Add the graphic
 1550:     my $title = &mt('View the FAQ');
 1551:     my $faqicon=&lonhttpdurl("/adm/lonMisc/smallFAQ.gif");
 1552:     $template .= <<"ENDTEMPLATE";
 1553:  <a target="_top" href="$link" title="$title"><img src="$faqicon" border="0" alt="(FAQ: $topic)" /></a>
 1554: ENDTEMPLATE
 1555:     if ($text ne '') { $template.='</td></tr></table>' };
 1556:     return $template;
 1557: 
 1558: }
 1559: 
 1560: ###############################################################
 1561: ###############################################################
 1562: 
 1563: =pod
 1564: 
 1565: =item * &change_content_javascript():
 1566: 
 1567: This and the next function allow you to create small sections of an
 1568: otherwise static HTML page that you can update on the fly with
 1569: Javascript, even in Netscape 4.
 1570: 
 1571: The Javascript fragment returned by this function (no E<lt>scriptE<gt> tag)
 1572: must be written to the HTML page once. It will prove the Javascript
 1573: function "change(name, content)". Calling the change function with the
 1574: name of the section 
 1575: you want to update, matching the name passed to C<changable_area>, and
 1576: the new content you want to put in there, will put the content into
 1577: that area.
 1578: 
 1579: B<Note>: Netscape 4 only reserves enough space for the changable area
 1580: to contain room for the original contents. You need to "make space"
 1581: for whatever changes you wish to make, and be B<sure> to check your
 1582: code in Netscape 4. This feature in Netscape 4 is B<not> powerful;
 1583: it's adequate for updating a one-line status display, but little more.
 1584: This script will set the space to 100% width, so you only need to
 1585: worry about height in Netscape 4.
 1586: 
 1587: Modern browsers are much less limiting, and if you can commit to the
 1588: user not using Netscape 4, this feature may be used freely with
 1589: pretty much any HTML.
 1590: 
 1591: =cut
 1592: 
 1593: sub change_content_javascript {
 1594:     # If we're on Netscape 4, we need to use Layer-based code
 1595:     if ($env{'browser.type'} eq 'netscape' &&
 1596: 	$env{'browser.version'} =~ /^4\./) {
 1597: 	return (<<NETSCAPE4);
 1598: 	function change(name, content) {
 1599: 	    doc = document.layers[name+"___escape"].layers[0].document;
 1600: 	    doc.open();
 1601: 	    doc.write(content);
 1602: 	    doc.close();
 1603: 	}
 1604: NETSCAPE4
 1605:     } else {
 1606: 	# Otherwise, we need to use semi-standards-compliant code
 1607: 	# (technically, "innerHTML" isn't standard but the equivalent
 1608: 	# is really scary, and every useful browser supports it
 1609: 	return (<<DOMBASED);
 1610: 	function change(name, content) {
 1611: 	    element = document.getElementById(name);
 1612: 	    element.innerHTML = content;
 1613: 	}
 1614: DOMBASED
 1615:     }
 1616: }
 1617: 
 1618: =pod
 1619: 
 1620: =item * &changable_area($name,$origContent):
 1621: 
 1622: This provides a "changable area" that can be modified on the fly via
 1623: the Javascript code provided in C<change_content_javascript>. $name is
 1624: the name you will use to reference the area later; do not repeat the
 1625: same name on a given HTML page more then once. $origContent is what
 1626: the area will originally contain, which can be left blank.
 1627: 
 1628: =cut
 1629: 
 1630: sub changable_area {
 1631:     my ($name, $origContent) = @_;
 1632: 
 1633:     if ($env{'browser.type'} eq 'netscape' &&
 1634: 	$env{'browser.version'} =~ /^4\./) {
 1635: 	# If this is netscape 4, we need to use the Layer tag
 1636: 	return "<ilayer width='100%' id='${name}___escape' overflow='none'><layer width='100%' id='$name' overflow='none'>$origContent</layer></ilayer>";
 1637:     } else {
 1638: 	return "<span id='$name'>$origContent</span>";
 1639:     }
 1640: }
 1641: 
 1642: =pod
 1643: 
 1644: =item * &viewport_geometry_js 
 1645: 
 1646: Provides javascript object (Geometry) which can provide information about the viewport geometry for the client browser.
 1647: 
 1648: =cut
 1649: 
 1650: 
 1651: sub viewport_geometry_js { 
 1652:     return <<"GEOMETRY";
 1653: var Geometry = {};
 1654: function init_geometry() {
 1655:     if (Geometry.init) { return };
 1656:     Geometry.init=1;
 1657:     if (window.innerHeight) {
 1658:         Geometry.getViewportHeight   = function() { return window.innerHeight; };
 1659:         Geometry.getViewportWidth   = function() { return window.innerWidth; };
 1660:         Geometry.getHorizontalScroll = function() { return window.pageXOffset; };
 1661:         Geometry.getVerticalScroll   = function() { return window.pageYOffset; };
 1662:     }
 1663:     else if (document.documentElement && document.documentElement.clientHeight) {
 1664:         Geometry.getViewportHeight =
 1665:             function() { return document.documentElement.clientHeight; };
 1666:         Geometry.getViewportWidth =
 1667:             function() { return document.documentElement.clientWidth; };
 1668: 
 1669:         Geometry.getHorizontalScroll =
 1670:             function() { return document.documentElement.scrollLeft; };
 1671:         Geometry.getVerticalScroll =
 1672:             function() { return document.documentElement.scrollTop; };
 1673:     }
 1674:     else if (document.body.clientHeight) {
 1675:         Geometry.getViewportHeight =
 1676:             function() { return document.body.clientHeight; };
 1677:         Geometry.getViewportWidth =
 1678:             function() { return document.body.clientWidth; };
 1679:         Geometry.getHorizontalScroll =
 1680:             function() { return document.body.scrollLeft; };
 1681:         Geometry.getVerticalScroll =
 1682:             function() { return document.body.scrollTop; };
 1683:     }
 1684: }
 1685: 
 1686: GEOMETRY
 1687: }
 1688: 
 1689: =pod
 1690: 
 1691: =item * &viewport_size_js()
 1692: 
 1693: 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. 
 1694: 
 1695: =cut
 1696: 
 1697: sub viewport_size_js {
 1698:     my $geometry = &viewport_geometry_js();
 1699:     return <<"DIMS";
 1700: 
 1701: $geometry
 1702: 
 1703: function getViewportDims(width,height) {
 1704:     init_geometry();
 1705:     width.value = Geometry.getViewportWidth();
 1706:     height.value = Geometry.getViewportHeight();
 1707:     return;
 1708: }
 1709: 
 1710: DIMS
 1711: }
 1712: 
 1713: =pod
 1714: 
 1715: =item * &resize_textarea_js()
 1716: 
 1717: emits the needed javascript to resize a textarea to be as big as possible
 1718: 
 1719: creates a function resize_textrea that takes two IDs first should be
 1720: the id of the element to resize, second should be the id of a div that
 1721: surrounds everything that comes after the textarea, this routine needs
 1722: to be attached to the <body> for the onload and onresize events.
 1723: 
 1724: =back
 1725: 
 1726: =cut
 1727: 
 1728: sub resize_textarea_js {
 1729:     my $geometry = &viewport_geometry_js();
 1730:     return <<"RESIZE";
 1731:     <script type="text/javascript">
 1732: // <![CDATA[
 1733: $geometry
 1734: 
 1735: function getX(element) {
 1736:     var x = 0;
 1737:     while (element) {
 1738: 	x += element.offsetLeft;
 1739: 	element = element.offsetParent;
 1740:     }
 1741:     return x;
 1742: }
 1743: function getY(element) {
 1744:     var y = 0;
 1745:     while (element) {
 1746: 	y += element.offsetTop;
 1747: 	element = element.offsetParent;
 1748:     }
 1749:     return y;
 1750: }
 1751: 
 1752: 
 1753: function resize_textarea(textarea_id,bottom_id) {
 1754:     init_geometry();
 1755:     var textarea        = document.getElementById(textarea_id);
 1756:     //alert(textarea);
 1757: 
 1758:     var textarea_top    = getY(textarea);
 1759:     var textarea_height = textarea.offsetHeight;
 1760:     var bottom          = document.getElementById(bottom_id);
 1761:     var bottom_top      = getY(bottom);
 1762:     var bottom_height   = bottom.offsetHeight;
 1763:     var window_height   = Geometry.getViewportHeight();
 1764:     var fudge           = 23;
 1765:     var new_height      = window_height-fudge-textarea_top-bottom_height;
 1766:     if (new_height < 300) {
 1767: 	new_height = 300;
 1768:     }
 1769:     textarea.style.height=new_height+'px';
 1770: }
 1771: // ]]>
 1772: </script>
 1773: RESIZE
 1774: 
 1775: }
 1776: 
 1777: sub colorfuleditor_js {
 1778:     my $browse_or_search;
 1779:     my $respath;
 1780:     my ($cnum,$cdom) = &crsauthor_url();
 1781:     if ($cnum) {
 1782:         $respath = "/res/$cdom/$cnum/";
 1783:         my %js_lt = &Apache::lonlocal::texthash(
 1784:             sunm => 'Sub-directory name',
 1785:             save => 'Save page to make this permanent',
 1786:         );
 1787:         &js_escape(\%js_lt);
 1788:         $browse_or_search = <<"END";
 1789: 
 1790:     function toggleChooser(form,element,titleid,only,search) {
 1791:         var disp = 'none';
 1792:         if (document.getElementById('chooser_'+element)) {
 1793:             var curr = document.getElementById('chooser_'+element).style.display;
 1794:             if (curr == 'none') {
 1795:                 disp='inline';
 1796:                 if (form.elements['chooser_'+element].length) {
 1797:                     for (var i=0; i<form.elements['chooser_'+element].length; i++) {
 1798:                         form.elements['chooser_'+element][i].checked = false;
 1799:                     }
 1800:                 }
 1801:                 toggleResImport(form,element);
 1802:             }
 1803:             document.getElementById('chooser_'+element).style.display = disp;
 1804:         }
 1805:     }
 1806: 
 1807:     function toggleCrsFile(form,element,numdirs) {
 1808:         if (document.getElementById('chooser_'+element+'_crsres')) {
 1809:             var curr = document.getElementById('chooser_'+element+'_crsres').style.display;
 1810:             if (curr == 'none') {
 1811:                 if (numdirs) {
 1812:                     form.elements['coursepath_'+element].selectedIndex = 0;
 1813:                     if (numdirs > 1) {
 1814:                         window['select1'+element+'_changed']();
 1815:                     }
 1816:                 }
 1817:             } 
 1818:             document.getElementById('chooser_'+element+'_crsres').style.display = 'block';
 1819:             
 1820:         }
 1821:         if (document.getElementById('chooser_'+element+'_upload')) {
 1822:             document.getElementById('chooser_'+element+'_upload').style.display = 'none';
 1823:             if (document.getElementById('uploadcrsres_'+element)) {
 1824:                 document.getElementById('uploadcrsres_'+element).value = '';
 1825:             }
 1826:         }
 1827:         return;
 1828:     }
 1829: 
 1830:     function toggleCrsUpload(form,element,numcrsdirs) {
 1831:         if (document.getElementById('chooser_'+element+'_crsres')) {
 1832:             document.getElementById('chooser_'+element+'_crsres').style.display = 'none';
 1833:         }
 1834:         if (document.getElementById('chooser_'+element+'_upload')) {
 1835:             var curr = document.getElementById('chooser_'+element+'_upload').style.display;
 1836:             if (curr == 'none') {
 1837:                 if (numcrsdirs) {
 1838:                    form.elements['crsauthorpath_'+element].selectedIndex = 0;
 1839:                    form.elements['newsubdir_'+element][0].checked = true;
 1840:                    toggleNewsubdir(form,element);
 1841:                 }
 1842:             }
 1843:             document.getElementById('chooser_'+element+'_upload').style.display = 'block';
 1844:         }
 1845:         return;
 1846:     }
 1847: 
 1848:     function toggleResImport(form,element) {
 1849:         var choices = new Array('crsres','upload');
 1850:         for (var i=0; i<choices.length; i++) {
 1851:             if (document.getElementById('chooser_'+element+'_'+choices[i])) {
 1852:                 document.getElementById('chooser_'+element+'_'+choices[i]).style.display = 'none';
 1853:             }
 1854:         }
 1855:     }
 1856: 
 1857:     function toggleNewsubdir(form,element) {
 1858:         var newsub = form.elements['newsubdir_'+element];
 1859:         if (newsub) {
 1860:             if (newsub.length) {
 1861:                 for (var j=0; j<newsub.length; j++) {
 1862:                     if (newsub[j].checked) {
 1863:                         if (document.getElementById('newsubdirname_'+element)) {
 1864:                             if (newsub[j].value == '1') {
 1865:                                 document.getElementById('newsubdirname_'+element).type = "text";
 1866:                                 if (document.getElementById('newsubdir_'+element)) {
 1867:                                     document.getElementById('newsubdir_'+element).innerHTML = '<br />$js_lt{sunm}';
 1868:                                 }
 1869:                             } else {
 1870:                                 document.getElementById('newsubdirname_'+element).type = "hidden";
 1871:                                 document.getElementById('newsubdirname_'+element).value = "";
 1872:                                 document.getElementById('newsubdir_'+element).innerHTML = "";
 1873:                             }
 1874:                         }
 1875:                         break; 
 1876:                     }
 1877:                 }
 1878:             }
 1879:         }
 1880:     }
 1881: 
 1882:     function updateCrsFile(form,element) {
 1883:         var directory = form.elements['coursepath_'+element];
 1884:         var filename = form.elements['coursefile_'+element];
 1885:         var path = directory.options[directory.selectedIndex].value;
 1886:         var file = filename.options[filename.selectedIndex].value;
 1887:         form.elements[element].value = '$respath';
 1888:         if (path == '/') {
 1889:             form.elements[element].value += file;
 1890:         } else {
 1891:             form.elements[element].value += path+'/'+file;
 1892:         }
 1893:         unClean();
 1894:         if (document.getElementById('previewimg_'+element)) {
 1895:             document.getElementById('previewimg_'+element).src = form.elements[element].value;
 1896:             var newsrc = document.getElementById('previewimg_'+element).src; 
 1897:         }
 1898:         if (document.getElementById('showimg_'+element)) {
 1899:             document.getElementById('showimg_'+element).innerHTML = '($js_lt{save})';
 1900:         }
 1901:         toggleChooser(form,element);
 1902:         return;
 1903:     }
 1904: 
 1905:     function uploadDone(suffix,name) {
 1906:         if (name) {
 1907: 	    document.forms["lonhomework"].elements[suffix].value = name;
 1908:             unClean();
 1909:             toggleChooser(document.forms["lonhomework"],suffix);
 1910:         }
 1911:     }
 1912: 
 1913: \$(document).ready(function(){
 1914: 
 1915:     \$(document).delegate('form :submit', 'click', function( event ) {
 1916:         if ( \$( this ).hasClass( "LC_uploadcrsres" ) ) {
 1917:             var buttonId = this.id;
 1918:             var suffix = buttonId.toString();
 1919:             suffix = suffix.replace(/^crsupload_/,'');
 1920:             event.preventDefault();
 1921:             document.lonhomework.target = 'crsupload_target_'+suffix;
 1922:             document.lonhomework.action = '/adm/coursepub?LC_uploadcrsres='+suffix;
 1923:             \$(this.form).submit();
 1924:             document.lonhomework.target = '';
 1925:             if (document.getElementById('crsuploadto_'+suffix)) {
 1926:                 document.lonhomework.action = document.getElementById('crsuploadto_'+suffix).value;
 1927:             }
 1928:             return false;
 1929:         }
 1930:     });
 1931: });
 1932: END
 1933:     }
 1934:     return <<"COLORFULEDIT"
 1935: <script type="text/javascript">
 1936: // <![CDATA[>
 1937:     function fold_box(curDepth, lastresource){
 1938: 
 1939:     // we need a list because there can be several blocks you need to fold in one tag
 1940:         var block = document.getElementsByName('foldblock_'+curDepth);
 1941:     // but there is only one folding button per tag
 1942:         var foldbutton = document.getElementById('folding_btn_'+curDepth);
 1943: 
 1944:         if(block.item(0).style.display == 'none'){
 1945: 
 1946:             foldbutton.value = '@{[&mt("Hide")]}';
 1947:             for (i = 0; i < block.length; i++){
 1948:                 block.item(i).style.display = '';
 1949:             }
 1950:         }else{
 1951: 
 1952:             foldbutton.value = '@{[&mt("Show")]}';
 1953:             for (i = 0; i < block.length; i++){
 1954:                 // block.item(i).style.visibility = 'collapse';
 1955:                 block.item(i).style.display = 'none';
 1956:             }
 1957:         };
 1958:         saveState(lastresource);
 1959:     }
 1960: 
 1961:     function saveState (lastresource) {
 1962: 
 1963:         var tag_list = getTagList();
 1964:         if(tag_list != null){
 1965:             var timestamp = new Date().getTime();
 1966:             var key = lastresource;
 1967: 
 1968:             // the value pattern is: 'time;key1,value1;key2,value2; ... '
 1969:             // starting with timestamp
 1970:             var value = timestamp+';';
 1971: 
 1972:             // building the list of key-value pairs
 1973:             for(var i = 0; i < tag_list.length; i++){
 1974:                 value += tag_list[i]+',';
 1975:                 value += document.getElementsByName(tag_list[i])[0].style.display+';';
 1976:             }
 1977: 
 1978:             // only iterate whole storage if nothing to override
 1979:             if(localStorage.getItem(key) == null){        
 1980: 
 1981:                 // prevent storage from growing large
 1982:                 if(localStorage.length > 50){
 1983:                     var regex_getTimestamp = /^(?:\d)+;/;
 1984:                     var oldest_timestamp = regex_getTimestamp.exec(localStorage.key(0));
 1985:                     var oldest_key;
 1986:                     
 1987:                     for(var i = 1; i < localStorage.length; i++){
 1988:                         if (regex_getTimestamp.exec(localStorage.key(i)) < oldest_timestamp) {
 1989:                             oldest_key = localStorage.key(i);
 1990:                             oldest_timestamp = regex_getTimestamp.exec(oldest_key);
 1991:                         }
 1992:                     }
 1993:                     localStorage.removeItem(oldest_key);
 1994:                 }
 1995:             }
 1996:             localStorage.setItem(key,value);
 1997:         }
 1998:     }
 1999: 
 2000:     // restore folding status of blocks (on page load)
 2001:     function restoreState (lastresource) {
 2002:         if(localStorage.getItem(lastresource) != null){
 2003:             var key = lastresource;
 2004:             var value = localStorage.getItem(key);
 2005:             var regex_delTimestamp = /^\d+;/;
 2006: 
 2007:             value.replace(regex_delTimestamp, '');
 2008: 
 2009:             var valueArr = value.split(';');
 2010:             var pairs;
 2011:             var elements;
 2012:             for (var i = 0; i < valueArr.length; i++){
 2013:                 pairs = valueArr[i].split(',');
 2014:                 elements = document.getElementsByName(pairs[0]);
 2015: 
 2016:                 for (var j = 0; j < elements.length; j++){  
 2017:                     elements[j].style.display = pairs[1];
 2018:                     if (pairs[1] == "none"){
 2019:                         var regex_id = /([_\\d]+)\$/;
 2020:                         regex_id.exec(pairs[0]);
 2021:                         document.getElementById("folding_btn"+RegExp.\$1).value = "Show";
 2022:                     }
 2023:                 }
 2024:             }
 2025:         }
 2026:     }
 2027: 
 2028:     function getTagList () {
 2029:         
 2030:         var stringToSearch = document.lonhomework.innerHTML;
 2031: 
 2032:         var ret = new Array();
 2033:         var regex_findBlock = /(foldblock_.*?)"/g;
 2034:         var tag_list = stringToSearch.match(regex_findBlock);
 2035: 
 2036:         if(tag_list != null){
 2037:             for(var i = 0; i < tag_list.length; i++){            
 2038:                 ret.push(tag_list[i].replace(/"/, ''));
 2039:             }
 2040:         }
 2041:         return ret;
 2042:     }
 2043: 
 2044:     function saveScrollPosition (resource) {
 2045:         var tag_list = getTagList();
 2046: 
 2047:         // we dont always want to jump to the first block
 2048:         // 170 is roughly above the "Problem Editing" header. we just want to save if the user scrolled down further than this
 2049:         if(\$(window).scrollTop() > 170){
 2050:             if(tag_list != null){
 2051:                 var result;
 2052:                 for(var i = 0; i < tag_list.length; i++){
 2053:                     if(isElementInViewport(tag_list[i])){
 2054:                         result += tag_list[i]+';';
 2055:                     }
 2056:                 }
 2057:                 sessionStorage.setItem('anchor_'+resource, result);
 2058:             }
 2059:         } else {
 2060:             // we dont need to save zero, just delete the item to leave everything tidy
 2061:             sessionStorage.removeItem('anchor_'+resource);
 2062:         }
 2063:     }
 2064: 
 2065:     function restoreScrollPosition(resource){
 2066: 
 2067:         var elem = sessionStorage.getItem('anchor_'+resource);
 2068:         if(elem != null){
 2069:             var tag_list = elem.split(';');
 2070:             var elem_list;
 2071: 
 2072:             for(var i = 0; i < tag_list.length; i++){
 2073:                 elem_list = document.getElementsByName(tag_list[i]);
 2074:                 
 2075:                 if(elem_list.length > 0){
 2076:                     elem = elem_list[0];
 2077:                     break;
 2078:                 }
 2079:             }
 2080:             elem.scrollIntoView();
 2081:         }
 2082:     }
 2083: 
 2084:     function isElementInViewport(el) {
 2085: 
 2086:         // change to last element instead of first
 2087:         var elem = document.getElementsByName(el);
 2088:         var rect = elem[0].getBoundingClientRect();
 2089: 
 2090:         return (
 2091:             rect.top >= 0 &&
 2092:             rect.left >= 0 &&
 2093:             rect.bottom <= (window.innerHeight || document.documentElement.clientHeight) && /*or $(window).height() */
 2094:             rect.right <= (window.innerWidth || document.documentElement.clientWidth) /*or $(window).width() */
 2095:         );
 2096:     }
 2097:     
 2098:     function autosize(depth){
 2099:         var cmInst = window['cm'+depth];
 2100:         var fitsizeButton = document.getElementById('fitsize'+depth);
 2101: 
 2102:         // is fixed size, switching to dynamic
 2103:         if (sessionStorage.getItem("autosized_"+depth) == null) {
 2104:             cmInst.setSize("","auto");
 2105:             fitsizeButton.value = "@{[&mt('Fixed size')]}";
 2106:             sessionStorage.setItem("autosized_"+depth, "yes");
 2107: 
 2108:         // is dynamic size, switching to fixed
 2109:         } else {
 2110:             cmInst.setSize("","300px");
 2111:             fitsizeButton.value = "@{[&mt('Dynamic size')]}";
 2112:             sessionStorage.removeItem("autosized_"+depth);
 2113:         }
 2114:     }
 2115: 
 2116: $browse_or_search
 2117: 
 2118: // ]]>
 2119: </script>
 2120: COLORFULEDIT
 2121: }
 2122: 
 2123: sub xmleditor_js {
 2124:     return <<XMLEDIT
 2125: <script type="text/javascript" src="/adm/jQuery/addons/jquery-scrolltofixed.js"></script>
 2126: <script type="text/javascript">
 2127: // <![CDATA[>
 2128: 
 2129:     function saveScrollPosition (resource) {
 2130: 
 2131:         var scrollPos = \$(window).scrollTop();
 2132:         sessionStorage.setItem(resource,scrollPos);
 2133:     }
 2134: 
 2135:     function restoreScrollPosition(resource){
 2136: 
 2137:         var scrollPos = sessionStorage.getItem(resource);
 2138:         \$(window).scrollTop(scrollPos);
 2139:     }
 2140: 
 2141:     // unless internet explorer
 2142:     if (!(window.navigator.appName == "Microsoft Internet Explorer" && (document.documentMode || document.compatMode))){
 2143: 
 2144:         \$(document).ready(function() {
 2145:              \$(".LC_edit_actionbar").scrollToFixed(\{zIndex: 100\});
 2146:         });
 2147:     }
 2148: 
 2149:     // inserts text at cursor position into codemirror (xml editor only)
 2150:     function insertText(text){
 2151:         cm.focus();
 2152:         var curPos = cm.getCursor();
 2153:         cm.replaceRange(text.replace(/ESCAPEDSCRIPT/g,'script'), {line: curPos.line,ch: curPos.ch});
 2154:     }
 2155: // ]]>
 2156: </script>
 2157: XMLEDIT
 2158: }
 2159: 
 2160: sub insert_folding_button {
 2161:     my $curDepth = $Apache::lonxml::curdepth;
 2162:     my $lastresource = $env{'request.ambiguous'};
 2163: 
 2164:     return "<input type=\"button\" id=\"folding_btn_$curDepth\" 
 2165:             value=\"".&mt('Hide')."\" onclick=\"fold_box('$curDepth','$lastresource')\">";
 2166: }
 2167: 
 2168: sub crsauthor_url {
 2169:     my ($url) = @_;
 2170:     if ($url eq '') {
 2171:         $url = $ENV{'REQUEST_URI'};
 2172:     }
 2173:     my ($cnum,$cdom);
 2174:     if ($env{'request.course.id'}) {
 2175:         my ($audom,$auname) = ($url =~ m{^/priv/($match_domain)/($match_name)/});
 2176:         if ($audom ne '' && $auname ne '') {
 2177:             if (($env{'course.'.$env{'request.course.id'}.'.num'} eq $auname) &&
 2178:                 ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $audom)) {
 2179:                 $cnum = $auname;
 2180:                 $cdom = $audom;
 2181:             }
 2182:         }
 2183:     }
 2184:     return ($cnum,$cdom);
 2185: }
 2186: 
 2187: sub import_crsauthor_form {
 2188:     my ($form,$firstselectname,$secondselectname,$onchangefirst,$only,$suffix) = @_;
 2189:     return (0) unless ($env{'request.course.id'});
 2190:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 2191:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 2192:     my $crshome = $env{'course.'.$env{'request.course.id'}.'.home'};
 2193:     return (0) unless (($cnum ne '') && ($cdom ne ''));
 2194:     my $londocroot = $Apache::lonnet::perlvar{'lonDocRoot'};
 2195:     my @ids=&Apache::lonnet::current_machine_ids();
 2196:     my ($output,$is_home,$relpath,%subdirs,%files,%selimport_menus);
 2197:     
 2198:     if (grep(/^\Q$crshome\E$/,@ids)) {
 2199:         $is_home = 1;
 2200:     }
 2201:     $relpath = "/priv/$cdom/$cnum";
 2202:     &Apache::lonnet::recursedirs($is_home,'priv',$londocroot,$relpath,'',\%subdirs,\%files);
 2203:     my %lt = &Apache::lonlocal::texthash (
 2204:         fnam => 'Filename',
 2205:         dire => 'Directory',
 2206:     );
 2207:     my $numdirs = scalar(keys(%files));
 2208:     my (%possexts,$singledir,@singledirfiles);
 2209:     if ($only) {
 2210:         map { $possexts{$_} = 1; } split(/\s*,\s*/,$only);
 2211:     }
 2212:     my (%nonemptydirs,$possdirs);
 2213:     if ($numdirs > 1) {
 2214:         my @order;
 2215:         foreach my $key (sort { lc($a) cmp lc($b) } (keys(%files))) {
 2216:             if (ref($files{$key}) eq 'HASH') {
 2217:                 my $shown = $key;
 2218:                 if ($key eq '') {
 2219:                     $shown = '/';
 2220:                 }
 2221:                 my @ordered = ();
 2222:                 foreach my $file (sort { lc($a) cmp lc($b) } (keys(%{$files{$key}}))) {
 2223:                     if ($only) {
 2224:                         my ($ext) = ($file =~ /\.([^.]+)$/);
 2225:                         unless ($possexts{lc($ext)}) {
 2226:                             next;
 2227:                         }
 2228:                     }
 2229:                     $selimport_menus{$key}->{'select2'}->{$file} = $file;
 2230:                     push(@ordered,$file);
 2231:                 }
 2232:                 if (@ordered) {
 2233:                     push(@order,$key);
 2234:                     $nonemptydirs{$key} = 1;
 2235:                     $selimport_menus{$key}->{'text'} = $shown;
 2236:                     $selimport_menus{$key}->{'default'} = '';
 2237:                     $selimport_menus{$key}->{'select2'}->{''} = '';
 2238:                     $selimport_menus{$key}->{'order'} = \@ordered;
 2239:                 }
 2240:             }
 2241:         }
 2242:         $possdirs = scalar(keys(%nonemptydirs));
 2243:         if ($possdirs > 1) {
 2244:             my @order = sort { lc($a) cmp lc($b) } (keys(%nonemptydirs));
 2245:             $output = $lt{'dire'}.
 2246:                       &linked_select_forms($form,'<br />'.
 2247:                                            $lt{'fnam'},'',
 2248:                                            $firstselectname,$secondselectname,
 2249:                                            \%selimport_menus,\@order,
 2250:                                            $onchangefirst,'',$suffix).'<br />';
 2251:         } elsif ($possdirs == 1) {
 2252:             $singledir = (keys(%nonemptydirs))[0];
 2253:             if (ref($selimport_menus{$singledir}->{'order'}) eq 'ARRAY') {
 2254:                 @singledirfiles = @{$selimport_menus{$singledir}->{'order'}};
 2255:             }
 2256:             delete($selimport_menus{$singledir});
 2257:         }
 2258:     } elsif ($numdirs == 1) {
 2259:         $singledir = (keys(%files))[0];
 2260:         foreach my $file (sort { lc($a) cmp lc($b) } (keys(%{$files{$singledir}}))) {
 2261:             if ($only) {
 2262:                 my ($ext) = ($file =~ /\.([^.]+)$/);
 2263:                 unless ($possexts{lc($ext)}) {
 2264:                     next;
 2265:                 }
 2266:             }
 2267:             push(@singledirfiles,$file);
 2268:         }
 2269:         if (@singledirfiles) {
 2270:             $possdirs == 1;
 2271:         }
 2272:     }
 2273:     if (($possdirs == 1) && (@singledirfiles)) {
 2274:         my $showdir = $singledir;
 2275:         if ($singledir eq '') {
 2276:             $showdir = '/';
 2277:         }
 2278:         $output = $lt{'dire'}.
 2279:                   '<select name="'.$firstselectname.'">'.
 2280:                   '<option value="'.$singledir.'">'.$showdir.'</option>'."\n".
 2281:                   '</select><br />'.
 2282:                   $lt{'fnam'}.'<select name="'.$secondselectname.'">'."\n".
 2283:                   '<option value="" selected="selected">'.$lt{'se'}.'</option>'."\n";
 2284:         foreach my $file (@singledirfiles) {
 2285:             $output .= '<option value="'.$file.'">'.$file.'</option>'."\n";
 2286:         }
 2287:         $output .= '</select><br />'."\n";
 2288:     }
 2289:     return ($possdirs,$output);
 2290: }
 2291: 
 2292: =pod
 2293: 
 2294: =head1 Excel and CSV file utility routines
 2295: 
 2296: =cut
 2297: 
 2298: ###############################################################
 2299: ###############################################################
 2300: 
 2301: =pod
 2302: 
 2303: =over 4
 2304: 
 2305: =item * &csv_translate($text) 
 2306: 
 2307: Translate $text to allow it to be output as a 'comma separated values' 
 2308: format.
 2309: 
 2310: =cut
 2311: 
 2312: ###############################################################
 2313: ###############################################################
 2314: sub csv_translate {
 2315:     my $text = shift;
 2316:     $text =~ s/\"/\"\"/g;
 2317:     $text =~ s/\n/ /g;
 2318:     return $text;
 2319: }
 2320: 
 2321: ###############################################################
 2322: ###############################################################
 2323: 
 2324: =pod
 2325: 
 2326: =item * &define_excel_formats()
 2327: 
 2328: Define some commonly used Excel cell formats.
 2329: 
 2330: Currently supported formats:
 2331: 
 2332: =over 4
 2333: 
 2334: =item header
 2335: 
 2336: =item bold
 2337: 
 2338: =item h1
 2339: 
 2340: =item h2
 2341: 
 2342: =item h3
 2343: 
 2344: =item h4
 2345: 
 2346: =item i
 2347: 
 2348: =item date
 2349: 
 2350: =back
 2351: 
 2352: Inputs: $workbook
 2353: 
 2354: Returns: $format, a hash reference.
 2355: 
 2356: 
 2357: =cut
 2358: 
 2359: ###############################################################
 2360: ###############################################################
 2361: sub define_excel_formats {
 2362:     my ($workbook) = @_;
 2363:     my $format;
 2364:     $format->{'header'} = $workbook->add_format(bold      => 1, 
 2365:                                                 bottom    => 1,
 2366:                                                 align     => 'center');
 2367:     $format->{'bold'} = $workbook->add_format(bold=>1);
 2368:     $format->{'h1'}   = $workbook->add_format(bold=>1, size=>18);
 2369:     $format->{'h2'}   = $workbook->add_format(bold=>1, size=>16);
 2370:     $format->{'h3'}   = $workbook->add_format(bold=>1, size=>14);
 2371:     $format->{'h4'}   = $workbook->add_format(bold=>1, size=>12);
 2372:     $format->{'i'}    = $workbook->add_format(italic=>1);
 2373:     $format->{'date'} = $workbook->add_format(num_format=>
 2374:                                             'mm/dd/yyyy hh:mm:ss');
 2375:     return $format;
 2376: }
 2377: 
 2378: ###############################################################
 2379: ###############################################################
 2380: 
 2381: =pod
 2382: 
 2383: =item * &create_workbook()
 2384: 
 2385: Create an Excel worksheet.  If it fails, output message on the
 2386: request object and return undefs.
 2387: 
 2388: Inputs: Apache request object
 2389: 
 2390: Returns (undef) on failure, 
 2391:     Excel worksheet object, scalar with filename, and formats 
 2392:     from &Apache::loncommon::define_excel_formats on success
 2393: 
 2394: =cut
 2395: 
 2396: ###############################################################
 2397: ###############################################################
 2398: sub create_workbook {
 2399:     my ($r) = @_;
 2400:         #
 2401:     # Create the excel spreadsheet
 2402:     my $filename = '/prtspool/'.
 2403:         $env{'user.name'}.'_'.$env{'user.domain'}.'_'.
 2404:         time.'_'.rand(1000000000).'.xls';
 2405:     my $workbook  = Spreadsheet::WriteExcel->new('/home/httpd'.$filename);
 2406:     if (! defined($workbook)) {
 2407:         $r->log_error("Error creating excel spreadsheet $filename: $!");
 2408:         $r->print(
 2409:             '<p class="LC_error">'
 2410:            .&mt('Problems occurred in creating the new Excel file.')
 2411:            .' '.&mt('This error has been logged.')
 2412:            .' '.&mt('Please alert your LON-CAPA administrator.')
 2413:            .'</p>'
 2414:         );
 2415:         return (undef);
 2416:     }
 2417:     #
 2418:     $workbook->set_tempdir(LONCAPA::tempdir());
 2419:     #
 2420:     my $format = &Apache::loncommon::define_excel_formats($workbook);
 2421:     return ($workbook,$filename,$format);
 2422: }
 2423: 
 2424: ###############################################################
 2425: ###############################################################
 2426: 
 2427: =pod
 2428: 
 2429: =item * &create_text_file()
 2430: 
 2431: Create a file to write to and eventually make available to the user.
 2432: If file creation fails, outputs an error message on the request object and 
 2433: return undefs.
 2434: 
 2435: Inputs: Apache request object, and file suffix
 2436: 
 2437: Returns (undef) on failure, 
 2438:     Filehandle and filename on success.
 2439: 
 2440: =cut
 2441: 
 2442: ###############################################################
 2443: ###############################################################
 2444: sub create_text_file {
 2445:     my ($r,$suffix) = @_;
 2446:     if (! defined($suffix)) { $suffix = 'txt'; };
 2447:     my $fh;
 2448:     my $filename = '/prtspool/'.
 2449:         $env{'user.name'}.'_'.$env{'user.domain'}.'_'.
 2450:         time.'_'.rand(1000000000).'.'.$suffix;
 2451:     $fh = Apache::File->new('>/home/httpd'.$filename);
 2452:     if (! defined($fh)) {
 2453:         $r->log_error("Couldn't open $filename for output $!");
 2454:         $r->print(
 2455:             '<p class="LC_error">'
 2456:            .&mt('Problems occurred in creating the output file.')
 2457:            .' '.&mt('This error has been logged.')
 2458:            .' '.&mt('Please alert your LON-CAPA administrator.')
 2459:            .'</p>'
 2460:         );
 2461:     }
 2462:     return ($fh,$filename)
 2463: }
 2464: 
 2465: 
 2466: =pod 
 2467: 
 2468: =back
 2469: 
 2470: =cut
 2471: 
 2472: ###############################################################
 2473: ##        Home server <option> list generating code          ##
 2474: ###############################################################
 2475: 
 2476: # ------------------------------------------
 2477: 
 2478: sub domain_select {
 2479:     my ($name,$value,$multiple)=@_;
 2480:     my %domains=map { 
 2481: 	$_ => $_.' '. &Apache::lonnet::domain($_,'description') 
 2482:     } &Apache::lonnet::all_domains();
 2483:     if ($multiple) {
 2484: 	$domains{''}=&mt('Any domain');
 2485: 	$domains{'select_form_order'} = [sort {lc($a) cmp lc($b) } (keys(%domains))];
 2486: 	return &multiple_select_form($name,$value,4,\%domains);
 2487:     } else {
 2488: 	$domains{'select_form_order'} = [sort {lc($a) cmp lc($b) } (keys(%domains))];
 2489: 	return &select_form($name,$value,\%domains);
 2490:     }
 2491: }
 2492: 
 2493: #-------------------------------------------
 2494: 
 2495: =pod
 2496: 
 2497: =head1 Routines for form select boxes
 2498: 
 2499: =over 4
 2500: 
 2501: =item * &multiple_select_form($name,$value,$size,$hash,$order)
 2502: 
 2503: Returns a string containing a <select> element int multiple mode
 2504: 
 2505: 
 2506: Args:
 2507:   $name - name of the <select> element
 2508:   $value - scalar or array ref of values that should already be selected
 2509:   $size - number of rows long the select element is
 2510:   $hash - the elements should be 'option' => 'shown text'
 2511:           (shown text should already have been &mt())
 2512:   $order - (optional) array ref of the order to show the elements in
 2513: 
 2514: =cut
 2515: 
 2516: #-------------------------------------------
 2517: sub multiple_select_form {
 2518:     my ($name,$value,$size,$hash,$order)=@_;
 2519:     my %selected = map { $_ => 1 } ref($value)?@{$value}:($value);
 2520:     my $output='';
 2521:     if (! defined($size)) {
 2522:         $size = 4;
 2523:         if (scalar(keys(%$hash))<4) {
 2524:             $size = scalar(keys(%$hash));
 2525:         }
 2526:     }
 2527:     $output.="\n".'<select name="'.$name.'" size="'.$size.'" multiple="multiple">';
 2528:     my @order;
 2529:     if (ref($order) eq 'ARRAY')  {
 2530:         @order = @{$order};
 2531:     } else {
 2532:         @order = sort(keys(%$hash));
 2533:     }
 2534:     if (exists($$hash{'select_form_order'})) {
 2535:         @order = @{$$hash{'select_form_order'}};
 2536:     }
 2537:         
 2538:     foreach my $key (@order) {
 2539:         $output.='<option value="'.&HTML::Entities::encode($key,'"<>&').'" ';
 2540:         $output.='selected="selected" ' if ($selected{$key});
 2541:         $output.='>'.$hash->{$key}."</option>\n";
 2542:     }
 2543:     $output.="</select>\n";
 2544:     return $output;
 2545: }
 2546: 
 2547: #-------------------------------------------
 2548: 
 2549: =pod
 2550: 
 2551: =item * &select_form($defdom,$name,$hashref,$onchange)
 2552: 
 2553: Returns a string containing a <select name='$name' size='1'> form to 
 2554: allow a user to select options from a ref to a hash containing:
 2555: option_name => displayed text. An optional $onchange can include
 2556: a javascript onchange item, e.g., onchange="this.form.submit();"  
 2557: 
 2558: See lonrights.pm for an example invocation and use.
 2559: 
 2560: =cut
 2561: 
 2562: #-------------------------------------------
 2563: sub select_form {
 2564:     my ($def,$name,$hashref,$onchange,$readonly) = @_;
 2565:     return unless (ref($hashref) eq 'HASH');
 2566:     if ($onchange) {
 2567:         $onchange = ' onchange="'.$onchange.'"';
 2568:     }
 2569:     my $disabled;
 2570:     if ($readonly) {
 2571:         $disabled = ' disabled="disabled"';
 2572:     }
 2573:     my $selectform = "<select name=\"$name\" size=\"1\"$onchange$disabled>\n";
 2574:     my @keys;
 2575:     if (exists($hashref->{'select_form_order'})) {
 2576: 	@keys=@{$hashref->{'select_form_order'}};
 2577:     } else {
 2578: 	@keys=sort(keys(%{$hashref}));
 2579:     }
 2580:     foreach my $key (@keys) {
 2581:         $selectform.=
 2582: 	    '<option value="'.&HTML::Entities::encode($key,'"<>&').'" '.
 2583:             ($key eq $def ? 'selected="selected" ' : '').
 2584:                 ">".$hashref->{$key}."</option>\n";
 2585:     }
 2586:     $selectform.="</select>";
 2587:     return $selectform;
 2588: }
 2589: 
 2590: # For display filters
 2591: 
 2592: sub display_filter {
 2593:     my ($context) = @_;
 2594:     if (!$env{'form.show'}) { $env{'form.show'}=10; }
 2595:     if (!$env{'form.displayfilter'}) { $env{'form.displayfilter'}='currentfolder'; }
 2596:     my $phraseinput = 'hidden';
 2597:     my $includeinput = 'hidden';
 2598:     my ($checked,$includetypestext);
 2599:     if ($env{'form.displayfilter'} eq 'containing') {
 2600:         $phraseinput = 'text'; 
 2601:         if ($context eq 'parmslog') {
 2602:             $includeinput = 'checkbox';
 2603:             if ($env{'form.includetypes'}) {
 2604:                 $checked = ' checked="checked"';
 2605:             }
 2606:             $includetypestext = &mt('Include parameter types');
 2607:         }
 2608:     } else {
 2609:         $includetypestext = '&nbsp;';
 2610:     }
 2611:     my ($additional,$secondid,$thirdid);
 2612:     if ($context eq 'parmslog') {
 2613:         $additional = 
 2614:             '<label><input type="'.$includeinput.'" name="includetypes"'. 
 2615:             $checked.' name="includetypes" value="1" id="includetypes" />'.
 2616:             '&nbsp;<span id="includetypestext">'.$includetypestext.'</span>'.
 2617:             '</label>';
 2618:         $secondid = 'includetypes';
 2619:         $thirdid = 'includetypestext';
 2620:     }
 2621:     my $onchange = "javascript:toggleHistoryOptions(this,'containingphrase','$context',
 2622:                                                     '$secondid','$thirdid')";
 2623:     return '<span class="LC_nobreak"><label>'.&mt('Records: [_1]',
 2624: 			       &Apache::lonmeta::selectbox('show',$env{'form.show'},undef,
 2625: 							   (&mt('all'),10,20,50,100,1000,10000))).
 2626: 	   '</label></span> <span class="LC_nobreak">'.
 2627:            &mt('Filter: [_1]',
 2628: 	   &select_form($env{'form.displayfilter'},
 2629: 			'displayfilter',
 2630: 			{'currentfolder' => 'Current folder/page',
 2631: 			 'containing' => 'Containing phrase',
 2632: 			 'none' => 'None'},$onchange)).'&nbsp;'.
 2633: 			 '<input type="'.$phraseinput.'" name="containingphrase" id="containingphrase" size="30" value="'.
 2634:                          &HTML::Entities::encode($env{'form.containingphrase'}).
 2635:                          '" />'.$additional;
 2636: }
 2637: 
 2638: sub display_filter_js {
 2639:     my $includetext = &mt('Include parameter types');
 2640:     return <<"ENDJS";
 2641:   
 2642: function toggleHistoryOptions(setter,firstid,context,secondid,thirdid) {
 2643:     var firstType = 'hidden';
 2644:     if (setter.options[setter.selectedIndex].value == 'containing') {
 2645:         firstType = 'text';
 2646:     }
 2647:     firstObject = document.getElementById(firstid);
 2648:     if (typeof(firstObject) == 'object') {
 2649:         if (firstObject.type != firstType) {
 2650:             changeInputType(firstObject,firstType);
 2651:         }
 2652:     }
 2653:     if (context == 'parmslog') {
 2654:         var secondType = 'hidden';
 2655:         if (firstType == 'text') {
 2656:             secondType = 'checkbox';
 2657:         }
 2658:         secondObject = document.getElementById(secondid);  
 2659:         if (typeof(secondObject) == 'object') {
 2660:             if (secondObject.type != secondType) {
 2661:                 changeInputType(secondObject,secondType);
 2662:             }
 2663:         }
 2664:         var textItem = document.getElementById(thirdid);
 2665:         var currtext = textItem.innerHTML;
 2666:         var newtext;
 2667:         if (firstType == 'text') {
 2668:             newtext = '$includetext';
 2669:         } else {
 2670:             newtext = '&nbsp;';
 2671:         }
 2672:         if (currtext != newtext) {
 2673:             textItem.innerHTML = newtext;
 2674:         }
 2675:     }
 2676:     return;
 2677: }
 2678: 
 2679: function changeInputType(oldObject,newType) {
 2680:     var newObject = document.createElement('input');
 2681:     newObject.type = newType;
 2682:     if (oldObject.size) {
 2683:         newObject.size = oldObject.size;
 2684:     }
 2685:     if (oldObject.value) {
 2686:         newObject.value = oldObject.value;
 2687:     }
 2688:     if (oldObject.name) {
 2689:         newObject.name = oldObject.name;
 2690:     }
 2691:     if (oldObject.id) {
 2692:         newObject.id = oldObject.id;
 2693:     }
 2694:     oldObject.parentNode.replaceChild(newObject,oldObject);
 2695:     return;
 2696: }
 2697: 
 2698: ENDJS
 2699: }
 2700: 
 2701: sub gradeleveldescription {
 2702:     my $gradelevel=shift;
 2703:     my %gradelevels=(0 => 'Not specified',
 2704: 		     1 => 'Grade 1',
 2705: 		     2 => 'Grade 2',
 2706: 		     3 => 'Grade 3',
 2707: 		     4 => 'Grade 4',
 2708: 		     5 => 'Grade 5',
 2709: 		     6 => 'Grade 6',
 2710: 		     7 => 'Grade 7',
 2711: 		     8 => 'Grade 8',
 2712: 		     9 => 'Grade 9',
 2713: 		     10 => 'Grade 10',
 2714: 		     11 => 'Grade 11',
 2715: 		     12 => 'Grade 12',
 2716: 		     13 => 'Grade 13',
 2717: 		     14 => '100 Level',
 2718: 		     15 => '200 Level',
 2719: 		     16 => '300 Level',
 2720: 		     17 => '400 Level',
 2721: 		     18 => 'Graduate Level');
 2722:     return &mt($gradelevels{$gradelevel});
 2723: }
 2724: 
 2725: sub select_level_form {
 2726:     my ($deflevel,$name)=@_;
 2727:     unless ($deflevel) { $deflevel=0; }
 2728:     my $selectform = "<select name=\"$name\" size=\"1\">\n";
 2729:     for (my $i=0; $i<=18; $i++) {
 2730:         $selectform.="<option value=\"$i\" ".
 2731:             ($i==$deflevel ? 'selected="selected" ' : '').
 2732:                 ">".&gradeleveldescription($i)."</option>\n";
 2733:     }
 2734:     $selectform.="</select>";
 2735:     return $selectform;
 2736: }
 2737: 
 2738: #-------------------------------------------
 2739: 
 2740: =pod
 2741: 
 2742: =item * &select_dom_form($defdom,$name,$includeempty,$showdomdesc,$onchange,$incdoms,$excdoms)
 2743: 
 2744: Returns a string containing a <select name='$name' size='1'> form to 
 2745: allow a user to select the domain to preform an operation in.  
 2746: See loncreateuser.pm for an example invocation and use.
 2747: 
 2748: If the $includeempty flag is set, it also includes an empty choice ("no domain
 2749: selected");
 2750: 
 2751: If the $showdomdesc flag is set, the domain name is followed by the domain description.
 2752: 
 2753: 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.
 2754: 
 2755: The optional $incdoms is a reference to an array of domains which will be the only available options.
 2756: 
 2757: The optional $excdoms is a reference to an array of domains which will be excluded from the available options.
 2758: 
 2759: =cut
 2760: 
 2761: #-------------------------------------------
 2762: sub select_dom_form {
 2763:     my ($defdom,$name,$includeempty,$showdomdesc,$onchange,$incdoms,$excdoms) = @_;
 2764:     if ($onchange) {
 2765:         $onchange = ' onchange="'.$onchange.'"';
 2766:     }
 2767:     my (@domains,%exclude);
 2768:     if (ref($incdoms) eq 'ARRAY') {
 2769:         @domains = sort {lc($a) cmp lc($b)} (@{$incdoms});
 2770:     } else {
 2771:         @domains = sort {lc($a) cmp lc($b)} (&Apache::lonnet::all_domains());
 2772:     }
 2773:     if ($includeempty) { @domains=('',@domains); }
 2774:     if (ref($excdoms) eq 'ARRAY') {
 2775:         map { $exclude{$_} = 1; } @{$excdoms}; 
 2776:     }
 2777:     my $selectdomain = "<select name=\"$name\" size=\"1\"$onchange>\n";
 2778:     foreach my $dom (@domains) {
 2779:         next if ($exclude{$dom});
 2780:         $selectdomain.="<option value=\"$dom\" ".
 2781:             ($dom eq $defdom ? 'selected="selected" ' : '').'>'.$dom;
 2782:         if ($showdomdesc) {
 2783:             if ($dom ne '') {
 2784:                 my $domdesc = &Apache::lonnet::domain($dom,'description');
 2785:                 if ($domdesc ne '') {
 2786:                     $selectdomain .= ' ('.$domdesc.')';
 2787:                 }
 2788:             } 
 2789:         }
 2790:         $selectdomain .= "</option>\n";
 2791:     }
 2792:     $selectdomain.="</select>";
 2793:     return $selectdomain;
 2794: }
 2795: 
 2796: #-------------------------------------------
 2797: 
 2798: =pod
 2799: 
 2800: =item * &home_server_form_item($domain,$name,$defaultflag)
 2801: 
 2802: input: 4 arguments (two required, two optional) - 
 2803:     $domain - domain of new user
 2804:     $name - name of form element
 2805:     $default - Value of 'default' causes a default item to be first 
 2806:                             option, and selected by default. 
 2807:     $hide - Value of 'hide' causes hiding of the name of the server, 
 2808:                             if 1 server found, or default, if 0 found.
 2809: output: returns 2 items: 
 2810: (a) form element which contains either:
 2811:    (i) <select name="$name">
 2812:         <option value="$hostid1">$hostid $servers{$hostid}</option>
 2813:         <option value="$hostid2">$hostid $servers{$hostid}</option>       
 2814:        </select>
 2815:        form item if there are multiple library servers in $domain, or
 2816:    (ii) an <input type="hidden" name="$name" value="$hostid" /> form item 
 2817:        if there is only one library server in $domain.
 2818: 
 2819: (b) number of library servers found.
 2820: 
 2821: See loncreateuser.pm for example of use.
 2822: 
 2823: =cut
 2824: 
 2825: #-------------------------------------------
 2826: sub home_server_form_item {
 2827:     my ($domain,$name,$default,$hide) = @_;
 2828:     my %servers = &Apache::lonnet::get_servers($domain,'library');
 2829:     my $result;
 2830:     my $numlib = keys(%servers);
 2831:     if ($numlib > 1) {
 2832:         $result .= '<select name="'.$name.'" />'."\n";
 2833:         if ($default) {
 2834:             $result .= '<option value="default" selected="selected">'.&mt('default').
 2835:                        '</option>'."\n";
 2836:         }
 2837:         foreach my $hostid (sort(keys(%servers))) {
 2838:             $result.= '<option value="'.$hostid.'">'.
 2839: 	              $hostid.' '.$servers{$hostid}."</option>\n";
 2840:         }
 2841:         $result .= '</select>'."\n";
 2842:     } elsif ($numlib == 1) {
 2843:         my $hostid;
 2844:         foreach my $item (keys(%servers)) {
 2845:             $hostid = $item;
 2846:         }
 2847:         $result .= '<input type="hidden" name="'.$name.'" value="'.
 2848:                    $hostid.'" />';
 2849:                    if (!$hide) {
 2850:                        $result .= $hostid.' '.$servers{$hostid};
 2851:                    }
 2852:                    $result .= "\n";
 2853:     } elsif ($default) {
 2854:         $result .= '<input type="hidden" name="'.$name.
 2855:                    '" value="default" />';
 2856:                    if (!$hide) {
 2857:                        $result .= &mt('default');
 2858:                    }
 2859:                    $result .= "\n";
 2860:     }
 2861:     return ($result,$numlib);
 2862: }
 2863: 
 2864: =pod
 2865: 
 2866: =back 
 2867: 
 2868: =cut
 2869: 
 2870: ###############################################################
 2871: ##                  Decoding User Agent                      ##
 2872: ###############################################################
 2873: 
 2874: =pod
 2875: 
 2876: =head1 Decoding the User Agent
 2877: 
 2878: =over 4
 2879: 
 2880: =item * &decode_user_agent()
 2881: 
 2882: Inputs: $r
 2883: 
 2884: Outputs:
 2885: 
 2886: =over 4
 2887: 
 2888: =item * $httpbrowser
 2889: 
 2890: =item * $clientbrowser
 2891: 
 2892: =item * $clientversion
 2893: 
 2894: =item * $clientmathml
 2895: 
 2896: =item * $clientunicode
 2897: 
 2898: =item * $clientos
 2899: 
 2900: =item * $clientmobile
 2901: 
 2902: =item * $clientinfo
 2903: 
 2904: =item * $clientosversion
 2905: 
 2906: =back
 2907: 
 2908: =back 
 2909: 
 2910: =cut
 2911: 
 2912: ###############################################################
 2913: ###############################################################
 2914: sub decode_user_agent {
 2915:     my ($r)=@_;
 2916:     my @browsertype=split(/\&/,$Apache::lonnet::perlvar{"lonBrowsDet"});
 2917:     my %mathcap=split(/\&/,$$Apache::lonnet::perlvar{"lonMathML"});
 2918:     my $httpbrowser=$ENV{"HTTP_USER_AGENT"};
 2919:     if (!$httpbrowser && $r) { $httpbrowser=$r->header_in('User-Agent'); }
 2920:     my $clientbrowser='unknown';
 2921:     my $clientversion='0';
 2922:     my $clientmathml='';
 2923:     my $clientunicode='0';
 2924:     my $clientmobile=0;
 2925:     my $clientosversion='';
 2926:     for (my $i=0;$i<=$#browsertype;$i++) {
 2927:         my ($bname,$match,$notmatch,$vreg,$minv,$univ)=split(/\%/,$browsertype[$i]);
 2928: 	if (($httpbrowser=~/$match/i)  && ($httpbrowser!~/$notmatch/i)) {
 2929: 	    $clientbrowser=$bname;
 2930:             $httpbrowser=~/$vreg/i;
 2931: 	    $clientversion=$1;
 2932:             $clientmathml=($clientversion>=$minv);
 2933:             $clientunicode=($clientversion>=$univ);
 2934: 	}
 2935:     }
 2936:     my $clientos='unknown';
 2937:     my $clientinfo;
 2938:     if (($httpbrowser=~/linux/i) ||
 2939:         ($httpbrowser=~/unix/i) ||
 2940:         ($httpbrowser=~/ux/i) ||
 2941:         ($httpbrowser=~/solaris/i)) { $clientos='unix'; }
 2942:     if (($httpbrowser=~/vax/i) ||
 2943:         ($httpbrowser=~/vms/i)) { $clientos='vms'; }
 2944:     if ($httpbrowser=~/next/i) { $clientos='next'; }
 2945:     if (($httpbrowser=~/mac/i) ||
 2946:         ($httpbrowser=~/powerpc/i)) { $clientos='mac'; }
 2947:     if ($httpbrowser=~/win/i) {
 2948:         $clientos='win';
 2949:         if ($httpbrowser =~/Windows\s+NT\s+(\d+\.\d+)/i) {
 2950:             $clientosversion = $1;
 2951:         }
 2952:     }
 2953:     if ($httpbrowser=~/embed/i) { $clientos='pda'; }
 2954:     if ($httpbrowser=~/(Android|iPod|iPad|iPhone|webOS|Blackberry|Windows Phone|Opera m(?:ob|in)|Fennec)/i) {
 2955:         $clientmobile=lc($1);
 2956:     }
 2957:     if ($httpbrowser=~ m{Firefox/(\d+\.\d+)}) {
 2958:         $clientinfo = 'firefox-'.$1;
 2959:     } elsif ($httpbrowser=~ m{chromeframe/(\d+\.\d+)\.}) {
 2960:         $clientinfo = 'chromeframe-'.$1;
 2961:     }
 2962:     return ($httpbrowser,$clientbrowser,$clientversion,$clientmathml,
 2963:             $clientunicode,$clientos,$clientmobile,$clientinfo,
 2964:             $clientosversion);
 2965: }
 2966: 
 2967: ###############################################################
 2968: ##    Authentication changing form generation subroutines    ##
 2969: ###############################################################
 2970: ##
 2971: ## All of the authform_xxxxxxx subroutines take their inputs in a
 2972: ## hash, and have reasonable default values.
 2973: ##
 2974: ##    formname = the name given in the <form> tag.
 2975: #-------------------------------------------
 2976: 
 2977: =pod
 2978: 
 2979: =head1 Authentication Routines
 2980: 
 2981: =over 4
 2982: 
 2983: =item * &authform_xxxxxx()
 2984: 
 2985: The authform_xxxxxx subroutines provide javascript and html forms which 
 2986: handle some of the conveniences required for authentication forms.  
 2987: This is not an optimal method, but it works.  
 2988: 
 2989: =over 4
 2990: 
 2991: =item * authform_header
 2992: 
 2993: =item * authform_authorwarning
 2994: 
 2995: =item * authform_nochange
 2996: 
 2997: =item * authform_kerberos
 2998: 
 2999: =item * authform_internal
 3000: 
 3001: =item * authform_filesystem
 3002: 
 3003: =back
 3004: 
 3005: See loncreateuser.pm for invocation and use examples.
 3006: 
 3007: =cut
 3008: 
 3009: #-------------------------------------------
 3010: sub authform_header{  
 3011:     my %in = (
 3012:         formname => 'cu',
 3013:         kerb_def_dom => '',
 3014:         @_,
 3015:     );
 3016:     $in{'formname'} = 'document.' . $in{'formname'};
 3017:     my $result='';
 3018: 
 3019: #---------------------------------------------- Code for upper case translation
 3020:     my $Javascript_toUpperCase;
 3021:     unless ($in{kerb_def_dom}) {
 3022:         $Javascript_toUpperCase =<<"END";
 3023:         switch (choice) {
 3024:            case 'krb': currentform.elements[choicearg].value =
 3025:                currentform.elements[choicearg].value.toUpperCase();
 3026:                break;
 3027:            default:
 3028:         }
 3029: END
 3030:     } else {
 3031:         $Javascript_toUpperCase = "";
 3032:     }
 3033: 
 3034:     my $radioval = "'nochange'";
 3035:     if (defined($in{'curr_authtype'})) {
 3036:         if ($in{'curr_authtype'} ne '') {
 3037:             $radioval = "'".$in{'curr_authtype'}."arg'";
 3038:         }
 3039:     }
 3040:     my $argfield = 'null';
 3041:     if (defined($in{'mode'})) {
 3042:         if ($in{'mode'} eq 'modifycourse')  {
 3043:             if (defined($in{'curr_autharg'})) {
 3044:                 if ($in{'curr_autharg'} ne '') {
 3045:                     $argfield = "'$in{'curr_autharg'}'";
 3046:                 }
 3047:             }
 3048:         }
 3049:     }
 3050: 
 3051:     $result.=<<"END";
 3052: var current = new Object();
 3053: current.radiovalue = $radioval;
 3054: current.argfield = $argfield;
 3055: 
 3056: function changed_radio(choice,currentform) {
 3057:     var choicearg = choice + 'arg';
 3058:     // If a radio button in changed, we need to change the argfield
 3059:     if (current.radiovalue != choice) {
 3060:         current.radiovalue = choice;
 3061:         if (current.argfield != null) {
 3062:             currentform.elements[current.argfield].value = '';
 3063:         }
 3064:         if (choice == 'nochange') {
 3065:             current.argfield = null;
 3066:         } else {
 3067:             current.argfield = choicearg;
 3068:             switch(choice) {
 3069:                 case 'krb': 
 3070:                     currentform.elements[current.argfield].value = 
 3071:                         "$in{'kerb_def_dom'}";
 3072:                 break;
 3073:               default:
 3074:                 break;
 3075:             }
 3076:         }
 3077:     }
 3078:     return;
 3079: }
 3080: 
 3081: function changed_text(choice,currentform) {
 3082:     var choicearg = choice + 'arg';
 3083:     if (currentform.elements[choicearg].value !='') {
 3084:         $Javascript_toUpperCase
 3085:         // clear old field
 3086:         if ((current.argfield != choicearg) && (current.argfield != null)) {
 3087:             currentform.elements[current.argfield].value = '';
 3088:         }
 3089:         current.argfield = choicearg;
 3090:     }
 3091:     set_auth_radio_buttons(choice,currentform);
 3092:     return;
 3093: }
 3094: 
 3095: function set_auth_radio_buttons(newvalue,currentform) {
 3096:     var numauthchoices = currentform.login.length;
 3097:     if (typeof numauthchoices  == "undefined") {
 3098:         return;
 3099:     } 
 3100:     var i=0;
 3101:     while (i < numauthchoices) {
 3102:         if (currentform.login[i].value == newvalue) { break; }
 3103:         i++;
 3104:     }
 3105:     if (i == numauthchoices) {
 3106:         return;
 3107:     }
 3108:     current.radiovalue = newvalue;
 3109:     currentform.login[i].checked = true;
 3110:     return;
 3111: }
 3112: END
 3113:     return $result;
 3114: }
 3115: 
 3116: sub authform_authorwarning {
 3117:     my $result='';
 3118:     $result='<i>'.
 3119:         &mt('As a general rule, only authors or co-authors should be '.
 3120:             'filesystem authenticated '.
 3121:             '(which allows access to the server filesystem).')."</i>\n";
 3122:     return $result;
 3123: }
 3124: 
 3125: sub authform_nochange {
 3126:     my %in = (
 3127:               formname => 'document.cu',
 3128:               kerb_def_dom => 'MSU.EDU',
 3129:               @_,
 3130:           );
 3131:     my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
 3132:     my $result;
 3133:     if (!$authnum) {
 3134:         $result = &mt('Under your current role you are not permitted to change login settings for this user');
 3135:     } else {
 3136:         $result = '<label>'.&mt('[_1] Do not change login data',
 3137:                   '<input type="radio" name="login" value="nochange" '.
 3138:                   'checked="checked" onclick="'.
 3139:             "javascript:changed_radio('nochange',$in{'formname'});".'" />').
 3140: 	    '</label>';
 3141:     }
 3142:     return $result;
 3143: }
 3144: 
 3145: sub authform_kerberos {
 3146:     my %in = (
 3147:               formname => 'document.cu',
 3148:               kerb_def_dom => 'MSU.EDU',
 3149:               kerb_def_auth => 'krb4',
 3150:               @_,
 3151:               );
 3152:     my ($check4,$check5,$krbcheck,$krbarg,$krbver,$result,$authtype,
 3153:         $autharg,$jscall);
 3154:     my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
 3155:     if ($in{'kerb_def_auth'} eq 'krb5') {
 3156:        $check5 = ' checked="checked"';
 3157:     } else {
 3158:        $check4 = ' checked="checked"';
 3159:     }
 3160:     $krbarg = $in{'kerb_def_dom'};
 3161:     if (defined($in{'curr_authtype'})) {
 3162:         if ($in{'curr_authtype'} eq 'krb') {
 3163:             $krbcheck = ' checked="checked"';
 3164:             if (defined($in{'mode'})) {
 3165:                 if ($in{'mode'} eq 'modifyuser') {
 3166:                     $krbcheck = '';
 3167:                 }
 3168:             }
 3169:             if (defined($in{'curr_kerb_ver'})) {
 3170:                 if ($in{'curr_krb_ver'} eq '5') {
 3171:                     $check5 = ' checked="checked"';
 3172:                     $check4 = '';
 3173:                 } else {
 3174:                     $check4 = ' checked="checked"';
 3175:                     $check5 = '';
 3176:                 }
 3177:             }
 3178:             if (defined($in{'curr_autharg'})) {
 3179:                 $krbarg = $in{'curr_autharg'};
 3180:             }
 3181:             if (!$can_assign{'krb4'} && !$can_assign{'krb5'}) {
 3182:                 if (defined($in{'curr_autharg'})) {
 3183:                     $result = 
 3184:     &mt('Currently Kerberos authenticated with domain [_1] Version [_2].',
 3185:         $in{'curr_autharg'},$krbver);
 3186:                 } else {
 3187:                     $result =
 3188:     &mt('Currently Kerberos authenticated, Version [_1].',$krbver);
 3189:                 }
 3190:                 return $result; 
 3191:             }
 3192:         }
 3193:     } else {
 3194:         if ($authnum == 1) {
 3195:             $authtype = '<input type="hidden" name="login" value="krb" />';
 3196:         }
 3197:     }
 3198:     if (!$can_assign{'krb4'} && !$can_assign{'krb5'}) {
 3199:         return;
 3200:     } elsif ($authtype eq '') {
 3201:         if (defined($in{'mode'})) {
 3202:             if ($in{'mode'} eq 'modifycourse') {
 3203:                 if ($authnum == 1) {
 3204:                     $authtype = '<input type="radio" name="login" value="krb" />';
 3205:                 }
 3206:             }
 3207:         }
 3208:     }
 3209:     $jscall = "javascript:changed_radio('krb',$in{'formname'});";
 3210:     if ($authtype eq '') {
 3211:         $authtype = '<input type="radio" name="login" value="krb" '.
 3212:                     'onclick="'.$jscall.'" onchange="'.$jscall.'"'.
 3213:                     $krbcheck.' />';
 3214:     }
 3215:     if (($can_assign{'krb4'} && $can_assign{'krb5'}) ||
 3216:         ($can_assign{'krb4'} && !$can_assign{'krb5'} &&
 3217:          $in{'curr_authtype'} eq 'krb5') ||
 3218:         (!$can_assign{'krb4'} && $can_assign{'krb5'} &&
 3219:          $in{'curr_authtype'} eq 'krb4')) {
 3220:         $result .= &mt
 3221:         ('[_1] Kerberos authenticated with domain [_2] '.
 3222:          '[_3] Version 4 [_4] Version 5 [_5]',
 3223:          '<label>'.$authtype,
 3224:          '</label><input type="text" size="10" name="krbarg" '.
 3225:              'value="'.$krbarg.'" '.
 3226:              'onchange="'.$jscall.'" />',
 3227:          '<label><input type="radio" name="krbver" value="4" '.$check4.' />',
 3228:          '</label><label><input type="radio" name="krbver" value="5" '.$check5.' />',
 3229: 	 '</label>');
 3230:     } elsif ($can_assign{'krb4'}) {
 3231:         $result .= &mt
 3232:         ('[_1] Kerberos authenticated with domain [_2] '.
 3233:          '[_3] Version 4 [_4]',
 3234:          '<label>'.$authtype,
 3235:          '</label><input type="text" size="10" name="krbarg" '.
 3236:              'value="'.$krbarg.'" '.
 3237:              'onchange="'.$jscall.'" />',
 3238:          '<label><input type="hidden" name="krbver" value="4" />',
 3239:          '</label>');
 3240:     } elsif ($can_assign{'krb5'}) {
 3241:         $result .= &mt
 3242:         ('[_1] Kerberos authenticated with domain [_2] '.
 3243:          '[_3] Version 5 [_4]',
 3244:          '<label>'.$authtype,
 3245:          '</label><input type="text" size="10" name="krbarg" '.
 3246:              'value="'.$krbarg.'" '.
 3247:              'onchange="'.$jscall.'" />',
 3248:          '<label><input type="hidden" name="krbver" value="5" />',
 3249:          '</label>');
 3250:     }
 3251:     return $result;
 3252: }
 3253: 
 3254: sub authform_internal {
 3255:     my %in = (
 3256:                 formname => 'document.cu',
 3257:                 kerb_def_dom => 'MSU.EDU',
 3258:                 @_,
 3259:                 );
 3260:     my ($intcheck,$intarg,$result,$authtype,$autharg,$jscall);
 3261:     my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
 3262:     if (defined($in{'curr_authtype'})) {
 3263:         if ($in{'curr_authtype'} eq 'int') {
 3264:             if ($can_assign{'int'}) {
 3265:                 $intcheck = 'checked="checked" ';
 3266:                 if (defined($in{'mode'})) {
 3267:                     if ($in{'mode'} eq 'modifyuser') {
 3268:                         $intcheck = '';
 3269:                     }
 3270:                 }
 3271:                 if (defined($in{'curr_autharg'})) {
 3272:                     $intarg = $in{'curr_autharg'};
 3273:                 }
 3274:             } else {
 3275:                 $result = &mt('Currently internally authenticated.');
 3276:                 return $result;
 3277:             }
 3278:         }
 3279:     } else {
 3280:         if ($authnum == 1) {
 3281:             $authtype = '<input type="hidden" name="login" value="int" />';
 3282:         }
 3283:     }
 3284:     if (!$can_assign{'int'}) {
 3285:         return;
 3286:     } elsif ($authtype eq '') {
 3287:         if (defined($in{'mode'})) {
 3288:             if ($in{'mode'} eq 'modifycourse') {
 3289:                 if ($authnum == 1) {
 3290:                     $authtype = '<input type="radio" name="login" value="int" />';
 3291:                 }
 3292:             }
 3293:         }
 3294:     }
 3295:     $jscall = "javascript:changed_radio('int',$in{'formname'});";
 3296:     if ($authtype eq '') {
 3297:         $authtype = '<input type="radio" name="login" value="int" '.$intcheck.
 3298:                     ' onchange="'.$jscall.'" onclick="'.$jscall.'" />';
 3299:     }
 3300:     $autharg = '<input type="password" size="10" name="intarg" value="'.
 3301:                $intarg.'" onchange="'.$jscall.'" />';
 3302:     $result = &mt
 3303:         ('[_1] Internally authenticated (with initial password [_2])',
 3304:          '<label>'.$authtype,'</label>'.$autharg);
 3305:     $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>';
 3306:     return $result;
 3307: }
 3308: 
 3309: sub authform_local {
 3310:     my %in = (
 3311:               formname => 'document.cu',
 3312:               kerb_def_dom => 'MSU.EDU',
 3313:               @_,
 3314:               );
 3315:     my ($loccheck,$locarg,$result,$authtype,$autharg,$jscall);
 3316:     my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
 3317:     if (defined($in{'curr_authtype'})) {
 3318:         if ($in{'curr_authtype'} eq 'loc') {
 3319:             if ($can_assign{'loc'}) {
 3320:                 $loccheck = 'checked="checked" ';
 3321:                 if (defined($in{'mode'})) {
 3322:                     if ($in{'mode'} eq 'modifyuser') {
 3323:                         $loccheck = '';
 3324:                     }
 3325:                 }
 3326:                 if (defined($in{'curr_autharg'})) {
 3327:                     $locarg = $in{'curr_autharg'};
 3328:                 }
 3329:             } else {
 3330:                 $result = &mt('Currently using local (institutional) authentication.');
 3331:                 return $result;
 3332:             }
 3333:         }
 3334:     } else {
 3335:         if ($authnum == 1) {
 3336:             $authtype = '<input type="hidden" name="login" value="loc" />';
 3337:         }
 3338:     }
 3339:     if (!$can_assign{'loc'}) {
 3340:         return;
 3341:     } elsif ($authtype eq '') {
 3342:         if (defined($in{'mode'})) {
 3343:             if ($in{'mode'} eq 'modifycourse') {
 3344:                 if ($authnum == 1) {
 3345:                     $authtype = '<input type="radio" name="login" value="loc" />';
 3346:                 }
 3347:             }
 3348:         }
 3349:     }
 3350:     $jscall = "javascript:changed_radio('loc',$in{'formname'});";
 3351:     if ($authtype eq '') {
 3352:         $authtype = '<input type="radio" name="login" value="loc" '.
 3353:                     $loccheck.' onchange="'.$jscall.'" onclick="'.
 3354:                     $jscall.'" />';
 3355:     }
 3356:     $autharg = '<input type="text" size="10" name="locarg" value="'.
 3357:                $locarg.'" onchange="'.$jscall.'" />';
 3358:     $result = &mt('[_1] Local Authentication with argument [_2]',
 3359:                   '<label>'.$authtype,'</label>'.$autharg);
 3360:     return $result;
 3361: }
 3362: 
 3363: sub authform_filesystem {
 3364:     my %in = (
 3365:               formname => 'document.cu',
 3366:               kerb_def_dom => 'MSU.EDU',
 3367:               @_,
 3368:               );
 3369:     my ($fsyscheck,$result,$authtype,$autharg,$jscall);
 3370:     my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
 3371:     if (defined($in{'curr_authtype'})) {
 3372:         if ($in{'curr_authtype'} eq 'fsys') {
 3373:             if ($can_assign{'fsys'}) {
 3374:                 $fsyscheck = 'checked="checked" ';
 3375:                 if (defined($in{'mode'})) {
 3376:                     if ($in{'mode'} eq 'modifyuser') {
 3377:                         $fsyscheck = '';
 3378:                     }
 3379:                 }
 3380:             } else {
 3381:                 $result = &mt('Currently Filesystem Authenticated.');
 3382:                 return $result;
 3383:             }           
 3384:         }
 3385:     } else {
 3386:         if ($authnum == 1) {
 3387:             $authtype = '<input type="hidden" name="login" value="fsys" />';
 3388:         }
 3389:     }
 3390:     if (!$can_assign{'fsys'}) {
 3391:         return;
 3392:     } elsif ($authtype eq '') {
 3393:         if (defined($in{'mode'})) {
 3394:             if ($in{'mode'} eq 'modifycourse') {
 3395:                 if ($authnum == 1) {
 3396:                     $authtype = '<input type="radio" name="login" value="fsys" />';
 3397:                 }
 3398:             }
 3399:         }
 3400:     }
 3401:     $jscall = "javascript:changed_radio('fsys',$in{'formname'});";
 3402:     if ($authtype eq '') {
 3403:         $authtype = '<input type="radio" name="login" value="fsys" '.
 3404:                     $fsyscheck.' onchange="'.$jscall.'" onclick="'.
 3405:                     $jscall.'" />';
 3406:     }
 3407:     $autharg = '<input type="text" size="10" name="fsysarg" value=""'.
 3408:                ' onchange="'.$jscall.'" />';
 3409:     $result = &mt
 3410:         ('[_1] Filesystem Authenticated (with initial password [_2])',
 3411:          '<label><input type="radio" name="login" value="fsys" '.
 3412:          $fsyscheck.'onchange="'.$jscall.'" onclick="'.$jscall.'" />',
 3413:          '</label><input type="password" size="10" name="fsysarg" value="" '.
 3414:                   'onchange="'.$jscall.'" />');
 3415:     return $result;
 3416: }
 3417: 
 3418: sub get_assignable_auth {
 3419:     my ($dom) = @_;
 3420:     if ($dom eq '') {
 3421:         $dom = $env{'request.role.domain'};
 3422:     }
 3423:     my %can_assign = (
 3424:                           krb4 => 1,
 3425:                           krb5 => 1,
 3426:                           int  => 1,
 3427:                           loc  => 1,
 3428:                      );
 3429:     my %domconfig = &Apache::lonnet::get_dom('configuration',['usercreation'],$dom);
 3430:     if (ref($domconfig{'usercreation'}) eq 'HASH') {
 3431:         if (ref($domconfig{'usercreation'}{'authtypes'}) eq 'HASH') {
 3432:             my $authhash = $domconfig{'usercreation'}{'authtypes'};
 3433:             my $context;
 3434:             if ($env{'request.role'} =~ /^au/) {
 3435:                 $context = 'author';
 3436:             } elsif ($env{'request.role'} =~ /^dc/) {
 3437:                 $context = 'domain';
 3438:             } elsif ($env{'request.course.id'}) {
 3439:                 $context = 'course';
 3440:             }
 3441:             if ($context) {
 3442:                 if (ref($authhash->{$context}) eq 'HASH') {
 3443:                    %can_assign = %{$authhash->{$context}}; 
 3444:                 }
 3445:             }
 3446:         }
 3447:     }
 3448:     my $authnum = 0;
 3449:     foreach my $key (keys(%can_assign)) {
 3450:         if ($can_assign{$key}) {
 3451:             $authnum ++;
 3452:         }
 3453:     }
 3454:     if ($can_assign{'krb4'} && $can_assign{'krb5'}) {
 3455:         $authnum --;
 3456:     }
 3457:     return ($authnum,%can_assign);
 3458: }
 3459: 
 3460: ###############################################################
 3461: ##    Get Kerberos Defaults for Domain                 ##
 3462: ###############################################################
 3463: ##
 3464: ## Returns default kerberos version and an associated argument
 3465: ## as listed in file domain.tab. If not listed, provides
 3466: ## appropriate default domain and kerberos version.
 3467: ##
 3468: #-------------------------------------------
 3469: 
 3470: =pod
 3471: 
 3472: =item * &get_kerberos_defaults()
 3473: 
 3474: get_kerberos_defaults($target_domain) returns the default kerberos
 3475: version and domain. If not found, it defaults to version 4 and the 
 3476: domain of the server.
 3477: 
 3478: =over 4
 3479: 
 3480: ($def_version, $def_krb_domain) = &get_kerberos_defaults($target_domain);
 3481: 
 3482: =back
 3483: 
 3484: =back
 3485: 
 3486: =cut
 3487: 
 3488: #-------------------------------------------
 3489: sub get_kerberos_defaults {
 3490:     my $domain=shift;
 3491:     my ($krbdef,$krbdefdom);
 3492:     my %domdefaults = &Apache::lonnet::get_domain_defaults($domain);
 3493:     if (($domdefaults{'auth_def'} =~/^krb(4|5)$/) && ($domdefaults{'auth_arg_def'} ne '')) {
 3494:         $krbdef = $domdefaults{'auth_def'};
 3495:         $krbdefdom = $domdefaults{'auth_arg_def'};
 3496:     } else {
 3497:         $ENV{'SERVER_NAME'}=~/(\w+\.\w+)$/;
 3498:         my $krbdefdom=$1;
 3499:         $krbdefdom=~tr/a-z/A-Z/;
 3500:         $krbdef = "krb4";
 3501:     }
 3502:     return ($krbdef,$krbdefdom);
 3503: }
 3504: 
 3505: 
 3506: ###############################################################
 3507: ##                Thesaurus Functions                        ##
 3508: ###############################################################
 3509: 
 3510: =pod
 3511: 
 3512: =head1 Thesaurus Functions
 3513: 
 3514: =over 4
 3515: 
 3516: =item * &initialize_keywords()
 3517: 
 3518: Initializes the package variable %Keywords if it is empty.  Uses the
 3519: package variable $thesaurus_db_file.
 3520: 
 3521: =cut
 3522: 
 3523: ###################################################
 3524: 
 3525: sub initialize_keywords {
 3526:     return 1 if (scalar keys(%Keywords));
 3527:     # If we are here, %Keywords is empty, so fill it up
 3528:     #   Make sure the file we need exists...
 3529:     if (! -e $thesaurus_db_file) {
 3530:         &Apache::lonnet::logthis("Attempt to access $thesaurus_db_file".
 3531:                                  " failed because it does not exist");
 3532:         return 0;
 3533:     }
 3534:     #   Set up the hash as a database
 3535:     my %thesaurus_db;
 3536:     if (! tie(%thesaurus_db,'GDBM_File',
 3537:               $thesaurus_db_file,&GDBM_READER(),0640)){
 3538:         &Apache::lonnet::logthis("Could not tie \%thesaurus_db to ".
 3539:                                  $thesaurus_db_file);
 3540:         return 0;
 3541:     } 
 3542:     #  Get the average number of appearances of a word.
 3543:     my $avecount = $thesaurus_db{'average.count'};
 3544:     #  Put keywords (those that appear > average) into %Keywords
 3545:     while (my ($word,$data)=each (%thesaurus_db)) {
 3546:         my ($count,undef) = split /:/,$data;
 3547:         $Keywords{$word}++ if ($count > $avecount);
 3548:     }
 3549:     untie %thesaurus_db;
 3550:     # Remove special values from %Keywords.
 3551:     foreach my $value ('total.count','average.count') {
 3552:         delete($Keywords{$value}) if (exists($Keywords{$value}));
 3553:   }
 3554:     return 1;
 3555: }
 3556: 
 3557: ###################################################
 3558: 
 3559: =pod
 3560: 
 3561: =item * &keyword($word)
 3562: 
 3563: Returns true if $word is a keyword.  A keyword is a word that appears more 
 3564: than the average number of times in the thesaurus database.  Calls 
 3565: &initialize_keywords
 3566: 
 3567: =cut
 3568: 
 3569: ###################################################
 3570: 
 3571: sub keyword {
 3572:     return if (!&initialize_keywords());
 3573:     my $word=lc(shift());
 3574:     $word=~s/\W//g;
 3575:     return exists($Keywords{$word});
 3576: }
 3577: 
 3578: ###############################################################
 3579: 
 3580: =pod 
 3581: 
 3582: =item * &get_related_words()
 3583: 
 3584: Look up a word in the thesaurus.  Takes a scalar argument and returns
 3585: an array of words.  If the keyword is not in the thesaurus, an empty array
 3586: will be returned.  The order of the words returned is determined by the
 3587: database which holds them.
 3588: 
 3589: Uses global $thesaurus_db_file.
 3590: 
 3591: 
 3592: =cut
 3593: 
 3594: ###############################################################
 3595: sub get_related_words {
 3596:     my $keyword = shift;
 3597:     my %thesaurus_db;
 3598:     if (! -e $thesaurus_db_file) {
 3599:         &Apache::lonnet::logthis("Attempt to access $thesaurus_db_file ".
 3600:                                  "failed because the file does not exist");
 3601:         return ();
 3602:     }
 3603:     if (! tie(%thesaurus_db,'GDBM_File',
 3604:               $thesaurus_db_file,&GDBM_READER(),0640)){
 3605:         return ();
 3606:     } 
 3607:     my @Words=();
 3608:     my $count=0;
 3609:     if (exists($thesaurus_db{$keyword})) {
 3610: 	# The first element is the number of times
 3611: 	# the word appears.  We do not need it now.
 3612: 	my (undef,@RelatedWords) = (split(/:/,$thesaurus_db{$keyword}));
 3613: 	my (undef,$mostfrequentcount)=split(/\,/,$RelatedWords[0]);
 3614: 	my $threshold=$mostfrequentcount/10;
 3615:         foreach my $possibleword (@RelatedWords) {
 3616:             my ($word,$wordcount)=split(/\,/,$possibleword);
 3617:             if ($wordcount>$threshold) {
 3618: 		push(@Words,$word);
 3619:                 $count++;
 3620:                 if ($count>10) { last; }
 3621: 	    }
 3622:         }
 3623:     }
 3624:     untie %thesaurus_db;
 3625:     return @Words;
 3626: }
 3627: ###############################################################
 3628: #
 3629: #  Spell checking
 3630: #
 3631: 
 3632: =pod
 3633: 
 3634: =back
 3635: 
 3636: =head1 Spell checking
 3637: 
 3638: =over 4
 3639: 
 3640: =item * &check_spelling($wordlist $language)
 3641: 
 3642: Takes a string containing words and feeds it to an external
 3643: spellcheck program via a pipeline. Returns a string containing
 3644: them mis-spelled words.
 3645: 
 3646: Parameters:
 3647: 
 3648: =over 4
 3649: 
 3650: =item - $wordlist
 3651: 
 3652: String that will be fed into the spellcheck program.
 3653: 
 3654: =item - $language
 3655: 
 3656: Language string that specifies the language for which the spell
 3657: check will be performed.
 3658: 
 3659: =back
 3660: 
 3661: =back
 3662: 
 3663: Note: This sub assumes that aspell is installed.
 3664: 
 3665: 
 3666: =cut
 3667: 
 3668: 
 3669: sub check_spelling {
 3670:     my ($wordlist, $language) = @_;
 3671:     my @misspellings;
 3672:     
 3673:     # Generate the speller and set the langauge.
 3674:     # if explicitly selected:
 3675: 
 3676:     my $speller = Text::Aspell->new;
 3677:     if ($language) {
 3678: 	$speller->set_option('lang', $language);
 3679:     }
 3680: 
 3681:     # Turn the word list into an array of words by splittingon whitespace
 3682: 
 3683:     my @words = split(/\s+/, $wordlist);
 3684: 
 3685:     foreach my $word (@words) {
 3686: 	if(! $speller->check($word)) {
 3687: 	    push(@misspellings, $word);
 3688: 	}
 3689:     }
 3690:     return join(' ', @misspellings);
 3691:     
 3692: }
 3693: 
 3694: # -------------------------------------------------------------- Plaintext name
 3695: =pod
 3696: 
 3697: =head1 User Name Functions
 3698: 
 3699: =over 4
 3700: 
 3701: =item * &plainname($uname,$udom,$first)
 3702: 
 3703: Takes a users logon name and returns it as a string in
 3704: "first middle last generation" form 
 3705: if $first is set to 'lastname' then it returns it as
 3706: 'lastname generation, firstname middlename' if their is a lastname
 3707: 
 3708: =cut
 3709: 
 3710: 
 3711: ###############################################################
 3712: sub plainname {
 3713:     my ($uname,$udom,$first)=@_;
 3714:     return if (!defined($uname) || !defined($udom));
 3715:     my %names=&getnames($uname,$udom);
 3716:     my $name=&Apache::lonnet::format_name($names{'firstname'},
 3717: 					  $names{'middlename'},
 3718: 					  $names{'lastname'},
 3719: 					  $names{'generation'},$first);
 3720:     $name=~s/^\s+//;
 3721:     $name=~s/\s+$//;
 3722:     $name=~s/\s+/ /g;
 3723:     if ($name !~ /\S/) { $name=$uname.':'.$udom; }
 3724:     return $name;
 3725: }
 3726: 
 3727: # -------------------------------------------------------------------- Nickname
 3728: =pod
 3729: 
 3730: =item * &nickname($uname,$udom)
 3731: 
 3732: Gets a users name and returns it as a string as
 3733: 
 3734: "&quot;nickname&quot;"
 3735: 
 3736: if the user has a nickname or
 3737: 
 3738: "first middle last generation"
 3739: 
 3740: if the user does not
 3741: 
 3742: =cut
 3743: 
 3744: sub nickname {
 3745:     my ($uname,$udom)=@_;
 3746:     return if (!defined($uname) || !defined($udom));
 3747:     my %names=&getnames($uname,$udom);
 3748:     my $name=$names{'nickname'};
 3749:     if ($name) {
 3750:        $name='&quot;'.$name.'&quot;'; 
 3751:     } else {
 3752:        $name=$names{'firstname'}.' '.$names{'middlename'}.' '.
 3753: 	     $names{'lastname'}.' '.$names{'generation'};
 3754:        $name=~s/\s+$//;
 3755:        $name=~s/\s+/ /g;
 3756:     }
 3757:     return $name;
 3758: }
 3759: 
 3760: sub getnames {
 3761:     my ($uname,$udom)=@_;
 3762:     return if (!defined($uname) || !defined($udom));
 3763:     if ($udom eq 'public' && $uname eq 'public') {
 3764: 	return ('lastname' => &mt('Public'));
 3765:     }
 3766:     my $id=$uname.':'.$udom;
 3767:     my ($names,$cached)=&Apache::lonnet::is_cached_new('namescache',$id);
 3768:     if ($cached) {
 3769: 	return %{$names};
 3770:     } else {
 3771: 	my %loadnames=&Apache::lonnet::get('environment',
 3772:                     ['firstname','middlename','lastname','generation','nickname'],
 3773: 					 $udom,$uname);
 3774: 	&Apache::lonnet::do_cache_new('namescache',$id,\%loadnames);
 3775: 	return %loadnames;
 3776:     }
 3777: }
 3778: 
 3779: # -------------------------------------------------------------------- getemails
 3780: 
 3781: =pod
 3782: 
 3783: =item * &getemails($uname,$udom)
 3784: 
 3785: Gets a user's email information and returns it as a hash with keys:
 3786: notification, critnotification, permanentemail
 3787: 
 3788: For notification and critnotification, values are comma-separated lists 
 3789: of e-mail addresses; for permanentemail, value is a single e-mail address.
 3790:  
 3791: 
 3792: =cut
 3793: 
 3794: 
 3795: sub getemails {
 3796:     my ($uname,$udom)=@_;
 3797:     if ($udom eq 'public' && $uname eq 'public') {
 3798: 	return;
 3799:     }
 3800:     if (!$udom) { $udom=$env{'user.domain'}; }
 3801:     if (!$uname) { $uname=$env{'user.name'}; }
 3802:     my $id=$uname.':'.$udom;
 3803:     my ($names,$cached)=&Apache::lonnet::is_cached_new('emailscache',$id);
 3804:     if ($cached) {
 3805: 	return %{$names};
 3806:     } else {
 3807: 	my %loadnames=&Apache::lonnet::get('environment',
 3808:                     			   ['notification','critnotification',
 3809: 					    'permanentemail'],
 3810: 					   $udom,$uname);
 3811: 	&Apache::lonnet::do_cache_new('emailscache',$id,\%loadnames);
 3812: 	return %loadnames;
 3813:     }
 3814: }
 3815: 
 3816: sub flush_email_cache {
 3817:     my ($uname,$udom)=@_;
 3818:     if (!$udom)  { $udom =$env{'user.domain'}; }
 3819:     if (!$uname) { $uname=$env{'user.name'};   }
 3820:     return if ($udom eq 'public' && $uname eq 'public');
 3821:     my $id=$uname.':'.$udom;
 3822:     &Apache::lonnet::devalidate_cache_new('emailscache',$id);
 3823: }
 3824: 
 3825: # -------------------------------------------------------------------- getlangs
 3826: 
 3827: =pod
 3828: 
 3829: =item * &getlangs($uname,$udom)
 3830: 
 3831: Gets a user's language preference and returns it as a hash with key:
 3832: language.
 3833: 
 3834: =cut
 3835: 
 3836: 
 3837: sub getlangs {
 3838:     my ($uname,$udom) = @_;
 3839:     if (!$udom)  { $udom =$env{'user.domain'}; }
 3840:     if (!$uname) { $uname=$env{'user.name'};   }
 3841:     my $id=$uname.':'.$udom;
 3842:     my ($langs,$cached)=&Apache::lonnet::is_cached_new('userlangs',$id);
 3843:     if ($cached) {
 3844:         return %{$langs};
 3845:     } else {
 3846:         my %loadlangs=&Apache::lonnet::get('environment',['languages'],
 3847:                                            $udom,$uname);
 3848:         &Apache::lonnet::do_cache_new('userlangs',$id,\%loadlangs);
 3849:         return %loadlangs;
 3850:     }
 3851: }
 3852: 
 3853: sub flush_langs_cache {
 3854:     my ($uname,$udom)=@_;
 3855:     if (!$udom)  { $udom =$env{'user.domain'}; }
 3856:     if (!$uname) { $uname=$env{'user.name'};   }
 3857:     return if ($udom eq 'public' && $uname eq 'public');
 3858:     my $id=$uname.':'.$udom;
 3859:     &Apache::lonnet::devalidate_cache_new('userlangs',$id);
 3860: }
 3861: 
 3862: # ------------------------------------------------------------------ Screenname
 3863: 
 3864: =pod
 3865: 
 3866: =item * &screenname($uname,$udom)
 3867: 
 3868: Gets a users screenname and returns it as a string
 3869: 
 3870: =cut
 3871: 
 3872: sub screenname {
 3873:     my ($uname,$udom)=@_;
 3874:     if ($uname eq $env{'user.name'} &&
 3875: 	$udom eq $env{'user.domain'}) {return $env{'environment.screenname'};}
 3876:     my %names=&Apache::lonnet::get('environment',['screenname'],$udom,$uname);
 3877:     return $names{'screenname'};
 3878: }
 3879: 
 3880: 
 3881: # ------------------------------------------------------------- Confirm Wrapper
 3882: =pod
 3883: 
 3884: =item * &confirmwrapper($message)
 3885: 
 3886: Wrap messages about completion of operation in box
 3887: 
 3888: =cut
 3889: 
 3890: sub confirmwrapper {
 3891:     my ($message)=@_;
 3892:     if ($message) {
 3893:         return "\n".'<div class="LC_confirm_box">'."\n"
 3894:                .$message."\n"
 3895:                .'</div>'."\n";
 3896:     } else {
 3897:         return $message;
 3898:     }
 3899: }
 3900: 
 3901: # ------------------------------------------------------------- Message Wrapper
 3902: 
 3903: sub messagewrapper {
 3904:     my ($link,$username,$domain,$subject,$text)=@_;
 3905:     return 
 3906:         '<a href="/adm/email?compose=individual&amp;'.
 3907:         'recname='.$username.'&amp;recdom='.$domain.
 3908: 	'&amp;subject='.&escape($subject).'&amp;text='.&escape($text).'" '.
 3909:         'title="'.&mt('Send message').'">'.$link.'</a>';
 3910: }
 3911: 
 3912: # --------------------------------------------------------------- Notes Wrapper
 3913: 
 3914: sub noteswrapper {
 3915:     my ($link,$un,$do)=@_;
 3916:     return 
 3917: "<a href='/adm/email?recordftf=retrieve&amp;recname=$un&amp;recdom=$do'>$link</a>";
 3918: }
 3919: 
 3920: # ------------------------------------------------------------- Aboutme Wrapper
 3921: 
 3922: sub aboutmewrapper {
 3923:     my ($link,$username,$domain,$target,$class)=@_;
 3924:     if (!defined($username)  && !defined($domain)) {
 3925:         return;
 3926:     }
 3927:     return '<a href="/adm/'.$domain.'/'.$username.'/aboutme"'.
 3928: 	($target?' target="'.$target.'"':'').($class?' class="'.$class.'"':'').' title="'.&mt("View this user's personal information page").'">'.$link.'</a>';
 3929: }
 3930: 
 3931: # ------------------------------------------------------------ Syllabus Wrapper
 3932: 
 3933: sub syllabuswrapper {
 3934:     my ($linktext,$coursedir,$domain)=@_;
 3935:     return qq{<a href="/public/$domain/$coursedir/syllabus">$linktext</a>};
 3936: }
 3937: 
 3938: # -----------------------------------------------------------------------------
 3939: 
 3940: sub track_student_link {
 3941:     my ($linktext,$sname,$sdom,$target,$start,$only_body) = @_;
 3942:     my $link ="/adm/trackstudent?";
 3943:     my $title = 'View recent activity';
 3944:     if (defined($sname) && $sname !~ /^\s*$/ &&
 3945:         defined($sdom)  && $sdom  !~ /^\s*$/) {
 3946:         $link .= "selected_student=$sname:$sdom";
 3947:         $title .= ' of this student';
 3948:     } 
 3949:     if (defined($target) && $target !~ /^\s*$/) {
 3950:         $target = qq{target="$target"};
 3951:     } else {
 3952:         $target = '';
 3953:     }
 3954:     if ($start) { $link.='&amp;start='.$start; }
 3955:     if ($only_body) { $link .= '&amp;only_body=1'; }
 3956:     $title = &mt($title);
 3957:     $linktext = &mt($linktext);
 3958:     return qq{<a href="$link" title="$title" $target>$linktext</a>}.
 3959: 	&help_open_topic('View_recent_activity');
 3960: }
 3961: 
 3962: sub slot_reservations_link {
 3963:     my ($linktext,$sname,$sdom,$target) = @_;
 3964:     my $link ="/adm/slotrequest?command=showresv&amp;origin=aboutme";
 3965:     my $title = 'View slot reservation history';
 3966:     if (defined($sname) && $sname !~ /^\s*$/ &&
 3967:         defined($sdom)  && $sdom  !~ /^\s*$/) {
 3968:         $link .= "&amp;uname=$sname&amp;udom=$sdom";
 3969:         $title .= ' of this student';
 3970:     }
 3971:     if (defined($target) && $target !~ /^\s*$/) {
 3972:         $target = qq{target="$target"};
 3973:     } else {
 3974:         $target = '';
 3975:     }
 3976:     $title = &mt($title);
 3977:     $linktext = &mt($linktext);
 3978:     return qq{<a href="$link" title="$title" $target>$linktext</a>};
 3979: # FIXME uncomment when help item created: &help_open_topic('Slot_Reservation_History');
 3980: 
 3981: }
 3982: 
 3983: # ===================================================== Display a student photo
 3984: 
 3985: 
 3986: sub student_image_tag {
 3987:     my ($domain,$user)=@_;
 3988:     my $imgsrc=&Apache::lonnet::studentphoto($domain,$user,'jpg');
 3989:     if (($imgsrc) && ($imgsrc ne '/adm/lonKaputt/lonlogo_broken.gif')) {
 3990: 	return '<img src="'.$imgsrc.'" align="right" />';
 3991:     } else {
 3992: 	return '';
 3993:     }
 3994: }
 3995: 
 3996: =pod
 3997: 
 3998: =back
 3999: 
 4000: =head1 Access .tab File Data
 4001: 
 4002: =over 4
 4003: 
 4004: =item * &languageids() 
 4005: 
 4006: returns list of all language ids
 4007: 
 4008: =cut
 4009: 
 4010: sub languageids {
 4011:     return sort(keys(%language));
 4012: }
 4013: 
 4014: =pod
 4015: 
 4016: =item * &languagedescription() 
 4017: 
 4018: returns description of a specified language id
 4019: 
 4020: =cut
 4021: 
 4022: sub languagedescription {
 4023:     my $code=shift;
 4024:     return  ($supported_language{$code}?'* ':'').
 4025:             $language{$code}.
 4026: 	    ($supported_language{$code}?' ('.&mt('interface available').')':'');
 4027: }
 4028: 
 4029: =pod
 4030: 
 4031: =item * &plainlanguagedescription
 4032: 
 4033: Returns both the plain language description (e.g. 'Creoles and Pidgins, English-based (Other)')
 4034: and the language character encoding (e.g. ISO) separated by a ' - ' string.
 4035: 
 4036: =cut
 4037: 
 4038: sub plainlanguagedescription {
 4039:     my $code=shift;
 4040:     return $language{$code};
 4041: }
 4042: 
 4043: =pod
 4044: 
 4045: =item * &supportedlanguagecode
 4046: 
 4047: Returns the supported language code (e.g. sptutf maps to pt) given a language
 4048: code.
 4049: 
 4050: =cut
 4051: 
 4052: sub supportedlanguagecode {
 4053:     my $code=shift;
 4054:     return $supported_language{$code};
 4055: }
 4056: 
 4057: =pod
 4058: 
 4059: =item * &latexlanguage()
 4060: 
 4061: Given a language key code returns the correspondnig language to use
 4062: to select the correct hyphenation on LaTeX printouts.  This is undef if there
 4063: is no supported hyphenation for the language code.
 4064: 
 4065: =cut
 4066: 
 4067: sub latexlanguage {
 4068:     my $code = shift;
 4069:     return $latex_language{$code};
 4070: }
 4071: 
 4072: =pod
 4073: 
 4074: =item * &latexhyphenation()
 4075: 
 4076: Same as above but what's supplied is the language as it might be stored
 4077: in the metadata.
 4078: 
 4079: =cut
 4080: 
 4081: sub latexhyphenation {
 4082:     my $key = shift;
 4083:     return $latex_language_bykey{$key};
 4084: }
 4085: 
 4086: =pod
 4087: 
 4088: =item * &copyrightids() 
 4089: 
 4090: returns list of all copyrights
 4091: 
 4092: =cut
 4093: 
 4094: sub copyrightids {
 4095:     return sort(keys(%cprtag));
 4096: }
 4097: 
 4098: =pod
 4099: 
 4100: =item * &copyrightdescription() 
 4101: 
 4102: returns description of a specified copyright id
 4103: 
 4104: =cut
 4105: 
 4106: sub copyrightdescription {
 4107:     return &mt($cprtag{shift(@_)});
 4108: }
 4109: 
 4110: =pod
 4111: 
 4112: =item * &source_copyrightids() 
 4113: 
 4114: returns list of all source copyrights
 4115: 
 4116: =cut
 4117: 
 4118: sub source_copyrightids {
 4119:     return sort(keys(%scprtag));
 4120: }
 4121: 
 4122: =pod
 4123: 
 4124: =item * &source_copyrightdescription() 
 4125: 
 4126: returns description of a specified source copyright id
 4127: 
 4128: =cut
 4129: 
 4130: sub source_copyrightdescription {
 4131:     return &mt($scprtag{shift(@_)});
 4132: }
 4133: 
 4134: =pod
 4135: 
 4136: =item * &filecategories() 
 4137: 
 4138: returns list of all file categories
 4139: 
 4140: =cut
 4141: 
 4142: sub filecategories {
 4143:     return sort(keys(%category_extensions));
 4144: }
 4145: 
 4146: =pod
 4147: 
 4148: =item * &filecategorytypes() 
 4149: 
 4150: returns list of file types belonging to a given file
 4151: category
 4152: 
 4153: =cut
 4154: 
 4155: sub filecategorytypes {
 4156:     my ($cat) = @_;
 4157:     if (ref($category_extensions{lc($cat)}) eq 'ARRAY') { 
 4158:         return @{$category_extensions{lc($cat)}};
 4159:     } else {
 4160:         return ();
 4161:     }
 4162: }
 4163: 
 4164: =pod
 4165: 
 4166: =item * &fileembstyle() 
 4167: 
 4168: returns embedding style for a specified file type
 4169: 
 4170: =cut
 4171: 
 4172: sub fileembstyle {
 4173:     return $fe{lc(shift(@_))};
 4174: }
 4175: 
 4176: sub filemimetype {
 4177:     return $fm{lc(shift(@_))};
 4178: }
 4179: 
 4180: 
 4181: sub filecategoryselect {
 4182:     my ($name,$value)=@_;
 4183:     return &select_form($value,$name,
 4184:                         {'' => &mt('Any category'), map { $_,$_ } sort(keys(%category_extensions))});
 4185: }
 4186: 
 4187: =pod
 4188: 
 4189: =item * &filedescription() 
 4190: 
 4191: returns description for a specified file type
 4192: 
 4193: =cut
 4194: 
 4195: sub filedescription {
 4196:     my $file_description = $fd{lc(shift())};
 4197:     $file_description =~ s:([\[\]]):~$1:g;
 4198:     return &mt($file_description);
 4199: }
 4200: 
 4201: =pod
 4202: 
 4203: =item * &filedescriptionex() 
 4204: 
 4205: returns description for a specified file type with
 4206: extra formatting
 4207: 
 4208: =cut
 4209: 
 4210: sub filedescriptionex {
 4211:     my $ex=shift;
 4212:     my $file_description = $fd{lc($ex)};
 4213:     $file_description =~ s:([\[\]]):~$1:g;
 4214:     return '.'.$ex.' '.&mt($file_description);
 4215: }
 4216: 
 4217: # End of .tab access
 4218: =pod
 4219: 
 4220: =back
 4221: 
 4222: =cut
 4223: 
 4224: # ------------------------------------------------------------------ File Types
 4225: sub fileextensions {
 4226:     return sort(keys(%fe));
 4227: }
 4228: 
 4229: # ----------------------------------------------------------- Display Languages
 4230: # returns a hash with all desired display languages
 4231: #
 4232: 
 4233: sub display_languages {
 4234:     my %languages=();
 4235:     foreach my $lang (&Apache::lonlocal::preferred_languages()) {
 4236: 	$languages{$lang}=1;
 4237:     }
 4238:     &get_unprocessed_cgi($ENV{'QUERY_STRING'},['displaylanguage']);
 4239:     if ($env{'form.displaylanguage'}) {
 4240: 	foreach my $lang (split(/\s*(\,|\;|\:)\s*/,$env{'form.displaylanguage'})) {
 4241: 	    $languages{$lang}=1;
 4242:         }
 4243:     }
 4244:     return %languages;
 4245: }
 4246: 
 4247: sub languages {
 4248:     my ($possible_langs) = @_;
 4249:     my @preferred_langs = &Apache::lonlocal::preferred_languages();
 4250:     if (!ref($possible_langs)) {
 4251: 	if( wantarray ) {
 4252: 	    return @preferred_langs;
 4253: 	} else {
 4254: 	    return $preferred_langs[0];
 4255: 	}
 4256:     }
 4257:     my %possibilities = map { $_ => 1 } (@$possible_langs);
 4258:     my @preferred_possibilities;
 4259:     foreach my $preferred_lang (@preferred_langs) {
 4260: 	if (exists($possibilities{$preferred_lang})) {
 4261: 	    push(@preferred_possibilities, $preferred_lang);
 4262: 	}
 4263:     }
 4264:     if( wantarray ) {
 4265: 	return @preferred_possibilities;
 4266:     }
 4267:     return $preferred_possibilities[0];
 4268: }
 4269: 
 4270: sub user_lang {
 4271:     my ($touname,$toudom,$fromcid) = @_;
 4272:     my @userlangs;
 4273:     if (($fromcid ne '') && ($env{'course.'.$fromcid.'.languages'} ne '')) {
 4274:         @userlangs=(@userlangs,split(/\s*(\,|\;|\:)\s*/,
 4275:                     $env{'course.'.$fromcid.'.languages'}));
 4276:     } else {
 4277:         my %langhash = &getlangs($touname,$toudom);
 4278:         if ($langhash{'languages'} ne '') {
 4279:             @userlangs = split(/\s*(\,|\;|\:)\s*/,$langhash{'languages'});
 4280:         } else {
 4281:             my %domdefs = &Apache::lonnet::get_domain_defaults($toudom);
 4282:             if ($domdefs{'lang_def'} ne '') {
 4283:                 @userlangs = ($domdefs{'lang_def'});
 4284:             }
 4285:         }
 4286:     }
 4287:     my @languages=&Apache::lonlocal::get_genlanguages(@userlangs);
 4288:     my $user_lh = Apache::localize->get_handle(@languages);
 4289:     return $user_lh;
 4290: }
 4291: 
 4292: 
 4293: ###############################################################
 4294: ##               Student Answer Attempts                     ##
 4295: ###############################################################
 4296: 
 4297: =pod
 4298: 
 4299: =head1 Alternate Problem Views
 4300: 
 4301: =over 4
 4302: 
 4303: =item * &get_previous_attempt($symb, $username, $domain, $course,
 4304:     $getattempt, $regexp, $gradesub, $usec, $identifier)
 4305: 
 4306: Return string with previous attempt on problem. Arguments:
 4307: 
 4308: =over 4
 4309: 
 4310: =item * $symb: Problem, including path
 4311: 
 4312: =item * $username: username of the desired student
 4313: 
 4314: =item * $domain: domain of the desired student
 4315: 
 4316: =item * $course: Course ID
 4317: 
 4318: =item * $getattempt: Leave blank for all attempts, otherwise put
 4319:     something
 4320: 
 4321: =item * $regexp: if string matches this regexp, the string will be
 4322:     sent to $gradesub
 4323: 
 4324: =item * $gradesub: routine that processes the string if it matches $regexp
 4325: 
 4326: =item * $usec: section of the desired student
 4327: 
 4328: =item * $identifier: counter for student (multiple students one problem) or 
 4329:     problem (one student; whole sequence).
 4330: 
 4331: =back
 4332: 
 4333: The output string is a table containing all desired attempts, if any.
 4334: 
 4335: =cut
 4336: 
 4337: sub get_previous_attempt {
 4338:   my ($symb,$username,$domain,$course,$getattempt,$regexp,$gradesub,$usec,$identifier)=@_;
 4339:   my $prevattempts='';
 4340:   no strict 'refs';
 4341:   if ($symb) {
 4342:     my (%returnhash)=
 4343:       &Apache::lonnet::restore($symb,$course,$domain,$username);
 4344:     if ($returnhash{'version'}) {
 4345:       my %lasthash=();
 4346:       my $version;
 4347:       for ($version=1;$version<=$returnhash{'version'};$version++) {
 4348:         foreach my $key (reverse(sort(split(/\:/,$returnhash{$version.':keys'})))) {
 4349:             if ($key =~ /\.rawrndseed$/) {
 4350:                 my ($id) = ($key =~ /^(.+)\.rawrndseed$/);
 4351:                 $lasthash{$id.'.rndseed'} = $returnhash{$version.':'.$key};
 4352:             } else {
 4353:                 $lasthash{$key}=$returnhash{$version.':'.$key};
 4354:             }
 4355:         }
 4356:       }
 4357:       $prevattempts=&start_data_table().&start_data_table_header_row();
 4358:       $prevattempts.='<th>'.&mt('History').'</th>';
 4359:       my (%typeparts,%lasthidden,%regraded,%hidestatus);
 4360:       my $showsurv=&Apache::lonnet::allowed('vas',$env{'request.course.id'});
 4361:       foreach my $key (sort(keys(%lasthash))) {
 4362: 	my ($ign,@parts) = split(/\./,$key);
 4363: 	if ($#parts > 0) {
 4364: 	  my $data=$parts[-1];
 4365:           next if ($data eq 'foilorder');
 4366: 	  pop(@parts);
 4367:           $prevattempts.='<th>'.&mt('Part ').join('.',@parts).'<br />'.$data.'&nbsp;</th>';
 4368:           if ($data eq 'type') {
 4369:               unless ($showsurv) {
 4370:                   my $id = join(',',@parts);
 4371:                   $typeparts{$ign.'.'.$id} = $lasthash{$key};
 4372:                   if (($lasthash{$key} eq 'anonsurvey') || ($lasthash{$key} eq 'anonsurveycred')) {
 4373:                       $lasthidden{$ign.'.'.$id} = 1;
 4374:                   }
 4375:               }
 4376:               if ($identifier ne '') {
 4377:                   my $id = join(',',@parts);
 4378:                   if (&Apache::lonnet::EXT("resource.$id.problemstatus",$symb,
 4379:                                                $domain,$username,$usec,undef,$course) =~ /^no/) {
 4380:                       $hidestatus{$ign.'.'.$id} = 1;
 4381:                   }
 4382:               }
 4383:           } elsif ($data eq 'regrader') {
 4384:               if (($identifier ne '') && (@parts)) {
 4385:                   my $id = join(',',@parts);
 4386:                   $regraded{$ign.'.'.$id} = 1;
 4387:               }
 4388:           } 
 4389: 	} else {
 4390: 	  if ($#parts == 0) {
 4391: 	    $prevattempts.='<th>'.$parts[0].'</th>';
 4392: 	  } else {
 4393: 	    $prevattempts.='<th>'.$ign.'</th>';
 4394: 	  }
 4395: 	}
 4396:       }
 4397:       $prevattempts.=&end_data_table_header_row();
 4398:       if ($getattempt eq '') {
 4399:         my (%solved,%resets,%probstatus);
 4400:         if (($identifier ne '') && (keys(%regraded) > 0)) {
 4401:             for ($version=1;$version<=$returnhash{'version'};$version++) {
 4402:                 foreach my $id (keys(%regraded)) {
 4403:                     if (($returnhash{$version.':'.$id.'.regrader'}) &&
 4404:                         ($returnhash{$version.':'.$id.'.tries'} eq '') &&
 4405:                         ($returnhash{$version.':'.$id.'.award'} eq '')) {
 4406:                         push(@{$resets{$id}},$version);
 4407:                     }
 4408:                 }
 4409:             }
 4410:         }
 4411: 	for ($version=1;$version<=$returnhash{'version'};$version++) {
 4412:             my (@hidden,@unsolved);
 4413:             if (%typeparts) {
 4414:                 foreach my $id (keys(%typeparts)) {
 4415:                     if (($returnhash{$version.':'.$id.'.type'} eq 'anonsurvey') || 
 4416:                         ($returnhash{$version.':'.$id.'.type'} eq 'anonsurveycred')) {
 4417:                         push(@hidden,$id);
 4418:                     } elsif ($identifier ne '') {
 4419:                         unless (($returnhash{$version.':'.$id.'.type'} eq 'survey') ||
 4420:                                 ($returnhash{$version.':'.$id.'.type'} eq 'surveycred') ||
 4421:                                 ($hidestatus{$id})) {
 4422:                             next if ((ref($resets{$id}) eq 'ARRAY') && grep(/^\Q$version\E$/,@{$resets{$id}}));
 4423:                             if ($returnhash{$version.':'.$id.'.solved'} eq 'correct_by_student') {
 4424:                                 push(@{$solved{$id}},$version);
 4425:                             } elsif (($returnhash{$version.':'.$id.'.solved'} ne '') &&
 4426:                                      (ref($solved{$id}) eq 'ARRAY')) {
 4427:                                 my $skip;
 4428:                                 if (ref($resets{$id}) eq 'ARRAY') {
 4429:                                     foreach my $reset (@{$resets{$id}}) {
 4430:                                         if ($reset > $solved{$id}[-1]) {
 4431:                                             $skip=1;
 4432:                                             last;
 4433:                                         }
 4434:                                     }
 4435:                                 }
 4436:                                 unless ($skip) {
 4437:                                     my ($ign,$partslist) = split(/\./,$id,2);
 4438:                                     push(@unsolved,$partslist);
 4439:                                 }
 4440:                             }
 4441:                         }
 4442:                     }
 4443:                 }
 4444:             }
 4445:             $prevattempts.=&start_data_table_row().
 4446:                            '<td>'.&mt('Transaction [_1]',$version);
 4447:             if (@unsolved) {
 4448:                 $prevattempts .= '<span class="LC_nobreak"><label>'.
 4449:                                  '<input type="checkbox" name="HIDE'.$identifier.'" value="'.$version.':'.join('_',@unsolved).'" />'.
 4450:                                  &mt('Hide').'</label></span>';
 4451:             }
 4452:             $prevattempts .= '</td>';
 4453:             if (@hidden) {
 4454:                 foreach my $key (sort(keys(%lasthash))) {
 4455:                     next if ($key =~ /\.foilorder$/);
 4456:                     my $hide;
 4457:                     foreach my $id (@hidden) {
 4458:                         if ($key =~ /^\Q$id\E/) {
 4459:                             $hide = 1;
 4460:                             last;
 4461:                         }
 4462:                     }
 4463:                     if ($hide) {
 4464:                         my ($id,$data) = ($key =~ /^(.+)\.([^.]+)$/);
 4465:                         if (($data eq 'award') || ($data eq 'awarddetail')) {
 4466:                             my $value = &format_previous_attempt_value($key,
 4467:                                              $returnhash{$version.':'.$key});
 4468:                             $prevattempts.='<td>'.$value.'&nbsp;</td>';
 4469:                         } else {
 4470:                             $prevattempts.='<td>&nbsp;</td>';
 4471:                         }
 4472:                     } else {
 4473:                         if ($key =~ /\./) {
 4474:                             my $value = $returnhash{$version.':'.$key};
 4475:                             if ($key =~ /\.rndseed$/) {
 4476:                                 my ($id) = ($key =~ /^(.+)\.[^.]+$/);
 4477:                                 if (exists($returnhash{$version.':'.$id.'.rawrndseed'})) {
 4478:                                     $value = $returnhash{$version.':'.$id.'.rawrndseed'};
 4479:                                 }
 4480:                             }
 4481:                             $prevattempts.='<td>'.&format_previous_attempt_value($key,$value).
 4482:                                            '&nbsp;</td>';
 4483:                         } else {
 4484:                             $prevattempts.='<td>&nbsp;</td>';
 4485:                         }
 4486:                     }
 4487:                 }
 4488:             } else {
 4489: 	        foreach my $key (sort(keys(%lasthash))) {
 4490:                     next if ($key =~ /\.foilorder$/);
 4491:                     my $value = $returnhash{$version.':'.$key};
 4492:                     if ($key =~ /\.rndseed$/) {
 4493:                         my ($id) = ($key =~ /^(.+)\.[^.]+$/);
 4494:                         if (exists($returnhash{$version.':'.$id.'.rawrndseed'})) {
 4495:                             $value = $returnhash{$version.':'.$id.'.rawrndseed'};
 4496:                         }
 4497:                     }
 4498:                     $prevattempts.='<td>'.&format_previous_attempt_value($key,$value).
 4499:                                    '&nbsp;</td>';
 4500: 	        }
 4501:             }
 4502: 	    $prevattempts.=&end_data_table_row();
 4503: 	 }
 4504:       }
 4505:       my @currhidden = keys(%lasthidden);
 4506:       $prevattempts.=&start_data_table_row().'<td>'.&mt('Current').'</td>';
 4507:       foreach my $key (sort(keys(%lasthash))) {
 4508:           next if ($key =~ /\.foilorder$/);
 4509:           if (%typeparts) {
 4510:               my $hidden;
 4511:               foreach my $id (@currhidden) {
 4512:                   if ($key =~ /^\Q$id\E/) {
 4513:                       $hidden = 1;
 4514:                       last;
 4515:                   }
 4516:               }
 4517:               if ($hidden) {
 4518:                   my ($id,$data) = ($key =~ /^(.+)\.([^.]+)$/);
 4519:                   if (($data eq 'award') || ($data eq 'awarddetail')) {
 4520:                       my $value = &format_previous_attempt_value($key,$lasthash{$key});
 4521:                       if ($key =~/$regexp$/ && (defined &$gradesub)) {
 4522:                           $value = &$gradesub($value);
 4523:                       }
 4524:                       $prevattempts.='<td>'. $value.'&nbsp;</td>';
 4525:                   } else {
 4526:                       $prevattempts.='<td>&nbsp;</td>';
 4527:                   }
 4528:               } else {
 4529:                   my $value = &format_previous_attempt_value($key,$lasthash{$key});
 4530:                   if ($key =~/$regexp$/ && (defined &$gradesub)) {
 4531:                       $value = &$gradesub($value);
 4532:                   }
 4533:                   $prevattempts.='<td>'.$value.'&nbsp;</td>';
 4534:               }
 4535:           } else {
 4536: 	      my $value = &format_previous_attempt_value($key,$lasthash{$key});
 4537: 	      if ($key =~/$regexp$/ && (defined &$gradesub)) {
 4538:                   $value = &$gradesub($value);
 4539:               }
 4540: 	     $prevattempts.='<td>'.$value.'&nbsp;</td>';
 4541:           }
 4542:       }
 4543:       $prevattempts.= &end_data_table_row().&end_data_table();
 4544:     } else {
 4545:       $prevattempts=
 4546: 	  &start_data_table().&start_data_table_row().
 4547: 	  '<td>'.&mt('Nothing submitted - no attempts.').'</td>'.
 4548: 	  &end_data_table_row().&end_data_table();
 4549:     }
 4550:   } else {
 4551:     $prevattempts=
 4552: 	  &start_data_table().&start_data_table_row().
 4553: 	  '<td>'.&mt('No data.').'</td>'.
 4554: 	  &end_data_table_row().&end_data_table();
 4555:   }
 4556: }
 4557: 
 4558: sub format_previous_attempt_value {
 4559:     my ($key,$value) = @_;
 4560:     if (($key =~ /timestamp/) || ($key=~/duedate/)) {
 4561:         $value = &Apache::lonlocal::locallocaltime($value);
 4562:     } elsif (ref($value) eq 'ARRAY') {
 4563:         $value = &HTML::Entities::encode('('.join(', ', @{ $value }).')','"<>&');
 4564:     } elsif ($key =~ /answerstring$/) {
 4565:         my %answers = &Apache::lonnet::str2hash($value);
 4566:         my @answer = %answers;
 4567:         %answers = map {&HTML::Entities::encode($_, '"<>&')} @answer;
 4568:         my @anskeys = sort(keys(%answers));
 4569:         if (@anskeys == 1) {
 4570:             my $answer = $answers{$anskeys[0]};
 4571:             if ($answer =~ m{\0}) {
 4572:                 $answer =~ s{\0}{,}g;
 4573:             }
 4574:             my $tag_internal_answer_name = 'INTERNAL';
 4575:             if ($anskeys[0] eq $tag_internal_answer_name) {
 4576:                 $value = $answer; 
 4577:             } else {
 4578:                 $value = $anskeys[0].'='.$answer;
 4579:             }
 4580:         } else {
 4581:             foreach my $ans (@anskeys) {
 4582:                 my $answer = $answers{$ans};
 4583:                 if ($answer =~ m{\0}) {
 4584:                     $answer =~ s{\0}{,}g;
 4585:                 }
 4586:                 $value .=  $ans.'='.$answer.'<br />';;
 4587:             } 
 4588:         }
 4589:     } else {
 4590:         $value = &HTML::Entities::encode(&unescape($value), '"<>&');
 4591:     }
 4592:     return $value;
 4593: }
 4594: 
 4595: 
 4596: sub relative_to_absolute {
 4597:     my ($url,$output)=@_;
 4598:     my $parser=HTML::TokeParser->new(\$output);
 4599:     my $token;
 4600:     my $thisdir=$url;
 4601:     my @rlinks=();
 4602:     while ($token=$parser->get_token) {
 4603: 	if ($token->[0] eq 'S') {
 4604: 	    if ($token->[1] eq 'a') {
 4605: 		if ($token->[2]->{'href'}) {
 4606: 		    $rlinks[$#rlinks+1]=$token->[2]->{'href'};
 4607: 		}
 4608: 	    } elsif ($token->[1] eq 'img' || $token->[1] eq 'embed' ) {
 4609: 		$rlinks[$#rlinks+1]=$token->[2]->{'src'};
 4610: 	    } elsif ($token->[1] eq 'base') {
 4611: 		$thisdir=$token->[2]->{'href'};
 4612: 	    }
 4613: 	}
 4614:     }
 4615:     $thisdir=~s-/[^/]*$--;
 4616:     foreach my $link (@rlinks) {
 4617: 	unless (($link=~/^https?\:\/\//i) ||
 4618: 		($link=~/^\//) ||
 4619: 		($link=~/^javascript:/i) ||
 4620: 		($link=~/^mailto:/i) ||
 4621: 		($link=~/^\#/)) {
 4622: 	    my $newlocation=&Apache::lonnet::hreflocation($thisdir,$link);
 4623: 	    $output=~s/(\"|\'|\=\s*)\Q$link\E(\"|\'|\s|\>)/$1$newlocation$2/;
 4624: 	}
 4625:     }
 4626: # -------------------------------------------------- Deal with Applet codebases
 4627:     $output=~s/(\<applet[^\>]+)(codebase\=[^\S\>]+)*([^\>]*)\>/$1.($2?$2:' codebase="'.$thisdir.'"').$3.'>'/gei;
 4628:     return $output;
 4629: }
 4630: 
 4631: =pod
 4632: 
 4633: =item * &get_student_view()
 4634: 
 4635: show a snapshot of what student was looking at
 4636: 
 4637: =cut
 4638: 
 4639: sub get_student_view {
 4640:   my ($symb,$username,$domain,$courseid,$target,$moreenv) = @_;
 4641:   my ($map,$id,$feedurl) = &Apache::lonnet::decode_symb($symb);
 4642:   my (%form);
 4643:   my @elements=('symb','courseid','domain','username');
 4644:   foreach my $element (@elements) {
 4645:       $form{'grade_'.$element}=eval '$'.$element #'
 4646:   }
 4647:   if (defined($moreenv)) {
 4648:       %form=(%form,%{$moreenv});
 4649:   }
 4650:   if (defined($target)) { $form{'grade_target'} = $target; }
 4651:   $feedurl=&Apache::lonnet::clutter($feedurl);
 4652:   my ($userview,$response)=&Apache::lonnet::ssi_body($feedurl,%form);
 4653:   $userview=~s/\<body[^\>]*\>//gi;
 4654:   $userview=~s/\<\/body\>//gi;
 4655:   $userview=~s/\<html\>//gi;
 4656:   $userview=~s/\<\/html\>//gi;
 4657:   $userview=~s/\<head\>//gi;
 4658:   $userview=~s/\<\/head\>//gi;
 4659:   $userview=~s/action\s*\=/would_be_action\=/gi;
 4660:   $userview=&relative_to_absolute($feedurl,$userview);
 4661:   if (wantarray) {
 4662:      return ($userview,$response);
 4663:   } else {
 4664:      return $userview;
 4665:   }
 4666: }
 4667: 
 4668: sub get_student_view_with_retries {
 4669:   my ($symb,$retries,$username,$domain,$courseid,$target,$moreenv) = @_;
 4670: 
 4671:     my $ok = 0;                 # True if we got a good response.
 4672:     my $content;
 4673:     my $response;
 4674: 
 4675:     # Try to get the student_view done. within the retries count:
 4676:     
 4677:     do {
 4678:          ($content, $response) = &get_student_view($symb,$username,$domain,$courseid,$target,$moreenv);
 4679:          $ok      = $response->is_success;
 4680:          if (!$ok) {
 4681:             &Apache::lonnet::logthis("Failed get_student_view_with_retries on $symb: ".$response->is_success.', '.$response->code.', '.$response->message);
 4682:          }
 4683:          $retries--;
 4684:     } while (!$ok && ($retries > 0));
 4685:     
 4686:     if (!$ok) {
 4687:        $content = '';          # On error return an empty content.
 4688:     }
 4689:     if (wantarray) {
 4690:        return ($content, $response);
 4691:     } else {
 4692:        return $content;
 4693:     }
 4694: }
 4695: 
 4696: =pod
 4697: 
 4698: =item * &get_student_answers() 
 4699: 
 4700: show a snapshot of how student was answering problem
 4701: 
 4702: =cut
 4703: 
 4704: sub get_student_answers {
 4705:   my ($symb,$username,$domain,$courseid,%form) = @_;
 4706:   my ($map,$id,$feedurl) = &Apache::lonnet::decode_symb($symb);
 4707:   my (%moreenv);
 4708:   my @elements=('symb','courseid','domain','username');
 4709:   foreach my $element (@elements) {
 4710:     $moreenv{'grade_'.$element}=eval '$'.$element #'
 4711:   }
 4712:   $moreenv{'grade_target'}='answer';
 4713:   %moreenv=(%form,%moreenv);
 4714:   $feedurl = &Apache::lonnet::clutter($feedurl);
 4715:   my $userview=&Apache::lonnet::ssi($feedurl,%moreenv);
 4716:   return $userview;
 4717: }
 4718: 
 4719: =pod
 4720: 
 4721: =item * &submlink()
 4722: 
 4723: Inputs: $text $uname $udom $symb $target
 4724: 
 4725: Returns: A link to grades.pm such as to see the SUBM view of a student
 4726: 
 4727: =cut
 4728: 
 4729: ###############################################
 4730: sub submlink {
 4731:     my ($text,$uname,$udom,$symb,$target)=@_;
 4732:     if (!($uname && $udom)) {
 4733: 	(my $cursymb, my $courseid,$udom,$uname)=
 4734: 	    &Apache::lonnet::whichuser($symb);
 4735: 	if (!$symb) { $symb=$cursymb; }
 4736:     }
 4737:     if (!$symb) { $symb=&Apache::lonnet::symbread(); }
 4738:     $symb=&escape($symb);
 4739:     if ($target) { $target=" target=\"$target\""; }
 4740:     return
 4741:         '<a href="/adm/grades?command=submission'.
 4742:         '&amp;symb='.$symb.
 4743:         '&amp;student='.$uname.
 4744:         '&amp;userdom='.$udom.'"'.
 4745:         $target.'>'.$text.'</a>';
 4746: }
 4747: ##############################################
 4748: 
 4749: =pod
 4750: 
 4751: =item * &pgrdlink()
 4752: 
 4753: Inputs: $text $uname $udom $symb $target
 4754: 
 4755: Returns: A link to grades.pm such as to see the PGRD view of a student
 4756: 
 4757: =cut
 4758: 
 4759: ###############################################
 4760: sub pgrdlink {
 4761:     my $link=&submlink(@_);
 4762:     $link=~s/(&command=submission)/$1&showgrading=yes/;
 4763:     return $link;
 4764: }
 4765: ##############################################
 4766: 
 4767: =pod
 4768: 
 4769: =item * &pprmlink()
 4770: 
 4771: Inputs: $text $uname $udom $symb $target
 4772: 
 4773: Returns: A link to parmset.pm such as to see the PPRM view of a
 4774: student and a specific resource
 4775: 
 4776: =cut
 4777: 
 4778: ###############################################
 4779: sub pprmlink {
 4780:     my ($text,$uname,$udom,$symb,$target)=@_;
 4781:     if (!($uname && $udom)) {
 4782: 	(my $cursymb, my $courseid,$udom,$uname)=
 4783: 	    &Apache::lonnet::whichuser($symb);
 4784: 	if (!$symb) { $symb=$cursymb; }
 4785:     }
 4786:     if (!$symb) { $symb=&Apache::lonnet::symbread(); }
 4787:     $symb=&escape($symb);
 4788:     if ($target) { $target="target=\"$target\""; }
 4789:     return '<a href="/adm/parmset?command=set&amp;'.
 4790: 	'symb='.$symb.'&amp;uname='.$uname.
 4791: 	'&amp;udom='.$udom.'" '.$target.'>'.$text.'</a>';
 4792: }
 4793: ##############################################
 4794: 
 4795: =pod
 4796: 
 4797: =back
 4798: 
 4799: =cut
 4800: 
 4801: ###############################################
 4802: 
 4803: 
 4804: sub timehash {
 4805:     my ($thistime) = @_;
 4806:     my $timezone = &Apache::lonlocal::gettimezone();
 4807:     my $dt = DateTime->from_epoch(epoch => $thistime)
 4808:                      ->set_time_zone($timezone);
 4809:     my $wday = $dt->day_of_week();
 4810:     if ($wday == 7) { $wday = 0; }
 4811:     return ( 'second' => $dt->second(),
 4812:              'minute' => $dt->minute(),
 4813:              'hour'   => $dt->hour(),
 4814:              'day'     => $dt->day_of_month(),
 4815:              'month'   => $dt->month(),
 4816:              'year'    => $dt->year(),
 4817:              'weekday' => $wday,
 4818:              'dayyear' => $dt->day_of_year(),
 4819:              'dlsav'   => $dt->is_dst() );
 4820: }
 4821: 
 4822: sub utc_string {
 4823:     my ($date)=@_;
 4824:     return strftime("%Y%m%dT%H%M%SZ",gmtime($date));
 4825: }
 4826: 
 4827: sub maketime {
 4828:     my %th=@_;
 4829:     my ($epoch_time,$timezone,$dt);
 4830:     $timezone = &Apache::lonlocal::gettimezone();
 4831:     eval {
 4832:         $dt = DateTime->new( year   => $th{'year'},
 4833:                              month  => $th{'month'},
 4834:                              day    => $th{'day'},
 4835:                              hour   => $th{'hour'},
 4836:                              minute => $th{'minute'},
 4837:                              second => $th{'second'},
 4838:                              time_zone => $timezone,
 4839:                          );
 4840:     };
 4841:     if (!$@) {
 4842:         $epoch_time = $dt->epoch;
 4843:         if ($epoch_time) {
 4844:             return $epoch_time;
 4845:         }
 4846:     }
 4847:     return POSIX::mktime(
 4848:         ($th{'seconds'},$th{'minutes'},$th{'hours'},
 4849:          $th{'day'},$th{'month'}-1,$th{'year'}-1900,0,0,-1));
 4850: }
 4851: 
 4852: #########################################
 4853: 
 4854: sub findallcourses {
 4855:     my ($roles,$uname,$udom) = @_;
 4856:     my %roles;
 4857:     if (ref($roles)) { %roles = map { $_ => 1 } @{$roles}; }
 4858:     my %courses;
 4859:     my $now=time;
 4860:     if (!defined($uname)) {
 4861:         $uname = $env{'user.name'};
 4862:     }
 4863:     if (!defined($udom)) {
 4864:         $udom = $env{'user.domain'};
 4865:     }
 4866:     if (($uname ne $env{'user.name'}) || ($udom ne $env{'user.domain'})) {
 4867:         my %roleshash = &Apache::lonnet::dump('roles',$udom,$uname);
 4868:         if (!%roles) {
 4869:             %roles = (
 4870:                        cc => 1,
 4871:                        co => 1,
 4872:                        in => 1,
 4873:                        ep => 1,
 4874:                        ta => 1,
 4875:                        cr => 1,
 4876:                        st => 1,
 4877:              );
 4878:         }
 4879:         foreach my $entry (keys(%roleshash)) {
 4880:             my ($trole,$tend,$tstart) = split(/_/,$roleshash{$entry});
 4881:             if ($trole =~ /^cr/) { 
 4882:                 next if (!exists($roles{$trole}) && !exists($roles{'cr'}));
 4883:             } else {
 4884:                 next if (!exists($roles{$trole}));
 4885:             }
 4886:             if ($tend) {
 4887:                 next if ($tend < $now);
 4888:             }
 4889:             if ($tstart) {
 4890:                 next if ($tstart > $now);
 4891:             }
 4892:             my ($cdom,$cnum,$sec,$cnumpart,$secpart,$role);
 4893:             (undef,$cdom,$cnumpart,$secpart) = split(/\//,$entry);
 4894:             my $value = $trole.'/'.$cdom.'/';
 4895:             if ($secpart eq '') {
 4896:                 ($cnum,$role) = split(/_/,$cnumpart); 
 4897:                 $sec = 'none';
 4898:                 $value .= $cnum.'/';
 4899:             } else {
 4900:                 $cnum = $cnumpart;
 4901:                 ($sec,$role) = split(/_/,$secpart);
 4902:                 $value .= $cnum.'/'.$sec;
 4903:             }
 4904:             if (ref($courses{$cdom.'_'.$cnum}{$sec}) eq 'ARRAY') {
 4905:                 unless (grep(/^\Q$value\E$/,@{$courses{$cdom.'_'.$cnum}{$sec}})) {
 4906:                     push(@{$courses{$cdom.'_'.$cnum}{$sec}},$value);
 4907:                 }
 4908:             } else {
 4909:                 @{$courses{$cdom.'_'.$cnum}{$sec}} = ($value);
 4910:             }
 4911:         }
 4912:     } else {
 4913:         foreach my $key (keys(%env)) {
 4914: 	    if ( $key=~m{^user\.role\.(\w+)\./($match_domain)/($match_courseid)/?(\w*)$} ||
 4915:                  $key=~m{^user\.role\.(cr/$match_domain/$match_username/\w+)\./($match_domain)/($match_courseid)/?(\w*)$}) {
 4916: 	        my ($role,$cdom,$cnum,$sec) = ($1,$2,$3,$4);
 4917: 	        next if ($role eq 'ca' || $role eq 'aa');
 4918: 	        next if (%roles && !exists($roles{$role}));
 4919: 	        my ($starttime,$endtime)=split(/\./,$env{$key});
 4920:                 my $active=1;
 4921:                 if ($starttime) {
 4922: 		    if ($now<$starttime) { $active=0; }
 4923:                 }
 4924:                 if ($endtime) {
 4925:                     if ($now>$endtime) { $active=0; }
 4926:                 }
 4927:                 if ($active) {
 4928:                     my $value = $role.'/'.$cdom.'/'.$cnum.'/';
 4929:                     if ($sec eq '') {
 4930:                         $sec = 'none';
 4931:                     } else {
 4932:                         $value .= $sec;
 4933:                     }
 4934:                     if (ref($courses{$cdom.'_'.$cnum}{$sec}) eq 'ARRAY') {
 4935:                         unless (grep(/^\Q$value\E$/,@{$courses{$cdom.'_'.$cnum}{$sec}})) {
 4936:                             push(@{$courses{$cdom.'_'.$cnum}{$sec}},$value);
 4937:                         }
 4938:                     } else {
 4939:                         @{$courses{$cdom.'_'.$cnum}{$sec}} = ($value);
 4940:                     }
 4941:                 }
 4942:             }
 4943:         }
 4944:     }
 4945:     return %courses;
 4946: }
 4947: 
 4948: ###############################################
 4949: 
 4950: sub blockcheck {
 4951:     my ($setters,$activity,$uname,$udom,$url,$is_course) = @_;
 4952: 
 4953:     if (defined($udom) && defined($uname)) {
 4954:         # If uname and udom are for a course, check for blocks in the course.
 4955:         if (($is_course) || (&Apache::lonnet::is_course($udom,$uname))) {
 4956:             my ($startblock,$endblock,$triggerblock) =
 4957:                 &get_blocks($setters,$activity,$udom,$uname,$url);
 4958:             return ($startblock,$endblock,$triggerblock);
 4959:         }
 4960:     } else {
 4961:         $udom = $env{'user.domain'};
 4962:         $uname = $env{'user.name'};
 4963:     }
 4964: 
 4965:     my $startblock = 0;
 4966:     my $endblock = 0;
 4967:     my $triggerblock = '';
 4968:     my %live_courses = &findallcourses(undef,$uname,$udom);
 4969: 
 4970:     # If uname is for a user, and activity is course-specific, i.e.,
 4971:     # boards, chat or groups, check for blocking in current course only.
 4972: 
 4973:     if (($activity eq 'boards' || $activity eq 'chat' ||
 4974:          $activity eq 'groups' || $activity eq 'printout') &&
 4975:         ($env{'request.course.id'})) {
 4976:         foreach my $key (keys(%live_courses)) {
 4977:             if ($key ne $env{'request.course.id'}) {
 4978:                 delete($live_courses{$key});
 4979:             }
 4980:         }
 4981:     }
 4982: 
 4983:     my $otheruser = 0;
 4984:     my %own_courses;
 4985:     if ((($uname ne $env{'user.name'})) || ($udom ne $env{'user.domain'})) {
 4986:         # Resource belongs to user other than current user.
 4987:         $otheruser = 1;
 4988:         # Gather courses for current user
 4989:         %own_courses = 
 4990:             &findallcourses(undef,$env{'user.name'},$env{'user.domain'});
 4991:     }
 4992: 
 4993:     # Gather active course roles - course coordinator, instructor, 
 4994:     # exam proctor, ta, student, or custom role.
 4995: 
 4996:     foreach my $course (keys(%live_courses)) {
 4997:         my ($cdom,$cnum);
 4998:         if ((defined($env{'course.'.$course.'.domain'})) && (defined($env{'course.'.$course.'.num'}))) {
 4999:             $cdom = $env{'course.'.$course.'.domain'};
 5000:             $cnum = $env{'course.'.$course.'.num'};
 5001:         } else {
 5002:             ($cdom,$cnum) = split(/_/,$course); 
 5003:         }
 5004:         my $no_ownblock = 0;
 5005:         my $no_userblock = 0;
 5006:         if ($otheruser && $activity ne 'com') {
 5007:             # Check if current user has 'evb' priv for this
 5008:             if (defined($own_courses{$course})) {
 5009:                 foreach my $sec (keys(%{$own_courses{$course}})) {
 5010:                     my $checkrole = 'cm./'.$cdom.'/'.$cnum;
 5011:                     if ($sec ne 'none') {
 5012:                         $checkrole .= '/'.$sec;
 5013:                     }
 5014:                     if (&Apache::lonnet::allowed('evb',undef,undef,$checkrole)) {
 5015:                         $no_ownblock = 1;
 5016:                         last;
 5017:                     }
 5018:                 }
 5019:             }
 5020:             # if they have 'evb' priv and are currently not playing student
 5021:             next if (($no_ownblock) &&
 5022:                  ($env{'request.role'} !~ m{^st\./$cdom/$cnum}));
 5023:         }
 5024:         foreach my $sec (keys(%{$live_courses{$course}})) {
 5025:             my $checkrole = 'cm./'.$cdom.'/'.$cnum;
 5026:             if ($sec ne 'none') {
 5027:                 $checkrole .= '/'.$sec;
 5028:             }
 5029:             if ($otheruser) {
 5030:                 # Resource belongs to user other than current user.
 5031:                 # Assemble privs for that user, and check for 'evb' priv.
 5032:                 my (%allroles,%userroles);
 5033:                 if (ref($live_courses{$course}{$sec}) eq 'ARRAY') {
 5034:                     foreach my $entry (@{$live_courses{$course}{$sec}}) { 
 5035:                         my ($trole,$tdom,$tnum,$tsec);
 5036:                         if ($entry =~ /^cr/) {
 5037:                             ($trole,$tdom,$tnum,$tsec) = 
 5038:                                 ($entry =~ m|^(cr/$match_domain/$match_username/\w+)\./($match_domain)/($match_username)/?(\w*)$|);
 5039:                         } else {
 5040:                            ($trole,$tdom,$tnum,$tsec) = split(/\//,$entry);
 5041:                         }
 5042:                         my ($spec,$area,$trest);
 5043:                         $area = '/'.$tdom.'/'.$tnum;
 5044:                         $trest = $tnum;
 5045:                         if ($tsec ne '') {
 5046:                             $area .= '/'.$tsec;
 5047:                             $trest .= '/'.$tsec;
 5048:                         }
 5049:                         $spec = $trole.'.'.$area;
 5050:                         if ($trole =~ /^cr/) {
 5051:                             &Apache::lonnet::custom_roleprivs(\%allroles,$trole,
 5052:                                                               $tdom,$spec,$trest,$area);
 5053:                         } else {
 5054:                             &Apache::lonnet::standard_roleprivs(\%allroles,$trole,
 5055:                                                                 $tdom,$spec,$trest,$area);
 5056:                         }
 5057:                     }
 5058:                     my ($author,$adv) = &Apache::lonnet::set_userprivs(\%userroles,\%allroles);
 5059:                     if ($userroles{'user.priv.'.$checkrole} =~ /evb\&([^\:]*)/) {
 5060:                         if ($1) {
 5061:                             $no_userblock = 1;
 5062:                             last;
 5063:                         }
 5064:                     }
 5065:                 }
 5066:             } else {
 5067:                 # Resource belongs to current user
 5068:                 # Check for 'evb' priv via lonnet::allowed().
 5069:                 if (&Apache::lonnet::allowed('evb',undef,undef,$checkrole)) {
 5070:                     $no_ownblock = 1;
 5071:                     last;
 5072:                 }
 5073:             }
 5074:         }
 5075:         # if they have the evb priv and are currently not playing student
 5076:         next if (($no_ownblock) &&
 5077:                  ($env{'request.role'} !~ m{^st\./\Q$cdom\E/\Q$cnum\E}));
 5078:         next if ($no_userblock);
 5079: 
 5080:         # Retrieve blocking times and identity of locker for course
 5081:         # of specified user, unless user has 'evb' privilege.
 5082:         
 5083:         my ($start,$end,$trigger) = 
 5084:             &get_blocks($setters,$activity,$cdom,$cnum,$url);
 5085:         if (($start != 0) && 
 5086:             (($startblock == 0) || ($startblock > $start))) {
 5087:             $startblock = $start;
 5088:             if ($trigger ne '') {
 5089:                 $triggerblock = $trigger;
 5090:             }
 5091:         }
 5092:         if (($end != 0)  &&
 5093:             (($endblock == 0) || ($endblock < $end))) {
 5094:             $endblock = $end;
 5095:             if ($trigger ne '') {
 5096:                 $triggerblock = $trigger;
 5097:             }
 5098:         }
 5099:     }
 5100:     return ($startblock,$endblock,$triggerblock);
 5101: }
 5102: 
 5103: sub get_blocks {
 5104:     my ($setters,$activity,$cdom,$cnum,$url) = @_;
 5105:     my $startblock = 0;
 5106:     my $endblock = 0;
 5107:     my $triggerblock = '';
 5108:     my $course = $cdom.'_'.$cnum;
 5109:     $setters->{$course} = {};
 5110:     $setters->{$course}{'staff'} = [];
 5111:     $setters->{$course}{'times'} = [];
 5112:     $setters->{$course}{'triggers'} = [];
 5113:     my (@blockers,%triggered);
 5114:     my $now = time;
 5115:     my %commblocks = &Apache::lonnet::get_comm_blocks($cdom,$cnum);
 5116:     if ($activity eq 'docs') {
 5117:         @blockers = &Apache::lonnet::has_comm_blocking('bre',undef,$url,\%commblocks);
 5118:         foreach my $block (@blockers) {
 5119:             if ($block =~ /^firstaccess____(.+)$/) {
 5120:                 my $item = $1;
 5121:                 my $type = 'map';
 5122:                 my $timersymb = $item;
 5123:                 if ($item eq 'course') {
 5124:                     $type = 'course';
 5125:                 } elsif ($item =~ /___\d+___/) {
 5126:                     $type = 'resource';
 5127:                 } else {
 5128:                     $timersymb = &Apache::lonnet::symbread($item);
 5129:                 }
 5130:                 my $start = $env{'course.'.$cdom.'_'.$cnum.'.firstaccess.'.$timersymb};
 5131:                 my $end = $start + $env{'course.'.$cdom.'_'.$cnum.'.timerinterval.'.$timersymb};
 5132:                 $triggered{$block} = {
 5133:                                        start => $start,
 5134:                                        end   => $end,
 5135:                                        type  => $type,
 5136:                                      };
 5137:             }
 5138:         }
 5139:     } else {
 5140:         foreach my $block (keys(%commblocks)) {
 5141:             if ($block =~ m/^(\d+)____(\d+)$/) { 
 5142:                 my ($start,$end) = ($1,$2);
 5143:                 if ($start <= time && $end >= time) {
 5144:                     if (ref($commblocks{$block}) eq 'HASH') {
 5145:                         if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
 5146:                             if ($commblocks{$block}{'blocks'}{$activity} eq 'on') {
 5147:                                 unless(grep(/^\Q$block\E$/,@blockers)) {
 5148:                                     push(@blockers,$block);
 5149:                                 }
 5150:                             }
 5151:                         }
 5152:                     }
 5153:                 }
 5154:             } elsif ($block =~ /^firstaccess____(.+)$/) {
 5155:                 my $item = $1;
 5156:                 my $timersymb = $item; 
 5157:                 my $type = 'map';
 5158:                 if ($item eq 'course') {
 5159:                     $type = 'course';
 5160:                 } elsif ($item =~ /___\d+___/) {
 5161:                     $type = 'resource';
 5162:                 } else {
 5163:                     $timersymb = &Apache::lonnet::symbread($item);
 5164:                 }
 5165:                 my $start = $env{'course.'.$cdom.'_'.$cnum.'.firstaccess.'.$timersymb};
 5166:                 my $end = $start + $env{'course.'.$cdom.'_'.$cnum.'.timerinterval.'.$timersymb}; 
 5167:                 if ($start && $end) {
 5168:                     if (($start <= time) && ($end >= time)) {
 5169:                         unless (grep(/^\Q$block\E$/,@blockers)) {
 5170:                             push(@blockers,$block);
 5171:                             $triggered{$block} = {
 5172:                                                    start => $start,
 5173:                                                    end   => $end,
 5174:                                                    type  => $type,
 5175:                                                  };
 5176:                         }
 5177:                     }
 5178:                 }
 5179:             }
 5180:         }
 5181:     }
 5182:     foreach my $blocker (@blockers) {
 5183:         my ($staff_name,$staff_dom,$title,$blocks) =
 5184:             &parse_block_record($commblocks{$blocker});
 5185:         push(@{$$setters{$course}{'staff'}},[$staff_name,$staff_dom]);
 5186:         my ($start,$end,$triggertype);
 5187:         if ($blocker =~ m/^(\d+)____(\d+)$/) {
 5188:             ($start,$end) = ($1,$2);
 5189:         } elsif (ref($triggered{$blocker}) eq 'HASH') {
 5190:             $start = $triggered{$blocker}{'start'};
 5191:             $end = $triggered{$blocker}{'end'};
 5192:             $triggertype = $triggered{$blocker}{'type'};
 5193:         }
 5194:         if ($start) {
 5195:             push(@{$$setters{$course}{'times'}}, [$start,$end]);
 5196:             if ($triggertype) {
 5197:                 push(@{$$setters{$course}{'triggers'}},$triggertype);
 5198:             } else {
 5199:                 push(@{$$setters{$course}{'triggers'}},0);
 5200:             }
 5201:             if ( ($startblock == 0) || ($startblock > $start) ) {
 5202:                 $startblock = $start;
 5203:                 if ($triggertype) {
 5204:                     $triggerblock = $blocker;
 5205:                 }
 5206:             }
 5207:             if ( ($endblock == 0) || ($endblock < $end) ) {
 5208:                $endblock = $end;
 5209:                if ($triggertype) {
 5210:                    $triggerblock = $blocker;
 5211:                }
 5212:             }
 5213:         }
 5214:     }
 5215:     return ($startblock,$endblock,$triggerblock);
 5216: }
 5217: 
 5218: sub parse_block_record {
 5219:     my ($record) = @_;
 5220:     my ($setuname,$setudom,$title,$blocks);
 5221:     if (ref($record) eq 'HASH') {
 5222:         ($setuname,$setudom) = split(/:/,$record->{'setter'});
 5223:         $title = &unescape($record->{'event'});
 5224:         $blocks = $record->{'blocks'};
 5225:     } else {
 5226:         my @data = split(/:/,$record,3);
 5227:         if (scalar(@data) eq 2) {
 5228:             $title = $data[1];
 5229:             ($setuname,$setudom) = split(/@/,$data[0]);
 5230:         } else {
 5231:             ($setuname,$setudom,$title) = @data;
 5232:         }
 5233:         $blocks = { 'com' => 'on' };
 5234:     }
 5235:     return ($setuname,$setudom,$title,$blocks);
 5236: }
 5237: 
 5238: sub blocking_status {
 5239:     my ($activity,$uname,$udom,$url,$is_course) = @_;
 5240:     my %setters;
 5241: 
 5242: # check for active blocking
 5243:     my ($startblock,$endblock,$triggerblock) = 
 5244:         &blockcheck(\%setters,$activity,$uname,$udom,$url,$is_course);
 5245:     my $blocked = 0;
 5246:     if ($startblock && $endblock) {
 5247:         $blocked = 1;
 5248:     }
 5249: 
 5250: # caller just wants to know whether a block is active
 5251:     if (!wantarray) { return $blocked; }
 5252: 
 5253: # build a link to a popup window containing the details
 5254:     my $querystring  = "?activity=$activity";
 5255: # $uname and $udom decide whose portfolio the user is trying to look at
 5256:     if (($activity eq 'port') || ($activity eq 'passwd')) {
 5257:         $querystring .= "&amp;udom=$udom"      if ($udom =~ /^$match_domain$/); 
 5258:         $querystring .= "&amp;uname=$uname"    if ($uname =~ /^$match_username$/);
 5259:     } elsif ($activity eq 'docs') {
 5260:         $querystring .= '&amp;url='.&HTML::Entities::encode($url,'&"');
 5261:     }
 5262: 
 5263:     my $output .= <<'END_MYBLOCK';
 5264: function openWindow(url, wdwName, w, h, toolbar,scrollbar) {
 5265:     var options = "width=" + w + ",height=" + h + ",";
 5266:     options += "resizable=yes,scrollbars="+scrollbar+",status=no,";
 5267:     options += "menubar=no,toolbar="+toolbar+",location=no,directories=no";
 5268:     var newWin = window.open(url, wdwName, options);
 5269:     newWin.focus();
 5270: }
 5271: END_MYBLOCK
 5272: 
 5273:     $output = Apache::lonhtmlcommon::scripttag($output);
 5274:   
 5275:     my $popupUrl = "/adm/blockingstatus/$querystring";
 5276:     my $text = &mt('Communication Blocked');
 5277:     my $class = 'LC_comblock';
 5278:     if ($activity eq 'docs') {
 5279:         $text = &mt('Content Access Blocked');
 5280:         $class = '';
 5281:     } elsif ($activity eq 'printout') {
 5282:         $text = &mt('Printing Blocked');
 5283:     } elsif ($activity eq 'passwd') {
 5284:         $text = &mt('Password Changing Blocked');
 5285:     }
 5286:     $output .= <<"END_BLOCK";
 5287: <div class='$class'>
 5288:   <a onclick='openWindow("$popupUrl","Blocking Table",600,300,"no","no");return false;' href='/adm/blockingstatus/$querystring'
 5289:   title='$text'>
 5290:   <img class='LC_noBorder LC_middle' title='$text' src='/res/adm/pages/comblock.png' alt='$text'/></a>
 5291:   <a onclick='openWindow("$popupUrl","Blocking Table",600,300,"no","no");return false;' href='/adm/blockingstatus/$querystring' 
 5292:   title='$text'>$text</a>
 5293: </div>
 5294: 
 5295: END_BLOCK
 5296: 
 5297:     return ($blocked, $output);
 5298: }
 5299: 
 5300: ###############################################
 5301: 
 5302: sub check_ip_acc {
 5303:     my ($acc,$clientip)=@_;
 5304:     &Apache::lonxml::debug("acc is $acc");
 5305:     if (!defined($acc) || $acc =~ /^\s*$/ || $acc =~/^\s*no\s*$/i) {
 5306:         return 1;
 5307:     }
 5308:     my $allowed;
 5309:     my $ip=$env{'request.host'} || $ENV{'REMOTE_ADDR'} || $clientip;
 5310: 
 5311:     my $name;
 5312:     my %access = (
 5313:                      allowfrom => 1,
 5314:                      denyfrom  => 0,
 5315:                  );
 5316:     my @allows;
 5317:     my @denies;
 5318:     foreach my $item (split(',',$acc)) {
 5319:         $item =~ s/^\s*//;
 5320:         $item =~ s/\s*$//;
 5321:         my $pattern;
 5322:         if ($item =~ /^\!(.+)$/) {
 5323:             push(@denies,$1);
 5324:         } else {
 5325:             push(@allows,$item);
 5326:         }
 5327:    }
 5328:    my $numdenies = scalar(@denies);
 5329:    my $numallows = scalar(@allows);
 5330:    my $count = 0;
 5331:    foreach my $pattern (@denies,@allows) {
 5332:         $count ++; 
 5333:         my $acctype = 'allowfrom';
 5334:         if ($count <= $numdenies) {
 5335:             $acctype = 'denyfrom';
 5336:         }
 5337:         if ($pattern =~ /\*$/) {
 5338:             #35.8.*
 5339:             $pattern=~s/\*//;
 5340:             if ($ip =~ /^\Q$pattern\E/) { $allowed=$access{$acctype}; }
 5341:         } elsif ($pattern =~ /(\d+\.\d+\.\d+)\.\[(\d+)-(\d+)\]$/) {
 5342:             #35.8.3.[34-56]
 5343:             my $low=$2;
 5344:             my $high=$3;
 5345:             $pattern=$1;
 5346:             if ($ip =~ /^\Q$pattern\E/) {
 5347:                 my $last=(split(/\./,$ip))[3];
 5348:                 if ($last <=$high && $last >=$low) { $allowed=$access{$acctype}; }
 5349:             }
 5350:         } elsif ($pattern =~ /^\*/) {
 5351:             #*.msu.edu
 5352:             $pattern=~s/\*//;
 5353:             if (!defined($name)) {
 5354:                 use Socket;
 5355:                 my $netaddr=inet_aton($ip);
 5356:                 ($name)=gethostbyaddr($netaddr,AF_INET);
 5357:             }
 5358:             if ($name =~ /\Q$pattern\E$/i) { $allowed=$access{$acctype}; }
 5359:         } elsif ($pattern =~ /\d+\.\d+\.\d+\.\d+/) {
 5360:             #127.0.0.1
 5361:             if ($ip =~ /^\Q$pattern\E/) { $allowed=$access{$acctype}; }
 5362:         } else {
 5363:             #some.name.com
 5364:             if (!defined($name)) {
 5365:                 use Socket;
 5366:                 my $netaddr=inet_aton($ip);
 5367:                 ($name)=gethostbyaddr($netaddr,AF_INET);
 5368:             }
 5369:             if ($name =~ /\Q$pattern\E$/i) { $allowed=$access{$acctype}; }
 5370:         }
 5371:         if ($allowed =~ /^(0|1)$/) { last; }
 5372:     }
 5373:     if ($allowed eq '') {
 5374:         if ($numdenies && !$numallows) {
 5375:             $allowed = 1;
 5376:         } else {
 5377:             $allowed = 0;
 5378:         }
 5379:     }
 5380:     return $allowed;
 5381: }
 5382: 
 5383: ###############################################
 5384: 
 5385: =pod
 5386: 
 5387: =head1 Domain Template Functions
 5388: 
 5389: =over 4
 5390: 
 5391: =item * &determinedomain()
 5392: 
 5393: Inputs: $domain (usually will be undef)
 5394: 
 5395: Returns: Determines which domain should be used for designs
 5396: 
 5397: =cut
 5398: 
 5399: ###############################################
 5400: sub determinedomain {
 5401:     my $domain=shift;
 5402:     if (! $domain) {
 5403:         # Determine domain if we have not been given one
 5404:         $domain = &Apache::lonnet::default_login_domain();
 5405:         if ($env{'user.domain'}) { $domain=$env{'user.domain'}; }
 5406:         if ($env{'request.role.domain'}) { 
 5407:             $domain=$env{'request.role.domain'}; 
 5408:         }
 5409:     }
 5410:     return $domain;
 5411: }
 5412: ###############################################
 5413: 
 5414: sub devalidate_domconfig_cache {
 5415:     my ($udom)=@_;
 5416:     &Apache::lonnet::devalidate_cache_new('domainconfig',$udom);
 5417: }
 5418: 
 5419: # ---------------------- Get domain configuration for a domain
 5420: sub get_domainconf {
 5421:     my ($udom) = @_;
 5422:     my $cachetime=1800;
 5423:     my ($result,$cached)=&Apache::lonnet::is_cached_new('domainconfig',$udom);
 5424:     if (defined($cached)) { return %{$result}; }
 5425: 
 5426:     my %domconfig = &Apache::lonnet::get_dom('configuration',
 5427: 					     ['login','rolecolors','autoenroll'],$udom);
 5428:     my (%designhash,%legacy);
 5429:     if (keys(%domconfig) > 0) {
 5430:         if (ref($domconfig{'login'}) eq 'HASH') {
 5431:             if (keys(%{$domconfig{'login'}})) {
 5432:                 foreach my $key (keys(%{$domconfig{'login'}})) {
 5433:                     if (ref($domconfig{'login'}{$key}) eq 'HASH') {
 5434:                         if (($key eq 'loginvia') || ($key eq 'headtag')) {
 5435:                             if (ref($domconfig{'login'}{$key}) eq 'HASH') {
 5436:                                 foreach my $hostname (keys(%{$domconfig{'login'}{$key}})) {
 5437:                                     if (ref($domconfig{'login'}{$key}{$hostname}) eq 'HASH') {
 5438:                                         if ($key eq 'loginvia') {
 5439:                                             if ($domconfig{'login'}{'loginvia'}{$hostname}{'server'}) {
 5440:                                                 my $server = $domconfig{'login'}{'loginvia'}{$hostname}{'server'};
 5441:                                                 $designhash{$udom.'.login.loginvia'} = $server;
 5442:                                                 if ($domconfig{'login'}{'loginvia'}{$hostname}{'serverpath'} eq 'custom') {
 5443: 
 5444:                                                     $designhash{$udom.'.login.loginvia_'.$hostname} = $server.':'.$domconfig{'login'}{'loginvia'}{$hostname}{'custompath'};
 5445:                                                 } else {
 5446:                                                     $designhash{$udom.'.login.loginvia_'.$hostname} = $server.':'.$domconfig{'login'}{'loginvia'}{$hostname}{'serverpath'};
 5447:                                                 }
 5448:                                             }
 5449:                                         } elsif ($key eq 'headtag') {
 5450:                                             if ($domconfig{'login'}{'headtag'}{$hostname}{'url'}) {
 5451:                                                 $designhash{$udom.'.login.headtag_'.$hostname} = $domconfig{'login'}{'headtag'}{$hostname}{'url'};
 5452:                                             }
 5453:                                         }
 5454:                                         if ($domconfig{'login'}{$key}{$hostname}{'exempt'}) {
 5455:                                             $designhash{$udom.'.login.'.$key.'_exempt_'.$hostname} = $domconfig{'login'}{$key}{$hostname}{'exempt'};
 5456:                                         }
 5457:                                     }
 5458:                                 }
 5459:                             }
 5460:                         } else {
 5461:                             foreach my $img (keys(%{$domconfig{'login'}{$key}})) {
 5462:                                 $designhash{$udom.'.login.'.$key.'_'.$img} = 
 5463:                                     $domconfig{'login'}{$key}{$img};
 5464:                             }
 5465:                         }
 5466:                     } else {
 5467:                         $designhash{$udom.'.login.'.$key}=$domconfig{'login'}{$key};
 5468:                     }
 5469:                 }
 5470:             } else {
 5471:                 $legacy{'login'} = 1;
 5472:             }
 5473:         } else {
 5474:             $legacy{'login'} = 1;
 5475:         }
 5476:         if (ref($domconfig{'rolecolors'}) eq 'HASH') {
 5477:             if (keys(%{$domconfig{'rolecolors'}})) {
 5478:                 foreach my $role (keys(%{$domconfig{'rolecolors'}})) {
 5479:                     if (ref($domconfig{'rolecolors'}{$role}) eq 'HASH') {
 5480:                         foreach my $item (keys(%{$domconfig{'rolecolors'}{$role}})) {
 5481:                             $designhash{$udom.'.'.$role.'.'.$item}=$domconfig{'rolecolors'}{$role}{$item};
 5482:                         }
 5483:                     }
 5484:                 }
 5485:             } else {
 5486:                 $legacy{'rolecolors'} = 1;
 5487:             }
 5488:         } else {
 5489:             $legacy{'rolecolors'} = 1;
 5490:         }
 5491:         if (ref($domconfig{'autoenroll'}) eq 'HASH') {
 5492:             if ($domconfig{'autoenroll'}{'co-owners'}) {
 5493:                 $designhash{$udom.'.autoassign.co-owners'}=$domconfig{'autoenroll'}{'co-owners'};
 5494:             }
 5495:         }
 5496:         if (keys(%legacy) > 0) {
 5497:             my %legacyhash = &get_legacy_domconf($udom);
 5498:             foreach my $item (keys(%legacyhash)) {
 5499:                 if ($item =~ /^\Q$udom\E\.login/) {
 5500:                     if ($legacy{'login'}) { 
 5501:                         $designhash{$item} = $legacyhash{$item};
 5502:                     }
 5503:                 } else {
 5504:                     if ($legacy{'rolecolors'}) {
 5505:                         $designhash{$item} = $legacyhash{$item};
 5506:                     }
 5507:                 }
 5508:             }
 5509:         }
 5510:     } else {
 5511:         %designhash = &get_legacy_domconf($udom); 
 5512:     }
 5513:     &Apache::lonnet::do_cache_new('domainconfig',$udom,\%designhash,
 5514: 				  $cachetime);
 5515:     return %designhash;
 5516: }
 5517: 
 5518: sub get_legacy_domconf {
 5519:     my ($udom) = @_;
 5520:     my %legacyhash;
 5521:     my $designdir=$Apache::lonnet::perlvar{'lonTabDir'}.'/lonDomColors';
 5522:     my $designfile =  $designdir.'/'.$udom.'.tab';
 5523:     if (-e $designfile) {
 5524:         if ( open (my $fh,"<$designfile") ) {
 5525:             while (my $line = <$fh>) {
 5526:                 next if ($line =~ /^\#/);
 5527:                 chomp($line);
 5528:                 my ($key,$val)=(split(/\=/,$line));
 5529:                 if ($val) { $legacyhash{$udom.'.'.$key}=$val; }
 5530:             }
 5531:             close($fh);
 5532:         }
 5533:     }
 5534:     if (-e $Apache::lonnet::perlvar{'lonDocRoot'}.'/adm/lonDomLogos/'.$udom.'.gif') {
 5535:         $legacyhash{$udom.'.login.domlogo'} = "/adm/lonDomLogos/$udom.gif";
 5536:     }
 5537:     return %legacyhash;
 5538: }
 5539: 
 5540: =pod
 5541: 
 5542: =item * &domainlogo()
 5543: 
 5544: Inputs: $domain (usually will be undef)
 5545: 
 5546: Returns: A link to a domain logo, if the domain logo exists.
 5547: If the domain logo does not exist, a description of the domain.
 5548: 
 5549: =cut
 5550: 
 5551: ###############################################
 5552: sub domainlogo {
 5553:     my $domain = &determinedomain(shift);
 5554:     my %designhash = &get_domainconf($domain);    
 5555:     # See if there is a logo
 5556:     if ($designhash{$domain.'.login.domlogo'} ne '') {
 5557:         my $imgsrc = $designhash{$domain.'.login.domlogo'};
 5558:         if ($imgsrc =~ m{^/(adm|res)/}) {
 5559: 	    if ($imgsrc =~ m{^/res/}) {
 5560: 		my $local_name = &Apache::lonnet::filelocation('',$imgsrc);
 5561: 		&Apache::lonnet::repcopy($local_name);
 5562: 	    }
 5563: 	   $imgsrc = &lonhttpdurl($imgsrc);
 5564:         } 
 5565:         return '<img src="'.$imgsrc.'" alt="'.$domain.'" />';
 5566:     } elsif (defined(&Apache::lonnet::domain($domain,'description'))) {
 5567:         return &Apache::lonnet::domain($domain,'description');
 5568:     } else {
 5569:         return '';
 5570:     }
 5571: }
 5572: ##############################################
 5573: 
 5574: =pod
 5575: 
 5576: =item * &designparm()
 5577: 
 5578: Inputs: $which parameter; $domain (usually will be undef)
 5579: 
 5580: Returns: value of designparamter $which
 5581: 
 5582: =cut
 5583: 
 5584: 
 5585: ##############################################
 5586: sub designparm {
 5587:     my ($which,$domain)=@_;
 5588:     if (exists($env{'environment.color.'.$which})) {
 5589:         return $env{'environment.color.'.$which};
 5590:     }
 5591:     $domain=&determinedomain($domain);
 5592:     my %domdesign;
 5593:     unless ($domain eq 'public') {
 5594:         %domdesign = &get_domainconf($domain);
 5595:     }
 5596:     my $output;
 5597:     if ($domdesign{$domain.'.'.$which} ne '') {
 5598:         $output = $domdesign{$domain.'.'.$which};
 5599:     } else {
 5600:         $output = $defaultdesign{$which};
 5601:     }
 5602:     if (($which =~ /^(student|coordinator|author|admin)\.img$/) ||
 5603:         ($which =~ /login\.(img|logo|domlogo|login)/)) {
 5604:         if ($output =~ m{^/(adm|res)/}) {
 5605:             if ($output =~ m{^/res/}) {
 5606:                 my $local_name = &Apache::lonnet::filelocation('',$output);
 5607:                 &Apache::lonnet::repcopy($local_name);
 5608:             }
 5609:             $output = &lonhttpdurl($output);
 5610:         }
 5611:     }
 5612:     return $output;
 5613: }
 5614: 
 5615: ##############################################
 5616: =pod
 5617: 
 5618: =item * &authorspace()
 5619: 
 5620: Inputs: $url (usually will be undef).
 5621: 
 5622: Returns: Path to Authoring Space containing the resource or 
 5623:          directory being viewed (or for which action is being taken). 
 5624:          If $url is provided, and begins /priv/<domain>/<uname>
 5625:          the path will be that portion of the $context argument.
 5626:          Otherwise the path will be for the author space of the current
 5627:          user when the current role is author, or for that of the 
 5628:          co-author/assistant co-author space when the current role 
 5629:          is co-author or assistant co-author.
 5630: 
 5631: =cut
 5632: 
 5633: sub authorspace {
 5634:     my ($url) = @_;
 5635:     if ($url ne '') {
 5636:         if ($url =~ m{^(/priv/$match_domain/$match_username/)}) {
 5637:            return $1;
 5638:         }
 5639:     }
 5640:     my $caname = '';
 5641:     my $cadom = '';
 5642:     if ($env{'request.role'} =~ /^(?:ca|aa)/) {
 5643:         ($cadom,$caname) =
 5644:             ($env{'request.role'}=~/($match_domain)\/($match_username)$/);
 5645:     } elsif ($env{'request.role'} =~ m{^au\./($match_domain)/}) {
 5646:         $caname = $env{'user.name'};
 5647:         $cadom = $env{'user.domain'};
 5648:     }
 5649:     if (($caname ne '') && ($cadom ne '')) {
 5650:         return "/priv/$cadom/$caname/";
 5651:     }
 5652:     return;
 5653: }
 5654: 
 5655: ##############################################
 5656: =pod
 5657: 
 5658: =item * &head_subbox()
 5659: 
 5660: Inputs: $content (contains HTML code with page functions, etc.)
 5661: 
 5662: Returns: HTML div with $content
 5663:          To be included in page header
 5664: 
 5665: =cut
 5666: 
 5667: sub head_subbox {
 5668:     my ($content)=@_;
 5669:     my $output =
 5670:         '<div class="LC_head_subbox">'
 5671:        .$content
 5672:        .'</div>'
 5673: }
 5674: 
 5675: ##############################################
 5676: =pod
 5677: 
 5678: =item * &CSTR_pageheader()
 5679: 
 5680: Input: (optional) filename from which breadcrumb trail is built.
 5681:        In most cases no input as needed, as $env{'request.filename'}
 5682:        is appropriate for use in building the breadcrumb trail.
 5683: 
 5684: Returns: HTML div with CSTR path and recent box
 5685:          To be included on Authoring Space pages
 5686: 
 5687: =cut
 5688: 
 5689: sub CSTR_pageheader {
 5690:     my ($trailfile) = @_;
 5691:     if ($trailfile eq '') {
 5692:         $trailfile = $env{'request.filename'};
 5693:     }
 5694: 
 5695: # this is for resources; directories have customtitle, and crumbs
 5696: # and select recent are created in lonpubdir.pm
 5697: 
 5698:     my $londocroot = $Apache::lonnet::perlvar{'lonDocRoot'};
 5699:     my ($udom,$uname,$thisdisfn)=
 5700:         ($trailfile =~ m{^\Q$londocroot\E/priv/([^/]+)/([^/]+)(?:|/(.*))$});
 5701:     my $formaction = "/priv/$udom/$uname/$thisdisfn";
 5702:     $formaction =~ s{/+}{/}g;
 5703: 
 5704:     my $parentpath = '';
 5705:     my $lastitem = '';
 5706:     if ($thisdisfn =~ m-(.+/)([^/]*)$-) {
 5707:         $parentpath = $1;
 5708:         $lastitem = $2;
 5709:     } else {
 5710:         $lastitem = $thisdisfn;
 5711:     }
 5712: 
 5713:     my ($crsauthor,$title);
 5714:     if (($env{'request.course.id'}) &&
 5715:         ($env{'course.'.$env{'request.course.id'}.'.num'} eq $uname) &&
 5716:         ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom)) {
 5717:         $crsauthor = 1;
 5718:         $title = &mt('Course Authoring Space');
 5719:     } else {
 5720:         $title = &mt('Authoring Space');
 5721:     }
 5722: 
 5723:     my $output =
 5724:          '<div>'
 5725:         .&Apache::loncommon::help_open_menu('','',3,'Authoring') #FIXME: Broken? Where is it?
 5726:         .'<b>'.$title.'</b> '
 5727:         .'<form name="dirs" method="post" action="'.$formaction
 5728:         .'" target="_top">' #FIXME lonpubdir: target="_parent"
 5729:         .&Apache::lonhtmlcommon::crumbs($uname.'/'.$parentpath,'_top','/priv/'.$udom,undef,undef);
 5730: 
 5731:     if ($lastitem) {
 5732:         $output .=
 5733:              '<span class="LC_filename">'
 5734:             .$lastitem
 5735:             .'</span>';
 5736:     }
 5737: 
 5738:     if ($crsauthor) {
 5739:         $output .= '</form>'.&Apache::lonmenu::constspaceform();
 5740:     } else {
 5741:         $output .=
 5742:              '<br />'
 5743:             #FIXME lonpubdir: &Apache::lonhtmlcommon::crumbs($uname.$thisdisfn.'/','_top','/priv','','+1',1)."</b></tt><br />"
 5744:             .&Apache::lonhtmlcommon::select_recent('construct','recent','this.form.action=this.form.recent.value;this.form.submit()')
 5745:             .'</form>'
 5746:             .&Apache::lonmenu::constspaceform();
 5747:     }
 5748:     $output .= '</div>';
 5749: 
 5750:     return $output;
 5751: }
 5752: 
 5753: ###############################################
 5754: ###############################################
 5755: 
 5756: =pod
 5757: 
 5758: =back
 5759: 
 5760: =head1 HTML Helpers
 5761: 
 5762: =over 4
 5763: 
 5764: =item * &bodytag()
 5765: 
 5766: Returns a uniform header for LON-CAPA web pages.
 5767: 
 5768: Inputs: 
 5769: 
 5770: =over 4
 5771: 
 5772: =item * $title, A title to be displayed on the page.
 5773: 
 5774: =item * $function, the current role (can be undef).
 5775: 
 5776: =item * $addentries, extra parameters for the <body> tag.
 5777: 
 5778: =item * $bodyonly, if defined, only return the <body> tag.
 5779: 
 5780: =item * $domain, if defined, force a given domain.
 5781: 
 5782: =item * $forcereg, if page should register as content page (relevant for 
 5783:             text interface only)
 5784: 
 5785: =item * $no_nav_bar, if true, keep the 'what is this' info but remove the
 5786:                      navigational links
 5787: 
 5788: =item * $bgcolor, used to override the bgcolor on a webpage to a specific value
 5789: 
 5790: =item * $args, optional argument valid values are
 5791:             no_auto_mt_title -> prevents &mt()ing the title arg
 5792: 
 5793: =item * $advtoolsref, optional argument, ref to an array containing
 5794:             inlineremote items to be added in "Functions" menu below
 5795:             breadcrumbs.
 5796: 
 5797: =back
 5798: 
 5799: Returns: A uniform header for LON-CAPA web pages.  
 5800: If $bodyonly is nonzero, a string containing a <body> tag will be returned.
 5801: If $bodyonly is undef or zero, an html string containing a <body> tag and 
 5802: other decorations will be returned.
 5803: 
 5804: =cut
 5805: 
 5806: sub bodytag {
 5807:     my ($title,$function,$addentries,$bodyonly,$domain,$forcereg,
 5808:         $no_nav_bar,$bgcolor,$args,$advtoolsref)=@_;
 5809: 
 5810:     my $public;
 5811:     if ((($env{'user.name'} eq 'public') && ($env{'user.domain'} eq 'public'))
 5812:         || ($env{'user.name'} eq '') && ($env{'user.domain'} eq '')) {
 5813:         $public = 1;
 5814:     }
 5815:     if (!$args->{'no_auto_mt_title'}) { $title = &mt($title); }
 5816:     my $httphost = $args->{'use_absolute'};
 5817: 
 5818:     $function = &get_users_function() if (!$function);
 5819:     my $img =    &designparm($function.'.img',$domain);
 5820:     my $font =   &designparm($function.'.font',$domain);
 5821:     my $pgbg   = $bgcolor || &designparm($function.'.pgbg',$domain);
 5822: 
 5823:     my %design = ( 'style'   => 'margin-top: 0',
 5824: 		   'bgcolor' => $pgbg,
 5825: 		   'text'    => $font,
 5826:                    'alink'   => &designparm($function.'.alink',$domain),
 5827: 		   'vlink'   => &designparm($function.'.vlink',$domain),
 5828: 		   'link'    => &designparm($function.'.link',$domain),);
 5829:     @design{keys(%$addentries)} = @$addentries{keys(%$addentries)}; 
 5830: 
 5831:  # role and realm
 5832:     my ($role,$realm) = split(m{\./},$env{'request.role'},2);
 5833:     if ($realm) {
 5834:         $realm = '/'.$realm;
 5835:     }
 5836:     if ($role  eq 'ca') {
 5837:         my ($rdom,$rname) = ($realm =~ m{^/($match_domain)/($match_username)$});
 5838:         $realm = &plainname($rname,$rdom);
 5839:     } 
 5840: # realm
 5841:     if ($env{'request.course.id'}) {
 5842:         if ($env{'request.role'} !~ /^cr/) {
 5843:             $role = &Apache::lonnet::plaintext($role,&course_type());
 5844:         }
 5845:         if ($env{'request.course.sec'}) {
 5846:             $role .= ('&nbsp;'x2).'-&nbsp;'.&mt('section:').'&nbsp;'.$env{'request.course.sec'};
 5847:         }   
 5848: 	$realm = $env{'course.'.$env{'request.course.id'}.'.description'};
 5849:     } else {
 5850:         $role = &Apache::lonnet::plaintext($role);
 5851:     }
 5852: 
 5853:     if (!$realm) { $realm='&nbsp;'; }
 5854: 
 5855:     my $extra_body_attr = &make_attr_string($forcereg,\%design);
 5856: 
 5857: # construct main body tag
 5858:     my $bodytag = "<body $extra_body_attr>".
 5859: 	&Apache::lontexconvert::init_math_support();
 5860: 
 5861:     &get_unprocessed_cgi($ENV{'QUERY_STRING'}, ['inhibitmenu']);
 5862: 
 5863:     if (($bodyonly) || ($no_nav_bar) || ($env{'form.inhibitmenu'} eq 'yes')) {
 5864:         return $bodytag;
 5865:     }
 5866: 
 5867:     if ($public) {
 5868: 	undef($role);
 5869:     }
 5870:     
 5871:     my $titleinfo = '<h1>'.$title.'</h1>';
 5872:     #
 5873:     # Extra info if you are the DC
 5874:     my $dc_info = '';
 5875:     if ($env{'user.adv'} && exists($env{'user.role.dc./'.
 5876:                         $env{'course.'.$env{'request.course.id'}.
 5877:                                  '.domain'}.'/'})) {
 5878:         my $cid = $env{'request.course.id'};
 5879:         $dc_info = $cid.' '.$env{'course.'.$cid.'.internal.coursecode'};
 5880:         $dc_info =~ s/\s+$//;
 5881:     }
 5882: 
 5883:     my $crstype;
 5884:     if ($env{'request.course.id'}) {
 5885:         $crstype = $env{'course.'.$env{'request.course.id'}.'.type'};
 5886:     } elsif ($args->{'crstype'}) {
 5887:         $crstype = $args->{'crstype'};
 5888:     }
 5889:     if (($crstype eq 'Placement') && (!$env{'request.role.adv'})) {
 5890:         undef($role);
 5891:     } else {
 5892:         $role = '<span class="LC_nobreak">('.$role.')</span>' if ($role && !$env{'browser.mobile'});
 5893:     }
 5894: 
 5895:         if ($env{'request.state'} eq 'construct') { $forcereg=1; }
 5896: 
 5897:         #    if ($env{'request.state'} eq 'construct') {
 5898:         #        $titleinfo = &CSTR_pageheader(); #FIXME: Will be removed once all scripts have their own calls
 5899:         #    }
 5900: 
 5901:         $bodytag .= Apache::lonhtmlcommon::scripttag(
 5902:             Apache::lonmenu::utilityfunctions($httphost), 'start');
 5903: 
 5904:         my ($left,$right) = Apache::lonmenu::primary_menu($crstype);
 5905: 
 5906:         if ($env{'request.noversionuri'} =~ m{^/res/adm/pages/}) {
 5907:              if ($dc_info) {
 5908:                  $dc_info = qq|<span class="LC_cusr_subheading">$dc_info</span>|;
 5909:              }
 5910:              $bodytag .= qq|<div id="LC_nav_bar">$left $role<br />
 5911:                 <em>$realm</em> $dc_info</div>|;
 5912:             return $bodytag;
 5913:         }
 5914: 
 5915:         unless ($env{'request.symb'} =~ m/\.page___\d+___/) {
 5916:             $bodytag .= qq|<div id="LC_nav_bar">$left $role</div>|;
 5917:         }
 5918: 
 5919:         $bodytag .= $right;
 5920: 
 5921:         if ($dc_info) {
 5922:             $dc_info = &dc_courseid_toggle($dc_info);
 5923:         }
 5924:         $bodytag .= qq|<div id="LC_realm">$realm $dc_info</div>|;
 5925: 
 5926:         #if directed to not display the secondary menu, don't.  
 5927:         if ($args->{'no_secondary_menu'}) {
 5928:             return $bodytag;
 5929:         }
 5930:         #don't show menus for public users
 5931:         if (!$public){
 5932:             $bodytag .= Apache::lonmenu::secondary_menu($httphost);
 5933:             $bodytag .= Apache::lonmenu::serverform();
 5934:             $bodytag .= Apache::lonhtmlcommon::scripttag('', 'end');
 5935:             if ($env{'request.state'} eq 'construct') {
 5936:                 $bodytag .= &Apache::lonmenu::innerregister($forcereg,
 5937:                                 $args->{'bread_crumbs'});
 5938:             } elsif ($forcereg) {
 5939:                 $bodytag .= &Apache::lonmenu::innerregister($forcereg,undef,
 5940:                                                             $args->{'group'});
 5941:             } else {
 5942:                 $bodytag .= 
 5943:                     &Apache::lonmenu::prepare_functions($env{'request.noversionuri'},
 5944:                                                         $forcereg,$args->{'group'},
 5945:                                                         $args->{'bread_crumbs'},
 5946:                                                         $advtoolsref);
 5947:             }
 5948:         }else{
 5949:             # this is to seperate menu from content when there's no secondary
 5950:             # menu. Especially needed for public accessible ressources.
 5951:             $bodytag .= '<hr style="clear:both" />';
 5952:             $bodytag .= Apache::lonhtmlcommon::scripttag('', 'end'); 
 5953:         }
 5954: 
 5955:         return $bodytag;
 5956: }
 5957: 
 5958: sub dc_courseid_toggle {
 5959:     my ($dc_info) = @_;
 5960:     return ' <span id="dccidtext" class="LC_cusr_subheading LC_nobreak">'.
 5961:            '<a href="javascript:showCourseID();" class="LC_menubuttons_link">'.
 5962:            &mt('(More ...)').'</a></span>'.
 5963:            '<div id="dccid" class="LC_dccid">'.$dc_info.'</div>';
 5964: }
 5965: 
 5966: sub make_attr_string {
 5967:     my ($register,$attr_ref) = @_;
 5968: 
 5969:     if ($attr_ref && !ref($attr_ref)) {
 5970: 	die("addentries Must be a hash ref ".
 5971: 	    join(':',caller(1))." ".
 5972: 	    join(':',caller(0))." ");
 5973:     }
 5974: 
 5975:     if ($register) {
 5976: 	my ($on_load,$on_unload);
 5977: 	foreach my $key (keys(%{$attr_ref})) {
 5978: 	    if      (lc($key) eq 'onload') {
 5979: 		$on_load.=$attr_ref->{$key}.';';
 5980: 		delete($attr_ref->{$key});
 5981: 
 5982: 	    } elsif (lc($key) eq 'onunload') {
 5983: 		$on_unload.=$attr_ref->{$key}.';';
 5984: 		delete($attr_ref->{$key});
 5985: 	    }
 5986: 	}
 5987: 	$attr_ref->{'onload'}  = $on_load;
 5988: 	$attr_ref->{'onunload'}= $on_unload;
 5989:     }
 5990: 
 5991:     my $attr_string;
 5992:     foreach my $attr (sort(keys(%$attr_ref))) {
 5993: 	$attr_string .= " $attr=\"".$attr_ref->{$attr}.'" ';
 5994:     }
 5995:     return $attr_string;
 5996: }
 5997: 
 5998: 
 5999: ###############################################
 6000: ###############################################
 6001: 
 6002: =pod
 6003: 
 6004: =item * &endbodytag()
 6005: 
 6006: Returns a uniform footer for LON-CAPA web pages.
 6007: 
 6008: Inputs: 1 - optional reference to an args hash
 6009: If in the hash, key for noredirectlink has a value which evaluates to true,
 6010: a 'Continue' link is not displayed if the page contains an
 6011: internal redirect in the <head></head> section,
 6012: i.e., $env{'internal.head.redirect'} exists   
 6013: 
 6014: =cut
 6015: 
 6016: sub endbodytag {
 6017:     my ($args) = @_;
 6018:     my $endbodytag;
 6019:     unless ((ref($args) eq 'HASH') && ($args->{'notbody'})) {
 6020:         $endbodytag='</body>';
 6021:     }
 6022:     if ( exists( $env{'internal.head.redirect'} ) ) {
 6023:         if (!(ref($args) eq 'HASH' && $args->{'noredirectlink'})) {
 6024: 	    $endbodytag=
 6025: 	        "<br /><a href=\"$env{'internal.head.redirect'}\">".
 6026: 	        &mt('Continue').'</a>'.
 6027: 	        $endbodytag;
 6028:         }
 6029:     }
 6030:     return $endbodytag;
 6031: }
 6032: 
 6033: =pod
 6034: 
 6035: =item * &standard_css()
 6036: 
 6037: Returns a style sheet
 6038: 
 6039: Inputs: (all optional)
 6040:             domain         -> force to color decorate a page for a specific
 6041:                                domain
 6042:             function       -> force usage of a specific rolish color scheme
 6043:             bgcolor        -> override the default page bgcolor
 6044: 
 6045: =cut
 6046: 
 6047: sub standard_css {
 6048:     my ($function,$domain,$bgcolor) = @_;
 6049:     $function  = &get_users_function() if (!$function);
 6050:     my $img    = &designparm($function.'.img',   $domain);
 6051:     my $tabbg  = &designparm($function.'.tabbg', $domain);
 6052:     my $font   = &designparm($function.'.font',  $domain);
 6053:     my $fontmenu = &designparm($function.'.fontmenu', $domain);
 6054: #second colour for later usage
 6055:     my $sidebg = &designparm($function.'.sidebg',$domain);
 6056:     my $pgbg_or_bgcolor =
 6057: 	         $bgcolor ||
 6058: 	         &designparm($function.'.pgbg',  $domain);
 6059:     my $pgbg   = &designparm($function.'.pgbg',  $domain);
 6060:     my $alink  = &designparm($function.'.alink', $domain);
 6061:     my $vlink  = &designparm($function.'.vlink', $domain);
 6062:     my $link   = &designparm($function.'.link',  $domain);
 6063: 
 6064:     my $sans                 = 'Verdana,Arial,Helvetica,sans-serif';
 6065:     my $mono                 = 'monospace';
 6066:     my $data_table_head      = $sidebg;
 6067:     my $data_table_light     = '#FAFAFA';
 6068:     my $data_table_dark      = '#E0E0E0';
 6069:     my $data_table_darker    = '#CCCCCC';
 6070:     my $data_table_highlight = '#FFFF00';
 6071:     my $mail_new             = '#FFBB77';
 6072:     my $mail_new_hover       = '#DD9955';
 6073:     my $mail_read            = '#BBBB77';
 6074:     my $mail_read_hover      = '#999944';
 6075:     my $mail_replied         = '#AAAA88';
 6076:     my $mail_replied_hover   = '#888855';
 6077:     my $mail_other           = '#99BBBB';
 6078:     my $mail_other_hover     = '#669999';
 6079:     my $table_header         = '#DDDDDD';
 6080:     my $feedback_link_bg     = '#BBBBBB';
 6081:     my $lg_border_color      = '#C8C8C8';
 6082:     my $button_hover         = '#BF2317';
 6083: 
 6084:     my $border = ($env{'browser.type'} eq 'explorer' ||
 6085:       $env{'browser.type'} eq 'safari'     ) ? '0 2px 0 2px'
 6086:                                              : '0 3px 0 4px';
 6087: 
 6088: 
 6089:     return <<END;
 6090: 
 6091: /* needed for iframe to allow 100% height in FF */
 6092: body, html { 
 6093:     margin: 0;
 6094:     padding: 0 0.5%;
 6095:     height: 99%; /* to avoid scrollbars */
 6096: }
 6097: 
 6098: body {
 6099:   font-family: $sans;
 6100:   line-height:130%;
 6101:   font-size:0.83em;
 6102:   color:$font;
 6103: }
 6104: 
 6105: a:focus,
 6106: a:focus img {
 6107:   color: red;
 6108: }
 6109: 
 6110: form, .inline {
 6111:   display: inline;
 6112: }
 6113: 
 6114: .LC_right {
 6115:   text-align:right;
 6116: }
 6117: 
 6118: .LC_middle {
 6119:   vertical-align:middle;
 6120: }
 6121: 
 6122: .LC_floatleft {
 6123:   float: left;
 6124: }
 6125: 
 6126: .LC_floatright {
 6127:   float: right;
 6128: }
 6129: 
 6130: .LC_400Box {
 6131:   width:400px;
 6132: }
 6133: 
 6134: .LC_iframecontainer {
 6135:     width: 98%;
 6136:     margin: 0;
 6137:     position: fixed;
 6138:     top: 8.5em;
 6139:     bottom: 0;
 6140: }
 6141: 
 6142: .LC_iframecontainer iframe{
 6143:     border: none;
 6144:     width: 100%;
 6145:     height: 100%;
 6146: }
 6147: 
 6148: .LC_filename {
 6149:   font-family: $mono;
 6150:   white-space:pre;
 6151:   font-size: 120%;
 6152: }
 6153: 
 6154: .LC_fileicon {
 6155:   border: none;
 6156:   height: 1.3em;
 6157:   vertical-align: text-bottom;
 6158:   margin-right: 0.3em;
 6159:   text-decoration:none;
 6160: }
 6161: 
 6162: .LC_setting {
 6163:   text-decoration:underline;
 6164: }
 6165: 
 6166: .LC_error {
 6167:   color: red;
 6168: }
 6169: 
 6170: .LC_warning {
 6171:   color: darkorange;
 6172: }
 6173: 
 6174: .LC_diff_removed {
 6175:   color: red;
 6176: }
 6177: 
 6178: .LC_info,
 6179: .LC_success,
 6180: .LC_diff_added {
 6181:   color: green;
 6182: }
 6183: 
 6184: div.LC_confirm_box {
 6185:   background-color: #FAFAFA;
 6186:   border: 1px solid $lg_border_color;
 6187:   margin-right: 0;
 6188:   padding: 5px;
 6189: }
 6190: 
 6191: div.LC_confirm_box .LC_error img,
 6192: div.LC_confirm_box .LC_success img {
 6193:   vertical-align: middle;
 6194: }
 6195: 
 6196: .LC_maxwidth {
 6197:   max-width: 100%;
 6198:   height: auto;
 6199: }
 6200: 
 6201: .LC_textsize_mobile {
 6202:   \@media only screen and (max-device-width: 480px) {
 6203:       -webkit-text-size-adjust:100%; -moz-text-size-adjust:100%; -ms-text-size-adjust:100%;
 6204:   }
 6205: }
 6206: 
 6207: .LC_icon {
 6208:   border: none;
 6209:   vertical-align: middle;
 6210: }
 6211: 
 6212: .LC_docs_spacer {
 6213:   width: 25px;
 6214:   height: 1px;
 6215:   border: none;
 6216: }
 6217: 
 6218: .LC_internal_info {
 6219:   color: #999999;
 6220: }
 6221: 
 6222: .LC_discussion {
 6223:   background: $data_table_dark;
 6224:   border: 1px solid black;
 6225:   margin: 2px;
 6226: }
 6227: 
 6228: .LC_disc_action_left {
 6229:   background: $sidebg;
 6230:   text-align: left;
 6231:   padding: 4px;
 6232:   margin: 2px;
 6233: }
 6234: 
 6235: .LC_disc_action_right {
 6236:   background: $sidebg;
 6237:   text-align: right;
 6238:   padding: 4px;
 6239:   margin: 2px;
 6240: }
 6241: 
 6242: .LC_disc_new_item {
 6243:   background: white;
 6244:   border: 2px solid red;
 6245:   margin: 4px;
 6246:   padding: 4px;
 6247: }
 6248: 
 6249: .LC_disc_old_item {
 6250:   background: white;
 6251:   margin: 4px;
 6252:   padding: 4px;
 6253: }
 6254: 
 6255: table.LC_pastsubmission {
 6256:   border: 1px solid black;
 6257:   margin: 2px;
 6258: }
 6259: 
 6260: table#LC_menubuttons {
 6261:   width: 100%;
 6262:   background: $pgbg;
 6263:   border: 2px;
 6264:   border-collapse: separate;
 6265:   padding: 0;
 6266: }
 6267: 
 6268: table#LC_title_bar a {
 6269:   color: $fontmenu;
 6270: }
 6271: 
 6272: table#LC_title_bar {
 6273:   clear: both;
 6274:   display: none;
 6275: }
 6276: 
 6277: table#LC_title_bar,
 6278: table.LC_breadcrumbs, /* obsolete? */
 6279: table#LC_title_bar.LC_with_remote {
 6280:   width: 100%;
 6281:   border-color: $pgbg;
 6282:   border-style: solid;
 6283:   border-width: $border;
 6284:   background: $pgbg;
 6285:   color: $fontmenu;
 6286:   border-collapse: collapse;
 6287:   padding: 0;
 6288:   margin: 0;
 6289: }
 6290: 
 6291: ul.LC_breadcrumb_tools_outerlist {
 6292:     margin: 0;
 6293:     padding: 0;
 6294:     position: relative;
 6295:     list-style: none;
 6296: }
 6297: ul.LC_breadcrumb_tools_outerlist li {
 6298:     display: inline;
 6299: }
 6300: 
 6301: .LC_breadcrumb_tools_navigation {
 6302:     padding: 0;
 6303:     margin: 0;
 6304:     float: left;
 6305: }
 6306: .LC_breadcrumb_tools_tools {
 6307:     padding: 0;
 6308:     margin: 0;
 6309:     float: right;
 6310: }
 6311: 
 6312: .LC_placement_prog {
 6313:     padding-right: 20px;
 6314:     font-weight: bold;
 6315:     font-size: 90%;
 6316: }
 6317: 
 6318: table#LC_title_bar td {
 6319:   background: $tabbg;
 6320: }
 6321: 
 6322: table#LC_menubuttons img {
 6323:   border: none;
 6324: }
 6325: 
 6326: .LC_breadcrumbs_component {
 6327:   float: right;
 6328:   margin: 0 1em;
 6329: }
 6330: .LC_breadcrumbs_component img {
 6331:   vertical-align: middle;
 6332: }
 6333: 
 6334: .LC_breadcrumbs_hoverable {
 6335:   background: $sidebg;
 6336: }
 6337: 
 6338: td.LC_table_cell_checkbox {
 6339:   text-align: center;
 6340: }
 6341: 
 6342: .LC_fontsize_small {
 6343:   font-size: 70%;
 6344: }
 6345: 
 6346: #LC_breadcrumbs {
 6347:   clear:both;
 6348:   background: $sidebg;
 6349:   border-bottom: 1px solid $lg_border_color;
 6350:   line-height: 2.5em;
 6351:   overflow: hidden;
 6352:   margin: 0;
 6353:   padding: 0;
 6354:   text-align: left;
 6355: }
 6356: 
 6357: .LC_head_subbox, .LC_actionbox {
 6358:   clear:both;
 6359:   background: #F8F8F8; /* $sidebg; */
 6360:   border: 1px solid $sidebg;
 6361:   margin: 0 0 10px 0;
 6362:   padding: 3px;
 6363:   text-align: left;
 6364: }
 6365: 
 6366: .LC_fontsize_medium {
 6367:   font-size: 85%;
 6368: }
 6369: 
 6370: .LC_fontsize_large {
 6371:   font-size: 120%;
 6372: }
 6373: 
 6374: .LC_menubuttons_inline_text {
 6375:   color: $font;
 6376:   font-size: 90%;
 6377:   padding-left:3px;
 6378: }
 6379: 
 6380: .LC_menubuttons_inline_text img{
 6381:   vertical-align: middle;
 6382: }
 6383: 
 6384: li.LC_menubuttons_inline_text img {
 6385:   cursor:pointer;
 6386:   text-decoration: none;
 6387: }
 6388: 
 6389: .LC_menubuttons_link {
 6390:   text-decoration: none;
 6391: }
 6392: 
 6393: .LC_menubuttons_category {
 6394:   color: $font;
 6395:   background: $pgbg;
 6396:   font-size: larger;
 6397:   font-weight: bold;
 6398: }
 6399: 
 6400: td.LC_menubuttons_text {
 6401:   color: $font;
 6402: }
 6403: 
 6404: .LC_current_location {
 6405:   background: $tabbg;
 6406: }
 6407: 
 6408: table.LC_data_table {
 6409:   border: 1px solid #000000;
 6410:   border-collapse: separate;
 6411:   border-spacing: 1px;
 6412:   background: $pgbg;
 6413: }
 6414: 
 6415: .LC_data_table_dense {
 6416:   font-size: small;
 6417: }
 6418: 
 6419: table.LC_nested_outer {
 6420:   border: 1px solid #000000;
 6421:   border-collapse: collapse;
 6422:   border-spacing: 0;
 6423:   width: 100%;
 6424: }
 6425: 
 6426: table.LC_innerpickbox,
 6427: table.LC_nested {
 6428:   border: none;
 6429:   border-collapse: collapse;
 6430:   border-spacing: 0;
 6431:   width: 100%;
 6432: }
 6433: 
 6434: table.LC_data_table tr th,
 6435: table.LC_calendar tr th,
 6436: table.LC_prior_tries tr th,
 6437: table.LC_innerpickbox tr th {
 6438:   font-weight: bold;
 6439:   background-color: $data_table_head;
 6440:   color:$fontmenu;
 6441:   font-size:90%;
 6442: }
 6443: 
 6444: table.LC_innerpickbox tr th,
 6445: table.LC_innerpickbox tr td {
 6446:   vertical-align: top;
 6447: }
 6448: 
 6449: table.LC_data_table tr.LC_info_row > td {
 6450:   background-color: #CCCCCC;
 6451:   font-weight: bold;
 6452:   text-align: left;
 6453: }
 6454: 
 6455: table.LC_data_table tr.LC_odd_row > td {
 6456:   background-color: $data_table_light;
 6457:   padding: 2px;
 6458:   vertical-align: top;
 6459: }
 6460: 
 6461: table.LC_pick_box tr > td.LC_odd_row {
 6462:   background-color: $data_table_light;
 6463:   vertical-align: top;
 6464: }
 6465: 
 6466: table.LC_data_table tr.LC_even_row > td {
 6467:   background-color: $data_table_dark;
 6468:   padding: 2px;
 6469:   vertical-align: top;
 6470: }
 6471: 
 6472: table.LC_pick_box tr > td.LC_even_row {
 6473:   background-color: $data_table_dark;
 6474:   vertical-align: top;
 6475: }
 6476: 
 6477: table.LC_data_table tr.LC_data_table_highlight td {
 6478:   background-color: $data_table_darker;
 6479: }
 6480: 
 6481: table.LC_data_table tr td.LC_leftcol_header {
 6482:   background-color: $data_table_head;
 6483:   font-weight: bold;
 6484: }
 6485: 
 6486: table.LC_data_table tr.LC_empty_row td,
 6487: table.LC_nested tr.LC_empty_row td {
 6488:   font-weight: bold;
 6489:   font-style: italic;
 6490:   text-align: center;
 6491:   padding: 8px;
 6492: }
 6493: 
 6494: table.LC_data_table tr.LC_empty_row td,
 6495: table.LC_data_table tr.LC_footer_row td {
 6496:   background-color: $sidebg;
 6497: }
 6498: 
 6499: table.LC_nested tr.LC_empty_row td {
 6500:   background-color: #FFFFFF;
 6501: }
 6502: 
 6503: table.LC_caption {
 6504: }
 6505: 
 6506: table.LC_nested tr.LC_empty_row td {
 6507:   padding: 4ex
 6508: }
 6509: 
 6510: table.LC_nested_outer tr th {
 6511:   font-weight: bold;
 6512:   color:$fontmenu;
 6513:   background-color: $data_table_head;
 6514:   font-size: small;
 6515:   border-bottom: 1px solid #000000;
 6516: }
 6517: 
 6518: table.LC_nested_outer tr td.LC_subheader {
 6519:   background-color: $data_table_head;
 6520:   font-weight: bold;
 6521:   font-size: small;
 6522:   border-bottom: 1px solid #000000;
 6523:   text-align: right;
 6524: }
 6525: 
 6526: table.LC_nested tr.LC_info_row td {
 6527:   background-color: #CCCCCC;
 6528:   font-weight: bold;
 6529:   font-size: small;
 6530:   text-align: center;
 6531: }
 6532: 
 6533: table.LC_nested tr.LC_info_row td.LC_left_item,
 6534: table.LC_nested_outer tr th.LC_left_item {
 6535:   text-align: left;
 6536: }
 6537: 
 6538: table.LC_nested td {
 6539:   background-color: #FFFFFF;
 6540:   font-size: small;
 6541: }
 6542: 
 6543: table.LC_nested_outer tr th.LC_right_item,
 6544: table.LC_nested tr.LC_info_row td.LC_right_item,
 6545: table.LC_nested tr.LC_odd_row td.LC_right_item,
 6546: table.LC_nested tr td.LC_right_item {
 6547:   text-align: right;
 6548: }
 6549: 
 6550: table.LC_nested tr.LC_odd_row td {
 6551:   background-color: #EEEEEE;
 6552: }
 6553: 
 6554: table.LC_createuser {
 6555: }
 6556: 
 6557: table.LC_createuser tr.LC_section_row td {
 6558:   font-size: small;
 6559: }
 6560: 
 6561: table.LC_createuser tr.LC_info_row td  {
 6562:   background-color: #CCCCCC;
 6563:   font-weight: bold;
 6564:   text-align: center;
 6565: }
 6566: 
 6567: table.LC_calendar {
 6568:   border: 1px solid #000000;
 6569:   border-collapse: collapse;
 6570:   width: 98%;
 6571: }
 6572: 
 6573: table.LC_calendar_pickdate {
 6574:   font-size: xx-small;
 6575: }
 6576: 
 6577: table.LC_calendar tr td {
 6578:   border: 1px solid #000000;
 6579:   vertical-align: top;
 6580:   width: 14%;
 6581: }
 6582: 
 6583: table.LC_calendar tr td.LC_calendar_day_empty {
 6584:   background-color: $data_table_dark;
 6585: }
 6586: 
 6587: table.LC_calendar tr td.LC_calendar_day_current {
 6588:   background-color: $data_table_highlight;
 6589: }
 6590: 
 6591: table.LC_data_table tr td.LC_mail_new {
 6592:   background-color: $mail_new;
 6593: }
 6594: 
 6595: table.LC_data_table tr.LC_mail_new:hover {
 6596:   background-color: $mail_new_hover;
 6597: }
 6598: 
 6599: table.LC_data_table tr td.LC_mail_read {
 6600:   background-color: $mail_read;
 6601: }
 6602: 
 6603: /*
 6604: table.LC_data_table tr.LC_mail_read:hover {
 6605:   background-color: $mail_read_hover;
 6606: }
 6607: */
 6608: 
 6609: table.LC_data_table tr td.LC_mail_replied {
 6610:   background-color: $mail_replied;
 6611: }
 6612: 
 6613: /*
 6614: table.LC_data_table tr.LC_mail_replied:hover {
 6615:   background-color: $mail_replied_hover;
 6616: }
 6617: */
 6618: 
 6619: table.LC_data_table tr td.LC_mail_other {
 6620:   background-color: $mail_other;
 6621: }
 6622: 
 6623: /*
 6624: table.LC_data_table tr.LC_mail_other:hover {
 6625:   background-color: $mail_other_hover;
 6626: }
 6627: */
 6628: 
 6629: table.LC_data_table tr > td.LC_browser_file,
 6630: table.LC_data_table tr > td.LC_browser_file_published {
 6631:   background: #AAEE77;
 6632: }
 6633: 
 6634: table.LC_data_table tr > td.LC_browser_file_locked,
 6635: table.LC_data_table tr > td.LC_browser_file_unpublished {
 6636:   background: #FFAA99;
 6637: }
 6638: 
 6639: table.LC_data_table tr > td.LC_browser_file_obsolete {
 6640:   background: #888888;
 6641: }
 6642: 
 6643: table.LC_data_table tr > td.LC_browser_file_modified,
 6644: table.LC_data_table tr > td.LC_browser_file_metamodified {
 6645:   background: #F8F866;
 6646: }
 6647: 
 6648: table.LC_data_table tr.LC_browser_folder > td {
 6649:   background: #E0E8FF;
 6650: }
 6651: 
 6652: table.LC_data_table tr > td.LC_roles_is {
 6653:   /* background: #77FF77; */
 6654: }
 6655: 
 6656: table.LC_data_table tr > td.LC_roles_future {
 6657:   border-right: 8px solid #FFFF77;
 6658: }
 6659: 
 6660: table.LC_data_table tr > td.LC_roles_will {
 6661:   border-right: 8px solid #FFAA77;
 6662: }
 6663: 
 6664: table.LC_data_table tr > td.LC_roles_expired {
 6665:   border-right: 8px solid #FF7777;
 6666: }
 6667: 
 6668: table.LC_data_table tr > td.LC_roles_will_not {
 6669:   border-right: 8px solid #AAFF77;
 6670: }
 6671: 
 6672: table.LC_data_table tr > td.LC_roles_selected {
 6673:   border-right: 8px solid #11CC55;
 6674: }
 6675: 
 6676: span.LC_current_location {
 6677:   font-size:larger;
 6678:   background: $pgbg;
 6679: }
 6680: 
 6681: span.LC_current_nav_location {
 6682:   font-weight:bold;
 6683:   background: $sidebg;
 6684: }
 6685: 
 6686: span.LC_parm_menu_item {
 6687:   font-size: larger;
 6688: }
 6689: 
 6690: span.LC_parm_scope_all {
 6691:   color: red;
 6692: }
 6693: 
 6694: span.LC_parm_scope_folder {
 6695:   color: green;
 6696: }
 6697: 
 6698: span.LC_parm_scope_resource {
 6699:   color: orange;
 6700: }
 6701: 
 6702: span.LC_parm_part {
 6703:   color: blue;
 6704: }
 6705: 
 6706: span.LC_parm_folder,
 6707: span.LC_parm_symb {
 6708:   font-size: x-small;
 6709:   font-family: $mono;
 6710:   color: #AAAAAA;
 6711: }
 6712: 
 6713: ul.LC_parm_parmlist li {
 6714:   display: inline-block;
 6715:   padding: 0.3em 0.8em;
 6716:   vertical-align: top;
 6717:   width: 150px;
 6718:   border-top:1px solid $lg_border_color;
 6719: }
 6720: 
 6721: td.LC_parm_overview_level_menu,
 6722: td.LC_parm_overview_map_menu,
 6723: td.LC_parm_overview_parm_selectors,
 6724: td.LC_parm_overview_restrictions  {
 6725:   border: 1px solid black;
 6726:   border-collapse: collapse;
 6727: }
 6728: 
 6729: table.LC_parm_overview_restrictions td {
 6730:   border-width: 1px 4px 1px 4px;
 6731:   border-style: solid;
 6732:   border-color: $pgbg;
 6733:   text-align: center;
 6734: }
 6735: 
 6736: table.LC_parm_overview_restrictions th {
 6737:   background: $tabbg;
 6738:   border-width: 1px 4px 1px 4px;
 6739:   border-style: solid;
 6740:   border-color: $pgbg;
 6741: }
 6742: 
 6743: table#LC_helpmenu {
 6744:   border: none;
 6745:   height: 55px;
 6746:   border-spacing: 0;
 6747: }
 6748: 
 6749: table#LC_helpmenu fieldset legend {
 6750:   font-size: larger;
 6751: }
 6752: 
 6753: table#LC_helpmenu_links {
 6754:   width: 100%;
 6755:   border: 1px solid black;
 6756:   background: $pgbg;
 6757:   padding: 0;
 6758:   border-spacing: 1px;
 6759: }
 6760: 
 6761: table#LC_helpmenu_links tr td {
 6762:   padding: 1px;
 6763:   background: $tabbg;
 6764:   text-align: center;
 6765:   font-weight: bold;
 6766: }
 6767: 
 6768: table#LC_helpmenu_links a:link,
 6769: table#LC_helpmenu_links a:visited,
 6770: table#LC_helpmenu_links a:active {
 6771:   text-decoration: none;
 6772:   color: $font;
 6773: }
 6774: 
 6775: table#LC_helpmenu_links a:hover {
 6776:   text-decoration: underline;
 6777:   color: $vlink;
 6778: }
 6779: 
 6780: .LC_chrt_popup_exists {
 6781:   border: 1px solid #339933;
 6782:   margin: -1px;
 6783: }
 6784: 
 6785: .LC_chrt_popup_up {
 6786:   border: 1px solid yellow;
 6787:   margin: -1px;
 6788: }
 6789: 
 6790: .LC_chrt_popup {
 6791:   border: 1px solid #8888FF;
 6792:   background: #CCCCFF;
 6793: }
 6794: 
 6795: table.LC_pick_box {
 6796:   border-collapse: separate;
 6797:   background: white;
 6798:   border: 1px solid black;
 6799:   border-spacing: 1px;
 6800: }
 6801: 
 6802: table.LC_pick_box td.LC_pick_box_title {
 6803:   background: $sidebg;
 6804:   font-weight: bold;
 6805:   text-align: left;
 6806:   vertical-align: top;
 6807:   width: 184px;
 6808:   padding: 8px;
 6809: }
 6810: 
 6811: table.LC_pick_box td.LC_pick_box_value {
 6812:   text-align: left;
 6813:   padding: 8px;
 6814: }
 6815: 
 6816: table.LC_pick_box td.LC_pick_box_select {
 6817:   text-align: left;
 6818:   padding: 8px;
 6819: }
 6820: 
 6821: table.LC_pick_box td.LC_pick_box_separator {
 6822:   padding: 0;
 6823:   height: 1px;
 6824:   background: black;
 6825: }
 6826: 
 6827: table.LC_pick_box td.LC_pick_box_submit {
 6828:   text-align: right;
 6829: }
 6830: 
 6831: table.LC_pick_box td.LC_evenrow_value {
 6832:   text-align: left;
 6833:   padding: 8px;
 6834:   background-color: $data_table_light;
 6835: }
 6836: 
 6837: table.LC_pick_box td.LC_oddrow_value {
 6838:   text-align: left;
 6839:   padding: 8px;
 6840:   background-color: $data_table_light;
 6841: }
 6842: 
 6843: span.LC_helpform_receipt_cat {
 6844:   font-weight: bold;
 6845: }
 6846: 
 6847: table.LC_group_priv_box {
 6848:   background: white;
 6849:   border: 1px solid black;
 6850:   border-spacing: 1px;
 6851: }
 6852: 
 6853: table.LC_group_priv_box td.LC_pick_box_title {
 6854:   background: $tabbg;
 6855:   font-weight: bold;
 6856:   text-align: right;
 6857:   width: 184px;
 6858: }
 6859: 
 6860: table.LC_group_priv_box td.LC_groups_fixed {
 6861:   background: $data_table_light;
 6862:   text-align: center;
 6863: }
 6864: 
 6865: table.LC_group_priv_box td.LC_groups_optional {
 6866:   background: $data_table_dark;
 6867:   text-align: center;
 6868: }
 6869: 
 6870: table.LC_group_priv_box td.LC_groups_functionality {
 6871:   background: $data_table_darker;
 6872:   text-align: center;
 6873:   font-weight: bold;
 6874: }
 6875: 
 6876: table.LC_group_priv td {
 6877:   text-align: left;
 6878:   padding: 0;
 6879: }
 6880: 
 6881: .LC_navbuttons {
 6882:   margin: 2ex 0ex 2ex 0ex;
 6883: }
 6884: 
 6885: .LC_topic_bar {
 6886:   font-weight: bold;
 6887:   background: $tabbg;
 6888:   margin: 1em 0em 1em 2em;
 6889:   padding: 3px;
 6890:   font-size: 1.2em;
 6891: }
 6892: 
 6893: .LC_topic_bar span {
 6894:   left: 0.5em;
 6895:   position: absolute;
 6896:   vertical-align: middle;
 6897:   font-size: 1.2em;
 6898: }
 6899: 
 6900: table.LC_course_group_status {
 6901:   margin: 20px;
 6902: }
 6903: 
 6904: table.LC_status_selector td {
 6905:   vertical-align: top;
 6906:   text-align: center;
 6907:   padding: 4px;
 6908: }
 6909: 
 6910: div.LC_feedback_link {
 6911:   clear: both;
 6912:   background: $sidebg;
 6913:   width: 100%;
 6914:   padding-bottom: 10px;
 6915:   border: 1px $tabbg solid;
 6916:   height: 22px;
 6917:   line-height: 22px;
 6918:   padding-top: 5px;
 6919: }
 6920: 
 6921: div.LC_feedback_link img {
 6922:   height: 22px;
 6923:   vertical-align:middle;
 6924: }
 6925: 
 6926: div.LC_feedback_link a {
 6927:   text-decoration: none;
 6928: }
 6929: 
 6930: div.LC_comblock {
 6931:   display:inline;
 6932:   color:$font;
 6933:   font-size:90%;
 6934: }
 6935: 
 6936: div.LC_feedback_link div.LC_comblock {
 6937:   padding-left:5px;
 6938: }
 6939: 
 6940: div.LC_feedback_link div.LC_comblock a {
 6941:   color:$font;
 6942: }
 6943: 
 6944: span.LC_feedback_link {
 6945:   /* background: $feedback_link_bg; */
 6946:   font-size: larger;
 6947: }
 6948: 
 6949: span.LC_message_link {
 6950:   /* background: $feedback_link_bg; */
 6951:   font-size: larger;
 6952:   position: absolute;
 6953:   right: 1em;
 6954: }
 6955: 
 6956: table.LC_prior_tries {
 6957:   border: 1px solid #000000;
 6958:   border-collapse: separate;
 6959:   border-spacing: 1px;
 6960: }
 6961: 
 6962: table.LC_prior_tries td {
 6963:   padding: 2px;
 6964: }
 6965: 
 6966: .LC_answer_correct {
 6967:   background: lightgreen;
 6968:   color: darkgreen;
 6969:   padding: 6px;
 6970: }
 6971: 
 6972: .LC_answer_charged_try {
 6973:   background: #FFAAAA;
 6974:   color: darkred;
 6975:   padding: 6px;
 6976: }
 6977: 
 6978: .LC_answer_not_charged_try,
 6979: .LC_answer_no_grade,
 6980: .LC_answer_late {
 6981:   background: lightyellow;
 6982:   color: black;
 6983:   padding: 6px;
 6984: }
 6985: 
 6986: .LC_answer_previous {
 6987:   background: lightblue;
 6988:   color: darkblue;
 6989:   padding: 6px;
 6990: }
 6991: 
 6992: .LC_answer_no_message {
 6993:   background: #FFFFFF;
 6994:   color: black;
 6995:   padding: 6px;
 6996: }
 6997: 
 6998: .LC_answer_unknown {
 6999:   background: orange;
 7000:   color: black;
 7001:   padding: 6px;
 7002: }
 7003: 
 7004: span.LC_prior_numerical,
 7005: span.LC_prior_string,
 7006: span.LC_prior_custom,
 7007: span.LC_prior_reaction,
 7008: span.LC_prior_math {
 7009:   font-family: $mono;
 7010:   white-space: pre;
 7011: }
 7012: 
 7013: span.LC_prior_string {
 7014:   font-family: $mono;
 7015:   white-space: pre;
 7016: }
 7017: 
 7018: table.LC_prior_option {
 7019:   width: 100%;
 7020:   border-collapse: collapse;
 7021: }
 7022: 
 7023: table.LC_prior_rank,
 7024: table.LC_prior_match {
 7025:   border-collapse: collapse;
 7026: }
 7027: 
 7028: table.LC_prior_option tr td,
 7029: table.LC_prior_rank tr td,
 7030: table.LC_prior_match tr td {
 7031:   border: 1px solid #000000;
 7032: }
 7033: 
 7034: .LC_nobreak {
 7035:   white-space: nowrap;
 7036: }
 7037: 
 7038: span.LC_cusr_emph {
 7039:   font-style: italic;
 7040: }
 7041: 
 7042: span.LC_cusr_subheading {
 7043:   font-weight: normal;
 7044:   font-size: 85%;
 7045: }
 7046: 
 7047: div.LC_docs_entry_move {
 7048:   border: 1px solid #BBBBBB;
 7049:   background: #DDDDDD;
 7050:   width: 22px;
 7051:   padding: 1px;
 7052:   margin: 0;
 7053: }
 7054: 
 7055: table.LC_data_table tr > td.LC_docs_entry_commands,
 7056: table.LC_data_table tr > td.LC_docs_entry_parameter {
 7057:   font-size: x-small;
 7058: }
 7059: 
 7060: .LC_docs_entry_parameter {
 7061:   white-space: nowrap;
 7062: }
 7063: 
 7064: .LC_docs_copy {
 7065:   color: #000099;
 7066: }
 7067: 
 7068: .LC_docs_cut {
 7069:   color: #550044;
 7070: }
 7071: 
 7072: .LC_docs_rename {
 7073:   color: #009900;
 7074: }
 7075: 
 7076: .LC_docs_remove {
 7077:   color: #990000;
 7078: }
 7079: 
 7080: .LC_docs_reinit_warn,
 7081: .LC_docs_ext_edit {
 7082:   font-size: x-small;
 7083: }
 7084: 
 7085: table.LC_docs_adddocs td,
 7086: table.LC_docs_adddocs th {
 7087:   border: 1px solid #BBBBBB;
 7088:   padding: 4px;
 7089:   background: #DDDDDD;
 7090: }
 7091: 
 7092: table.LC_sty_begin {
 7093:   background: #BBFFBB;
 7094: }
 7095: 
 7096: table.LC_sty_end {
 7097:   background: #FFBBBB;
 7098: }
 7099: 
 7100: table.LC_double_column {
 7101:   border-width: 0;
 7102:   border-collapse: collapse;
 7103:   width: 100%;
 7104:   padding: 2px;
 7105: }
 7106: 
 7107: table.LC_double_column tr td.LC_left_col {
 7108:   top: 2px;
 7109:   left: 2px;
 7110:   width: 47%;
 7111:   vertical-align: top;
 7112: }
 7113: 
 7114: table.LC_double_column tr td.LC_right_col {
 7115:   top: 2px;
 7116:   right: 2px;
 7117:   width: 47%;
 7118:   vertical-align: top;
 7119: }
 7120: 
 7121: div.LC_left_float {
 7122:   float: left;
 7123:   padding-right: 5%;
 7124:   padding-bottom: 4px;
 7125: }
 7126: 
 7127: div.LC_clear_float_header {
 7128:   padding-bottom: 2px;
 7129: }
 7130: 
 7131: div.LC_clear_float_footer {
 7132:   padding-top: 10px;
 7133:   clear: both;
 7134: }
 7135: 
 7136: div.LC_grade_show_user {
 7137: /*  border-left: 5px solid $sidebg; */
 7138:   border-top: 5px solid #000000;
 7139:   margin: 50px 0 0 0;
 7140:   padding: 15px 0 5px 10px;
 7141: }
 7142: 
 7143: div.LC_grade_show_user_odd_row {
 7144: /*  border-left: 5px solid #000000; */
 7145: }
 7146: 
 7147: div.LC_grade_show_user div.LC_Box {
 7148:   margin-right: 50px;
 7149: }
 7150: 
 7151: div.LC_grade_submissions,
 7152: div.LC_grade_message_center,
 7153: div.LC_grade_info_links {
 7154:   margin: 5px;
 7155:   width: 99%;
 7156:   background: #FFFFFF;
 7157: }
 7158: 
 7159: div.LC_grade_submissions_header,
 7160: div.LC_grade_message_center_header {
 7161:   font-weight: bold;
 7162:   font-size: large;
 7163: }
 7164: 
 7165: div.LC_grade_submissions_body,
 7166: div.LC_grade_message_center_body {
 7167:   border: 1px solid black;
 7168:   width: 99%;
 7169:   background: #FFFFFF;
 7170: }
 7171: 
 7172: table.LC_scantron_action {
 7173:   width: 100%;
 7174: }
 7175: 
 7176: table.LC_scantron_action tr th {
 7177:   font-weight:bold;
 7178:   font-style:normal;
 7179: }
 7180: 
 7181: .LC_edit_problem_header,
 7182: div.LC_edit_problem_footer {
 7183:   font-weight: normal;
 7184:   font-size:  medium;
 7185:   margin: 2px;
 7186:   background-color: $sidebg;
 7187: }
 7188: 
 7189: div.LC_edit_problem_header,
 7190: div.LC_edit_problem_header div,
 7191: div.LC_edit_problem_footer,
 7192: div.LC_edit_problem_footer div,
 7193: div.LC_edit_problem_editxml_header,
 7194: div.LC_edit_problem_editxml_header div {
 7195:   z-index: 100;
 7196: }
 7197: 
 7198: div.LC_edit_problem_header_title {
 7199:   font-weight: bold;
 7200:   font-size: larger;
 7201:   background: $tabbg;
 7202:   padding: 3px;
 7203:   margin: 0 0 5px 0;
 7204: }
 7205: 
 7206: table.LC_edit_problem_header_title {
 7207:   width: 100%;
 7208:   background: $tabbg;
 7209: }
 7210: 
 7211: div.LC_edit_actionbar {
 7212:     background-color: $sidebg;
 7213:     margin: 0;
 7214:     padding: 0;
 7215:     line-height: 200%;
 7216: }
 7217: 
 7218: div.LC_edit_actionbar div{
 7219:     padding: 0;
 7220:     margin: 0;
 7221:     display: inline-block;
 7222: }
 7223: 
 7224: .LC_edit_opt {
 7225:   padding-left: 1em;
 7226:   white-space: nowrap;
 7227: }
 7228: 
 7229: .LC_edit_problem_latexhelper{
 7230:     text-align: right;
 7231: }
 7232: 
 7233: #LC_edit_problem_colorful div{
 7234:     margin-left: 40px;
 7235: }
 7236: 
 7237: #LC_edit_problem_codemirror div{
 7238:     margin-left: 0px;
 7239: }
 7240: 
 7241: img.stift {
 7242:   border-width: 0;
 7243:   vertical-align: middle;
 7244: }
 7245: 
 7246: table td.LC_mainmenu_col_fieldset {
 7247:   vertical-align: top;
 7248: }
 7249: 
 7250: div.LC_createcourse {
 7251:   margin: 10px 10px 10px 10px;
 7252: }
 7253: 
 7254: .LC_dccid {
 7255:   float: right;
 7256:   margin: 0.2em 0 0 0;
 7257:   padding: 0;
 7258:   font-size: 90%;
 7259:   display:none;
 7260: }
 7261: 
 7262: ol.LC_primary_menu a:hover,
 7263: ol#LC_MenuBreadcrumbs a:hover,
 7264: ol#LC_PathBreadcrumbs a:hover,
 7265: ul#LC_secondary_menu a:hover,
 7266: .LC_FormSectionClearButton input:hover
 7267: ul.LC_TabContent   li:hover a {
 7268:   color:$button_hover;
 7269:   text-decoration:none;
 7270: }
 7271: 
 7272: h1 {
 7273:   padding: 0;
 7274:   line-height:130%;
 7275: }
 7276: 
 7277: h2,
 7278: h3,
 7279: h4,
 7280: h5,
 7281: h6 {
 7282:   margin: 5px 0 5px 0;
 7283:   padding: 0;
 7284:   line-height:130%;
 7285: }
 7286: 
 7287: .LC_hcell {
 7288:   padding:3px 15px 3px 15px;
 7289:   margin: 0;
 7290:   background-color:$tabbg;
 7291:   color:$fontmenu;
 7292:   border-bottom:solid 1px $lg_border_color;
 7293: }
 7294: 
 7295: .LC_Box > .LC_hcell {
 7296:   margin: 0 -10px 10px -10px;
 7297: }
 7298: 
 7299: .LC_noBorder {
 7300:   border: 0;
 7301: }
 7302: 
 7303: .LC_FormSectionClearButton input {
 7304:   background-color:transparent;
 7305:   border: none;
 7306:   cursor:pointer;
 7307:   text-decoration:underline;
 7308: }
 7309: 
 7310: .LC_help_open_topic {
 7311:   color: #FFFFFF;
 7312:   background-color: #EEEEFF;
 7313:   margin: 1px;
 7314:   padding: 4px;
 7315:   border: 1px solid #000033;
 7316:   white-space: nowrap;
 7317:   /* vertical-align: middle; */
 7318: }
 7319: 
 7320: dl,
 7321: ul,
 7322: div,
 7323: fieldset {
 7324:   margin: 10px 10px 10px 0;
 7325:   /* overflow: hidden; */
 7326: }
 7327: 
 7328: article.geogebraweb div {
 7329:     margin: 0;
 7330: }
 7331: 
 7332: fieldset > legend {
 7333:   font-weight: bold;
 7334:   padding: 0 5px 0 5px;
 7335: }
 7336: 
 7337: #LC_nav_bar {
 7338:   float: left;
 7339:   background-color: $pgbg_or_bgcolor;
 7340:   margin: 0 0 2px 0;
 7341: }
 7342: 
 7343: #LC_realm {
 7344:   margin: 0.2em 0 0 0;
 7345:   padding: 0;
 7346:   font-weight: bold;
 7347:   text-align: center;
 7348:   background-color: $pgbg_or_bgcolor;
 7349: }
 7350: 
 7351: #LC_nav_bar em {
 7352:   font-weight: bold;
 7353:   font-style: normal;
 7354: }
 7355: 
 7356: ol.LC_primary_menu {
 7357:   margin: 0;
 7358:   padding: 0;
 7359: }
 7360: 
 7361: ol#LC_PathBreadcrumbs {
 7362:   margin: 0;
 7363: }
 7364: 
 7365: ol.LC_primary_menu li {
 7366:   color: RGB(80, 80, 80);
 7367:   vertical-align: middle;
 7368:   text-align: left;
 7369:   list-style: none;
 7370:   position: relative;
 7371:   float: left;
 7372:   z-index: 100; /* will be displayed above codemirror and underneath the help-layer */
 7373:   line-height: 1.5em;
 7374: }
 7375: 
 7376: ol.LC_primary_menu li a,
 7377: ol.LC_primary_menu li p {
 7378:   display: block;
 7379:   margin: 0;
 7380:   padding: 0 5px 0 10px;
 7381:   text-decoration: none;
 7382: }
 7383: 
 7384: ol.LC_primary_menu li p span.LC_primary_menu_innertitle {
 7385:   display: inline-block;
 7386:   width: 95%;
 7387:   text-align: left;
 7388: }
 7389: 
 7390: ol.LC_primary_menu li p span.LC_primary_menu_innerarrow {
 7391:   display: inline-block;	
 7392:   width: 5%;
 7393:   float: right;
 7394:   text-align: right;
 7395:   font-size: 70%;
 7396: }
 7397: 
 7398: ol.LC_primary_menu ul {
 7399:   display: none;
 7400:   width: 15em;
 7401:   background-color: $data_table_light;
 7402:   position: absolute;
 7403:   top: 100%;
 7404: }
 7405: 
 7406: ol.LC_primary_menu ul ul {
 7407:   left: 100%;
 7408:   top: 0;
 7409: }
 7410: 
 7411: ol.LC_primary_menu li:hover > ul, ol.LC_primary_menu li.hover > ul {
 7412:   display: block;
 7413:   position: absolute;
 7414:   margin: 0;
 7415:   padding: 0;
 7416:   z-index: 2;
 7417: }
 7418: 
 7419: ol.LC_primary_menu li:hover li, ol.LC_primary_menu li.hover li {
 7420: /* First Submenu -> size should be smaller than the menu title of the whole menu */
 7421:   font-size: 90%;
 7422:   vertical-align: top;
 7423:   float: none;
 7424:   border-left: 1px solid black;
 7425:   border-right: 1px solid black;
 7426: /* A dark bottom border to visualize different menu options; 
 7427: overwritten in the create_submenu routine for the last border-bottom of the menu */
 7428:   border-bottom: 1px solid $data_table_dark; 
 7429: }
 7430: 
 7431: ol.LC_primary_menu li li p:hover {
 7432:   color:$button_hover;
 7433:   text-decoration:none;
 7434:   background-color:$data_table_dark;
 7435: }
 7436: 
 7437: ol.LC_primary_menu li li a:hover {
 7438:    color:$button_hover;
 7439:    background-color:$data_table_dark;
 7440: }
 7441: 
 7442: /* Font-size equal to the size of the predecessors*/
 7443: ol.LC_primary_menu li:hover li li {
 7444:   font-size: 100%;
 7445: }
 7446: 
 7447: ol.LC_primary_menu li img {
 7448:   vertical-align: bottom;
 7449:   height: 1.1em;
 7450:   margin: 0.2em 0 0 0;
 7451: }
 7452: 
 7453: ol.LC_primary_menu a {
 7454:   color: RGB(80, 80, 80);
 7455:   text-decoration: none;
 7456: }
 7457: 
 7458: ol.LC_primary_menu a.LC_new_message {
 7459:   font-weight:bold;
 7460:   color: darkred;
 7461: }
 7462: 
 7463: ol.LC_docs_parameters {
 7464:   margin-left: 0;
 7465:   padding: 0;
 7466:   list-style: none;
 7467: }
 7468: 
 7469: ol.LC_docs_parameters li {
 7470:   margin: 0;
 7471:   padding-right: 20px;
 7472:   display: inline;
 7473: }
 7474: 
 7475: ol.LC_docs_parameters li:before {
 7476:   content: "\\002022 \\0020";
 7477: }
 7478: 
 7479: li.LC_docs_parameters_title {
 7480:   font-weight: bold;
 7481: }
 7482: 
 7483: ol.LC_docs_parameters li.LC_docs_parameters_title:before {
 7484:   content: "";
 7485: }
 7486: 
 7487: ul#LC_secondary_menu {
 7488:   clear: right;
 7489:   color: $fontmenu;
 7490:   background: $tabbg;
 7491:   list-style: none;
 7492:   padding: 0;
 7493:   margin: 0;
 7494:   width: 100%;
 7495:   text-align: left;
 7496:   float: left;
 7497: }
 7498: 
 7499: ul#LC_secondary_menu li {
 7500:   font-weight: bold;
 7501:   line-height: 1.8em;
 7502:   border-right: 1px solid black;
 7503:   float: left;
 7504: }
 7505: 
 7506: ul#LC_secondary_menu li.LC_hoverable:hover, ul#LC_secondary_menu li.hover {
 7507:   background-color: $data_table_light;
 7508: }
 7509: 
 7510: ul#LC_secondary_menu li a {
 7511:   padding: 0 0.8em;
 7512: }
 7513: 
 7514: ul#LC_secondary_menu li ul {
 7515:   display: none;
 7516: }
 7517: 
 7518: ul#LC_secondary_menu li:hover ul, ul#LC_secondary_menu li.hover ul {
 7519:   display: block;
 7520:   position: absolute;
 7521:   margin: 0;
 7522:   padding: 0;
 7523:   list-style:none;
 7524:   float: none;
 7525:   background-color: $data_table_light;
 7526:   z-index: 2;
 7527:   margin-left: -1px;
 7528: }
 7529: 
 7530: ul#LC_secondary_menu li ul li {
 7531:   font-size: 90%;
 7532:   vertical-align: top;
 7533:   border-left: 1px solid black;
 7534:   border-right: 1px solid black;
 7535:   background-color: $data_table_light;
 7536:   list-style:none;
 7537:   float: none;
 7538: }
 7539: 
 7540: ul#LC_secondary_menu li ul li:hover, ul#LC_secondary_menu li ul li.hover {
 7541:   background-color: $data_table_dark;
 7542: }
 7543: 
 7544: ul.LC_TabContent {
 7545:   display:block;
 7546:   background: $sidebg;
 7547:   border-bottom: solid 1px $lg_border_color;
 7548:   list-style:none;
 7549:   margin: -1px -10px 0 -10px;
 7550:   padding: 0;
 7551: }
 7552: 
 7553: ul.LC_TabContent li,
 7554: ul.LC_TabContentBigger li {
 7555:   float:left;
 7556: }
 7557: 
 7558: ul#LC_secondary_menu li a {
 7559:   color: $fontmenu;
 7560:   text-decoration: none;
 7561: }
 7562: 
 7563: ul.LC_TabContent {
 7564:   min-height:20px;
 7565: }
 7566: 
 7567: ul.LC_TabContent li {
 7568:   vertical-align:middle;
 7569:   padding: 0 16px 0 10px;
 7570:   background-color:$tabbg;
 7571:   border-bottom:solid 1px $lg_border_color;
 7572:   border-left: solid 1px $font;
 7573: }
 7574: 
 7575: ul.LC_TabContent .right {
 7576:   float:right;
 7577: }
 7578: 
 7579: ul.LC_TabContent li a,
 7580: ul.LC_TabContent li {
 7581:   color:rgb(47,47,47);
 7582:   text-decoration:none;
 7583:   font-size:95%;
 7584:   font-weight:bold;
 7585:   min-height:20px;
 7586: }
 7587: 
 7588: ul.LC_TabContent li a:hover,
 7589: ul.LC_TabContent li a:focus {
 7590:   color: $button_hover;
 7591:   background:none;
 7592:   outline:none;
 7593: }
 7594: 
 7595: ul.LC_TabContent li:hover {
 7596:   color: $button_hover;
 7597:   cursor:pointer;
 7598: }
 7599: 
 7600: ul.LC_TabContent li.active {
 7601:   color: $font;
 7602:   background:#FFFFFF url(/adm/lonIcons/open.gif) no-repeat scroll right center;
 7603:   border-bottom:solid 1px #FFFFFF;
 7604:   cursor: default;
 7605: }
 7606: 
 7607: ul.LC_TabContent li.active a {
 7608:   color:$font;
 7609:   background:#FFFFFF;
 7610:   outline: none;
 7611: }
 7612: 
 7613: ul.LC_TabContent li.goback {
 7614:   float: left;
 7615:   border-left: none;
 7616: }
 7617: 
 7618: #maincoursedoc {
 7619:   clear:both;
 7620: }
 7621: 
 7622: ul.LC_TabContentBigger {
 7623:   display:block;
 7624:   list-style:none;
 7625:   padding: 0;
 7626: }
 7627: 
 7628: ul.LC_TabContentBigger li {
 7629:   vertical-align:bottom;
 7630:   height: 30px;
 7631:   font-size:110%;
 7632:   font-weight:bold;
 7633:   color: #737373;
 7634: }
 7635: 
 7636: ul.LC_TabContentBigger li.active {
 7637:   position: relative;
 7638:   top: 1px;
 7639: }
 7640: 
 7641: ul.LC_TabContentBigger li a {
 7642:   background:url('/adm/lonIcons/tabbgleft.gif') left bottom no-repeat;
 7643:   height: 30px;
 7644:   line-height: 30px;
 7645:   text-align: center;
 7646:   display: block;
 7647:   text-decoration: none;
 7648:   outline: none;  
 7649: }
 7650: 
 7651: ul.LC_TabContentBigger li.active a {
 7652:   background:url('/adm/lonIcons/tabbgleft.gif') left top no-repeat;
 7653:   color:$font;
 7654: }
 7655: 
 7656: ul.LC_TabContentBigger li b {
 7657:   background: url('/adm/lonIcons/tabbgright.gif') no-repeat right bottom;
 7658:   display: block;
 7659:   float: left;
 7660:   padding: 0 30px;
 7661:   border-bottom: 1px solid $lg_border_color;
 7662: }
 7663: 
 7664: ul.LC_TabContentBigger li:hover b {
 7665:   color:$button_hover;
 7666: }
 7667: 
 7668: ul.LC_TabContentBigger li.active b {
 7669:   background:url('/adm/lonIcons/tabbgright.gif') right top no-repeat;
 7670:   color:$font;
 7671:   border: 0;
 7672: }
 7673: 
 7674: 
 7675: ul.LC_CourseBreadcrumbs {
 7676:   background: $sidebg;
 7677:   height: 2em;
 7678:   padding-left: 10px;
 7679:   margin: 0;
 7680:   list-style-position: inside;
 7681: }
 7682: 
 7683: ol#LC_MenuBreadcrumbs,
 7684: ol#LC_PathBreadcrumbs {
 7685:   padding-left: 10px;
 7686:   margin: 0;
 7687:   height: 2.5em;  /* equal to #LC_breadcrumbs line-height */
 7688: }
 7689: 
 7690: ol#LC_MenuBreadcrumbs li,
 7691: ol#LC_PathBreadcrumbs li,
 7692: ul.LC_CourseBreadcrumbs li {
 7693:   display: inline;
 7694:   white-space: normal;  
 7695: }
 7696: 
 7697: ol#LC_MenuBreadcrumbs li a,
 7698: ul.LC_CourseBreadcrumbs li a {
 7699:   text-decoration: none;
 7700:   font-size:90%;
 7701: }
 7702: 
 7703: ol#LC_MenuBreadcrumbs h1 {
 7704:   display: inline;
 7705:   font-size: 90%;
 7706:   line-height: 2.5em;
 7707:   margin: 0;
 7708:   padding: 0;
 7709: }
 7710: 
 7711: ol#LC_PathBreadcrumbs li a {
 7712:   text-decoration:none;
 7713:   font-size:100%;
 7714:   font-weight:bold;
 7715: }
 7716: 
 7717: .LC_Box {
 7718:   border: solid 1px $lg_border_color;
 7719:   padding: 0 10px 10px 10px;
 7720: }
 7721: 
 7722: .LC_DocsBox {
 7723:   border: solid 1px $lg_border_color;
 7724:   padding: 0 0 10px 10px;
 7725: }
 7726: 
 7727: .LC_AboutMe_Image {
 7728:   float:left;
 7729:   margin-right:10px;
 7730: }
 7731: 
 7732: .LC_Clear_AboutMe_Image {
 7733:   clear:left;
 7734: }
 7735: 
 7736: dl.LC_ListStyleClean dt {
 7737:   padding-right: 5px;
 7738:   display: table-header-group;
 7739: }
 7740: 
 7741: dl.LC_ListStyleClean dd {
 7742:   display: table-row;
 7743: }
 7744: 
 7745: .LC_ListStyleClean,
 7746: .LC_ListStyleSimple,
 7747: .LC_ListStyleNormal,
 7748: .LC_ListStyleSpecial {
 7749:   /* display:block; */
 7750:   list-style-position: inside;
 7751:   list-style-type: none;
 7752:   overflow: hidden;
 7753:   padding: 0;
 7754: }
 7755: 
 7756: .LC_ListStyleSimple li,
 7757: .LC_ListStyleSimple dd,
 7758: .LC_ListStyleNormal li,
 7759: .LC_ListStyleNormal dd,
 7760: .LC_ListStyleSpecial li,
 7761: .LC_ListStyleSpecial dd {
 7762:   margin: 0;
 7763:   padding: 5px 5px 5px 10px;
 7764:   clear: both;
 7765: }
 7766: 
 7767: .LC_ListStyleClean li,
 7768: .LC_ListStyleClean dd {
 7769:   padding-top: 0;
 7770:   padding-bottom: 0;
 7771: }
 7772: 
 7773: .LC_ListStyleSimple dd,
 7774: .LC_ListStyleSimple li {
 7775:   border-bottom: solid 1px $lg_border_color;
 7776: }
 7777: 
 7778: .LC_ListStyleSpecial li,
 7779: .LC_ListStyleSpecial dd {
 7780:   list-style-type: none;
 7781:   background-color: RGB(220, 220, 220);
 7782:   margin-bottom: 4px;
 7783: }
 7784: 
 7785: table.LC_SimpleTable {
 7786:   margin:5px;
 7787:   border:solid 1px $lg_border_color;
 7788: }
 7789: 
 7790: table.LC_SimpleTable tr {
 7791:   padding: 0;
 7792:   border:solid 1px $lg_border_color;
 7793: }
 7794: 
 7795: table.LC_SimpleTable thead {
 7796:   background:rgb(220,220,220);
 7797: }
 7798: 
 7799: div.LC_columnSection {
 7800:   display: block;
 7801:   clear: both;
 7802:   overflow: hidden;
 7803:   margin: 0;
 7804: }
 7805: 
 7806: div.LC_columnSection>* {
 7807:   float: left;
 7808:   margin: 10px 20px 10px 0;
 7809:   overflow:hidden;
 7810: }
 7811: 
 7812: table em {
 7813:   font-weight: bold;
 7814:   font-style: normal;
 7815: }
 7816: 
 7817: table.LC_tableBrowseRes,
 7818: table.LC_tableOfContent {
 7819:   border:none;
 7820:   border-spacing: 1px;
 7821:   padding: 3px;
 7822:   background-color: #FFFFFF;
 7823:   font-size: 90%;
 7824: }
 7825: 
 7826: table.LC_tableOfContent {
 7827:   border-collapse: collapse;
 7828: }
 7829: 
 7830: table.LC_tableBrowseRes a,
 7831: table.LC_tableOfContent a {
 7832:   background-color: transparent;
 7833:   text-decoration: none;
 7834: }
 7835: 
 7836: table.LC_tableOfContent img {
 7837:   border: none;
 7838:   height: 1.3em;
 7839:   vertical-align: text-bottom;
 7840:   margin-right: 0.3em;
 7841: }
 7842: 
 7843: a#LC_content_toolbar_firsthomework {
 7844:   background-image:url(/res/adm/pages/open-first-problem.gif);
 7845: }
 7846: 
 7847: a#LC_content_toolbar_everything {
 7848:   background-image:url(/res/adm/pages/show-all.gif);
 7849: }
 7850: 
 7851: a#LC_content_toolbar_uncompleted {
 7852:   background-image:url(/res/adm/pages/show-incomplete-problems.gif);
 7853: }
 7854: 
 7855: #LC_content_toolbar_clearbubbles {
 7856:   background-image:url(/res/adm/pages/mark-discussionentries-read.gif);
 7857: }
 7858: 
 7859: a#LC_content_toolbar_changefolder {
 7860:   background : url(/res/adm/pages/close-all-folders.gif) top center ;
 7861: }
 7862: 
 7863: a#LC_content_toolbar_changefolder_toggled {
 7864:   background-image:url(/res/adm/pages/open-all-folders.gif);
 7865: }
 7866: 
 7867: a#LC_content_toolbar_edittoplevel {
 7868:   background-image:url(/res/adm/pages/edittoplevel.gif);
 7869: }
 7870: 
 7871: ul#LC_toolbar li a:hover {
 7872:   background-position: bottom center;
 7873: }
 7874: 
 7875: ul#LC_toolbar {
 7876:   padding: 0;
 7877:   margin: 2px;
 7878:   list-style:none;
 7879:   position:relative;
 7880:   background-color:white;
 7881:   overflow: auto;
 7882: }
 7883: 
 7884: ul#LC_toolbar li {
 7885:   border:1px solid white;
 7886:   padding: 0;
 7887:   margin: 0;
 7888:   float: left;
 7889:   display:inline;
 7890:   vertical-align:middle;
 7891:   white-space: nowrap;
 7892: }
 7893: 
 7894: 
 7895: a.LC_toolbarItem {
 7896:   display:block;
 7897:   padding: 0;
 7898:   margin: 0;
 7899:   height: 32px;
 7900:   width: 32px;
 7901:   color:white;
 7902:   border: none;
 7903:   background-repeat:no-repeat;
 7904:   background-color:transparent;
 7905: }
 7906: 
 7907: ul.LC_funclist {
 7908:     margin: 0;
 7909:     padding: 0.5em 1em 0.5em 0;
 7910: }
 7911: 
 7912: ul.LC_funclist > li:first-child {
 7913:     font-weight:bold; 
 7914:     margin-left:0.8em;
 7915: }
 7916: 
 7917: ul.LC_funclist + ul.LC_funclist {
 7918:     /* 
 7919:        left border as a seperator if we have more than
 7920:        one list 
 7921:     */
 7922:     border-left: 1px solid $sidebg;
 7923:     /* 
 7924:        this hides the left border behind the border of the 
 7925:        outer box if element is wrapped to the next 'line' 
 7926:     */
 7927:     margin-left: -1px;
 7928: }
 7929: 
 7930: ul.LC_funclist li {
 7931:   display: inline;
 7932:   white-space: nowrap;
 7933:   margin: 0 0 0 25px;
 7934:   line-height: 150%;
 7935: }
 7936: 
 7937: .LC_hidden {
 7938:   display: none;
 7939: }
 7940: 
 7941: .LCmodal-overlay {
 7942: 		position:fixed;
 7943: 		top:0;
 7944: 		right:0;
 7945: 		bottom:0;
 7946: 		left:0;
 7947: 		height:100%;
 7948: 		width:100%;
 7949: 		margin:0;
 7950: 		padding:0;
 7951: 		background:#999;
 7952: 		opacity:.75;
 7953: 		filter: alpha(opacity=75);
 7954: 		-moz-opacity: 0.75;
 7955: 		z-index:101;
 7956: }
 7957: 
 7958: * html .LCmodal-overlay {   
 7959: 		position: absolute;
 7960: 		height: expression(document.body.scrollHeight > document.body.offsetHeight ? document.body.scrollHeight : document.body.offsetHeight + 'px');
 7961: }
 7962: 
 7963: .LCmodal-window {
 7964: 		position:fixed;
 7965: 		top:50%;
 7966: 		left:50%;
 7967: 		margin:0;
 7968: 		padding:0;
 7969: 		z-index:102;
 7970: 	}
 7971: 
 7972: * html .LCmodal-window {
 7973: 		position:absolute;
 7974: }
 7975: 
 7976: .LCclose-window {
 7977: 		position:absolute;
 7978: 		width:32px;
 7979: 		height:32px;
 7980: 		right:8px;
 7981: 		top:8px;
 7982: 		background:transparent url('/res/adm/pages/process-stop.png') no-repeat scroll right top;
 7983: 		text-indent:-99999px;
 7984: 		overflow:hidden;
 7985: 		cursor:pointer;
 7986: }
 7987: 
 7988: /*
 7989:   styles used for response display
 7990: */
 7991: div.LC_radiofoil, div.LC_rankfoil {
 7992:   margin: .5em 0em .5em 0em;
 7993: }
 7994: table.LC_itemgroup {
 7995:   margin-top: 1em;
 7996: }
 7997: 
 7998: /*
 7999:   styles used by TTH when "Default set of options to pass to tth/m
 8000:   when converting TeX" in course settings has been set
 8001: 
 8002:   option passed: -t
 8003: 
 8004: */
 8005: 
 8006: td div.comp { margin-top: -0.6ex; margin-bottom: -1ex;}
 8007: td div.comb { margin-top: -0.6ex; margin-bottom: -.6ex;}
 8008: td div.hrcomp { line-height: 0.9; margin-top: -0.8ex; margin-bottom: -1ex;}
 8009: td div.norm {line-height:normal;}
 8010: 
 8011: /*
 8012:   option passed -y3
 8013: */
 8014: 
 8015: span.roman {font-family: serif; font-style: normal; font-weight: normal;}
 8016: span.overacc2 {position: relative;  left: .8em; top: -1.2ex;}
 8017: span.overacc1 {position: relative;  left: .6em; top: -1.2ex;}
 8018: 
 8019: /*
 8020:   sections with roles, for content only
 8021: */
 8022: section[class^="role-"] {
 8023:   padding-left: 10px;
 8024:   padding-right: 5px;
 8025:   margin-top: 8px;
 8026:   margin-bottom: 8px;
 8027:   border: 1px solid #2A4;
 8028:   border-radius: 5px;
 8029:   box-shadow: 0px 1px 1px #BBB;
 8030: }
 8031: section[class^="role-"]>h1 {
 8032:   position: relative;
 8033:   margin: 0px;
 8034:   padding-top: 10px;
 8035:   padding-left: 40px;
 8036: }
 8037: section[class^="role-"]>h1:before {
 8038:   position: absolute;
 8039:   left: -5px;
 8040:   top: 5px;
 8041: }
 8042: section.role-activity>h1:before {
 8043:   content:url('/adm/daxe/images/section_icons/activity.png');
 8044: }
 8045: section.role-advice>h1:before {
 8046:   content:url('/adm/daxe/images/section_icons/advice.png');
 8047: }
 8048: section.role-bibliography>h1:before {
 8049:   content:url('/adm/daxe/images/section_icons/bibliography.png');
 8050: }
 8051: section.role-citation>h1:before {
 8052:   content:url('/adm/daxe/images/section_icons/citation.png');
 8053: }
 8054: section.role-conclusion>h1:before {
 8055:   content:url('/adm/daxe/images/section_icons/conclusion.png');
 8056: }
 8057: section.role-definition>h1:before {
 8058:   content:url('/adm/daxe/images/section_icons/definition.png');
 8059: }
 8060: section.role-demonstration>h1:before {
 8061:   content:url('/adm/daxe/images/section_icons/demonstration.png');
 8062: }
 8063: section.role-example>h1:before {
 8064:   content:url('/adm/daxe/images/section_icons/example.png');
 8065: }
 8066: section.role-explanation>h1:before {
 8067:   content:url('/adm/daxe/images/section_icons/explanation.png');
 8068: }
 8069: section.role-introduction>h1:before {
 8070:   content:url('/adm/daxe/images/section_icons/introduction.png');
 8071: }
 8072: section.role-method>h1:before {
 8073:   content:url('/adm/daxe/images/section_icons/method.png');
 8074: }
 8075: section.role-more_information>h1:before {
 8076:   content:url('/adm/daxe/images/section_icons/more_information.png');
 8077: }
 8078: section.role-objectives>h1:before {
 8079:   content:url('/adm/daxe/images/section_icons/objectives.png');
 8080: }
 8081: section.role-prerequisites>h1:before {
 8082:   content:url('/adm/daxe/images/section_icons/prerequisites.png');
 8083: }
 8084: section.role-remark>h1:before {
 8085:   content:url('/adm/daxe/images/section_icons/remark.png');
 8086: }
 8087: section.role-reminder>h1:before {
 8088:   content:url('/adm/daxe/images/section_icons/reminder.png');
 8089: }
 8090: section.role-summary>h1:before {
 8091:   content:url('/adm/daxe/images/section_icons/summary.png');
 8092: }
 8093: section.role-syntax>h1:before {
 8094:   content:url('/adm/daxe/images/section_icons/syntax.png');
 8095: }
 8096: section.role-warning>h1:before {
 8097:   content:url('/adm/daxe/images/section_icons/warning.png');
 8098: }
 8099: 
 8100: END
 8101: }
 8102: 
 8103: =pod
 8104: 
 8105: =item * &headtag()
 8106: 
 8107: Returns a uniform footer for LON-CAPA web pages.
 8108: 
 8109: Inputs: $title - optional title for the head
 8110:         $head_extra - optional extra HTML to put inside the <head>
 8111:         $args - optional arguments
 8112:             force_register - if is true call registerurl so the remote is 
 8113:                              informed
 8114:             redirect       -> array ref of
 8115:                                    1- seconds before redirect occurs
 8116:                                    2- url to redirect to
 8117:                                    3- whether the side effect should occur
 8118:                            (side effect of setting 
 8119:                                $env{'internal.head.redirect'} to the url 
 8120:                                redirected too)
 8121:             domain         -> force to color decorate a page for a specific
 8122:                                domain
 8123:             function       -> force usage of a specific rolish color scheme
 8124:             bgcolor        -> override the default page bgcolor
 8125:             no_auto_mt_title
 8126:                            -> prevent &mt()ing the title arg
 8127: 
 8128: =cut
 8129: 
 8130: sub headtag {
 8131:     my ($title,$head_extra,$args) = @_;
 8132:     
 8133:     my $function = $args->{'function'} || &get_users_function();
 8134:     my $domain   = $args->{'domain'}   || &determinedomain();
 8135:     my $bgcolor  = $args->{'bgcolor'}  || &designparm($function.'.pgbg',$domain);
 8136:     my $httphost = $args->{'use_absolute'};
 8137:     my $url = join(':',$env{'user.name'},$env{'user.domain'},
 8138: 		   $Apache::lonnet::perlvar{'lonVersion'},
 8139: 		   #time(),
 8140: 		   $env{'environment.color.timestamp'},
 8141: 		   $function,$domain,$bgcolor);
 8142: 
 8143:     $url = '/adm/css/'.&escape($url).'.css';
 8144: 
 8145:     my $result =
 8146: 	'<head>'.
 8147: 	&font_settings($args);
 8148: 
 8149:     my $inhibitprint;
 8150:     if ($args->{'print_suppress'}) {
 8151:         $inhibitprint = &print_suppression();
 8152:     }
 8153: 
 8154:     if (!$args->{'frameset'}) {
 8155: 	$result .= &Apache::lonhtmlcommon::htmlareaheaders();
 8156:     }
 8157:     if ($args->{'force_register'} && $env{'request.noversionuri'} !~ m{^/res/adm/pages/}) {
 8158:         $result .= Apache::lonxml::display_title();
 8159:     }
 8160:     if (!$args->{'no_nav_bar'} 
 8161: 	&& !$args->{'only_body'}
 8162: 	&& !$args->{'frameset'}) {
 8163: 	$result .= &help_menu_js($httphost);
 8164:         $result.=&modal_window();
 8165:         $result.=&togglebox_script();
 8166:         $result.=&wishlist_window();
 8167:         $result.=&LCprogressbarUpdate_script();
 8168:     } else {
 8169:         if ($args->{'add_modal'}) {
 8170:            $result.=&modal_window();
 8171:         }
 8172:         if ($args->{'add_wishlist'}) {
 8173:            $result.=&wishlist_window();
 8174:         }
 8175:         if ($args->{'add_togglebox'}) {
 8176:            $result.=&togglebox_script();
 8177:         }
 8178:         if ($args->{'add_progressbar'}) {
 8179:            $result.=&LCprogressbarUpdate_script();
 8180:         }
 8181:     }
 8182:     if (ref($args->{'redirect'})) {
 8183: 	my ($time,$url,$inhibit_continue) = @{$args->{'redirect'}};
 8184: 	$url = &Apache::lonenc::check_encrypt($url);
 8185: 	if (!$inhibit_continue) {
 8186: 	    $env{'internal.head.redirect'} = $url;
 8187: 	}
 8188: 	$result.=<<ADDMETA
 8189: <meta http-equiv="pragma" content="no-cache" />
 8190: <meta http-equiv="Refresh" content="$time; url=$url" />
 8191: ADDMETA
 8192:     } else {
 8193:         unless (($args->{'frameset'}) || ($args->{'js_ready'}) || ($args->{'only_body'}) || ($args->{'no_nav_bar'})) {
 8194:             my $requrl = $env{'request.uri'};
 8195:             if ($requrl eq '') {
 8196:                 $requrl = $ENV{'REQUEST_URI'};
 8197:                 $requrl =~ s/\?.+$//;
 8198:             }
 8199:             unless (($requrl =~ m{^/adm/(?:switchserver|login|authenticate|logout|groupsort|cleanup|helper|slotrequest|grades)(\?|$)}) ||
 8200:                     (($requrl =~ m{^/res/}) && (($env{'form.submitted'} eq 'scantron') ||
 8201:                      ($env{'form.grade_symb'}) || ($Apache::lonhomework::scantronmode)))) {
 8202:                 my $dom_in_use = $Apache::lonnet::perlvar{'lonDefDomain'};
 8203:                 unless (&Apache::lonnet::allowed('mau',$dom_in_use)) {
 8204:                     my %domdefs = &Apache::lonnet::get_domain_defaults($dom_in_use);
 8205:                     if (ref($domdefs{'offloadnow'}) eq 'HASH') {
 8206:                         my $lonhost = $Apache::lonnet::perlvar{'lonHostID'};
 8207:                         if ($domdefs{'offloadnow'}{$lonhost}) {
 8208:                             my $newserver = &Apache::lonnet::spareserver(30000,undef,1,$dom_in_use);
 8209:                             if (($newserver) && ($newserver ne $lonhost)) {
 8210:                                 my $numsec = 5;
 8211:                                 my $timeout = $numsec * 1000;
 8212:                                 my ($newurl,$locknum,%locks,$msg);
 8213:                                 if ($env{'request.role.adv'}) {
 8214:                                     ($locknum,%locks) = &Apache::lonnet::get_locks();
 8215:                                 }
 8216:                                 my $disable_submit = 0;
 8217:                                 if ($requrl =~ /$LONCAPA::assess_re/) {
 8218:                                     $disable_submit = 1;
 8219:                                 }
 8220:                                 if ($locknum) {
 8221:                                     my @lockinfo = sort(values(%locks));
 8222:                                     $msg = &mt('Once the following tasks are complete: ')."\\n".
 8223:                                            join(", ",sort(values(%locks)))."\\n".
 8224:                                            &mt('your session will be transferred to a different server, after you click "Roles".');
 8225:                                 } else {
 8226:                                     if (($requrl =~ m{^/res/}) && ($env{'form.submitted'} =~ /^part_/)) {
 8227:                                         $msg = &mt('Your LON-CAPA submission has been recorded')."\\n";
 8228:                                     }
 8229:                                     $msg .= &mt('Your current LON-CAPA session will be transferred to a different server in [quant,_1,second].',$numsec);
 8230:                                     $newurl = '/adm/switchserver?otherserver='.$newserver;
 8231:                                     if (($env{'request.role'}) && ($env{'request.role'} ne 'cm')) {
 8232:                                         $newurl .= '&role='.$env{'request.role'};
 8233:                                     }
 8234:                                     if ($env{'request.symb'}) {
 8235:                                         $newurl .= '&symb='.$env{'request.symb'};
 8236:                                     } else {
 8237:                                         $newurl .= '&origurl='.$requrl;
 8238:                                     }
 8239:                                 }
 8240:                                 &js_escape(\$msg);
 8241:                                 $result.=<<OFFLOAD
 8242: <meta http-equiv="pragma" content="no-cache" />
 8243: <script type="text/javascript">
 8244: // <![CDATA[
 8245: function LC_Offload_Now() {
 8246:     var dest = "$newurl";
 8247:     if (dest != '') {
 8248:         window.location.href="$newurl";
 8249:     }
 8250: }
 8251: \$(document).ready(function () {
 8252:     window.alert('$msg');
 8253:     if ($disable_submit) {
 8254:         \$(".LC_hwk_submit").prop("disabled", true);
 8255:         \$( ".LC_textline" ).prop( "readonly", "readonly");
 8256:     }
 8257:     setTimeout('LC_Offload_Now()', $timeout);
 8258: });
 8259: // ]]>
 8260: </script>
 8261: OFFLOAD
 8262:                             }
 8263:                         }
 8264:                     }
 8265:                 }
 8266:             }
 8267:         }
 8268:     }
 8269:     if (!defined($title)) {
 8270: 	$title = 'The LearningOnline Network with CAPA';
 8271:     }
 8272:     if (!$args->{'no_auto_mt_title'}) { $title = &mt($title); }
 8273:     $result .= '<title> LON-CAPA '.$title.'</title>'
 8274: 	.'<link rel="stylesheet" type="text/css" href="'.$url.'"';
 8275:     if (!$args->{'frameset'}) {
 8276:         $result .= ' /';
 8277:     }
 8278:     $result .= '>' 
 8279:         .$inhibitprint
 8280: 	.$head_extra;
 8281:     my $clientmobile;
 8282:     if (($env{'user.name'} eq '') && ($env{'user.domain'} eq '')) {
 8283:         (undef,undef,undef,undef,undef,undef,$clientmobile) = &decode_user_agent();
 8284:     } else {
 8285:         $clientmobile = $env{'browser.mobile'};
 8286:     }
 8287:     if ($clientmobile) {
 8288:         $result .= '
 8289: <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=0, minimum-scale=1.0, maximum-scale=1.0">
 8290: <meta name="apple-mobile-web-app-capable" content="yes" />';
 8291:     }
 8292:     return $result.'</head>';
 8293: }
 8294: 
 8295: =pod
 8296: 
 8297: =item * &font_settings()
 8298: 
 8299: Returns neccessary <meta> to set the proper encoding
 8300: 
 8301: Inputs: optional reference to HASH -- $args passed to &headtag()
 8302: 
 8303: =cut
 8304: 
 8305: sub font_settings {
 8306:     my ($args) = @_;
 8307:     my $headerstring='';
 8308:     if ((!$env{'browser.mathml'} && $env{'browser.unicode'}) ||
 8309:         ((ref($args) eq 'HASH') && ($args->{'browser.unicode'}))) {
 8310:         $headerstring.=
 8311:             '<meta http-equiv="Content-Type" content="text/html; charset=utf-8"';
 8312:         if (!$args->{'frameset'}) {
 8313: 	    $headerstring.= ' /';
 8314:         }
 8315: 	$headerstring .= '>'."\n";
 8316:     }
 8317:     return $headerstring;
 8318: }
 8319: 
 8320: =pod
 8321: 
 8322: =item * &print_suppression()
 8323: 
 8324: In course context returns css which causes the body to be blank when media="print",
 8325: if printout generation is unavailable for the current resource.
 8326: 
 8327: This could be because:
 8328: 
 8329: (a) printstartdate is in the future
 8330: 
 8331: (b) printenddate is in the past
 8332: 
 8333: (c) there is an active exam block with "printout"
 8334: functionality blocked
 8335: 
 8336: Users with pav, pfo or evb privileges are exempt.
 8337: 
 8338: Inputs: none
 8339: 
 8340: =cut
 8341: 
 8342: 
 8343: sub print_suppression {
 8344:     my $noprint;
 8345:     if ($env{'request.course.id'}) {
 8346:         my $scope = $env{'request.course.id'};
 8347:         if ((&Apache::lonnet::allowed('pav',$scope)) ||
 8348:             (&Apache::lonnet::allowed('pfo',$scope))) {
 8349:             return;
 8350:         }
 8351:         if ($env{'request.course.sec'} ne '') {
 8352:             $scope .= "/$env{'request.course.sec'}";
 8353:             if ((&Apache::lonnet::allowed('pav',$scope)) ||
 8354:                 (&Apache::lonnet::allowed('pfo',$scope))) {
 8355:                 return;
 8356:             }
 8357:         }
 8358:         my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 8359:         my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 8360:         my $blocked = &blocking_status('printout',$cnum,$cdom,undef,1);
 8361:         if ($blocked) {
 8362:             my $checkrole = "cm./$cdom/$cnum";
 8363:             if ($env{'request.course.sec'} ne '') {
 8364:                 $checkrole .= "/$env{'request.course.sec'}";
 8365:             }
 8366:             unless ((&Apache::lonnet::allowed('evb',undef,undef,$checkrole)) &&
 8367:                     ($env{'request.role'} !~ m{^st\./$cdom/$cnum})) {
 8368:                 $noprint = 1;
 8369:             }
 8370:         }
 8371:         unless ($noprint) {
 8372:             my $symb = &Apache::lonnet::symbread();
 8373:             if ($symb ne '') {
 8374:                 my $navmap = Apache::lonnavmaps::navmap->new();
 8375:                 if (ref($navmap)) {
 8376:                     my $res = $navmap->getBySymb($symb);
 8377:                     if (ref($res)) {
 8378:                         if (!$res->resprintable()) {
 8379:                             $noprint = 1;
 8380:                         }
 8381:                     }
 8382:                 }
 8383:             }
 8384:         }
 8385:         if ($noprint) {
 8386:             return <<"ENDSTYLE";
 8387: <style type="text/css" media="print">
 8388:     body { display:none }
 8389: </style>
 8390: ENDSTYLE
 8391:         }
 8392:     }
 8393:     return;
 8394: }
 8395: 
 8396: =pod
 8397: 
 8398: =item * &xml_begin()
 8399: 
 8400: Returns the needed doctype and <html>
 8401: 
 8402: Inputs: none
 8403: 
 8404: =cut
 8405: 
 8406: sub xml_begin {
 8407:     my ($is_frameset) = @_;
 8408:     my $output='';
 8409: 
 8410:     if ($env{'browser.mathml'}) {
 8411: 	$output='<?xml version="1.0"?>'
 8412:             #.'<?xml-stylesheet type="text/css" href="/adm/MathML/mathml.css"?>'."\n"
 8413: #            .'<!DOCTYPE html SYSTEM "/adm/MathML/mathml.dtd" '
 8414:             
 8415: #	    .'<!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">] >'
 8416: 	    .'<!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">'
 8417:             .'<html xmlns:math="http://www.w3.org/1998/Math/MathML" ' 
 8418: 	    .'xmlns="http://www.w3.org/1999/xhtml">';
 8419:     } elsif ($is_frameset) {
 8420:         $output='<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Frameset//EN" "http://www.w3.org/TR/html4/frameset.dtd">'."\n".
 8421:                 '<html>'."\n";
 8422:     } else {
 8423: 	$output='<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">'."\n".
 8424:                 '<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">'."\n";
 8425:     }
 8426:     return $output;
 8427: }
 8428: 
 8429: =pod
 8430: 
 8431: =item * &start_page()
 8432: 
 8433: Returns a complete <html> .. <body> section for LON-CAPA web pages.
 8434: 
 8435: Inputs:
 8436: 
 8437: =over 4
 8438: 
 8439: $title - optional title for the page
 8440: 
 8441: $head_extra - optional extra HTML to incude inside the <head>
 8442: 
 8443: $args - additional optional args supported are:
 8444: 
 8445: =over 8
 8446: 
 8447:              only_body      -> is true will set &bodytag() onlybodytag
 8448:                                     arg on
 8449:              no_nav_bar     -> is true will set &bodytag() no_nav_bar arg on
 8450:              add_entries    -> additional attributes to add to the  <body>
 8451:              domain         -> force to color decorate a page for a 
 8452:                                     specific domain
 8453:              function       -> force usage of a specific rolish color
 8454:                                     scheme
 8455:              redirect       -> see &headtag()
 8456:              bgcolor        -> override the default page bg color
 8457:              js_ready       -> return a string ready for being used in 
 8458:                                     a javascript writeln
 8459:              html_encode    -> return a string ready for being used in 
 8460:                                     a html attribute
 8461:              force_register -> if is true will turn on the &bodytag()
 8462:                                     $forcereg arg
 8463:              frameset       -> if true will start with a <frameset>
 8464:                                     rather than <body>
 8465:              skip_phases    -> hash ref of 
 8466:                                     head -> skip the <html><head> generation
 8467:                                     body -> skip all <body> generation
 8468:              no_auto_mt_title -> prevent &mt()ing the title arg
 8469:              bread_crumbs ->             Array containing breadcrumbs
 8470:              bread_crumbs_component ->  if exists show it as headline else show only the breadcrumbs
 8471:              group          -> includes the current group, if page is for a 
 8472:                                specific group  
 8473: 
 8474: =back
 8475: 
 8476: =back
 8477: 
 8478: =cut
 8479: 
 8480: sub start_page {
 8481:     my ($title,$head_extra,$args) = @_;
 8482:     #&Apache::lonnet::logthis("start_page ".join(':',caller(0)));
 8483: 
 8484:     $env{'internal.start_page'}++;
 8485:     my ($result,@advtools);
 8486: 
 8487:     if (! exists($args->{'skip_phases'}{'head'}) ) {
 8488:         $result .= &xml_begin($args->{'frameset'}) . &headtag($title, $head_extra, $args);
 8489:     }
 8490:     
 8491:     if (! exists($args->{'skip_phases'}{'body'}) ) {
 8492: 	if ($args->{'frameset'}) {
 8493: 	    my $attr_string = &make_attr_string($args->{'force_register'},
 8494: 						$args->{'add_entries'});
 8495: 	    $result .= "\n<frameset $attr_string>\n";
 8496:         } else {
 8497:             $result .=
 8498:                 &bodytag($title, 
 8499:                          $args->{'function'},       $args->{'add_entries'},
 8500:                          $args->{'only_body'},      $args->{'domain'},
 8501:                          $args->{'force_register'}, $args->{'no_nav_bar'},
 8502:                          $args->{'bgcolor'},        $args,
 8503:                          \@advtools);
 8504:         }
 8505:     }
 8506: 
 8507:     if ($args->{'js_ready'}) {
 8508: 		$result = &js_ready($result);
 8509:     }
 8510:     if ($args->{'html_encode'}) {
 8511: 		$result = &html_encode($result);
 8512:     }
 8513: 
 8514:     # Preparation for new and consistent functionlist at top of screen
 8515:     # if ($args->{'functionlist'}) {
 8516:     #            $result .= &build_functionlist();
 8517:     #}
 8518: 
 8519:     # Don't add anything more if only_body wanted or in const space
 8520:     return $result if    $args->{'only_body'} 
 8521:                       || $env{'request.state'} eq 'construct';
 8522: 
 8523:     #Breadcrumbs
 8524:     if (exists($args->{'bread_crumbs'}) or exists($args->{'bread_crumbs_component'})) {
 8525: 		&Apache::lonhtmlcommon::clear_breadcrumbs();
 8526: 		#if any br links exists, add them to the breadcrumbs
 8527: 		if (exists($args->{'bread_crumbs'}) and ref($args->{'bread_crumbs'}) eq 'ARRAY') {         
 8528: 			foreach my $crumb (@{$args->{'bread_crumbs'}}){
 8529: 				&Apache::lonhtmlcommon::add_breadcrumb($crumb);
 8530: 			}
 8531: 		}
 8532:                 # if @advtools array contains items add then to the breadcrumbs
 8533:                 if (@advtools > 0) {
 8534:                     &Apache::lonmenu::advtools_crumbs(@advtools);
 8535:                 }
 8536: 
 8537: 		#if bread_crumbs_component exists show it as headline else show only the breadcrumbs
 8538: 		if(exists($args->{'bread_crumbs_component'})){
 8539: 			$result .= &Apache::lonhtmlcommon::breadcrumbs($args->{'bread_crumbs_component'});
 8540: 		} elsif ($args->{'crstype'} eq 'Placement') {
 8541: 			$result .= &Apache::lonhtmlcommon::breadcrumbs('','','','','','','','','',
 8542:                                                                        $args->{'crstype'});
 8543:                 } else {
 8544: 			$result .= &Apache::lonhtmlcommon::breadcrumbs();
 8545: 		}
 8546:     }
 8547:     return $result;
 8548: }
 8549: 
 8550: sub end_page {
 8551:     my ($args) = @_;
 8552:     $env{'internal.end_page'}++;
 8553:     my $result;
 8554:     if ($args->{'discussion'}) {
 8555: 	my ($target,$parser);
 8556: 	if (ref($args->{'discussion'})) {
 8557: 	    ($target,$parser) =($args->{'discussion'}{'target'},
 8558: 				$args->{'discussion'}{'parser'});
 8559: 	}
 8560: 	$result .= &Apache::lonxml::xmlend($target,$parser);
 8561:     }
 8562:     if ($args->{'frameset'}) {
 8563: 	$result .= '</frameset>';
 8564:     } else {
 8565: 	$result .= &endbodytag($args);
 8566:     }
 8567:     unless ($args->{'notbody'}) {
 8568:         $result .= "\n</html>";
 8569:     }
 8570: 
 8571:     if ($args->{'js_ready'}) {
 8572: 	$result = &js_ready($result);
 8573:     }
 8574: 
 8575:     if ($args->{'html_encode'}) {
 8576: 	$result = &html_encode($result);
 8577:     }
 8578: 
 8579:     return $result;
 8580: }
 8581: 
 8582: sub wishlist_window {
 8583:     return(<<'ENDWISHLIST');
 8584: <script type="text/javascript">
 8585: // <![CDATA[
 8586: // <!-- BEGIN LON-CAPA Internal
 8587: function set_wishlistlink(title, path) {
 8588:     if (!title) {
 8589:         title = document.title;
 8590:         title = title.replace(/^LON-CAPA /,'');
 8591:     }
 8592:     title = encodeURIComponent(title);
 8593:     title = title.replace("'","\\\'");
 8594:     if (!path) {
 8595:         path = location.pathname;
 8596:     }
 8597:     path = encodeURIComponent(path);
 8598:     path = path.replace("'","\\\'");
 8599:     Win = window.open('/adm/wishlist?mode=newLink&setTitle='+title+'&setPath='+path,
 8600:                       'wishlistNewLink','width=560,height=350,scrollbars=0');
 8601: }
 8602: // END LON-CAPA Internal -->
 8603: // ]]>
 8604: </script>
 8605: ENDWISHLIST
 8606: }
 8607: 
 8608: sub modal_window {
 8609:     return(<<'ENDMODAL');
 8610: <script type="text/javascript">
 8611: // <![CDATA[
 8612: // <!-- BEGIN LON-CAPA Internal
 8613: var modalWindow = {
 8614: 	parent:"body",
 8615: 	windowId:null,
 8616: 	content:null,
 8617: 	width:null,
 8618: 	height:null,
 8619: 	close:function()
 8620: 	{
 8621: 	        $(".LCmodal-window").remove();
 8622: 	        $(".LCmodal-overlay").remove();
 8623: 	},
 8624: 	open:function()
 8625: 	{
 8626: 		var modal = "";
 8627: 		modal += "<div class=\"LCmodal-overlay\"></div>";
 8628: 		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;\">";
 8629: 		modal += this.content;
 8630: 		modal += "</div>";	
 8631: 
 8632: 		$(this.parent).append(modal);
 8633: 
 8634: 		$(".LCmodal-window").append("<a class=\"LCclose-window\"></a>");
 8635: 		$(".LCclose-window").click(function(){modalWindow.close();});
 8636: 		$(".LCmodal-overlay").click(function(){modalWindow.close();});
 8637: 	}
 8638: };
 8639: 	var openMyModal = function(source,width,height,scrolling,transparency,style)
 8640: 	{
 8641:                 source = source.replace("'","&#39;");
 8642: 		modalWindow.windowId = "myModal";
 8643: 		modalWindow.width = width;
 8644: 		modalWindow.height = height;
 8645: 		modalWindow.content = "<iframe width='"+width+"' height='"+height+"' frameborder='0' scrolling='"+scrolling+"' allowtransparency='"+transparency+"' src='" + source + "' style='"+style+"'></iframe>";
 8646: 		modalWindow.open();
 8647: 	};
 8648: // END LON-CAPA Internal -->
 8649: // ]]>
 8650: </script>
 8651: ENDMODAL
 8652: }
 8653: 
 8654: sub modal_link {
 8655:     my ($link,$linktext,$width,$height,$target,$scrolling,$title,$transparency,$style)=@_;
 8656:     unless ($width) { $width=480; }
 8657:     unless ($height) { $height=400; }
 8658:     unless ($scrolling) { $scrolling='yes'; }
 8659:     unless ($transparency) { $transparency='true'; }
 8660: 
 8661:     my $target_attr;
 8662:     if (defined($target)) {
 8663:         $target_attr = 'target="'.$target.'"';
 8664:     }
 8665:     return <<"ENDLINK";
 8666: <a href="$link" $target_attr title="$title" onclick="javascript:openMyModal('$link',$width,$height,'$scrolling','$transparency','$style'); return false;">
 8667:            $linktext</a>
 8668: ENDLINK
 8669: }
 8670: 
 8671: sub modal_adhoc_script {
 8672:     my ($funcname,$width,$height,$content)=@_;
 8673:     return (<<ENDADHOC);
 8674: <script type="text/javascript">
 8675: // <![CDATA[
 8676:         var $funcname = function()
 8677:         {
 8678:                 modalWindow.windowId = "myModal";
 8679:                 modalWindow.width = $width;
 8680:                 modalWindow.height = $height;
 8681:                 modalWindow.content = '$content';
 8682:                 modalWindow.open();
 8683:         };  
 8684: // ]]>
 8685: </script>
 8686: ENDADHOC
 8687: }
 8688: 
 8689: sub modal_adhoc_inner {
 8690:     my ($funcname,$width,$height,$content)=@_;
 8691:     my $innerwidth=$width-20;
 8692:     $content=&js_ready(
 8693:                  &start_page('Dialog',undef,{'only_body'=>1,'bgcolor'=>'#FFFFFF'}).
 8694:                  &start_scrollbox($width.'px',$innerwidth.'px',$height.'px','myModal','#FFFFFF',undef,1).
 8695:                  $content.
 8696:                  &end_scrollbox().
 8697:                  &end_page()
 8698:              );
 8699:     return &modal_adhoc_script($funcname,$width,$height,$content);
 8700: }
 8701: 
 8702: sub modal_adhoc_window {
 8703:     my ($funcname,$width,$height,$content,$linktext)=@_;
 8704:     return &modal_adhoc_inner($funcname,$width,$height,$content).
 8705:            "<a href=\"javascript:$funcname();void(0);\">".$linktext."</a>";
 8706: }
 8707: 
 8708: sub modal_adhoc_launch {
 8709:     my ($funcname,$width,$height,$content)=@_;
 8710:     return &modal_adhoc_inner($funcname,$width,$height,$content).(<<ENDLAUNCH);
 8711: <script type="text/javascript">
 8712: // <![CDATA[
 8713: $funcname();
 8714: // ]]>
 8715: </script>
 8716: ENDLAUNCH
 8717: }
 8718: 
 8719: sub modal_adhoc_close {
 8720:     return (<<ENDCLOSE);
 8721: <script type="text/javascript">
 8722: // <![CDATA[
 8723: modalWindow.close();
 8724: // ]]>
 8725: </script>
 8726: ENDCLOSE
 8727: }
 8728: 
 8729: sub togglebox_script {
 8730:    return(<<ENDTOGGLE);
 8731: <script type="text/javascript"> 
 8732: // <![CDATA[
 8733: function LCtoggleDisplay(id,hidetext,showtext) {
 8734:    link = document.getElementById(id + "link").childNodes[0];
 8735:    with (document.getElementById(id).style) {
 8736:       if (display == "none" ) {
 8737:           display = "inline";
 8738:           link.nodeValue = hidetext;
 8739:         } else {
 8740:           display = "none";
 8741:           link.nodeValue = showtext;
 8742:        }
 8743:    }
 8744: }
 8745: // ]]>
 8746: </script>
 8747: ENDTOGGLE
 8748: }
 8749: 
 8750: sub start_togglebox {
 8751:     my ($id,$heading,$headerbg,$hidetext,$showtext)=@_;
 8752:     unless ($heading) { $heading=''; } else { $heading.=' '; }
 8753:     unless ($showtext) { $showtext=&mt('show'); }
 8754:     unless ($hidetext) { $hidetext=&mt('hide'); }
 8755:     unless ($headerbg) { $headerbg='#FFFFFF'; }
 8756:     return &start_data_table().
 8757:            &start_data_table_header_row().
 8758:            '<td bgcolor="'.$headerbg.'">'.$heading.
 8759:            '[<a id="'.$id.'link" href="javascript:LCtoggleDisplay(\''.$id.'\',\''.$hidetext.'\',\''.
 8760:            $showtext.'\')">'.$showtext.'</a>]</td>'.
 8761:            &end_data_table_header_row().
 8762:            '<tr id="'.$id.'" style="display:none""><td>';
 8763: }
 8764: 
 8765: sub end_togglebox {
 8766:     return '</td></tr>'.&end_data_table();
 8767: }
 8768: 
 8769: sub LCprogressbar_script {
 8770:    my ($id)=@_;
 8771:    return(<<ENDPROGRESS);
 8772: <script type="text/javascript">
 8773: // <![CDATA[
 8774: \$('#progressbar$id').progressbar({
 8775:   value: 0,
 8776:   change: function(event, ui) {
 8777:     var newVal = \$(this).progressbar('option', 'value');
 8778:     \$('.pblabel', this).text(LCprogressTxt);
 8779:   }
 8780: });
 8781: // ]]>
 8782: </script>
 8783: ENDPROGRESS
 8784: }
 8785: 
 8786: sub LCprogressbarUpdate_script {
 8787:    return(<<ENDPROGRESSUPDATE);
 8788: <style type="text/css">
 8789: .ui-progressbar { position:relative; }
 8790: .pblabel { position: absolute; width: 100%; text-align: center; line-height: 1.9em; }
 8791: </style>
 8792: <script type="text/javascript">
 8793: // <![CDATA[
 8794: var LCprogressTxt='---';
 8795: 
 8796: function LCupdateProgress(percent,progresstext,id) {
 8797:    LCprogressTxt=progresstext;
 8798:    \$('#progressbar'+id).progressbar('value',percent);
 8799: }
 8800: // ]]>
 8801: </script>
 8802: ENDPROGRESSUPDATE
 8803: }
 8804: 
 8805: my $LClastpercent;
 8806: my $LCidcnt;
 8807: my $LCcurrentid;
 8808: 
 8809: sub LCprogressbar {
 8810:     my ($r)=(@_);
 8811:     $LClastpercent=0;
 8812:     $LCidcnt++;
 8813:     $LCcurrentid=$$.'_'.$LCidcnt;
 8814:     my $starting=&mt('Starting');
 8815:     my $content=(<<ENDPROGBAR);
 8816:   <div id="progressbar$LCcurrentid">
 8817:     <span class="pblabel">$starting</span>
 8818:   </div>
 8819: ENDPROGBAR
 8820:     &r_print($r,$content.&LCprogressbar_script($LCcurrentid));
 8821: }
 8822: 
 8823: sub LCprogressbarUpdate {
 8824:     my ($r,$val,$text)=@_;
 8825:     unless ($val) { 
 8826:        if ($LClastpercent) {
 8827:            $val=$LClastpercent;
 8828:        } else {
 8829:            $val=0;
 8830:        }
 8831:     }
 8832:     if ($val<0) { $val=0; }
 8833:     if ($val>100) { $val=0; }
 8834:     $LClastpercent=$val;
 8835:     unless ($text) { $text=$val.'%'; }
 8836:     $text=&js_ready($text);
 8837:     &r_print($r,<<ENDUPDATE);
 8838: <script type="text/javascript">
 8839: // <![CDATA[
 8840: LCupdateProgress($val,'$text','$LCcurrentid');
 8841: // ]]>
 8842: </script>
 8843: ENDUPDATE
 8844: }
 8845: 
 8846: sub LCprogressbarClose {
 8847:     my ($r)=@_;
 8848:     $LClastpercent=0;
 8849:     &r_print($r,<<ENDCLOSE);
 8850: <script type="text/javascript">
 8851: // <![CDATA[
 8852: \$("#progressbar$LCcurrentid").hide('slow'); 
 8853: // ]]>
 8854: </script>
 8855: ENDCLOSE
 8856: }
 8857: 
 8858: sub r_print {
 8859:     my ($r,$to_print)=@_;
 8860:     if ($r) {
 8861:       $r->print($to_print);
 8862:       $r->rflush();
 8863:     } else {
 8864:       print($to_print);
 8865:     }
 8866: }
 8867: 
 8868: sub html_encode {
 8869:     my ($result) = @_;
 8870: 
 8871:     $result = &HTML::Entities::encode($result,'<>&"');
 8872:     
 8873:     return $result;
 8874: }
 8875: 
 8876: sub js_ready {
 8877:     my ($result) = @_;
 8878: 
 8879:     $result =~ s/[\n\r]/ /xmsg;
 8880:     $result =~ s/\\/\\\\/xmsg;
 8881:     $result =~ s/'/\\'/xmsg;
 8882:     $result =~ s{</}{<\\/}xmsg;
 8883:     
 8884:     return $result;
 8885: }
 8886: 
 8887: sub validate_page {
 8888:     if (  exists($env{'internal.start_page'})
 8889: 	  &&     $env{'internal.start_page'} > 1) {
 8890: 	&Apache::lonnet::logthis('start_page called multiple times '.
 8891: 				 $env{'internal.start_page'}.' '.
 8892: 				 $ENV{'request.filename'});
 8893:     }
 8894:     if (  exists($env{'internal.end_page'})
 8895: 	  &&     $env{'internal.end_page'} > 1) {
 8896: 	&Apache::lonnet::logthis('end_page called multiple times '.
 8897: 				 $env{'internal.end_page'}.' '.
 8898: 				 $env{'request.filename'});
 8899:     }
 8900:     if (     exists($env{'internal.start_page'})
 8901: 	&& ! exists($env{'internal.end_page'})) {
 8902: 	&Apache::lonnet::logthis('start_page called without end_page '.
 8903: 				 $env{'request.filename'});
 8904:     }
 8905:     if (   ! exists($env{'internal.start_page'})
 8906: 	&&   exists($env{'internal.end_page'})) {
 8907: 	&Apache::lonnet::logthis('end_page called without start_page'.
 8908: 				 $env{'request.filename'});
 8909:     }
 8910: }
 8911: 
 8912: 
 8913: sub start_scrollbox {
 8914:     my ($outerwidth,$width,$height,$id,$bgcolor,$cursor,$needjsready) = @_;
 8915:     unless ($outerwidth) { $outerwidth='520px'; }
 8916:     unless ($width) { $width='500px'; }
 8917:     unless ($height) { $height='200px'; }
 8918:     my ($table_id,$div_id,$tdcol);
 8919:     if ($id ne '') {
 8920:         $table_id = ' id="table_'.$id.'"';
 8921:         $div_id = ' id="div_'.$id.'"';
 8922:     }
 8923:     if ($bgcolor ne '') {
 8924:         $tdcol = "background-color: $bgcolor;";
 8925:     }
 8926:     my $nicescroll_js;
 8927:     if ($env{'browser.mobile'}) {
 8928:         $nicescroll_js = &nicescroll_javascript('div_'.$id,$cursor,$needjsready);
 8929:     }
 8930:     return <<"END";
 8931: $nicescroll_js
 8932: 
 8933: <table style="width: $outerwidth; border: 1px solid none;"$table_id><tr><td style="width: $width;$tdcol">
 8934: <div style="overflow:auto; width:$width; height:$height;"$div_id>
 8935: END
 8936: }
 8937: 
 8938: sub end_scrollbox {
 8939:     return '</div></td></tr></table>';
 8940: }
 8941: 
 8942: sub nicescroll_javascript {
 8943:     my ($id,$cursor,$needjsready,$framecheck,$location) = @_;
 8944:     my %options;
 8945:     if (ref($cursor) eq 'HASH') {
 8946:         %options = %{$cursor};
 8947:     }
 8948:     unless ($options{'railalign'} =~ /^left|right$/) {
 8949:         $options{'railalign'} = 'left';
 8950:     }
 8951:     unless ($options{'cursorcolor'} =~ /^\#\w+$/) {
 8952:         my $function  = &get_users_function();
 8953:         $options{'cursorcolor'} = &designparm($function.'.sidebg',$env{'request.role.domain'});
 8954:         unless ($options{'cursorcolor'} =~ /^\#\w+$/) {
 8955:             $options{'cursorcolor'} = '#00F';
 8956:         }
 8957:     }
 8958:     if ($options{'cursoropacity'} =~ /^[\d.]+$/) {
 8959:         unless ($options{'cursoropacity'} >= 0.0 && $options{'cursoropacity'} <=1.0) {
 8960:             $options{'cursoropacity'}='1.0';
 8961:         }
 8962:     } else {
 8963:         $options{'cursoropacity'}='1.0';
 8964:     }
 8965:     if ($options{'cursorfixedheight'} eq 'none') {
 8966:         delete($options{'cursorfixedheight'});
 8967:     } else {
 8968:         unless ($options{'cursorfixedheight'} =~ /^\d+$/) { $options{'cursorfixedheight'}='50'; }
 8969:     }
 8970:     unless ($options{'railoffset'} =~ /^{[\w\:\d\-,]+}$/) {
 8971:         delete($options{'railoffset'});
 8972:     }
 8973:     my @niceoptions;
 8974:     while (my($key,$value) = each(%options)) {
 8975:         if ($value =~ /^\{.+\}$/) {
 8976:             push(@niceoptions,$key.':'.$value);
 8977:         } else {
 8978:             push(@niceoptions,$key.':"'.$value.'"');
 8979:         }
 8980:     }
 8981:     my $nicescroll_js = '
 8982: $(document).ready(
 8983:       function() {
 8984:           $("#'.$id.'").niceScroll({'.join(',',@niceoptions).'});
 8985:       }
 8986: );
 8987: ';
 8988:     if ($framecheck) {
 8989:         $nicescroll_js .= '
 8990: function expand_div(caller) {
 8991:     if (top === self) {
 8992:         document.getElementById("'.$id.'").style.width = "auto";
 8993:         document.getElementById("'.$id.'").style.height = "auto";
 8994:     } else {
 8995:         try {
 8996:             if (parent.frames) {
 8997:                 if (parent.frames.length > 1) {
 8998:                     var framesrc = parent.frames[1].location.href;
 8999:                     var currsrc = framesrc.replace(/\#.*$/,"");
 9000:                     if ((caller == "search") || (currsrc == "'.$location.'")) {
 9001:                         document.getElementById("'.$id.'").style.width = "auto";
 9002:                         document.getElementById("'.$id.'").style.height = "auto";
 9003:                     }
 9004:                 }
 9005:             }
 9006:         } catch (e) {
 9007:             return;
 9008:         }
 9009:     }
 9010:     return;
 9011: }
 9012: ';
 9013:     }
 9014:     if ($needjsready) {
 9015:         $nicescroll_js = '
 9016: <script type="text/javascript">'."\n".$nicescroll_js."\n</script>\n";
 9017:     } else {
 9018:         $nicescroll_js = &Apache::lonhtmlcommon::scripttag($nicescroll_js);
 9019:     }
 9020:     return $nicescroll_js;
 9021: }
 9022: 
 9023: sub simple_error_page {
 9024:     my ($r,$title,$msg,$args) = @_;
 9025:     if (ref($args) eq 'HASH') {
 9026:         if (!$args->{'no_auto_mt_msg'}) { $msg = &mt($msg); }
 9027:     } else {
 9028:         $msg = &mt($msg);
 9029:     }
 9030: 
 9031:     my $page =
 9032: 	&Apache::loncommon::start_page($title).
 9033: 	'<p class="LC_error">'.$msg.'</p>'.
 9034: 	&Apache::loncommon::end_page();
 9035:     if (ref($r)) {
 9036: 	$r->print($page);
 9037: 	return;
 9038:     }
 9039:     return $page;
 9040: }
 9041: 
 9042: {
 9043:     my @row_count;
 9044: 
 9045:     sub start_data_table_count {
 9046:         unshift(@row_count, 0);
 9047:         return;
 9048:     }
 9049: 
 9050:     sub end_data_table_count {
 9051:         shift(@row_count);
 9052:         return;
 9053:     }
 9054: 
 9055:     sub start_data_table {
 9056: 	my ($add_class,$id) = @_;
 9057: 	my $css_class = (join(' ','LC_data_table',$add_class));
 9058:         my $table_id;
 9059:         if (defined($id)) {
 9060:             $table_id = ' id="'.$id.'"';
 9061:         }
 9062: 	&start_data_table_count();
 9063: 	return '<table class="'.$css_class.'"'.$table_id.'>'."\n";
 9064:     }
 9065: 
 9066:     sub end_data_table {
 9067: 	&end_data_table_count();
 9068: 	return '</table>'."\n";;
 9069:     }
 9070: 
 9071:     sub start_data_table_row {
 9072: 	my ($add_class, $id) = @_;
 9073: 	$row_count[0]++;
 9074: 	my $css_class = ($row_count[0] % 2)?'LC_odd_row':'LC_even_row';
 9075: 	$css_class = (join(' ',$css_class,$add_class)) unless ($add_class eq '');
 9076:         $id = (' id="'.$id.'"') unless ($id eq '');
 9077:         return  '<tr class="'.$css_class.'"'.$id.'>'."\n";
 9078:     }
 9079:     
 9080:     sub continue_data_table_row {
 9081: 	my ($add_class, $id) = @_;
 9082: 	my $css_class = ($row_count[0] % 2)?'LC_odd_row':'LC_even_row';
 9083: 	$css_class = (join(' ',$css_class,$add_class)) unless ($add_class eq '');
 9084:         $id = (' id="'.$id.'"') unless ($id eq '');
 9085:         return  '<tr class="'.$css_class.'"'.$id.'>'."\n";
 9086:     }
 9087: 
 9088:     sub end_data_table_row {
 9089: 	return '</tr>'."\n";;
 9090:     }
 9091: 
 9092:     sub start_data_table_empty_row {
 9093: #	$row_count[0]++;
 9094: 	return  '<tr class="LC_empty_row" >'."\n";;
 9095:     }
 9096: 
 9097:     sub end_data_table_empty_row {
 9098: 	return '</tr>'."\n";;
 9099:     }
 9100: 
 9101:     sub start_data_table_header_row {
 9102: 	return  '<tr class="LC_header_row">'."\n";;
 9103:     }
 9104: 
 9105:     sub end_data_table_header_row {
 9106: 	return '</tr>'."\n";;
 9107:     }
 9108: 
 9109:     sub data_table_caption {
 9110:         my $caption = shift;
 9111:         return "<caption class=\"LC_caption\">$caption</caption>";
 9112:     }
 9113: }
 9114: 
 9115: =pod
 9116: 
 9117: =item * &inhibit_menu_check($arg)
 9118: 
 9119: Checks for a inhibitmenu state and generates output to preserve it
 9120: 
 9121: Inputs:         $arg - can be any of
 9122:                      - undef - in which case the return value is a string 
 9123:                                to add  into arguments list of a uri
 9124:                      - 'input' - in which case the return value is a HTML
 9125:                                  <form> <input> field of type hidden to
 9126:                                  preserve the value
 9127:                      - a url - in which case the return value is the url with
 9128:                                the neccesary cgi args added to preserve the
 9129:                                inhibitmenu state
 9130:                      - a ref to a url - no return value, but the string is
 9131:                                         updated to include the neccessary cgi
 9132:                                         args to preserve the inhibitmenu state
 9133: 
 9134: =cut
 9135: 
 9136: sub inhibit_menu_check {
 9137:     my ($arg) = @_;
 9138:     &get_unprocessed_cgi($ENV{'QUERY_STRING'}, ['inhibitmenu']);
 9139:     if ($arg eq 'input') {
 9140: 	if ($env{'form.inhibitmenu'}) {
 9141: 	    return '<input type="hidden" name="inhibitmenu" value="'.$env{'form.inhibitmenu'}.'" />';
 9142: 	} else {
 9143: 	    return
 9144: 	}
 9145:     }
 9146:     if ($env{'form.inhibitmenu'}) {
 9147: 	if (ref($arg)) {
 9148: 	    $$arg .= '?inhibitmenu='.$env{'form.inhibitmenu'};
 9149: 	} elsif ($arg eq '') {
 9150: 	    $arg .= 'inhibitmenu='.$env{'form.inhibitmenu'};
 9151: 	} else {
 9152: 	    $arg .= '?inhibitmenu='.$env{'form.inhibitmenu'};
 9153: 	}
 9154:     }
 9155:     if (!ref($arg)) {
 9156: 	return $arg;
 9157:     }
 9158: }
 9159: 
 9160: ###############################################
 9161: 
 9162: =pod
 9163: 
 9164: =back
 9165: 
 9166: =head1 User Information Routines
 9167: 
 9168: =over 4
 9169: 
 9170: =item * &get_users_function()
 9171: 
 9172: Used by &bodytag to determine the current users primary role.
 9173: Returns either 'student','coordinator','admin', or 'author'.
 9174: 
 9175: =cut
 9176: 
 9177: ###############################################
 9178: sub get_users_function {
 9179:     my $function = 'norole';
 9180:     if ($env{'request.role'}=~/^(st)/) {
 9181:         $function='student';
 9182:     }
 9183:     if ($env{'request.role'}=~/^(cc|co|in|ta|ep)/) {
 9184:         $function='coordinator';
 9185:     }
 9186:     if ($env{'request.role'}=~/^(su|dc|ad|li)/) {
 9187:         $function='admin';
 9188:     }
 9189:     if (($env{'request.role'}=~/^(au|ca|aa)/) ||
 9190:         ($ENV{'REQUEST_URI'}=~ m{/^(/priv)})) {
 9191:         $function='author';
 9192:     }
 9193:     return $function;
 9194: }
 9195: 
 9196: ###############################################
 9197: 
 9198: =pod
 9199: 
 9200: =item * &show_course()
 9201: 
 9202: Used by lonmenu.pm and lonroles.pm to determine whether to use the word
 9203: 'Courses' or 'Roles' in inline navigation and on screen displaying user's roles.
 9204: 
 9205: Inputs:
 9206: None
 9207: 
 9208: Outputs:
 9209: Scalar: 1 if 'Course' to be used, 0 otherwise.
 9210: 
 9211: =cut
 9212: 
 9213: ###############################################
 9214: sub show_course {
 9215:     my $course = !$env{'user.adv'};
 9216:     if (!$env{'user.adv'}) {
 9217:         foreach my $env (keys(%env)) {
 9218:             next if ($env !~ m/^user\.priv\./);
 9219:             if ($env !~ m/^user\.priv\.(?:st|cm)/) {
 9220:                 $course = 0;
 9221:                 last;
 9222:             }
 9223:         }
 9224:     }
 9225:     return $course;
 9226: }
 9227: 
 9228: ###############################################
 9229: 
 9230: =pod
 9231: 
 9232: =item * &check_user_status()
 9233: 
 9234: Determines current status of supplied role for a
 9235: specific user. Roles can be active, previous or future.
 9236: 
 9237: Inputs: 
 9238: user's domain, user's username, course's domain,
 9239: course's number, optional section ID.
 9240: 
 9241: Outputs:
 9242: role status: active, previous or future. 
 9243: 
 9244: =cut
 9245: 
 9246: sub check_user_status {
 9247:     my ($udom,$uname,$cdom,$crs,$role,$sec) = @_;
 9248:     my %userinfo = &Apache::lonnet::dump('roles',$udom,$uname);
 9249:     my @uroles = keys(%userinfo);
 9250:     my $srchstr;
 9251:     my $active_chk = 'none';
 9252:     my $now = time;
 9253:     if (@uroles > 0) {
 9254:         if (($role eq 'cc') || ($role eq 'co') || ($sec eq '') || (!defined($sec))) {
 9255:             $srchstr = '/'.$cdom.'/'.$crs.'_'.$role;
 9256:         } else {
 9257:             $srchstr = '/'.$cdom.'/'.$crs.'/'.$sec.'_'.$role;
 9258:         }
 9259:         if (grep/^\Q$srchstr\E$/,@uroles) {
 9260:             my $role_end = 0;
 9261:             my $role_start = 0;
 9262:             $active_chk = 'active';
 9263:             if ($userinfo{$srchstr} =~ m/^\Q$role\E_(\d+)/) {
 9264:                 $role_end = $1;
 9265:                 if ($userinfo{$srchstr} =~ m/^\Q$role\E_\Q$role_end\E_(\d+)$/) {
 9266:                     $role_start = $1;
 9267:                 }
 9268:             }
 9269:             if ($role_start > 0) {
 9270:                 if ($now < $role_start) {
 9271:                     $active_chk = 'future';
 9272:                 }
 9273:             }
 9274:             if ($role_end > 0) {
 9275:                 if ($now > $role_end) {
 9276:                     $active_chk = 'previous';
 9277:                 }
 9278:             }
 9279:         }
 9280:     }
 9281:     return $active_chk;
 9282: }
 9283: 
 9284: ###############################################
 9285: 
 9286: =pod
 9287: 
 9288: =item * &get_sections()
 9289: 
 9290: Determines all the sections for a course including
 9291: sections with students and sections containing other roles.
 9292: Incoming parameters: 
 9293: 
 9294: 1. domain
 9295: 2. course number 
 9296: 3. reference to array containing roles for which sections should 
 9297: be gathered (optional).
 9298: 4. reference to array containing status types for which sections 
 9299: should be gathered (optional).
 9300: 
 9301: If the third argument is undefined, sections are gathered for any role. 
 9302: If the fourth argument is undefined, sections are gathered for any status.
 9303: Permissible values are 'active' or 'future' or 'previous'.
 9304:  
 9305: Returns section hash (keys are section IDs, values are
 9306: number of users in each section), subject to the
 9307: optional roles filter, optional status filter 
 9308: 
 9309: =cut
 9310: 
 9311: ###############################################
 9312: sub get_sections {
 9313:     my ($cdom,$cnum,$possible_roles,$possible_status) = @_;
 9314:     if (!defined($cdom) || !defined($cnum)) {
 9315:         my $cid =  $env{'request.course.id'};
 9316: 
 9317: 	return if (!defined($cid));
 9318: 
 9319:         $cdom = $env{'course.'.$cid.'.domain'};
 9320:         $cnum = $env{'course.'.$cid.'.num'};
 9321:     }
 9322: 
 9323:     my %sectioncount;
 9324:     my $now = time;
 9325: 
 9326:     my $check_students = 1;
 9327:     my $only_students = 0;
 9328:     if (ref($possible_roles) eq 'ARRAY') {
 9329:         if (grep(/^st$/,@{$possible_roles})) {
 9330:             if (@{$possible_roles} == 1) {
 9331:                 $only_students = 1;
 9332:             }
 9333:         } else {
 9334:             $check_students = 0;
 9335:         }
 9336:     }
 9337: 
 9338:     if ($check_students) { 
 9339: 	my ($classlist) = &Apache::loncoursedata::get_classlist($cdom,$cnum);
 9340: 	my $sec_index = &Apache::loncoursedata::CL_SECTION();
 9341: 	my $status_index = &Apache::loncoursedata::CL_STATUS();
 9342:         my $start_index = &Apache::loncoursedata::CL_START();
 9343:         my $end_index = &Apache::loncoursedata::CL_END();
 9344:         my $status;
 9345: 	while (my ($student,$data) = each(%$classlist)) {
 9346: 	    my ($section,$stu_status,$start,$end) = ($data->[$sec_index],
 9347: 				                     $data->[$status_index],
 9348:                                                      $data->[$start_index],
 9349:                                                      $data->[$end_index]);
 9350:             if ($stu_status eq 'Active') {
 9351:                 $status = 'active';
 9352:             } elsif ($end < $now) {
 9353:                 $status = 'previous';
 9354:             } elsif ($start > $now) {
 9355:                 $status = 'future';
 9356:             } 
 9357: 	    if ($section ne '-1' && $section !~ /^\s*$/) {
 9358:                 if ((!defined($possible_status)) || (($status ne '') && 
 9359:                     (grep/^\Q$status\E$/,@{$possible_status}))) { 
 9360: 		    $sectioncount{$section}++;
 9361:                 }
 9362: 	    }
 9363: 	}
 9364:     }
 9365:     if ($only_students) {
 9366:         return %sectioncount;
 9367:     }
 9368:     my %courseroles = &Apache::lonnet::dump('nohist_userroles',$cdom,$cnum);
 9369:     foreach my $user (sort(keys(%courseroles))) {
 9370: 	if ($user !~ /^(\w{2})/) { next; }
 9371: 	my ($role) = ($user =~ /^(\w{2})/);
 9372: 	if ($possible_roles && !(grep(/^$role$/,@$possible_roles))) { next; }
 9373: 	my ($section,$status);
 9374: 	if ($role eq 'cr' &&
 9375: 	    $user =~ m-^$role/[^/]*/[^/]*/[^/]*:[^:]*:[^:]*:(\w+)-) {
 9376: 	    $section=$1;
 9377: 	}
 9378: 	if ($user =~ /^$role:[^:]*:[^:]*:(\w+)/) { $section=$1; }
 9379: 	if (!defined($section) || $section eq '-1') { next; }
 9380:         my ($end,$start) = ($courseroles{$user} =~ /^([^:]*):([^:]*)$/);
 9381:         if ($end == -1 && $start == -1) {
 9382:             next; #deleted role
 9383:         }
 9384:         if (!defined($possible_status)) { 
 9385:             $sectioncount{$section}++;
 9386:         } else {
 9387:             if ((!$end || $end >= $now) && (!$start || $start <= $now)) {
 9388:                 $status = 'active';
 9389:             } elsif ($end < $now) {
 9390:                 $status = 'future';
 9391:             } elsif ($start > $now) {
 9392:                 $status = 'previous';
 9393:             }
 9394:             if (($status ne '') && (grep/^\Q$status\E$/,@{$possible_status})) {
 9395:                 $sectioncount{$section}++;
 9396:             }
 9397:         }
 9398:     }
 9399:     return %sectioncount;
 9400: }
 9401: 
 9402: ###############################################
 9403: 
 9404: =pod
 9405: 
 9406: =item * &get_course_users()
 9407: 
 9408: Retrieves usernames:domains for users in the specified course
 9409: with specific role(s), and access status. 
 9410: 
 9411: Incoming parameters:
 9412: 1. course domain
 9413: 2. course number
 9414: 3. access status: users must have - either active, 
 9415: previous, future, or all.
 9416: 4. reference to array of permissible roles
 9417: 5. reference to array of section restrictions (optional)
 9418: 6. reference to results object (hash of hashes).
 9419: 7. reference to optional userdata hash
 9420: 8. reference to optional statushash
 9421: 9. flag if privileged users (except those set to unhide in
 9422:    course settings) should be excluded    
 9423: Keys of top level results hash are roles.
 9424: Keys of inner hashes are username:domain, with 
 9425: values set to access type.
 9426: Optional userdata hash returns an array with arguments in the 
 9427: same order as loncoursedata::get_classlist() for student data.
 9428: 
 9429: Optional statushash returns
 9430: 
 9431: Entries for end, start, section and status are blank because
 9432: of the possibility of multiple values for non-student roles.
 9433: 
 9434: =cut
 9435: 
 9436: ###############################################
 9437: 
 9438: sub get_course_users {
 9439:     my ($cdom,$cnum,$types,$roles,$sections,$users,$userdata,$statushash,$hidepriv) = @_;
 9440:     my %idx = ();
 9441:     my %seclists;
 9442: 
 9443:     $idx{udom} = &Apache::loncoursedata::CL_SDOM();
 9444:     $idx{uname} =  &Apache::loncoursedata::CL_SNAME();
 9445:     $idx{end} = &Apache::loncoursedata::CL_END();
 9446:     $idx{start} = &Apache::loncoursedata::CL_START();
 9447:     $idx{id} = &Apache::loncoursedata::CL_ID();
 9448:     $idx{section} = &Apache::loncoursedata::CL_SECTION();
 9449:     $idx{fullname} = &Apache::loncoursedata::CL_FULLNAME();
 9450:     $idx{status} = &Apache::loncoursedata::CL_STATUS();
 9451: 
 9452:     if (grep(/^st$/,@{$roles})) {
 9453:         my ($classlist,$keylist)=&Apache::loncoursedata::get_classlist($cdom,$cnum);
 9454:         my $now = time;
 9455:         foreach my $student (keys(%{$classlist})) {
 9456:             my $match = 0;
 9457:             my $secmatch = 0;
 9458:             my $section = $$classlist{$student}[$idx{section}];
 9459:             my $status = $$classlist{$student}[$idx{status}];
 9460:             if ($section eq '') {
 9461:                 $section = 'none';
 9462:             }
 9463:             if ((ref($sections) eq 'ARRAY') && (@{$sections} > 0)) {
 9464:                 if (grep(/^all$/,@{$sections})) {
 9465:                     $secmatch = 1;
 9466:                 } elsif ($$classlist{$student}[$idx{section}] eq '') {
 9467:                     if (grep(/^none$/,@{$sections})) {
 9468:                         $secmatch = 1;
 9469:                     }
 9470:                 } else {  
 9471: 		    if (grep(/^\Q$section\E$/,@{$sections})) {
 9472: 		        $secmatch = 1;
 9473:                     }
 9474: 		}
 9475:                 if (!$secmatch) {
 9476:                     next;
 9477:                 }
 9478:             }
 9479:             if (defined($$types{'active'})) {
 9480:                 if ($$classlist{$student}[$idx{status}] eq 'Active') {
 9481:                     push(@{$$users{st}{$student}},'active');
 9482:                     $match = 1;
 9483:                 }
 9484:             }
 9485:             if (defined($$types{'previous'})) {
 9486:                 if ($$classlist{$student}[$idx{status}] eq 'Expired') {
 9487:                     push(@{$$users{st}{$student}},'previous');
 9488:                     $match = 1;
 9489:                 }
 9490:             }
 9491:             if (defined($$types{'future'})) {
 9492:                 if ($$classlist{$student}[$idx{status}] eq 'Future') {
 9493:                     push(@{$$users{st}{$student}},'future');
 9494:                     $match = 1;
 9495:                 }
 9496:             }
 9497:             if ($match) {
 9498:                 push(@{$seclists{$student}},$section);
 9499:                 if (ref($userdata) eq 'HASH') {
 9500:                     $$userdata{$student} = $$classlist{$student};
 9501:                 }
 9502:                 if (ref($statushash) eq 'HASH') {
 9503:                     $statushash->{$student}{'st'}{$section} = $status;
 9504:                 }
 9505:             }
 9506:         }
 9507:     }
 9508:     if ((@{$roles} > 1) || ((@{$roles} == 1) && ($$roles[0] ne "st"))) {
 9509:         my %coursepersonnel = &Apache::lonnet::dump('nohist_userroles',$cdom,$cnum);
 9510:         my $now = time;
 9511:         my %displaystatus = ( previous => 'Expired',
 9512:                               active   => 'Active',
 9513:                               future   => 'Future',
 9514:                             );
 9515:         my (%nothide,@possdoms);
 9516:         if ($hidepriv) {
 9517:             my %coursehash=&Apache::lonnet::coursedescription($cdom.'_'.$cnum);
 9518:             foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
 9519:                 if ($user !~ /:/) {
 9520:                     $nothide{join(':',split(/[\@]/,$user))}=1;
 9521:                 } else {
 9522:                     $nothide{$user} = 1;
 9523:                 }
 9524:             }
 9525:             my @possdoms = ($cdom);
 9526:             if ($coursehash{'checkforpriv'}) {
 9527:                 push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
 9528:             }
 9529:         }
 9530:         foreach my $person (sort(keys(%coursepersonnel))) {
 9531:             my $match = 0;
 9532:             my $secmatch = 0;
 9533:             my $status;
 9534:             my ($role,$user,$usec) = ($person =~ /^([^:]*):([^:]+:[^:]+):([^:]*)/);
 9535:             $user =~ s/:$//;
 9536:             my ($end,$start) = split(/:/,$coursepersonnel{$person});
 9537:             if ($end == -1 || $start == -1) {
 9538:                 next;
 9539:             }
 9540:             if (($role) && ((grep(/^\Q$role\E$/,@{$roles})) ||
 9541:                 (grep(/^cr$/,@{$roles}) && $role =~ /^cr\//))) {
 9542:                 my ($uname,$udom) = split(/:/,$user);
 9543:                 if ((ref($sections) eq 'ARRAY') && (@{$sections} > 0)) {
 9544:                     if (grep(/^all$/,@{$sections})) {
 9545:                         $secmatch = 1;
 9546:                     } elsif ($usec eq '') {
 9547:                         if (grep(/^none$/,@{$sections})) {
 9548:                             $secmatch = 1;
 9549:                         }
 9550:                     } else {
 9551:                         if (grep(/^\Q$usec\E$/,@{$sections})) {
 9552:                             $secmatch = 1;
 9553:                         }
 9554:                     }
 9555:                     if (!$secmatch) {
 9556:                         next;
 9557:                     }
 9558:                 }
 9559:                 if ($usec eq '') {
 9560:                     $usec = 'none';
 9561:                 }
 9562:                 if ($uname ne '' && $udom ne '') {
 9563:                     if ($hidepriv) {
 9564:                         if ((&Apache::lonnet::privileged($uname,$udom,\@possdoms)) &&
 9565:                             (!$nothide{$uname.':'.$udom})) {
 9566:                             next;
 9567:                         }
 9568:                     }
 9569:                     if ($end > 0 && $end < $now) {
 9570:                         $status = 'previous';
 9571:                     } elsif ($start > $now) {
 9572:                         $status = 'future';
 9573:                     } else {
 9574:                         $status = 'active';
 9575:                     }
 9576:                     foreach my $type (keys(%{$types})) { 
 9577:                         if ($status eq $type) {
 9578:                             if (!grep(/^\Q$type\E$/,@{$$users{$role}{$user}})) {
 9579:                                 push(@{$$users{$role}{$user}},$type);
 9580:                             }
 9581:                             $match = 1;
 9582:                         }
 9583:                     }
 9584:                     if (($match) && (ref($userdata) eq 'HASH')) {
 9585:                         if (!exists($$userdata{$uname.':'.$udom})) {
 9586: 			    &get_user_info($udom,$uname,\%idx,$userdata);
 9587:                         }
 9588:                         if (!grep(/^\Q$usec\E$/,@{$seclists{$uname.':'.$udom}})) {
 9589:                             push(@{$seclists{$uname.':'.$udom}},$usec);
 9590:                         }
 9591:                         if (ref($statushash) eq 'HASH') {
 9592:                             $statushash->{$uname.':'.$udom}{$role}{$usec} = $displaystatus{$status};
 9593:                         }
 9594:                     }
 9595:                 }
 9596:             }
 9597:         }
 9598:         if (grep(/^ow$/,@{$roles})) {
 9599:             if ((defined($cdom)) && (defined($cnum))) {
 9600:                 my %csettings = &Apache::lonnet::get('environment',['internal.courseowner'],$cdom,$cnum);
 9601:                 if ( defined($csettings{'internal.courseowner'}) ) {
 9602:                     my $owner = $csettings{'internal.courseowner'};
 9603:                     next if ($owner eq '');
 9604:                     my ($ownername,$ownerdom);
 9605:                     if ($owner =~ /^([^:]+):([^:]+)$/) {
 9606:                         $ownername = $1;
 9607:                         $ownerdom = $2;
 9608:                     } else {
 9609:                         $ownername = $owner;
 9610:                         $ownerdom = $cdom;
 9611:                         $owner = $ownername.':'.$ownerdom;
 9612:                     }
 9613:                     @{$$users{'ow'}{$owner}} = 'any';
 9614:                     if (defined($userdata) && 
 9615: 			!exists($$userdata{$owner})) {
 9616: 			&get_user_info($ownerdom,$ownername,\%idx,$userdata);
 9617:                         if (!grep(/^none$/,@{$seclists{$owner}})) {
 9618:                             push(@{$seclists{$owner}},'none');
 9619:                         }
 9620:                         if (ref($statushash) eq 'HASH') {
 9621:                             $statushash->{$owner}{'ow'}{'none'} = 'Any';
 9622:                         }
 9623: 		    }
 9624:                 }
 9625:             }
 9626:         }
 9627:         foreach my $user (keys(%seclists)) {
 9628:             @{$seclists{$user}} = (sort {$a <=> $b} @{$seclists{$user}});
 9629:             $$userdata{$user}[$idx{section}] = join(',',@{$seclists{$user}});
 9630:         }
 9631:     }
 9632:     return;
 9633: }
 9634: 
 9635: sub get_user_info {
 9636:     my ($udom,$uname,$idx,$userdata) = @_;
 9637:     $$userdata{$uname.':'.$udom}[$$idx{fullname}] = 
 9638: 	&plainname($uname,$udom,'lastname');
 9639:     $$userdata{$uname.':'.$udom}[$$idx{uname}] = $uname;
 9640:     $$userdata{$uname.':'.$udom}[$$idx{udom}] = $udom;
 9641:     my %idhash =  &Apache::lonnet::idrget($udom,($uname));
 9642:     $$userdata{$uname.':'.$udom}[$$idx{id}] = $idhash{$uname}; 
 9643:     return;
 9644: }
 9645: 
 9646: ###############################################
 9647: 
 9648: =pod
 9649: 
 9650: =item * &get_user_quota()
 9651: 
 9652: Retrieves quota assigned for storage of user files.
 9653: Default is to report quota for portfolio files.
 9654: 
 9655: Incoming parameters:
 9656: 1. user's username
 9657: 2. user's domain
 9658: 3. quota name - portfolio, author, or course
 9659:    (if no quota name provided, defaults to portfolio).
 9660: 4. crstype - official, unofficial, textbook, placement or community, 
 9661:    if quota name is course
 9662: 
 9663: Returns:
 9664: 1. Disk quota (in MB) assigned to student.
 9665: 2. (Optional) Type of setting: custom or default
 9666:    (individually assigned or default for user's 
 9667:    institutional status).
 9668: 3. (Optional) - User's institutional status (e.g., faculty, staff
 9669:    or student - types as defined in localenroll::inst_usertypes 
 9670:    for user's domain, which determines default quota for user.
 9671: 4. (Optional) - Default quota which would apply to the user.
 9672: 
 9673: If a value has been stored in the user's environment, 
 9674: it will return that, otherwise it returns the maximal default
 9675: defined for the user's institutional status(es) in the domain.
 9676: 
 9677: =cut
 9678: 
 9679: ###############################################
 9680: 
 9681: 
 9682: sub get_user_quota {
 9683:     my ($uname,$udom,$quotaname,$crstype) = @_;
 9684:     my ($quota,$quotatype,$settingstatus,$defquota);
 9685:     if (!defined($udom)) {
 9686:         $udom = $env{'user.domain'};
 9687:     }
 9688:     if (!defined($uname)) {
 9689:         $uname = $env{'user.name'};
 9690:     }
 9691:     if (($udom eq '' || $uname eq '') ||
 9692:         ($udom eq 'public') && ($uname eq 'public')) {
 9693:         $quota = 0;
 9694:         $quotatype = 'default';
 9695:         $defquota = 0; 
 9696:     } else {
 9697:         my $inststatus;
 9698:         if ($quotaname eq 'course') {
 9699:             if (($env{'course.'.$udom.'_'.$uname.'.num'} eq $uname) &&
 9700:                 ($env{'course.'.$udom.'_'.$uname.'.domain'} eq $udom)) {
 9701:                 $quota = $env{'course.'.$udom.'_'.$uname.'.internal.uploadquota'};
 9702:             } else {
 9703:                 my %cenv = &Apache::lonnet::coursedescription("$udom/$uname");
 9704:                 $quota = $cenv{'internal.uploadquota'};
 9705:             }
 9706:         } else {
 9707:             if ($udom eq $env{'user.domain'} && $uname eq $env{'user.name'}) {
 9708:                 if ($quotaname eq 'author') {
 9709:                     $quota = $env{'environment.authorquota'};
 9710:                 } else {
 9711:                     $quota = $env{'environment.portfolioquota'};
 9712:                 }
 9713:                 $inststatus = $env{'environment.inststatus'};
 9714:             } else {
 9715:                 my %userenv = 
 9716:                     &Apache::lonnet::get('environment',['portfolioquota',
 9717:                                          'authorquota','inststatus'],$udom,$uname);
 9718:                 my ($tmp) = keys(%userenv);
 9719:                 if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
 9720:                     if ($quotaname eq 'author') {
 9721:                         $quota = $userenv{'authorquota'};
 9722:                     } else {
 9723:                         $quota = $userenv{'portfolioquota'};
 9724:                     }
 9725:                     $inststatus = $userenv{'inststatus'};
 9726:                 } else {
 9727:                     undef(%userenv);
 9728:                 }
 9729:             }
 9730:         }
 9731:         if ($quota eq '' || wantarray) {
 9732:             if ($quotaname eq 'course') {
 9733:                 my %domdefs = &Apache::lonnet::get_domain_defaults($udom);
 9734:                 if (($crstype eq 'official') || ($crstype eq 'unofficial') || 
 9735:                     ($crstype eq 'community') || ($crstype eq 'textbook') ||
 9736:                     ($crstype eq 'placement')) { 
 9737:                     $defquota = $domdefs{$crstype.'quota'};
 9738:                 }
 9739:                 if ($defquota eq '') {
 9740:                     $defquota = 500;
 9741:                 }
 9742:             } else {
 9743:                 ($defquota,$settingstatus) = &default_quota($udom,$inststatus,$quotaname);
 9744:             }
 9745:             if ($quota eq '') {
 9746:                 $quota = $defquota;
 9747:                 $quotatype = 'default';
 9748:             } else {
 9749:                 $quotatype = 'custom';
 9750:             }
 9751:         }
 9752:     }
 9753:     if (wantarray) {
 9754:         return ($quota,$quotatype,$settingstatus,$defquota);
 9755:     } else {
 9756:         return $quota;
 9757:     }
 9758: }
 9759: 
 9760: ###############################################
 9761: 
 9762: =pod
 9763: 
 9764: =item * &default_quota()
 9765: 
 9766: Retrieves default quota assigned for storage of user portfolio files,
 9767: given an (optional) user's institutional status.
 9768: 
 9769: Incoming parameters:
 9770: 
 9771: 1. domain
 9772: 2. (Optional) institutional status(es).  This is a : separated list of 
 9773:    status types (e.g., faculty, staff, student etc.)
 9774:    which apply to the user for whom the default is being retrieved.
 9775:    If the institutional status string in undefined, the domain
 9776:    default quota will be returned.
 9777: 3.  quota name - portfolio, author, or course
 9778:    (if no quota name provided, defaults to portfolio).
 9779: 
 9780: Returns:
 9781: 
 9782: 1. Default disk quota (in MB) for user portfolios in the domain.
 9783: 2. (Optional) institutional type which determined the value of the
 9784:    default quota.
 9785: 
 9786: If a value has been stored in the domain's configuration db,
 9787: it will return that, otherwise it returns 20 (for backwards 
 9788: compatibility with domains which have not set up a configuration
 9789: db file; the original statically defined portfolio quota was 20 MB). 
 9790: 
 9791: If the user's status includes multiple types (e.g., staff and student),
 9792: the largest default quota which applies to the user determines the
 9793: default quota returned.
 9794: 
 9795: =cut
 9796: 
 9797: ###############################################
 9798: 
 9799: 
 9800: sub default_quota {
 9801:     my ($udom,$inststatus,$quotaname) = @_;
 9802:     my ($defquota,$settingstatus);
 9803:     my %quotahash = &Apache::lonnet::get_dom('configuration',
 9804:                                             ['quotas'],$udom);
 9805:     my $key = 'defaultquota';
 9806:     if ($quotaname eq 'author') {
 9807:         $key = 'authorquota';
 9808:     }
 9809:     if (ref($quotahash{'quotas'}) eq 'HASH') {
 9810:         if ($inststatus ne '') {
 9811:             my @statuses = map { &unescape($_); } split(/:/,$inststatus);
 9812:             foreach my $item (@statuses) {
 9813:                 if (ref($quotahash{'quotas'}{$key}) eq 'HASH') {
 9814:                     if ($quotahash{'quotas'}{$key}{$item} ne '') {
 9815:                         if ($defquota eq '') {
 9816:                             $defquota = $quotahash{'quotas'}{$key}{$item};
 9817:                             $settingstatus = $item;
 9818:                         } elsif ($quotahash{'quotas'}{$key}{$item} > $defquota) {
 9819:                             $defquota = $quotahash{'quotas'}{$key}{$item};
 9820:                             $settingstatus = $item;
 9821:                         }
 9822:                     }
 9823:                 } elsif ($key eq 'defaultquota') {
 9824:                     if ($quotahash{'quotas'}{$item} ne '') {
 9825:                         if ($defquota eq '') {
 9826:                             $defquota = $quotahash{'quotas'}{$item};
 9827:                             $settingstatus = $item;
 9828:                         } elsif ($quotahash{'quotas'}{$item} > $defquota) {
 9829:                             $defquota = $quotahash{'quotas'}{$item};
 9830:                             $settingstatus = $item;
 9831:                         }
 9832:                     }
 9833:                 }
 9834:             }
 9835:         }
 9836:         if ($defquota eq '') {
 9837:             if (ref($quotahash{'quotas'}{$key}) eq 'HASH') {
 9838:                 $defquota = $quotahash{'quotas'}{$key}{'default'};
 9839:             } elsif ($key eq 'defaultquota') {
 9840:                 $defquota = $quotahash{'quotas'}{'default'};
 9841:             }
 9842:             $settingstatus = 'default';
 9843:             if ($defquota eq '') {
 9844:                 if ($quotaname eq 'author') {
 9845:                     $defquota = 500;
 9846:                 }
 9847:             }
 9848:         }
 9849:     } else {
 9850:         $settingstatus = 'default';
 9851:         if ($quotaname eq 'author') {
 9852:             $defquota = 500;
 9853:         } else {
 9854:             $defquota = 20;
 9855:         }
 9856:     }
 9857:     if (wantarray) {
 9858:         return ($defquota,$settingstatus);
 9859:     } else {
 9860:         return $defquota;
 9861:     }
 9862: }
 9863: 
 9864: ###############################################
 9865: 
 9866: =pod
 9867: 
 9868: =item * &excess_filesize_warning()
 9869: 
 9870: Returns warning message if upload of file to authoring space, or copying
 9871: of existing file within authoring space will cause quota for the authoring
 9872: space to be exceeded.
 9873: 
 9874: Same, if upload of a file directly to a course/community via Course Editor
 9875: will cause quota for uploaded content for the course to be exceeded.
 9876: 
 9877: Inputs: 7 
 9878: 1. username or coursenum
 9879: 2. domain
 9880: 3. context ('author' or 'course')
 9881: 4. filename of file for which action is being requested
 9882: 5. filesize (kB) of file
 9883: 6. action being taken: copy or upload.
 9884: 7. quotatype (in course context -- official, unofficial, textbook, placement or community).
 9885: 
 9886: Returns: 1 scalar: HTML to display containing warning if quota would be exceeded,
 9887:          otherwise return null.
 9888: 
 9889: =back
 9890: 
 9891: =cut
 9892: 
 9893: sub excess_filesize_warning {
 9894:     my ($uname,$udom,$context,$filename,$filesize,$action,$quotatype) = @_;
 9895:     my $current_disk_usage = 0;
 9896:     my $disk_quota = &get_user_quota($uname,$udom,$context,$quotatype); #expressed in MB
 9897:     if ($context eq 'author') {
 9898:         my $authorspace = $Apache::lonnet::perlvar{'lonDocRoot'}."/priv/$udom/$uname";
 9899:         $current_disk_usage = &Apache::lonnet::diskusage($udom,$uname,$authorspace);
 9900:     } else {
 9901:         foreach my $subdir ('docs','supplemental') {
 9902:             $current_disk_usage += &Apache::lonnet::diskusage($udom,$uname,"userfiles/$subdir",1);
 9903:         }
 9904:     }
 9905:     $disk_quota = int($disk_quota * 1000);
 9906:     if (($current_disk_usage + $filesize) > $disk_quota) {
 9907:         return '<p class="LC_warning">'.
 9908:                 &mt("Unable to $action [_1]. (size = [_2] kilobytes). Disk quota will be exceeded.",
 9909:                     '<span class="LC_filename">'.$filename.'</span>',$filesize).'</p>'.
 9910:                '<p>'.&mt('Disk quota is [_1] kilobytes. Your current disk usage is [_2] kilobytes.',
 9911:                             $disk_quota,$current_disk_usage).
 9912:                '</p>';
 9913:     }
 9914:     return;
 9915: }
 9916: 
 9917: ###############################################
 9918: 
 9919: 
 9920: 
 9921: 
 9922: sub get_secgrprole_info {
 9923:     my ($cdom,$cnum,$needroles,$type)  = @_;
 9924:     my %sections_count = &get_sections($cdom,$cnum);
 9925:     my @sections =  (sort {$a <=> $b} keys(%sections_count));
 9926:     my %curr_groups = &Apache::longroup::coursegroups($cdom,$cnum);
 9927:     my @groups = sort(keys(%curr_groups));
 9928:     my $allroles = [];
 9929:     my $rolehash;
 9930:     my $accesshash = {
 9931:                      active => 'Currently has access',
 9932:                      future => 'Will have future access',
 9933:                      previous => 'Previously had access',
 9934:                   };
 9935:     if ($needroles) {
 9936:         $rolehash = {'all' => 'all'};
 9937:         my %user_roles = &Apache::lonnet::dump('nohist_userroles',$cdom,$cnum);
 9938: 	if (&Apache::lonnet::error(%user_roles)) {
 9939: 	    undef(%user_roles);
 9940: 	}
 9941:         foreach my $item (keys(%user_roles)) {
 9942:             my ($role)=split(/\:/,$item,2);
 9943:             if ($role eq 'cr') { next; }
 9944:             if ($role =~ /^cr/) {
 9945:                 $$rolehash{$role} = (split('/',$role))[3];
 9946:             } else {
 9947:                 $$rolehash{$role} = &Apache::lonnet::plaintext($role,$type);
 9948:             }
 9949:         }
 9950:         foreach my $key (sort(keys(%{$rolehash}))) {
 9951:             push(@{$allroles},$key);
 9952:         }
 9953:         push (@{$allroles},'st');
 9954:         $$rolehash{'st'} = &Apache::lonnet::plaintext('st',$type);
 9955:     }
 9956:     return (\@sections,\@groups,$allroles,$rolehash,$accesshash);
 9957: }
 9958: 
 9959: sub user_picker {
 9960:     my ($dom,$srch,$forcenewuser,$caller,$cancreate,$usertype,$context) = @_;
 9961:     my $currdom = $dom;
 9962:     my %curr_selected = (
 9963:                         srchin => 'dom',
 9964:                         srchby => 'lastname',
 9965:                       );
 9966:     my $srchterm;
 9967:     if ((ref($srch) eq 'HASH') && ($env{'form.origform'} ne 'crtusername')) {
 9968:         if ($srch->{'srchby'} ne '') {
 9969:             $curr_selected{'srchby'} = $srch->{'srchby'};
 9970:         }
 9971:         if ($srch->{'srchin'} ne '') {
 9972:             $curr_selected{'srchin'} = $srch->{'srchin'};
 9973:         }
 9974:         if ($srch->{'srchtype'} ne '') {
 9975:             $curr_selected{'srchtype'} = $srch->{'srchtype'};
 9976:         }
 9977:         if ($srch->{'srchdomain'} ne '') {
 9978:             $currdom = $srch->{'srchdomain'};
 9979:         }
 9980:         $srchterm = $srch->{'srchterm'};
 9981:     }
 9982:     my %html_lt=&Apache::lonlocal::texthash(
 9983:                     'usr'       => 'Search criteria',
 9984:                     'doma'      => 'Domain/institution to search',
 9985:                     'uname'     => 'username',
 9986:                     'lastname'  => 'last name',
 9987:                     'lastfirst' => 'last name, first name',
 9988:                     'crs'       => 'in this course',
 9989:                     'dom'       => 'in selected LON-CAPA domain', 
 9990:                     'alc'       => 'all LON-CAPA',
 9991:                     'instd'     => 'in institutional directory for selected domain',
 9992:                     'exact'     => 'is',
 9993:                     'contains'  => 'contains',
 9994:                     'begins'    => 'begins with',
 9995:                                        );
 9996:     my %js_lt=&Apache::lonlocal::texthash(
 9997:                     'youm'      => "You must include some text to search for.",
 9998:                     'thte'      => "The text you are searching for must contain at least two characters when using a 'begins' type search.",
 9999:                     'thet'      => "The text you are searching for must contain at least three characters when using a 'contains' type search.",
10000:                     'yomc'      => "You must choose a domain when using an institutional directory search.",
10001:                     'ymcd'      => "You must choose a domain when using a domain search.",
10002:                     'whus'      => "When using searching by last,first you must include a comma as separator between last name and first name.",
10003:                     'whse'      => "When searching by last,first you must include at least one character in the first name.",
10004:                      'thfo'     => "The following need to be corrected before the search can be run:",
10005:                                        );
10006:     &html_escape(\%html_lt);
10007:     &js_escape(\%js_lt);
10008:     my $domform = &select_dom_form($currdom,'srchdomain',1,1);
10009:     my $srchinsel = ' <select name="srchin">';
10010: 
10011:     my @srchins = ('crs','dom','alc','instd');
10012: 
10013:     foreach my $option (@srchins) {
10014:         # FIXME 'alc' option unavailable until 
10015:         #       loncreateuser::print_user_query_page()
10016:         #       has been completed.
10017:         next if ($option eq 'alc');
10018:         next if (($option eq 'crs') && ($env{'form.form'} eq 'requestcrs'));  
10019:         next if ($option eq 'crs' && !$env{'request.course.id'});
10020:         if ($curr_selected{'srchin'} eq $option) {
10021:             $srchinsel .= ' 
10022:    <option value="'.$option.'" selected="selected">'.$html_lt{$option}.'</option>';
10023:         } else {
10024:             $srchinsel .= '
10025:    <option value="'.$option.'">'.$html_lt{$option}.'</option>';
10026:         }
10027:     }
10028:     $srchinsel .= "\n  </select>\n";
10029: 
10030:     my $srchbysel =  ' <select name="srchby">';
10031:     foreach my $option ('lastname','lastfirst','uname') {
10032:         if ($curr_selected{'srchby'} eq $option) {
10033:             $srchbysel .= '
10034:    <option value="'.$option.'" selected="selected">'.$html_lt{$option}.'</option>';
10035:         } else {
10036:             $srchbysel .= '
10037:    <option value="'.$option.'">'.$html_lt{$option}.'</option>';
10038:          }
10039:     }
10040:     $srchbysel .= "\n  </select>\n";
10041: 
10042:     my $srchtypesel = ' <select name="srchtype">';
10043:     foreach my $option ('begins','contains','exact') {
10044:         if ($curr_selected{'srchtype'} eq $option) {
10045:             $srchtypesel .= '
10046:    <option value="'.$option.'" selected="selected">'.$html_lt{$option}.'</option>';
10047:         } else {
10048:             $srchtypesel .= '
10049:    <option value="'.$option.'">'.$html_lt{$option}.'</option>';
10050:         }
10051:     }
10052:     $srchtypesel .= "\n  </select>\n";
10053: 
10054:     my ($newuserscript,$new_user_create);
10055:     my $context_dom = $env{'request.role.domain'};
10056:     if ($context eq 'requestcrs') {
10057:         if ($env{'form.coursedom'} ne '') { 
10058:             $context_dom = $env{'form.coursedom'};
10059:         }
10060:     }
10061:     if ($forcenewuser) {
10062:         if (ref($srch) eq 'HASH') {
10063:             if ($srch->{'srchby'} eq 'uname' && $srch->{'srchtype'} eq 'exact' && $srch->{'srchin'} eq 'dom' && $srch->{'srchdomain'} eq $context_dom) {
10064:                 if ($cancreate) {
10065:                     $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>';
10066:                 } else {
10067:                     my $helplink = 'javascript:helpMenu('."'display'".')';
10068:                     my %usertypetext = (
10069:                         official   => 'institutional',
10070:                         unofficial => 'non-institutional',
10071:                     );
10072:                     $new_user_create = '<p class="LC_warning">'
10073:                                       .&mt("You are not authorized to create new $usertypetext{$usertype} users in this domain.")
10074:                                       .' '
10075:                                       .&mt('Please contact the [_1]helpdesk[_2] for assistance.'
10076:                                           ,'<a href="'.$helplink.'">','</a>')
10077:                                       .'</p><br />';
10078:                 }
10079:             }
10080:         }
10081: 
10082:         $newuserscript = <<"ENDSCRIPT";
10083: 
10084: function setSearch(createnew,callingForm) {
10085:     if (createnew == 1) {
10086:         for (var i=0; i<callingForm.srchby.length; i++) {
10087:             if (callingForm.srchby.options[i].value == 'uname') {
10088:                 callingForm.srchby.selectedIndex = i;
10089:             }
10090:         }
10091:         for (var i=0; i<callingForm.srchin.length; i++) {
10092:             if ( callingForm.srchin.options[i].value == 'dom') {
10093: 		callingForm.srchin.selectedIndex = i;
10094:             }
10095:         }
10096:         for (var i=0; i<callingForm.srchtype.length; i++) {
10097:             if (callingForm.srchtype.options[i].value == 'exact') {
10098:                 callingForm.srchtype.selectedIndex = i;
10099:             }
10100:         }
10101:         for (var i=0; i<callingForm.srchdomain.length; i++) {
10102:             if (callingForm.srchdomain.options[i].value == '$context_dom') {
10103:                 callingForm.srchdomain.selectedIndex = i;
10104:             }
10105:         }
10106:     }
10107: }
10108: ENDSCRIPT
10109: 
10110:     }
10111: 
10112:     my $output = <<"END_BLOCK";
10113: <script type="text/javascript">
10114: // <![CDATA[
10115: function validateEntry(callingForm) {
10116: 
10117:     var checkok = 1;
10118:     var srchin;
10119:     for (var i=0; i<callingForm.srchin.length; i++) {
10120: 	if ( callingForm.srchin[i].checked ) {
10121: 	    srchin = callingForm.srchin[i].value;
10122: 	}
10123:     }
10124: 
10125:     var srchtype = callingForm.srchtype.options[callingForm.srchtype.selectedIndex].value;
10126:     var srchby = callingForm.srchby.options[callingForm.srchby.selectedIndex].value;
10127:     var srchdomain = callingForm.srchdomain.options[callingForm.srchdomain.selectedIndex].value;
10128:     var srchterm =  callingForm.srchterm.value;
10129:     var srchin = callingForm.srchin.options[callingForm.srchin.selectedIndex].value;
10130:     var msg = "";
10131: 
10132:     if (srchterm == "") {
10133:         checkok = 0;
10134:         msg += "$js_lt{'youm'}\\n";
10135:     }
10136: 
10137:     if (srchtype== 'begins') {
10138:         if (srchterm.length < 2) {
10139:             checkok = 0;
10140:             msg += "$js_lt{'thte'}\\n";
10141:         }
10142:     }
10143: 
10144:     if (srchtype== 'contains') {
10145:         if (srchterm.length < 3) {
10146:             checkok = 0;
10147:             msg += "$js_lt{'thet'}\\n";
10148:         }
10149:     }
10150:     if (srchin == 'instd') {
10151:         if (srchdomain == '') {
10152:             checkok = 0;
10153:             msg += "$js_lt{'yomc'}\\n";
10154:         }
10155:     }
10156:     if (srchin == 'dom') {
10157:         if (srchdomain == '') {
10158:             checkok = 0;
10159:             msg += "$js_lt{'ymcd'}\\n";
10160:         }
10161:     }
10162:     if (srchby == 'lastfirst') {
10163:         if (srchterm.indexOf(",") == -1) {
10164:             checkok = 0;
10165:             msg += "$js_lt{'whus'}\\n";
10166:         }
10167:         if (srchterm.indexOf(",") == srchterm.length -1) {
10168:             checkok = 0;
10169:             msg += "$js_lt{'whse'}\\n";
10170:         }
10171:     }
10172:     if (checkok == 0) {
10173:         alert("$js_lt{'thfo'}\\n"+msg);
10174:         return;
10175:     }
10176:     if (checkok == 1) {
10177:         callingForm.submit();
10178:     }
10179: }
10180: 
10181: $newuserscript
10182: 
10183: // ]]>
10184: </script>
10185: 
10186: $new_user_create
10187: 
10188: END_BLOCK
10189: 
10190:     $output .= &Apache::lonhtmlcommon::start_pick_box().
10191:                &Apache::lonhtmlcommon::row_title($html_lt{'doma'}).
10192:                $domform.
10193:                &Apache::lonhtmlcommon::row_closure().
10194:                &Apache::lonhtmlcommon::row_title($html_lt{'usr'}).
10195:                $srchbysel.
10196:                $srchtypesel. 
10197:                '<input type="text" size="15" name="srchterm" value="'.$srchterm.'" />'.
10198:                $srchinsel.
10199:                &Apache::lonhtmlcommon::row_closure(1). 
10200:                &Apache::lonhtmlcommon::end_pick_box().
10201:                '<br />';
10202:     return $output;
10203: }
10204: 
10205: sub user_rule_check {
10206:     my ($usershash,$checks,$alerts,$rulematch,$inst_results,$curr_rules,$got_rules) = @_;
10207:     my ($response,%inst_response);
10208:     if (ref($usershash) eq 'HASH') {
10209:         if (keys(%{$usershash}) > 1) {
10210:             my (%by_username,%by_id,%userdoms);
10211:             my $checkid; 
10212:             if (ref($checks) eq 'HASH') {
10213:                 if ((!defined($checks->{'username'})) && (defined($checks->{'id'}))) {
10214:                     $checkid = 1;
10215:                 }
10216:             }
10217:             foreach my $user (keys(%{$usershash})) {
10218:                 my ($uname,$udom) = split(/:/,$user);
10219:                 if ($checkid) {
10220:                     if (ref($usershash->{$user}) eq 'HASH') {
10221:                         if ($usershash->{$user}->{'id'} ne '') {
10222:                             $by_id{$udom}{$usershash->{$user}->{'id'}} = $uname; 
10223:                             $userdoms{$udom} = 1;
10224:                             if (ref($inst_results) eq 'HASH') {
10225:                                 $inst_results->{$uname.':'.$udom} = {};
10226:                             }
10227:                         }
10228:                     }
10229:                 } else {
10230:                     $by_username{$udom}{$uname} = 1;
10231:                     $userdoms{$udom} = 1;
10232:                     if (ref($inst_results) eq 'HASH') {
10233:                         $inst_results->{$uname.':'.$udom} = {};
10234:                     }
10235:                 }
10236:             }
10237:             foreach my $udom (keys(%userdoms)) {
10238:                 if (!$got_rules->{$udom}) {
10239:                     my %domconfig = &Apache::lonnet::get_dom('configuration',
10240:                                                              ['usercreation'],$udom);
10241:                     if (ref($domconfig{'usercreation'}) eq 'HASH') {
10242:                         foreach my $item ('username','id') {
10243:                             if (ref($domconfig{'usercreation'}{$item.'_rule'}) eq 'ARRAY') {
10244:                                 $$curr_rules{$udom}{$item} =
10245:                                     $domconfig{'usercreation'}{$item.'_rule'};
10246:                             }
10247:                         }
10248:                     }
10249:                     $got_rules->{$udom} = 1;
10250:                 }
10251:             }
10252:             if ($checkid) {
10253:                 foreach my $udom (keys(%by_id)) {
10254:                     my ($outcome,$results) = &Apache::lonnet::get_multiple_instusers($udom,$by_id{$udom},'id');
10255:                     if ($outcome eq 'ok') {
10256:                         foreach my $id (keys(%{$by_id{$udom}})) {
10257:                             my $uname = $by_id{$udom}{$id};
10258:                             $inst_response{$uname.':'.$udom} = $outcome;
10259:                         }
10260:                         if (ref($results) eq 'HASH') {
10261:                             foreach my $uname (keys(%{$results})) {
10262:                                 if (exists($inst_response{$uname.':'.$udom})) {
10263:                                     $inst_response{$uname.':'.$udom} = $outcome;
10264:                                     $inst_results->{$uname.':'.$udom} = $results->{$uname};
10265:                                 }
10266:                             }
10267:                         }
10268:                     }
10269:                 }
10270:             } else {
10271:                 foreach my $udom (keys(%by_username)) {
10272:                     my ($outcome,$results) = &Apache::lonnet::get_multiple_instusers($udom,$by_username{$udom});
10273:                     if ($outcome eq 'ok') {
10274:                         foreach my $uname (keys(%{$by_username{$udom}})) {
10275:                             $inst_response{$uname.':'.$udom} = $outcome;
10276:                         }
10277:                         if (ref($results) eq 'HASH') {
10278:                             foreach my $uname (keys(%{$results})) {
10279:                                 $inst_results->{$uname.':'.$udom} = $results->{$uname};
10280:                             }
10281:                         }
10282:                     }
10283:                 }
10284:             }
10285:         } elsif (keys(%{$usershash}) == 1) {
10286:             my $user = (keys(%{$usershash}))[0];
10287:             my ($uname,$udom) = split(/:/,$user);
10288:             if (($udom ne '') && ($uname ne '')) {
10289:                 if (ref($usershash->{$user}) eq 'HASH') {
10290:                     if (ref($checks) eq 'HASH') {
10291:                         if (defined($checks->{'username'})) {
10292:                             ($inst_response{$user},%{$inst_results->{$user}}) = 
10293:                                 &Apache::lonnet::get_instuser($udom,$uname);
10294:                         } elsif (defined($checks->{'id'})) {
10295:                             if ($usershash->{$user}->{'id'} ne '') {
10296:                                 ($inst_response{$user},%{$inst_results->{$user}}) =
10297:                                     &Apache::lonnet::get_instuser($udom,undef,
10298:                                                                   $usershash->{$user}->{'id'});
10299:                             } else {
10300:                                 ($inst_response{$user},%{$inst_results->{$user}}) =
10301:                                     &Apache::lonnet::get_instuser($udom,$uname);
10302:                             }
10303:                         }
10304:                     } else {
10305:                        ($inst_response{$user},%{$inst_results->{$user}}) =
10306:                             &Apache::lonnet::get_instuser($udom,$uname);
10307:                        return;
10308:                     }
10309:                     if (!$got_rules->{$udom}) {
10310:                         my %domconfig = &Apache::lonnet::get_dom('configuration',
10311:                                                                  ['usercreation'],$udom);
10312:                         if (ref($domconfig{'usercreation'}) eq 'HASH') {
10313:                             foreach my $item ('username','id') {
10314:                                 if (ref($domconfig{'usercreation'}{$item.'_rule'}) eq 'ARRAY') {
10315:                                    $$curr_rules{$udom}{$item} = 
10316:                                        $domconfig{'usercreation'}{$item.'_rule'};
10317:                                 }
10318:                             }
10319:                         }
10320:                         $got_rules->{$udom} = 1;
10321:                     }
10322:                 }
10323:             } else {
10324:                 return;
10325:             }
10326:         } else {
10327:             return;
10328:         }
10329:         foreach my $user (keys(%{$usershash})) {
10330:             my ($uname,$udom) = split(/:/,$user);
10331:             next if (($udom eq '') || ($uname eq ''));
10332:             my $id;
10333:             if (ref($inst_results) eq 'HASH') {
10334:                 if (ref($inst_results->{$user}) eq 'HASH') {
10335:                     $id = $inst_results->{$user}->{'id'};
10336:                 }
10337:             }
10338:             if ($id eq '') { 
10339:                 if (ref($usershash->{$user})) {
10340:                     $id = $usershash->{$user}->{'id'};
10341:                 }
10342:             }
10343:             foreach my $item (keys(%{$checks})) {
10344:                 if (ref($$curr_rules{$udom}) eq 'HASH') {
10345:                     if (ref($$curr_rules{$udom}{$item}) eq 'ARRAY') {
10346:                         if (@{$$curr_rules{$udom}{$item}} > 0) {
10347:                             my %rule_check = &Apache::lonnet::inst_rulecheck($udom,$uname,$id,$item,
10348:                                                                              $$curr_rules{$udom}{$item});
10349:                             foreach my $rule (@{$$curr_rules{$udom}{$item}}) {
10350:                                 if ($rule_check{$rule}) {
10351:                                     $$rulematch{$user}{$item} = $rule;
10352:                                     if ($inst_response{$user} eq 'ok') {
10353:                                         if (ref($inst_results) eq 'HASH') {
10354:                                             if (ref($inst_results->{$user}) eq 'HASH') {
10355:                                                 if (keys(%{$inst_results->{$user}}) == 0) {
10356:                                                     $$alerts{$item}{$udom}{$uname} = 1;
10357:                                                 } elsif ($item eq 'id') {
10358:                                                     if ($inst_results->{$user}->{'id'} eq '') {
10359:                                                         $$alerts{$item}{$udom}{$uname} = 1;
10360:                                                     }
10361:                                                 }
10362:                                             }
10363:                                         }
10364:                                     }
10365:                                     last;
10366:                                 }
10367:                             }
10368:                         }
10369:                     }
10370:                 }
10371:             }
10372:         }
10373:     }
10374:     return;
10375: }
10376: 
10377: sub user_rule_formats {
10378:     my ($domain,$domdesc,$curr_rules,$check) = @_;
10379:     my %text = ( 
10380:                  'username' => 'Usernames',
10381:                  'id'       => 'IDs',
10382:                );
10383:     my $output;
10384:     my ($rules,$ruleorder) = &Apache::lonnet::inst_userrules($domain,$check);
10385:     if ((ref($rules) eq 'HASH') && (ref($ruleorder) eq 'ARRAY')) {
10386:         if (@{$ruleorder} > 0) {
10387:             $output = '<br />'.
10388:                       &mt($text{$check}.' with the following format(s) may [_1]only[_2] be used for verified users at [_3]:',
10389:                           '<span class="LC_cusr_emph">','</span>',$domdesc).
10390:                       ' <ul>';
10391:             foreach my $rule (@{$ruleorder}) {
10392:                 if (ref($curr_rules) eq 'ARRAY') {
10393:                     if (grep(/^\Q$rule\E$/,@{$curr_rules})) {
10394:                         if (ref($rules->{$rule}) eq 'HASH') {
10395:                             $output .= '<li>'.$rules->{$rule}{'name'}.': '.
10396:                                         $rules->{$rule}{'desc'}.'</li>';
10397:                         }
10398:                     }
10399:                 }
10400:             }
10401:             $output .= '</ul>';
10402:         }
10403:     }
10404:     return $output;
10405: }
10406: 
10407: sub instrule_disallow_msg {
10408:     my ($checkitem,$domdesc,$count,$mode) = @_;
10409:     my $response;
10410:     my %text = (
10411:                   item   => 'username',
10412:                   items  => 'usernames',
10413:                   match  => 'matches',
10414:                   do     => 'does',
10415:                   action => 'a username',
10416:                   one    => 'one',
10417:                );
10418:     if ($count > 1) {
10419:         $text{'item'} = 'usernames';
10420:         $text{'match'} ='match';
10421:         $text{'do'} = 'do';
10422:         $text{'action'} = 'usernames',
10423:         $text{'one'} = 'ones';
10424:     }
10425:     if ($checkitem eq 'id') {
10426:         $text{'items'} = 'IDs';
10427:         $text{'item'} = 'ID';
10428:         $text{'action'} = 'an ID';
10429:         if ($count > 1) {
10430:             $text{'item'} = 'IDs';
10431:             $text{'action'} = 'IDs';
10432:         }
10433:     }
10434:     $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 />';
10435:     if ($mode eq 'upload') {
10436:         if ($checkitem eq 'username') {
10437:             $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'}.");
10438:         } elsif ($checkitem eq 'id') {
10439:             $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.");
10440:         }
10441:     } elsif ($mode eq 'selfcreate') {
10442:         if ($checkitem eq 'id') {
10443:             $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.");
10444:         }
10445:     } else {
10446:         if ($checkitem eq 'username') {
10447:             $response .= &mt("You must choose $text{'action'} with a different format --  $text{'one'} that will not conflict with 'official' institutional $text{'items'}.");
10448:         } elsif ($checkitem eq 'id') {
10449:             $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.");
10450:         }
10451:     }
10452:     return $response;
10453: }
10454: 
10455: sub personal_data_fieldtitles {
10456:     my %fieldtitles = &Apache::lonlocal::texthash (
10457:                         id => 'Student/Employee ID',
10458:                         permanentemail => 'E-mail address',
10459:                         lastname => 'Last Name',
10460:                         firstname => 'First Name',
10461:                         middlename => 'Middle Name',
10462:                         generation => 'Generation',
10463:                         gen => 'Generation',
10464:                         inststatus => 'Affiliation',
10465:                    );
10466:     return %fieldtitles;
10467: }
10468: 
10469: sub sorted_inst_types {
10470:     my ($dom) = @_;
10471:     my ($usertypes,$order);
10472:     my %domdefaults = &Apache::lonnet::get_domain_defaults($dom);
10473:     if (ref($domdefaults{'inststatus'}) eq 'HASH') {
10474:         $usertypes = $domdefaults{'inststatus'}{'inststatustypes'};
10475:         $order = $domdefaults{'inststatus'}{'inststatusorder'};
10476:     } else {
10477:         ($usertypes,$order) = &Apache::lonnet::retrieve_inst_usertypes($dom);
10478:     }
10479:     my $othertitle = &mt('All users');
10480:     if ($env{'request.course.id'}) {
10481:         $othertitle  = &mt('Any users');
10482:     }
10483:     my @types;
10484:     if (ref($order) eq 'ARRAY') {
10485:         @types = @{$order};
10486:     }
10487:     if (@types == 0) {
10488:         if (ref($usertypes) eq 'HASH') {
10489:             @types = sort(keys(%{$usertypes}));
10490:         }
10491:     }
10492:     if (keys(%{$usertypes}) > 0) {
10493:         $othertitle = &mt('Other users');
10494:     }
10495:     return ($othertitle,$usertypes,\@types);
10496: }
10497: 
10498: sub get_institutional_codes {
10499:     my ($settings,$allcourses,$LC_code) = @_;
10500: # Get complete list of course sections to update
10501:     my @currsections = ();
10502:     my @currxlists = ();
10503:     my $coursecode = $$settings{'internal.coursecode'};
10504: 
10505:     if ($$settings{'internal.sectionnums'} ne '') {
10506:         @currsections = split(/,/,$$settings{'internal.sectionnums'});
10507:     }
10508: 
10509:     if ($$settings{'internal.crosslistings'} ne '') {
10510:         @currxlists = split(/,/,$$settings{'internal.crosslistings'});
10511:     }
10512: 
10513:     if (@currxlists > 0) {
10514:         foreach (@currxlists) {
10515:             if (m/^([^:]+):(\w*)$/) {
10516:                 unless (grep/^$1$/,@{$allcourses}) {
10517:                     push @{$allcourses},$1;
10518:                     $$LC_code{$1} = $2;
10519:                 }
10520:             }
10521:         }
10522:     }
10523:  
10524:     if (@currsections > 0) {
10525:         foreach (@currsections) {
10526:             if (m/^(\w+):(\w*)$/) {
10527:                 my $sec = $coursecode.$1;
10528:                 my $lc_sec = $2;
10529:                 unless (grep/^$sec$/,@{$allcourses}) {
10530:                     push @{$allcourses},$sec;
10531:                     $$LC_code{$sec} = $lc_sec;
10532:                 }
10533:             }
10534:         }
10535:     }
10536:     return;
10537: }
10538: 
10539: sub get_standard_codeitems {
10540:     return ('Year','Semester','Department','Number','Section');
10541: }
10542: 
10543: =pod
10544: 
10545: =head1 Slot Helpers
10546: 
10547: =over 4
10548: 
10549: =item * sorted_slots()
10550: 
10551: Sorts an array of slot names in order of an optional sort key,
10552: default sort is by slot start time (earliest first). 
10553: 
10554: Inputs:
10555: 
10556: =over 4
10557: 
10558: slotsarr  - Reference to array of unsorted slot names.
10559: 
10560: slots     - Reference to hash of hash, where outer hash keys are slot names.
10561: 
10562: sortkey   - Name of key in inner hash to be sorted on (e.g., starttime).
10563: 
10564: =back
10565: 
10566: Returns:
10567: 
10568: =over 4
10569: 
10570: sorted   - An array of slot names sorted by a specified sort key 
10571:            (default sort key is start time of the slot).
10572: 
10573: =back
10574: 
10575: =cut
10576: 
10577: 
10578: sub sorted_slots {
10579:     my ($slotsarr,$slots,$sortkey) = @_;
10580:     if ($sortkey eq '') {
10581:         $sortkey = 'starttime';
10582:     }
10583:     my @sorted;
10584:     if ((ref($slotsarr) eq 'ARRAY') && (ref($slots) eq 'HASH')) {
10585:         @sorted =
10586:             sort {
10587:                      if (ref($slots->{$a}) && ref($slots->{$b})) {
10588:                          return $slots->{$a}{$sortkey} <=> $slots->{$b}{$sortkey}
10589:                      }
10590:                      if (ref($slots->{$a})) { return -1;}
10591:                      if (ref($slots->{$b})) { return 1;}
10592:                      return 0;
10593:                  } @{$slotsarr};
10594:     }
10595:     return @sorted;
10596: }
10597: 
10598: =pod
10599: 
10600: =item * get_future_slots()
10601: 
10602: Inputs:
10603: 
10604: =over 4
10605: 
10606: cnum - course number
10607: 
10608: cdom - course domain
10609: 
10610: now - current UNIX time
10611: 
10612: symb - optional symb
10613: 
10614: =back
10615: 
10616: Returns:
10617: 
10618: =over 4
10619: 
10620: sorted_reservable - ref to array of student_schedulable slots currently 
10621:                     reservable, ordered by end date of reservation period.
10622: 
10623: reservable_now - ref to hash of student_schedulable slots currently
10624:                  reservable.
10625: 
10626:     Keys in inner hash are:
10627:     (a) symb: either blank or symb to which slot use is restricted.
10628:     (b) endreserve: end date of reservation period.
10629:     (c) uniqueperiod: start,end dates when slot is to be uniquely
10630:         selected.
10631: 
10632: sorted_future - ref to array of student_schedulable slots reservable in
10633:                 the future, ordered by start date of reservation period.
10634: 
10635: future_reservable - ref to hash of student_schedulable slots reservable
10636:                     in the future.
10637: 
10638:     Keys in inner hash are:
10639:     (a) symb: either blank or symb to which slot use is restricted.
10640:     (b) startreserve: start date of reservation period.
10641:     (c) uniqueperiod: start,end dates when slot is to be uniquely
10642:         selected.
10643: 
10644: =back
10645: 
10646: =cut
10647: 
10648: sub get_future_slots {
10649:     my ($cnum,$cdom,$now,$symb) = @_;
10650:     my $map;
10651:     if ($symb) {
10652:         ($map) = &Apache::lonnet::decode_symb($symb);
10653:     }
10654:     my (%reservable_now,%future_reservable,@sorted_reservable,@sorted_future);
10655:     my %slots = &Apache::lonnet::get_course_slots($cnum,$cdom);
10656:     foreach my $slot (keys(%slots)) {
10657:         next unless($slots{$slot}->{'type'} eq 'schedulable_student');
10658:         if ($symb) {
10659:             if ($slots{$slot}->{'symb'} ne '') {
10660:                 my $canuse;
10661:                 my %oksymbs;
10662:                 my @slotsymbs = split(/\s*,\s*/,$slots{$slot}->{'symb'});
10663:                 map { $oksymbs{$_} = 1; } @slotsymbs;
10664:                 if ($oksymbs{$symb}) {
10665:                     $canuse = 1;
10666:                 } else {
10667:                     foreach my $item (@slotsymbs) {
10668:                         if ($item =~ /\.(page|sequence)$/) {
10669:                             (undef,undef,my $sloturl) = &Apache::lonnet::decode_symb($item);
10670:                             if (($map ne '') && ($map eq $sloturl)) {
10671:                                 $canuse = 1;
10672:                                 last;
10673:                             }
10674:                         }
10675:                     }
10676:                 }
10677:                 next unless ($canuse);
10678:             }
10679:         }
10680:         if (($slots{$slot}->{'starttime'} > $now) &&
10681:             ($slots{$slot}->{'endtime'} > $now)) {
10682:             if (($slots{$slot}->{'allowedsections'}) || ($slots{$slot}->{'allowedusers'})) {
10683:                 my $userallowed = 0;
10684:                 if ($slots{$slot}->{'allowedsections'}) {
10685:                     my @allowed_sec = split(',',$slots{$slot}->{'allowedsections'});
10686:                     if (!defined($env{'request.role.sec'})
10687:                         && grep(/^No section assigned$/,@allowed_sec)) {
10688:                         $userallowed=1;
10689:                     } else {
10690:                         if (grep(/^\Q$env{'request.role.sec'}\E$/,@allowed_sec)) {
10691:                             $userallowed=1;
10692:                         }
10693:                     }
10694:                     unless ($userallowed) {
10695:                         if (defined($env{'request.course.groups'})) {
10696:                             my @groups = split(/:/,$env{'request.course.groups'});
10697:                             foreach my $group (@groups) {
10698:                                 if (grep(/^\Q$group\E$/,@allowed_sec)) {
10699:                                     $userallowed=1;
10700:                                     last;
10701:                                 }
10702:                             }
10703:                         }
10704:                     }
10705:                 }
10706:                 if ($slots{$slot}->{'allowedusers'}) {
10707:                     my @allowed_users = split(',',$slots{$slot}->{'allowedusers'});
10708:                     my $user = $env{'user.name'}.':'.$env{'user.domain'};
10709:                     if (grep(/^\Q$user\E$/,@allowed_users)) {
10710:                         $userallowed = 1;
10711:                     }
10712:                 }
10713:                 next unless($userallowed);
10714:             }
10715:             my $startreserve = $slots{$slot}->{'startreserve'};
10716:             my $endreserve = $slots{$slot}->{'endreserve'};
10717:             my $symb = $slots{$slot}->{'symb'};
10718:             my $uniqueperiod;
10719:             if (ref($slots{$slot}->{'uniqueperiod'}) eq 'ARRAY') {
10720:                 $uniqueperiod = join(',',@{$slots{$slot}->{'uniqueperiod'}});
10721:             }
10722:             if (($startreserve < $now) &&
10723:                 (!$endreserve || $endreserve > $now)) {
10724:                 my $lastres = $endreserve;
10725:                 if (!$lastres) {
10726:                     $lastres = $slots{$slot}->{'starttime'};
10727:                 }
10728:                 $reservable_now{$slot} = {
10729:                                            symb       => $symb,
10730:                                            endreserve => $lastres,
10731:                                            uniqueperiod => $uniqueperiod,
10732:                                          };
10733:             } elsif (($startreserve > $now) &&
10734:                      (!$endreserve || $endreserve > $startreserve)) {
10735:                 $future_reservable{$slot} = {
10736:                                               symb         => $symb,
10737:                                               startreserve => $startreserve,
10738:                                               uniqueperiod => $uniqueperiod,
10739:                                             };
10740:             }
10741:         }
10742:     }
10743:     my @unsorted_reservable = keys(%reservable_now);
10744:     if (@unsorted_reservable > 0) {
10745:         @sorted_reservable = 
10746:             &sorted_slots(\@unsorted_reservable,\%reservable_now,'endreserve');
10747:     }
10748:     my @unsorted_future = keys(%future_reservable);
10749:     if (@unsorted_future > 0) {
10750:         @sorted_future =
10751:             &sorted_slots(\@unsorted_future,\%future_reservable,'startreserve');
10752:     }
10753:     return (\@sorted_reservable,\%reservable_now,\@sorted_future,\%future_reservable);
10754: }
10755: 
10756: =pod
10757: 
10758: =back
10759: 
10760: =head1 HTTP Helpers
10761: 
10762: =over 4
10763: 
10764: =item * &get_unprocessed_cgi($query,$possible_names)
10765: 
10766: Modify the %env hash to contain unprocessed CGI form parameters held in
10767: $query.  The parameters listed in $possible_names (an array reference),
10768: will be set in $env{'form.name'} if they do not already exist.
10769: 
10770: Typically called with $ENV{'QUERY_STRING'} as the first parameter.  
10771: $possible_names is an ref to an array of form element names.  As an example:
10772: get_unprocessed_cgi($ENV{'QUERY_STRING'},['uname','udom']);
10773: will result in $env{'form.uname'} and $env{'form.udom'} being set.
10774: 
10775: =cut
10776: 
10777: sub get_unprocessed_cgi {
10778:   my ($query,$possible_names)= @_;
10779:   # $Apache::lonxml::debug=1;
10780:   foreach my $pair (split(/&/,$query)) {
10781:     my ($name, $value) = split(/=/,$pair);
10782:     $name = &unescape($name);
10783:     if (!defined($possible_names) || (grep {$_ eq $name} @$possible_names)) {
10784:       $value =~ tr/+/ /;
10785:       $value =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack("C",hex($1))/eg;
10786:       unless (defined($env{'form.'.$name})) { &add_to_env('form.'.$name,$value) };
10787:     }
10788:   }
10789: }
10790: 
10791: =pod
10792: 
10793: =item * &cacheheader() 
10794: 
10795: returns cache-controlling header code
10796: 
10797: =cut
10798: 
10799: sub cacheheader {
10800:     unless ($env{'request.method'} eq 'GET') { return ''; }
10801:     my $date=strftime("%a, %d %b %Y %H:%M:%S GMT",gmtime);
10802:     my $output .='<meta HTTP-EQUIV="Expires" CONTENT="'.$date.'" />
10803:                 <meta HTTP-EQUIV="Cache-control" CONTENT="no-cache" />
10804:                 <meta HTTP-EQUIV="Pragma" CONTENT="no-cache" />';
10805:     return $output;
10806: }
10807: 
10808: =pod
10809: 
10810: =item * &no_cache($r) 
10811: 
10812: specifies header code to not have cache
10813: 
10814: =cut
10815: 
10816: sub no_cache {
10817:     my ($r) = @_;
10818:     if ($ENV{'REQUEST_METHOD'} ne 'GET' &&
10819: 	$env{'request.method'} ne 'GET') { return ''; }
10820:     my $date=strftime("%a, %d %b %Y %H:%M:%S GMT",gmtime(time));
10821:     $r->no_cache(1);
10822:     $r->header_out("Expires" => $date);
10823:     $r->header_out("Pragma" => "no-cache");
10824: }
10825: 
10826: sub content_type {
10827:     my ($r,$type,$charset) = @_;
10828:     if ($r) {
10829: 	#  Note that printout.pl calls this with undef for $r.
10830: 	&no_cache($r);
10831:     }
10832:     if ($env{'browser.mathml'} && $type eq 'text/html') { $type='text/xml'; }
10833:     unless ($charset) {
10834: 	$charset=&Apache::lonlocal::current_encoding;
10835:     }
10836:     if ($charset) { $type.='; charset='.$charset; }
10837:     if ($r) {
10838: 	$r->content_type($type);
10839:     } else {
10840: 	print("Content-type: $type\n\n");
10841:     }
10842: }
10843: 
10844: =pod
10845: 
10846: =item * &add_to_env($name,$value) 
10847: 
10848: adds $name to the %env hash with value
10849: $value, if $name already exists, the entry is converted to an array
10850: reference and $value is added to the array.
10851: 
10852: =cut
10853: 
10854: sub add_to_env {
10855:   my ($name,$value)=@_;
10856:   if (defined($env{$name})) {
10857:     if (ref($env{$name})) {
10858:       #already have multiple values
10859:       push(@{ $env{$name} },$value);
10860:     } else {
10861:       #first time seeing multiple values, convert hash entry to an arrayref
10862:       my $first=$env{$name};
10863:       undef($env{$name});
10864:       push(@{ $env{$name} },$first,$value);
10865:     }
10866:   } else {
10867:     $env{$name}=$value;
10868:   }
10869: }
10870: 
10871: =pod
10872: 
10873: =item * &get_env_multiple($name) 
10874: 
10875: gets $name from the %env hash, it seemlessly handles the cases where multiple
10876: values may be defined and end up as an array ref.
10877: 
10878: returns an array of values
10879: 
10880: =cut
10881: 
10882: sub get_env_multiple {
10883:     my ($name) = @_;
10884:     my @values;
10885:     if (defined($env{$name})) {
10886:         # exists is it an array
10887:         if (ref($env{$name})) {
10888:             @values=@{ $env{$name} };
10889:         } else {
10890:             $values[0]=$env{$name};
10891:         }
10892:     }
10893:     return(@values);
10894: }
10895: 
10896: # Looks at given dependencies, and returns something depending on the context.
10897: # For coursedocs paste, returns (undef, $counter, $numpathchg, \%existing).
10898: # For syllabus rewrites, returns (undef, $counter, $numpathchg, \%existing, \%mapping).
10899: # For all other contexts, returns ($output, $counter, $numpathchg).
10900: # $output: string with the HTML output. Can contain missing dependencies with an upload form, existing dependencies, and dependencies no longer in use.
10901: # $counter: integer with the number of existing dependencies when no HTML output is returned, and the number of missing dependencies when an HTML output is returned.
10902: # $numpathchg: integer with the number of cleaned up dependency paths.
10903: # \%existing: hash reference clean path -> 1 only for existing dependencies.
10904: # \%mapping: hash reference clean path -> original path for all dependencies.
10905: # @param {string} actionurl - The path to the handler, indicative of the context.
10906: # @param {string} state - Can contain HTML with hidden inputs that will be added to the output form.
10907: # @param {hash reference} allfiles - List of file info from lonnet::extract_embedded_items
10908: # @param {hash reference} codebase - undef, not modified by lonnet::extract_embedded_items ?
10909: # @param {hash reference} args - More parameters ! Possible keys: error_on_invalid_names (boolean), ignore_remote_references (boolean), current_path (string), docs_url (string), docs_title (string), context (string)
10910: # @return {Array} - array depending on the context (not a reference)
10911: sub ask_for_embedded_content {
10912:     # NOTE: documentation was added afterwards, it could be wrong
10913:     my ($actionurl,$state,$allfiles,$codebase,$args)=@_;
10914:     my (%subdependencies,%dependencies,%mapping,%existing,%newfiles,%pathchanges,
10915:         %currsubfile,%unused,$rem);
10916:     my $counter = 0;
10917:     my $numnew = 0;
10918:     my $numremref = 0;
10919:     my $numinvalid = 0;
10920:     my $numpathchg = 0;
10921:     my $numexisting = 0;
10922:     my $numunused = 0;
10923:     my ($output,$upload_output,$toplevel,$url,$udom,$uname,$getpropath,$cdom,$cnum,
10924:         $fileloc,$filename,$delete_output,$modify_output,$title,$symb,$path,$navmap);
10925:     my $heading = &mt('Upload embedded files');
10926:     my $buttontext = &mt('Upload');
10927: 
10928:     # fills these variables based on the context:
10929:     # $navmap, $cdom, $cnum, $udom, $uname, $url, $toplevel, $getpropath,
10930:     # $path, $fileloc, $title, $rem, $filename
10931:     if ($env{'request.course.id'}) {
10932:         if ($actionurl eq '/adm/dependencies') {
10933:             $navmap = Apache::lonnavmaps::navmap->new();
10934:         }
10935:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
10936:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
10937:     }
10938:     if (($actionurl eq '/adm/portfolio') || 
10939:         ($actionurl eq '/adm/coursegrp_portfolio')) {
10940:         my $current_path='/';
10941:         if ($env{'form.currentpath'}) {
10942:             $current_path = $env{'form.currentpath'};
10943:         }
10944:         if ($actionurl eq '/adm/coursegrp_portfolio') {
10945:             $udom = $cdom;
10946:             $uname = $cnum;
10947:             $url = '/userfiles/groups/'.$env{'form.group'}.'/portfolio';
10948:         } else {
10949:             $udom = $env{'user.domain'};
10950:             $uname = $env{'user.name'};
10951:             $url = '/userfiles/portfolio';
10952:         }
10953:         $toplevel = $url.'/';
10954:         $url .= $current_path;
10955:         $getpropath = 1;
10956:     } elsif (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank') ||
10957:              ($actionurl eq '/adm/imsimport')) { 
10958:         my ($udom,$uname,$rest) = ($args->{'current_path'} =~ m{/priv/($match_domain)/($match_username)/?(.*)$});
10959:         $url = $Apache::lonnet::perlvar{'lonDocRoot'}."/priv/$udom/$uname/";
10960:         $toplevel = $url;
10961:         if ($rest ne '') {
10962:             $url .= $rest;
10963:         }
10964:     } elsif ($actionurl eq '/adm/coursedocs') {
10965:         if (ref($args) eq 'HASH') {
10966:             $url = $args->{'docs_url'};
10967:             $toplevel = $url;
10968:             if ($args->{'context'} eq 'paste') {
10969:                 ($cdom,$cnum) = ($url =~ m{^\Q/uploaded/\E($match_domain)/($match_courseid)/});
10970:                 ($path) = 
10971:                     ($toplevel =~ m{^(\Q/uploaded/$cdom/$cnum/\E(?:docs|supplemental)/(?:default|\d+)/\d+)/});
10972:                 $fileloc = &Apache::lonnet::filelocation('',$toplevel);
10973:                 $fileloc =~ s{^/}{};
10974:             }
10975:         }
10976:     } elsif ($actionurl eq '/adm/dependencies')  {
10977:         if ($env{'request.course.id'} ne '') {
10978:             if (ref($args) eq 'HASH') {
10979:                 $url = $args->{'docs_url'};
10980:                 $title = $args->{'docs_title'};
10981:                 $toplevel = $url; 
10982:                 unless ($toplevel =~ m{^/}) {
10983:                     $toplevel = "/$url";
10984:                 }
10985:                 ($rem) = ($toplevel =~ m{^(.+/)[^/]+$});
10986:                 if ($toplevel =~ m{^(\Q/uploaded/$cdom/$cnum/portfolio/syllabus\E)}) {
10987:                     $path = $1;
10988:                 } else {
10989:                     ($path) =
10990:                         ($toplevel =~ m{^(\Q/uploaded/$cdom/$cnum/\E(?:docs|supplemental)/(?:default|\d+)/\d+)/});
10991:                 }
10992:                 if ($toplevel=~/^\/*(uploaded|editupload)/) {
10993:                     $fileloc = $toplevel;
10994:                     $fileloc=~ s/^\s*(\S+)\s*$/$1/;
10995:                     my ($udom,$uname,$fname) =
10996:                         ($fileloc=~ m{^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$});
10997:                     $fileloc = propath($udom,$uname).'/userfiles/'.$fname;
10998:                 } else {
10999:                     $fileloc = &Apache::lonnet::filelocation('',$toplevel);
11000:                 }
11001:                 $fileloc =~ s{^/}{};
11002:                 ($filename) = ($fileloc =~ m{.+/([^/]+)$});
11003:                 $heading = &mt('Status of dependencies in [_1]',"$title ($filename)");
11004:             }
11005:         }
11006:     } elsif ($actionurl eq "/public/$cdom/$cnum/syllabus") {
11007:         $udom = $cdom;
11008:         $uname = $cnum;
11009:         $url = "/uploaded/$cdom/$cnum/portfolio/syllabus";
11010:         $toplevel = $url;
11011:         $path = $url;
11012:         $fileloc = &Apache::lonnet::filelocation('',$toplevel).'/';
11013:         $fileloc =~ s{^/}{};
11014:     }
11015:     
11016:     # parses the dependency paths to get some info
11017:     # fills $newfiles, $mapping, $subdependencies, $dependencies
11018:     # $newfiles: hash URL -> 1 for new files or external URLs
11019:     # (will be completed later)
11020:     # $mapping:
11021:     #   for external URLs: external URL -> external URL
11022:     #   for relative paths: clean path -> original path
11023:     # $subdependencies: hash clean path -> clean file name -> 1 for relative paths in subdirectories
11024:     # $dependencies: hash clean or not file name -> 1 for relative paths not in subdirectories
11025:     foreach my $file (keys(%{$allfiles})) {
11026:         my $embed_file;
11027:         if (($path eq "/uploaded/$cdom/$cnum/portfolio/syllabus") && ($file =~ m{^\Q$path/\E(.+)$})) {
11028:             $embed_file = $1;
11029:         } else {
11030:             $embed_file = $file;
11031:         }
11032:         my ($absolutepath,$cleaned_file);
11033:         if ($embed_file =~ m{^\w+://}) {
11034:             $cleaned_file = $embed_file;
11035:             $newfiles{$cleaned_file} = 1;
11036:             $mapping{$cleaned_file} = $embed_file;
11037:         } else {
11038:             $cleaned_file = &clean_path($embed_file);
11039:             if ($embed_file =~ m{^/}) {
11040:                 $absolutepath = $embed_file;
11041:             }
11042:             if ($cleaned_file =~ m{/}) {
11043:                 my ($path,$fname) = ($cleaned_file =~ m{^(.+)/([^/]*)$});
11044:                 $path = &check_for_traversal($path,$url,$toplevel);
11045:                 my $item = $fname;
11046:                 if ($path ne '') {
11047:                     $item = $path.'/'.$fname;
11048:                     $subdependencies{$path}{$fname} = 1;
11049:                 } else {
11050:                     $dependencies{$item} = 1;
11051:                 }
11052:                 if ($absolutepath) {
11053:                     $mapping{$item} = $absolutepath;
11054:                 } else {
11055:                     $mapping{$item} = $embed_file;
11056:                 }
11057:             } else {
11058:                 $dependencies{$embed_file} = 1;
11059:                 if ($absolutepath) {
11060:                     $mapping{$cleaned_file} = $absolutepath;
11061:                 } else {
11062:                     $mapping{$cleaned_file} = $embed_file;
11063:                 }
11064:             }
11065:         }
11066:     }
11067:     
11068:     # looks for all existing files in dependency subdirectories (from $subdependencies filled above)
11069:     # and lists
11070:     # fills $currsubfile, $pathchanges, $existing, $numexisting, $newfiles, $unused
11071:     # $currsubfile: hash clean path -> file name -> 1 for all existing files in the path
11072:     # $pathchanges: hash clean path -> 1 if the file in subdirectory exists and
11073:     #                                    the path had to be cleaned up
11074:     # $existing: hash clean path -> 1 if the file exists
11075:     # $numexisting: number of keys in $existing
11076:     # $newfiles: updated with clean path -> 1 for files in subdirectories that do not exist
11077:     # $unused: only for /adm/dependencies, hash clean path -> 1 for existing files in
11078:     #                                      dependency subdirectories that are
11079:     #                                      not listed as dependencies, with some exceptions using $rem
11080:     my $dirptr = 16384;
11081:     foreach my $path (keys(%subdependencies)) {
11082:         $currsubfile{$path} = {};
11083:         if (($actionurl eq '/adm/portfolio') || 
11084:             ($actionurl eq '/adm/coursegrp_portfolio')) {
11085:             my ($sublistref,$listerror) =
11086:                 &Apache::lonnet::dirlist($url.$path,$udom,$uname,$getpropath);
11087:             if (ref($sublistref) eq 'ARRAY') {
11088:                 foreach my $line (@{$sublistref}) {
11089:                     my ($file_name,$rest) = split(/\&/,$line,2);
11090:                     $currsubfile{$path}{$file_name} = 1;
11091:                 }
11092:             }
11093:         } elsif (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank')) {
11094:             if (opendir(my $dir,$url.'/'.$path)) {
11095:                 my @subdir_list = grep(!/^\./,readdir($dir));
11096:                 map {$currsubfile{$path}{$_} = 1;} @subdir_list;
11097:             }
11098:         } elsif (($actionurl eq '/adm/dependencies') ||
11099:                  (($actionurl eq '/adm/coursedocs') && (ref($args) eq 'HASH') &&
11100:                   ($args->{'context'} eq 'paste')) ||
11101:                  ($actionurl eq "/public/$cdom/$cnum/syllabus")) {
11102:             if ($env{'request.course.id'} ne '') {
11103:                 my $dir;
11104:                 if ($actionurl eq "/public/$cdom/$cnum/syllabus") {
11105:                     $dir = $fileloc;
11106:                 } else {
11107:                     ($dir) = ($fileloc =~ m{^(.+/)[^/]+$});
11108:                 }
11109:                 if ($dir ne '') {
11110:                     my ($sublistref,$listerror) =
11111:                         &Apache::lonnet::dirlist($dir.$path,$cdom,$cnum,$getpropath,undef,'/');
11112:                     if (ref($sublistref) eq 'ARRAY') {
11113:                         foreach my $line (@{$sublistref}) {
11114:                             my ($file_name,$dom,undef,$testdir,undef,undef,undef,undef,$size,
11115:                                 undef,$mtime)=split(/\&/,$line,12);
11116:                             unless (($testdir&$dirptr) ||
11117:                                     ($file_name =~ /^\.\.?$/)) {
11118:                                 $currsubfile{$path}{$file_name} = [$size,$mtime];
11119:                             }
11120:                         }
11121:                     }
11122:                 }
11123:             }
11124:         }
11125:         foreach my $file (keys(%{$subdependencies{$path}})) {
11126:             if (exists($currsubfile{$path}{$file})) {
11127:                 my $item = $path.'/'.$file;
11128:                 unless ($mapping{$item} eq $item) {
11129:                     $pathchanges{$item} = 1;
11130:                 }
11131:                 $existing{$item} = 1;
11132:                 $numexisting ++;
11133:             } else {
11134:                 $newfiles{$path.'/'.$file} = 1;
11135:             }
11136:         }
11137:         if ($actionurl eq '/adm/dependencies') {
11138:             foreach my $path (keys(%currsubfile)) {
11139:                 if (ref($currsubfile{$path}) eq 'HASH') {
11140:                     foreach my $file (keys(%{$currsubfile{$path}})) {
11141:                          unless ($subdependencies{$path}{$file}) {
11142:                              next if (($rem ne '') &&
11143:                                       (($env{"httpref.$rem"."$path/$file"} ne '') ||
11144:                                        (ref($navmap) &&
11145:                                        (($navmap->getResourceByUrl($rem."$path/$file") ne '') ||
11146:                                         (($file =~ /^(.*\.s?html?)\.bak$/i) &&
11147:                                          ($navmap->getResourceByUrl($rem."$path/$1")))))));
11148:                              $unused{$path.'/'.$file} = 1; 
11149:                          }
11150:                     }
11151:                 }
11152:             }
11153:         }
11154:     }
11155:     
11156:     # fills $currfile, hash file name -> 1 or [$size,$mtime]
11157:     # for files in $url or $fileloc (target directory) in some contexts
11158:     my %currfile;
11159:     if (($actionurl eq '/adm/portfolio') ||
11160:         ($actionurl eq '/adm/coursegrp_portfolio')) {
11161:         my ($dirlistref,$listerror) =
11162:             &Apache::lonnet::dirlist($url,$udom,$uname,$getpropath);
11163:         if (ref($dirlistref) eq 'ARRAY') {
11164:             foreach my $line (@{$dirlistref}) {
11165:                 my ($file_name,$rest) = split(/\&/,$line,2);
11166:                 $currfile{$file_name} = 1;
11167:             }
11168:         }
11169:     } elsif (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank')) {
11170:         if (opendir(my $dir,$url)) {
11171:             my @dir_list = grep(!/^\./,readdir($dir));
11172:             map {$currfile{$_} = 1;} @dir_list;
11173:         }
11174:     } elsif (($actionurl eq '/adm/dependencies') ||
11175:              (($actionurl eq '/adm/coursedocs') && (ref($args) eq 'HASH') &&
11176:               ($args->{'context'} eq 'paste')) ||
11177:              ($actionurl eq "/public/$cdom/$cnum/syllabus")) {
11178:         if ($env{'request.course.id'} ne '') {
11179:             my ($dir) = ($fileloc =~ m{^(.+/)[^/]+$});
11180:             if ($dir ne '') {
11181:                 my ($dirlistref,$listerror) =
11182:                     &Apache::lonnet::dirlist($dir,$cdom,$cnum,$getpropath,undef,'/');
11183:                 if (ref($dirlistref) eq 'ARRAY') {
11184:                     foreach my $line (@{$dirlistref}) {
11185:                         my ($file_name,$dom,undef,$testdir,undef,undef,undef,undef,
11186:                             $size,undef,$mtime)=split(/\&/,$line,12);
11187:                         unless (($testdir&$dirptr) ||
11188:                                 ($file_name =~ /^\.\.?$/)) {
11189:                             $currfile{$file_name} = [$size,$mtime];
11190:                         }
11191:                     }
11192:                 }
11193:             }
11194:         }
11195:     }
11196:     # updates $pathchanges, $existing, $numexisting, $newfiles and $unused for files that
11197:     # are not in subdirectories, using $currfile
11198:     foreach my $file (keys(%dependencies)) {
11199:         if (exists($currfile{$file})) {
11200:             unless ($mapping{$file} eq $file) {
11201:                 $pathchanges{$file} = 1;
11202:             }
11203:             $existing{$file} = 1;
11204:             $numexisting ++;
11205:         } else {
11206:             $newfiles{$file} = 1;
11207:         }
11208:     }
11209:     foreach my $file (keys(%currfile)) {
11210:         unless (($file eq $filename) ||
11211:                 ($file eq $filename.'.bak') ||
11212:                 ($dependencies{$file})) {
11213:             if ($actionurl eq '/adm/dependencies') {
11214:                 unless ($toplevel =~ m{^\Q/uploaded/$cdom/$cnum/portfolio/syllabus\E}) {
11215:                     next if (($rem ne '') &&
11216:                              (($env{"httpref.$rem".$file} ne '') ||
11217:                               (ref($navmap) &&
11218:                               (($navmap->getResourceByUrl($rem.$file) ne '') ||
11219:                                (($file =~ /^(.*\.s?html?)\.bak$/i) &&
11220:                                 ($navmap->getResourceByUrl($rem.$1)))))));
11221:                 }
11222:             }
11223:             $unused{$file} = 1;
11224:         }
11225:     }
11226:     
11227:     # returns some results for coursedocs paste and syllabus rewrites ($output is undef)
11228:     if (($actionurl eq '/adm/coursedocs') && (ref($args) eq 'HASH') &&
11229:         ($args->{'context'} eq 'paste')) {
11230:         $counter = scalar(keys(%existing));
11231:         $numpathchg = scalar(keys(%pathchanges));
11232:         return ($output,$counter,$numpathchg,\%existing);
11233:     } elsif (($actionurl eq "/public/$cdom/$cnum/syllabus") && 
11234:              (ref($args) eq 'HASH') && ($args->{'context'} eq 'rewrites')) {
11235:         $counter = scalar(keys(%existing));
11236:         $numpathchg = scalar(keys(%pathchanges));
11237:         return ($output,$counter,$numpathchg,\%existing,\%mapping);
11238:     }
11239:     
11240:     # returns HTML otherwise, with dependency results and to ask for more uploads
11241:     
11242:     # $upload_output: missing dependencies (with upload form)
11243:     # $modify_output: uploaded dependencies (in use)
11244:     # $delete_output: files no longer in use (unused files are not listed for londocs, bug?)
11245:     foreach my $embed_file (sort {lc($a) cmp lc($b)} keys(%newfiles)) {
11246:         if ($actionurl eq '/adm/dependencies') {
11247:             next if ($embed_file =~ m{^\w+://});
11248:         }
11249:         $upload_output .= &start_data_table_row().
11250:                           '<td valign="top"><img src="'.&icon($embed_file).'" />&nbsp;'.
11251:                           '<span class="LC_filename">'.$embed_file.'</span>';
11252:         unless ($mapping{$embed_file} eq $embed_file) {
11253:             $upload_output .= '<br /><span class="LC_info" style="font-size:smaller;">'.
11254:                               &mt('changed from: [_1]',$mapping{$embed_file}).'</span>';
11255:         }
11256:         $upload_output .= '</td>';
11257:         if ($args->{'ignore_remote_references'} && $embed_file =~ m{^\w+://}) { 
11258:             $upload_output.='<td align="right">'.
11259:                             '<span class="LC_info LC_fontsize_medium">'.
11260:                             &mt("URL points to web address").'</span>';
11261:             $numremref++;
11262:         } elsif ($args->{'error_on_invalid_names'}
11263:             && $embed_file ne &Apache::lonnet::clean_filename($embed_file,{'keep_path' => 1,})) {
11264:             $upload_output.='<td align="right"><span class="LC_warning">'.
11265:                             &mt('Invalid characters').'</span>';
11266:             $numinvalid++;
11267:         } else {
11268:             $upload_output .= '<td>'.
11269:                               &embedded_file_element('upload_embedded',$counter,
11270:                                                      $embed_file,\%mapping,
11271:                                                      $allfiles,$codebase,'upload');
11272:             $counter ++;
11273:             $numnew ++;
11274:         }
11275:         $upload_output .= '</td>'.&Apache::loncommon::end_data_table_row()."\n";
11276:     }
11277:     foreach my $embed_file (sort {lc($a) cmp lc($b)} keys(%existing)) {
11278:         if ($actionurl eq '/adm/dependencies') {
11279:             my ($size,$mtime) = &get_dependency_details(\%currfile,\%currsubfile,$embed_file);
11280:             $modify_output .= &start_data_table_row().
11281:                               '<td><a href="'.$path.'/'.$embed_file.'" style="text-decoration:none;">'.
11282:                               '<img src="'.&icon($embed_file).'" border="0" />'.
11283:                               '&nbsp;<span class="LC_filename">'.$embed_file.'</span></a></td>'.
11284:                               '<td>'.$size.'</td>'.
11285:                               '<td>'.$mtime.'</td>'.
11286:                               '<td><label><input type="checkbox" name="mod_upload_dep" '.
11287:                               'onclick="toggleBrowse('."'$counter'".')" id="mod_upload_dep_'.
11288:                               $counter.'" value="'.$counter.'" />'.&mt('Yes').'</label>'.
11289:                               '<div id="moduploaddep_'.$counter.'" style="display:none;">'.
11290:                               &embedded_file_element('upload_embedded',$counter,
11291:                                                      $embed_file,\%mapping,
11292:                                                      $allfiles,$codebase,'modify').
11293:                               '</div></td>'.
11294:                               &end_data_table_row()."\n";
11295:             $counter ++;
11296:         } else {
11297:             $upload_output .= &start_data_table_row().
11298:                               '<td valign="top"><img src="'.&icon($embed_file).'" />&nbsp;'.
11299:                               '<span class="LC_filename">'.$embed_file.'</span></td>'.
11300:                               '<td align="right"><span class="LC_info LC_fontsize_medium">'.&mt('Already exists').'</span></td>'.
11301:                               &Apache::loncommon::end_data_table_row()."\n";
11302:         }
11303:     }
11304:     my $delidx = $counter;
11305:     foreach my $oldfile (sort {lc($a) cmp lc($b)} keys(%unused)) {
11306:         my ($size,$mtime) = &get_dependency_details(\%currfile,\%currsubfile,$oldfile);
11307:         $delete_output .= &start_data_table_row().
11308:                           '<td><img src="'.&icon($oldfile).'" />'.
11309:                           '&nbsp;<span class="LC_filename">'.$oldfile.'</span></td>'.
11310:                           '<td>'.$size.'</td>'.
11311:                           '<td>'.$mtime.'</td>'.
11312:                           '<td><label><input type="checkbox" name="del_upload_dep" '.
11313:                           ' value="'.$delidx.'" />'.&mt('Yes').'</label>'.
11314:                           &embedded_file_element('upload_embedded',$delidx,
11315:                                                  $oldfile,\%mapping,$allfiles,
11316:                                                  $codebase,'delete').'</td>'.
11317:                           &end_data_table_row()."\n"; 
11318:         $numunused ++;
11319:         $delidx ++;
11320:     }
11321:     if ($upload_output) {
11322:         $upload_output = &start_data_table().
11323:                          $upload_output.
11324:                          &end_data_table()."\n";
11325:     }
11326:     if ($modify_output) {
11327:         $modify_output = &start_data_table().
11328:                          &start_data_table_header_row().
11329:                          '<th>'.&mt('File').'</th>'.
11330:                          '<th>'.&mt('Size (KB)').'</th>'.
11331:                          '<th>'.&mt('Modified').'</th>'.
11332:                          '<th>'.&mt('Upload replacement?').'</th>'.
11333:                          &end_data_table_header_row().
11334:                          $modify_output.
11335:                          &end_data_table()."\n";
11336:     }
11337:     if ($delete_output) {
11338:         $delete_output = &start_data_table().
11339:                          &start_data_table_header_row().
11340:                          '<th>'.&mt('File').'</th>'.
11341:                          '<th>'.&mt('Size (KB)').'</th>'.
11342:                          '<th>'.&mt('Modified').'</th>'.
11343:                          '<th>'.&mt('Delete?').'</th>'.
11344:                          &end_data_table_header_row().
11345:                          $delete_output.
11346:                          &end_data_table()."\n";
11347:     }
11348:     my $applies = 0;
11349:     if ($numremref) {
11350:         $applies ++;
11351:     }
11352:     if ($numinvalid) {
11353:         $applies ++;
11354:     }
11355:     if ($numexisting) {
11356:         $applies ++;
11357:     }
11358:     if ($counter || $numunused) {
11359:         $output = '<form name="upload_embedded" action="'.$actionurl.'"'.
11360:                   ' method="post" enctype="multipart/form-data">'."\n".
11361:                   $state.'<h3>'.$heading.'</h3>'; 
11362:         if ($actionurl eq '/adm/dependencies') {
11363:             if ($numnew) {
11364:                 $output .= '<h4>'.&mt('Missing dependencies').'</h4>'.
11365:                            '<p>'.&mt('The following files need to be uploaded.').'</p>'."\n".
11366:                            $upload_output.'<br />'."\n";
11367:             }
11368:             if ($numexisting) {
11369:                 $output .= '<h4>'.&mt('Uploaded dependencies (in use)').'</h4>'.
11370:                            '<p>'.&mt('Upload a new file to replace the one currently in use.').'</p>'."\n".
11371:                            $modify_output.'<br />'."\n";
11372:                            $buttontext = &mt('Save changes');
11373:             }
11374:             if ($numunused) {
11375:                 $output .= '<h4>'.&mt('Unused files').'</h4>'.
11376:                            '<p>'.&mt('The following uploaded files are no longer used.').'</p>'."\n".
11377:                            $delete_output.'<br />'."\n";
11378:                            $buttontext = &mt('Save changes');
11379:             }
11380:         } else {
11381:             $output .= $upload_output.'<br />'."\n";
11382:         }
11383:         $output .= '<input type ="hidden" name="number_embedded_items" value="'.
11384:                    $counter.'" />'."\n";
11385:         if ($actionurl eq '/adm/dependencies') { 
11386:             $output .= '<input type ="hidden" name="number_newemb_items" value="'.
11387:                        $numnew.'" />'."\n";
11388:         } elsif ($actionurl eq '') {
11389:             $output .=  '<input type="hidden" name="phase" value="three" />';
11390:         }
11391:     } elsif ($applies) {
11392:         $output = '<b>'.&mt('Referenced files').'</b>:<br />';
11393:         if ($applies > 1) {
11394:             $output .=  
11395:                 &mt('No dependencies need to be uploaded, as one of the following applies to each reference:').'<ul>';
11396:             if ($numremref) {
11397:                 $output .= '<li>'.&mt('reference is to a URL which points to another server').'</li>'."\n";
11398:             }
11399:             if ($numinvalid) {
11400:                 $output .= '<li>'.&mt('reference is to file with a name containing invalid characters').'</li>'."\n";
11401:             }
11402:             if ($numexisting) {
11403:                 $output .= '<li>'.&mt('reference is to an existing file at the specified location').'</li>'."\n";
11404:             }
11405:             $output .= '</ul><br />';
11406:         } elsif ($numremref) {
11407:             $output .= '<p>'.&mt('None to upload, as all references are to URLs pointing to another server.').'</p>';
11408:         } elsif ($numinvalid) {
11409:             $output .= '<p>'.&mt('None to upload, as all references are to files with names containing invalid characters.').'</p>';
11410:         } elsif ($numexisting) {
11411:             $output .= '<p>'.&mt('None to upload, as all references are to existing files.').'</p>';
11412:         }
11413:         $output .= $upload_output.'<br />';
11414:     }
11415:     my ($pathchange_output,$chgcount);
11416:     $chgcount = $counter;
11417:     if (keys(%pathchanges) > 0) {
11418:         foreach my $embed_file (sort {lc($a) cmp lc($b)} keys(%pathchanges)) {
11419:             if ($counter) {
11420:                 $output .= &embedded_file_element('pathchange',$chgcount,
11421:                                                   $embed_file,\%mapping,
11422:                                                   $allfiles,$codebase,'change');
11423:             } else {
11424:                 $pathchange_output .= 
11425:                     &start_data_table_row().
11426:                     '<td><input type ="checkbox" name="namechange" value="'.
11427:                     $chgcount.'" checked="checked" /></td>'.
11428:                     '<td>'.$mapping{$embed_file}.'</td>'.
11429:                     '<td>'.$embed_file.
11430:                     &embedded_file_element('pathchange',$numpathchg,$embed_file,
11431:                                            \%mapping,$allfiles,$codebase,'change').
11432:                     '</td>'.&end_data_table_row();
11433:             }
11434:             $numpathchg ++;
11435:             $chgcount ++;
11436:         }
11437:     }
11438:     if (($counter) || ($numunused)) {
11439:         if ($numpathchg) {
11440:             $output .= '<input type ="hidden" name="number_pathchange_items" value="'.
11441:                        $numpathchg.'" />'."\n";
11442:         }
11443:         if (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank') || 
11444:             ($actionurl eq '/adm/imsimport')) {
11445:             $output .= '<input type="hidden" name="phase" value="three" />'."\n";
11446:         } elsif ($actionurl eq '/adm/portfolio' || $actionurl eq '/adm/coursegrp_portfolio') {
11447:             $output .= '<input type="hidden" name="action" value="upload_embedded" />';
11448:         } elsif ($actionurl eq '/adm/dependencies') {
11449:             $output .= '<input type="hidden" name="action" value="process_changes" />';
11450:         }
11451:         $output .= '<input type ="submit" value="'.$buttontext.'" />'."\n".'</form>'."\n";
11452:     } elsif ($numpathchg) {
11453:         my %pathchange = ();
11454:         $output .= &modify_html_form('pathchange',$actionurl,$state,\%pathchange,$pathchange_output);
11455:         if (($actionurl eq '/adm/portfolio') || ($actionurl eq '/adm/coursegrp_portfolio')) {
11456:             $output .= '<p>'.&mt('or').'</p>'; 
11457:         }
11458:     }
11459:     return ($output,$counter,$numpathchg);
11460: }
11461: 
11462: =pod
11463: 
11464: =item * clean_path($name)
11465: 
11466: Performs clean-up of directories, subdirectories and filename in an
11467: embedded object, referenced in an HTML file which is being uploaded
11468: to a course or portfolio, where 
11469: "Upload embedded images/multimedia files if HTML file" checkbox was
11470: checked.
11471: 
11472: Clean-up is similar to replacements in lonnet::clean_filename()
11473: except each / between sub-directory and next level is preserved.
11474: 
11475: =cut
11476: 
11477: sub clean_path {
11478:     my ($embed_file) = @_;
11479:     $embed_file =~s{^/+}{};
11480:     my @contents;
11481:     if ($embed_file =~ m{/}) {
11482:         @contents = split(/\//,$embed_file);
11483:     } else {
11484:         @contents = ($embed_file);
11485:     }
11486:     my $lastidx = scalar(@contents)-1;
11487:     for (my $i=0; $i<=$lastidx; $i++) { 
11488:         $contents[$i]=~s{\\}{/}g;
11489:         $contents[$i]=~s/\s+/\_/g;
11490:         $contents[$i]=~s{[^/\w\.\-]}{}g;
11491:         if ($i == $lastidx) {
11492:             $contents[$i]=~s/\.(\d+)(?=\.)/_$1/g;
11493:         }
11494:     }
11495:     if ($lastidx > 0) {
11496:         return join('/',@contents);
11497:     } else {
11498:         return $contents[0];
11499:     }
11500: }
11501: 
11502: sub embedded_file_element {
11503:     my ($context,$num,$embed_file,$mapping,$allfiles,$codebase,$type) = @_;
11504:     return unless ((ref($mapping) eq 'HASH') && (ref($allfiles) eq 'HASH') &&
11505:                    (ref($codebase) eq 'HASH'));
11506:     my $output;
11507:     if (($context eq 'upload_embedded') && ($type ne 'delete')) {
11508:        $output = '<input name="embedded_item_'.$num.'" type="file" value="" />'."\n";
11509:     }
11510:     $output .= '<input name="embedded_orig_'.$num.'" type="hidden" value="'.
11511:                &escape($embed_file).'" />';
11512:     unless (($context eq 'upload_embedded') && 
11513:             ($mapping->{$embed_file} eq $embed_file)) {
11514:         $output .='
11515:         <input name="embedded_ref_'.$num.'" type="hidden" value="'.&escape($mapping->{$embed_file}).'" />';
11516:     }
11517:     my $attrib;
11518:     if (ref($allfiles->{$mapping->{$embed_file}}) eq 'ARRAY') {
11519:         $attrib = &escape(join(':',@{$allfiles->{$mapping->{$embed_file}}}));
11520:     }
11521:     $output .=
11522:         "\n\t\t".
11523:         '<input name="embedded_attrib_'.$num.'" type="hidden" value="'.
11524:         $attrib.'" />';
11525:     if (exists($codebase->{$mapping->{$embed_file}})) {
11526:         $output .=
11527:             "\n\t\t".
11528:             '<input name="codebase_'.$num.'" type="hidden" value="'.
11529:             &escape($codebase->{$mapping->{$embed_file}}).'" />';
11530:     }
11531:     return $output;
11532: }
11533: 
11534: sub get_dependency_details {
11535:     my ($currfile,$currsubfile,$embed_file) = @_;
11536:     my ($size,$mtime,$showsize,$showmtime);
11537:     if ((ref($currfile) eq 'HASH') && (ref($currsubfile))) {
11538:         if ($embed_file =~ m{/}) {
11539:             my ($path,$fname) = split(/\//,$embed_file);
11540:             if (ref($currsubfile->{$path}{$fname}) eq 'ARRAY') {
11541:                 ($size,$mtime) = @{$currsubfile->{$path}{$fname}};
11542:             }
11543:         } else {
11544:             if (ref($currfile->{$embed_file}) eq 'ARRAY') {
11545:                 ($size,$mtime) = @{$currfile->{$embed_file}};
11546:             }
11547:         }
11548:         $showsize = $size/1024.0;
11549:         $showsize = sprintf("%.1f",$showsize);
11550:         if ($mtime > 0) {
11551:             $showmtime = &Apache::lonlocal::locallocaltime($mtime);
11552:         }
11553:     }
11554:     return ($showsize,$showmtime);
11555: }
11556: 
11557: sub ask_embedded_js {
11558:     return <<"END";
11559: <script type="text/javascript"">
11560: // <![CDATA[
11561: function toggleBrowse(counter) {
11562:     var chkboxid = document.getElementById('mod_upload_dep_'+counter);
11563:     var fileid = document.getElementById('embedded_item_'+counter);
11564:     var uploaddivid = document.getElementById('moduploaddep_'+counter);
11565:     if (chkboxid.checked == true) {
11566:         uploaddivid.style.display='block';
11567:     } else {
11568:         uploaddivid.style.display='none';
11569:         fileid.value = '';
11570:     }
11571: }
11572: // ]]>
11573: </script>
11574: 
11575: END
11576: }
11577: 
11578: sub upload_embedded {
11579:     my ($context,$dirpath,$uname,$udom,$dir_root,$url_root,$group,$disk_quota,
11580:         $current_disk_usage,$hiddenstate,$actionurl) = @_;
11581:     my (%pathchange,$output,$modifyform,$footer,$returnflag);
11582:     for (my $i=0; $i<$env{'form.number_embedded_items'}; $i++) {
11583:         next if (!exists($env{'form.embedded_item_'.$i.'.filename'}));
11584:         my $orig_uploaded_filename =
11585:             $env{'form.embedded_item_'.$i.'.filename'};
11586:         foreach my $type ('orig','ref','attrib','codebase') {
11587:             if ($env{'form.embedded_'.$type.'_'.$i} ne '') {
11588:                 $env{'form.embedded_'.$type.'_'.$i} =
11589:                     &unescape($env{'form.embedded_'.$type.'_'.$i});
11590:             }
11591:         }
11592:         my ($path,$fname) =
11593:             ($env{'form.embedded_orig_'.$i} =~ m{(.*/)([^/]*)});
11594:         # no path, whole string is fname
11595:         if (!$fname) { $fname = $env{'form.embedded_orig_'.$i} };
11596:         $fname = &Apache::lonnet::clean_filename($fname);
11597:         # See if there is anything left
11598:         next if ($fname eq '');
11599: 
11600:         # Check if file already exists as a file or directory.
11601:         my ($state,$msg);
11602:         if ($context eq 'portfolio') {
11603:             my $port_path = $dirpath;
11604:             if ($group ne '') {
11605:                 $port_path = "groups/$group/$port_path";
11606:             }
11607:             ($state,$msg) = &check_for_upload($env{'form.currentpath'}.$path,
11608:                                               $fname,$group,'embedded_item_'.$i,
11609:                                               $dir_root,$port_path,$disk_quota,
11610:                                               $current_disk_usage,$uname,$udom);
11611:             if ($state eq 'will_exceed_quota'
11612:                 || $state eq 'file_locked') {
11613:                 $output .= $msg;
11614:                 next;
11615:             }
11616:         } elsif (($context eq 'author') || ($context eq 'testbank')) {
11617:             ($state,$msg) = &check_for_existing($path,$fname,'embedded_item_'.$i);
11618:             if ($state eq 'exists') {
11619:                 $output .= $msg;
11620:                 next;
11621:             }
11622:         }
11623:         # Check if extension is valid
11624:         if (($fname =~ /\.(\w+)$/) &&
11625:             (&Apache::loncommon::fileembstyle($1) eq 'hdn')) {
11626:             $output .= &mt('Invalid file extension ([_1]) - reserved for internal use.',$1)
11627:                       .' '.&mt('Rename the file with a different extension and re-upload.').'<br />';
11628:             next;
11629:         } elsif (($fname =~ /\.(\w+)$/) &&
11630:                  (!defined(&Apache::loncommon::fileembstyle($1)))) {
11631:             $output .= &mt('Unrecognized file extension ([_1]) - rename the file with a proper extension and re-upload.',$1).'<br />';
11632:             next;
11633:         } elsif ($fname=~/\.(\d+)\.(\w+)$/) {
11634:             $output .= &mt('Filename not allowed - rename the file to remove the number immediately before the file extension([_1]) and re-upload.',$2).'<br />';
11635:             next;
11636:         }
11637:         $env{'form.embedded_item_'.$i.'.filename'}=$fname;
11638:         my $subdir = $path;
11639:         $subdir =~ s{/+$}{};
11640:         if ($context eq 'portfolio') {
11641:             my $result;
11642:             if ($state eq 'existingfile') {
11643:                 $result=
11644:                     &Apache::lonnet::userfileupload('embedded_item_'.$i,'existingfile',
11645:                                                     $dirpath.$env{'form.currentpath'}.$subdir);
11646:             } else {
11647:                 $result=
11648:                     &Apache::lonnet::userfileupload('embedded_item_'.$i,'',
11649:                                                     $dirpath.
11650:                                                     $env{'form.currentpath'}.$subdir);
11651:                 if ($result !~ m|^/uploaded/|) {
11652:                     $output .= '<span class="LC_error">'
11653:                                .&mt('An error occurred ([_1]) while trying to upload [_2] for embedded element [_3].'
11654:                                ,$result,$orig_uploaded_filename,$env{'form.embedded_orig_'.$i})
11655:                                .'</span><br />';
11656:                     next;
11657:                 } else {
11658:                     $output .= &mt('Uploaded [_1]','<span class="LC_filename">'.
11659:                                $path.$fname.'</span>').'<br />';     
11660:                 }
11661:             }
11662:         } elsif (($context eq 'coursedoc') || ($context eq 'syllabus')) {
11663:             my $extendedsubdir = $dirpath.'/'.$subdir;
11664:             $extendedsubdir =~ s{/+$}{};
11665:             my $result =
11666:                 &Apache::lonnet::userfileupload('embedded_item_'.$i,$context,$extendedsubdir);
11667:             if ($result !~ m|^/uploaded/|) {
11668:                 $output .= '<span class="LC_error">'
11669:                            .&mt('An error occurred ([_1]) while trying to upload [_2] for embedded element [_3].'
11670:                            ,$result,$orig_uploaded_filename,$env{'form.embedded_orig_'.$i})
11671:                            .'</span><br />';
11672:                     next;
11673:             } else {
11674:                 $output .= &mt('Uploaded [_1]','<span class="LC_filename">'.
11675:                            $path.$fname.'</span>').'<br />';
11676:                 if ($context eq 'syllabus') {
11677:                     &Apache::lonnet::make_public_indefinitely($result);
11678:                 }
11679:             }
11680:         } else {
11681: # Save the file
11682:             my $target = $env{'form.embedded_item_'.$i};
11683:             my $fullpath = $dir_root.$dirpath.'/'.$path;
11684:             my $dest = $fullpath.$fname;
11685:             my $url = $url_root.$dirpath.'/'.$path.$fname;
11686:             my @parts=split(/\//,"$dirpath/$path");
11687:             my $count;
11688:             my $filepath = $dir_root;
11689:             foreach my $subdir (@parts) {
11690:                 $filepath .= "/$subdir";
11691:                 if (!-e $filepath) {
11692:                     mkdir($filepath,0770);
11693:                 }
11694:             }
11695:             my $fh;
11696:             if (!open($fh,'>'.$dest)) {
11697:                 &Apache::lonnet::logthis('Failed to create '.$dest);
11698:                 $output .= '<span class="LC_error">'.
11699:                            &mt('An error occurred while trying to upload [_1] for embedded element [_2].',
11700:                                $orig_uploaded_filename,$env{'form.embedded_orig_'.$i}).
11701:                            '</span><br />';
11702:             } else {
11703:                 if (!print $fh $env{'form.embedded_item_'.$i}) {
11704:                     &Apache::lonnet::logthis('Failed to write to '.$dest);
11705:                     $output .= '<span class="LC_error">'.
11706:                               &mt('An error occurred while writing the file [_1] for embedded element [_2].',
11707:                                   $orig_uploaded_filename,$env{'form.embedded_orig_'.$i}).
11708:                               '</span><br />';
11709:                 } else {
11710:                     $output .= &mt('Uploaded [_1]','<span class="LC_filename">'.
11711:                                $url.'</span>').'<br />';
11712:                     unless ($context eq 'testbank') {
11713:                         $footer .= &mt('View embedded file: [_1]',
11714:                                        '<a href="'.$url.'">'.$fname.'</a>').'<br />';
11715:                     }
11716:                 }
11717:                 close($fh);
11718:             }
11719:         }
11720:         if ($env{'form.embedded_ref_'.$i}) {
11721:             $pathchange{$i} = 1;
11722:         }
11723:     }
11724:     if ($output) {
11725:         $output = '<p>'.$output.'</p>';
11726:     }
11727:     $output .= &modify_html_form('upload_embedded',$actionurl,$hiddenstate,\%pathchange);
11728:     $returnflag = 'ok';
11729:     my $numpathchgs = scalar(keys(%pathchange));
11730:     if ($numpathchgs > 0) {
11731:         if ($context eq 'portfolio') {
11732:             $output .= '<p>'.&mt('or').'</p>';
11733:         } elsif ($context eq 'testbank') {
11734:             $output .=  '<p>'.&mt('Or [_1]continue[_2] the testbank import without modifying the reference(s).',
11735:                                   '<a href="javascript:document.testbankForm.submit();">','</a>').'</p>';
11736:             $returnflag = 'modify_orightml';
11737:         }
11738:     }
11739:     return ($output.$footer,$returnflag,$numpathchgs);
11740: }
11741: 
11742: sub modify_html_form {
11743:     my ($context,$actionurl,$hiddenstate,$pathchange,$pathchgtable) = @_;
11744:     my $end = 0;
11745:     my $modifyform;
11746:     if ($context eq 'upload_embedded') {
11747:         return unless (ref($pathchange) eq 'HASH');
11748:         if ($env{'form.number_embedded_items'}) {
11749:             $end += $env{'form.number_embedded_items'};
11750:         }
11751:         if ($env{'form.number_pathchange_items'}) {
11752:             $end += $env{'form.number_pathchange_items'};
11753:         }
11754:         if ($end) {
11755:             for (my $i=0; $i<$end; $i++) {
11756:                 if ($i < $env{'form.number_embedded_items'}) {
11757:                     next unless($pathchange->{$i});
11758:                 }
11759:                 $modifyform .=
11760:                     &start_data_table_row().
11761:                     '<td><input type ="checkbox" name="namechange" value="'.$i.'" '.
11762:                     'checked="checked" /></td>'.
11763:                     '<td>'.$env{'form.embedded_ref_'.$i}.
11764:                     '<input type="hidden" name="embedded_ref_'.$i.'" value="'.
11765:                     &escape($env{'form.embedded_ref_'.$i}).'" />'.
11766:                     '<input type="hidden" name="embedded_codebase_'.$i.'" value="'.
11767:                     &escape($env{'form.embedded_codebase_'.$i}).'" />'.
11768:                     '<input type="hidden" name="embedded_attrib_'.$i.'" value="'.
11769:                     &escape($env{'form.embedded_attrib_'.$i}).'" /></td>'.
11770:                     '<td>'.$env{'form.embedded_orig_'.$i}.
11771:                     '<input type="hidden" name="embedded_orig_'.$i.'" value="'.
11772:                     &escape($env{'form.embedded_orig_'.$i}).'" /></td>'.
11773:                     &end_data_table_row();
11774:             }
11775:         }
11776:     } else {
11777:         $modifyform = $pathchgtable;
11778:         if (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank')) {
11779:             $hiddenstate .= '<input type="hidden" name="phase" value="four" />';
11780:         } elsif (($actionurl eq '/adm/portfolio') || ($actionurl eq '/adm/coursegrp_portfolio')) {
11781:             $hiddenstate .= '<input type="hidden" name="action" value="modify_orightml" />';
11782:         }
11783:     }
11784:     if ($modifyform) {
11785:         if ($actionurl eq '/adm/dependencies') {
11786:             $hiddenstate .= '<input type="hidden" name="action" value="modifyhrefs" />';
11787:         }
11788:         return '<h3>'.&mt('Changes in content of HTML file required').'</h3>'."\n".
11789:                '<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".
11790:                '<li>'.&mt('For consistency between the reference(s) and the location of the corresponding stored file within LON-CAPA.').'</li>'."\n".
11791:                '<li>'.&mt('To change absolute paths to relative paths, or replace directory traversal via "../" within the original reference.').'</li>'."\n".
11792:                '</ol></p>'."\n".'<p>'.
11793:                &mt('LON-CAPA can make the required changes to your HTML file.').'</p>'."\n".
11794:                '<form method="post" name="refchanger" action="'.$actionurl.'">'.
11795:                &start_data_table()."\n".
11796:                &start_data_table_header_row().
11797:                '<th>'.&mt('Change?').'</th>'.
11798:                '<th>'.&mt('Current reference').'</th>'.
11799:                '<th>'.&mt('Required reference').'</th>'.
11800:                &end_data_table_header_row()."\n".
11801:                $modifyform.
11802:                &end_data_table().'<br />'."\n".$hiddenstate.
11803:                '<input type="submit" name="pathchanges" value="'.&mt('Modify HTML file').'" />'.
11804:                '</form>'."\n";
11805:     }
11806:     return;
11807: }
11808: 
11809: sub modify_html_refs {
11810:     my ($context,$dirpath,$uname,$udom,$dir_root,$url) = @_;
11811:     my $container;
11812:     if ($context eq 'portfolio') {
11813:         $container = $env{'form.container'};
11814:     } elsif ($context eq 'coursedoc') {
11815:         $container = $env{'form.primaryurl'};
11816:     } elsif ($context eq 'manage_dependencies') {
11817:         (undef,undef,$container) = &Apache::lonnet::decode_symb($env{'form.symb'});
11818:         $container = "/$container";
11819:     } elsif ($context eq 'syllabus') {
11820:         $container = $url;
11821:     } else {
11822:         $container = $Apache::lonnet::perlvar{'lonDocRoot'}.$env{'form.filename'};
11823:     }
11824:     my (%allfiles,%codebase,$output,$content);
11825:     my @changes = &get_env_multiple('form.namechange');
11826:     unless ((@changes > 0) || ($context eq 'syllabus')) {
11827:         if (wantarray) {
11828:             return ('',0,0); 
11829:         } else {
11830:             return;
11831:         }
11832:     }
11833:     if (($context eq 'portfolio') || ($context eq 'coursedoc') || 
11834:         ($context eq 'manage_dependencies') || ($context eq 'syllabus')) {
11835:         unless ($container =~ m{^/uploaded/\Q$udom\E/\Q$uname\E/}) {
11836:             if (wantarray) {
11837:                 return ('',0,0);
11838:             } else {
11839:                 return;
11840:             }
11841:         } 
11842:         $content = &Apache::lonnet::getfile($container);
11843:         if ($content eq '-1') {
11844:             if (wantarray) {
11845:                 return ('',0,0);
11846:             } else {
11847:                 return;
11848:             }
11849:         }
11850:     } else {
11851:         unless ($container =~ /^\Q$dir_root\E/) {
11852:             if (wantarray) {
11853:                 return ('',0,0);
11854:             } else {
11855:                 return;
11856:             }
11857:         } 
11858:         if (open(my $fh,"<$container")) {
11859:             $content = join('', <$fh>);
11860:             close($fh);
11861:         } else {
11862:             if (wantarray) {
11863:                 return ('',0,0);
11864:             } else {
11865:                 return;
11866:             }
11867:         }
11868:     }
11869:     my ($count,$codebasecount) = (0,0);
11870:     my $mm = new File::MMagic;
11871:     my $mime_type = $mm->checktype_contents($content);
11872:     if ($mime_type eq 'text/html') {
11873:         my $parse_result = 
11874:             &Apache::lonnet::extract_embedded_items($container,\%allfiles,
11875:                                                     \%codebase,\$content);
11876:         if ($parse_result eq 'ok') {
11877:             foreach my $i (@changes) {
11878:                 my $orig = &unescape($env{'form.embedded_orig_'.$i});
11879:                 my $ref = &unescape($env{'form.embedded_ref_'.$i});
11880:                 if ($allfiles{$ref}) {
11881:                     my $newname =  $orig;
11882:                     my ($attrib_regexp,$codebase);
11883:                     $attrib_regexp = &unescape($env{'form.embedded_attrib_'.$i});
11884:                     if ($attrib_regexp =~ /:/) {
11885:                         $attrib_regexp =~ s/\:/|/g;
11886:                     }
11887:                     if ($content =~ m{($attrib_regexp\s*=\s*['"]?)\Q$ref\E(['"]?)}) {
11888:                         my $numchg = ($content =~ s{($attrib_regexp\s*=\s*['"]?)\Q$ref\E(['"]?)}{$1$newname$2}gi);
11889:                         $count += $numchg;
11890:                         $allfiles{$newname} = $allfiles{$ref};
11891:                         delete($allfiles{$ref});
11892:                     }
11893:                     if ($env{'form.embedded_codebase_'.$i} ne '') {
11894:                         $codebase = &unescape($env{'form.embedded_codebase_'.$i});
11895:                         my $numchg = ($content =~ s/(codebase\s*=\s*["']?)\Q$codebase\E(["']?)/$1.$2/i); #' stupid emacs
11896:                         $codebasecount ++;
11897:                     }
11898:                 }
11899:             }
11900:             my $skiprewrites;
11901:             if ($count || $codebasecount) {
11902:                 my $saveresult;
11903:                 if (($context eq 'portfolio') || ($context eq 'coursedoc') || 
11904:                     ($context eq 'manage_dependencies') || ($context eq 'syllabus')) {
11905:                     my $url = &Apache::lonnet::store_edited_file($container,$content,$udom,$uname,\$saveresult);
11906:                     if ($url eq $container) {
11907:                         my ($fname) = ($container =~ m{/([^/]+)$});
11908:                         $output = '<p>'.&mt('Updated [quant,_1,reference] in [_2].',
11909:                                             $count,'<span class="LC_filename">'.
11910:                                             $fname.'</span>').'</p>';
11911:                     } else {
11912:                          $output = '<p class="LC_error">'.
11913:                                    &mt('Error: update failed for: [_1].',
11914:                                    '<span class="LC_filename">'.
11915:                                    $container.'</span>').'</p>';
11916:                     }
11917:                     if ($context eq 'syllabus') {
11918:                         unless ($saveresult eq 'ok') {
11919:                             $skiprewrites = 1;
11920:                         }
11921:                     }
11922:                 } else {
11923:                     if (open(my $fh,">$container")) {
11924:                         print $fh $content;
11925:                         close($fh);
11926:                         $output = '<p>'.&mt('Updated [quant,_1,reference] in [_2].',
11927:                                   $count,'<span class="LC_filename">'.
11928:                                   $container.'</span>').'</p>';
11929:                     } else {
11930:                          $output = '<p class="LC_error">'.
11931:                                    &mt('Error: could not update [_1].',
11932:                                    '<span class="LC_filename">'.
11933:                                    $container.'</span>').'</p>';
11934:                     }
11935:                 }
11936:             }
11937:             if (($context eq 'syllabus') && (!$skiprewrites)) {
11938:                 my ($actionurl,$state);
11939:                 $actionurl = "/public/$udom/$uname/syllabus";
11940:                 my ($ignore,$num,$numpathchanges,$existing,$mapping) =
11941:                     &ask_for_embedded_content($actionurl,$state,\%allfiles,
11942:                                               \%codebase,
11943:                                               {'context' => 'rewrites',
11944:                                                'ignore_remote_references' => 1,});
11945:                 if (ref($mapping) eq 'HASH') {
11946:                     my $rewrites = 0;
11947:                     foreach my $key (keys(%{$mapping})) {
11948:                         next if ($key =~ m{^https?://});
11949:                         my $ref = $mapping->{$key};
11950:                         my $newname = "/uploaded/$udom/$uname/portfolio/syllabus/$key";
11951:                         my $attrib;
11952:                         if (ref($allfiles{$mapping->{$key}}) eq 'ARRAY') {
11953:                             $attrib = join('|',@{$allfiles{$mapping->{$key}}});
11954:                         }
11955:                         if ($content =~ m{($attrib\s*=\s*['"]?)\Q$ref\E(['"]?)}) {
11956:                             my $numchg = ($content =~ s{($attrib\s*=\s*['"]?)\Q$ref\E(['"]?)}{$1$newname$2}gi);
11957:                             $rewrites += $numchg;
11958:                         }
11959:                     }
11960:                     if ($rewrites) {
11961:                         my $saveresult; 
11962:                         my $url = &Apache::lonnet::store_edited_file($container,$content,$udom,$uname,\$saveresult);
11963:                         if ($url eq $container) {
11964:                             my ($fname) = ($container =~ m{/([^/]+)$});
11965:                             $output .= '<p>'.&mt('Rewrote [quant,_1,link] as [quant,_1,absolute link] in [_2].',
11966:                                             $count,'<span class="LC_filename">'.
11967:                                             $fname.'</span>').'</p>';
11968:                         } else {
11969:                             $output .= '<p class="LC_error">'.
11970:                                        &mt('Error: could not update links in [_1].',
11971:                                        '<span class="LC_filename">'.
11972:                                        $container.'</span>').'</p>';
11973: 
11974:                         }
11975:                     }
11976:                 }
11977:             }
11978:         } else {
11979:             &logthis('Failed to parse '.$container.
11980:                      ' to modify references: '.$parse_result);
11981:         }
11982:     }
11983:     if (wantarray) {
11984:         return ($output,$count,$codebasecount);
11985:     } else {
11986:         return $output;
11987:     }
11988: }
11989: 
11990: sub check_for_existing {
11991:     my ($path,$fname,$element) = @_;
11992:     my ($state,$msg);
11993:     if (-d $path.'/'.$fname) {
11994:         $state = 'exists';
11995:         $msg = &mt('Unable to upload [_1]. A directory by that name was found in [_2].','<span class="LC_filename">'.$fname.'</span>',$path);
11996:     } elsif (-e $path.'/'.$fname) {
11997:         $state = 'exists';
11998:         $msg = &mt('Unable to upload [_1]. A file by that name was found in [_2].','<span class="LC_filename">'.$fname.'</span>',$path);
11999:     }
12000:     if ($state eq 'exists') {
12001:         $msg = '<span class="LC_error">'.$msg.'</span><br />';
12002:     }
12003:     return ($state,$msg);
12004: }
12005: 
12006: sub check_for_upload {
12007:     my ($path,$fname,$group,$element,$portfolio_root,$port_path,
12008:         $disk_quota,$current_disk_usage,$uname,$udom) = @_;
12009:     my $filesize = length($env{'form.'.$element});
12010:     if (!$filesize) {
12011:         my $msg = '<span class="LC_error">'.
12012:                   &mt('Unable to upload [_1]. (size = [_2] bytes)', 
12013:                       '<span class="LC_filename">'.$fname.'</span>',
12014:                       $filesize).'<br />'.
12015:                   &mt('Either the file you attempted to upload was empty, or your web browser was unable to read its contents.').'<br />'.
12016:                   '</span>';
12017:         return ('zero_bytes',$msg);
12018:     }
12019:     $filesize =  $filesize/1000; #express in k (1024?)
12020:     my $getpropath = 1;
12021:     my ($dirlistref,$listerror) =
12022:          &Apache::lonnet::dirlist($portfolio_root.$path,$udom,$uname,$getpropath);
12023:     my $found_file = 0;
12024:     my $locked_file = 0;
12025:     my @lockers;
12026:     my $navmap;
12027:     if ($env{'request.course.id'}) {
12028:         $navmap = Apache::lonnavmaps::navmap->new();
12029:     }
12030:     if (ref($dirlistref) eq 'ARRAY') {
12031:         foreach my $line (@{$dirlistref}) {
12032:             my ($file_name,$rest)=split(/\&/,$line,2);
12033:             if ($file_name eq $fname){
12034:                 $file_name = $path.$file_name;
12035:                 if ($group ne '') {
12036:                     $file_name = $group.$file_name;
12037:                 }
12038:                 $found_file = 1;
12039:                 if (&Apache::lonnet::is_locked($file_name,$udom,$uname,\@lockers) eq 'true') {
12040:                     foreach my $lock (@lockers) {
12041:                         if (ref($lock) eq 'ARRAY') {
12042:                             my ($symb,$crsid) = @{$lock};
12043:                             if ($crsid eq $env{'request.course.id'}) {
12044:                                 if (ref($navmap)) {
12045:                                     my $res = $navmap->getBySymb($symb);
12046:                                     foreach my $part (@{$res->parts()}) { 
12047:                                         my ($slot_status,$slot_time,$slot_name)=$res->check_for_slot($part);
12048:                                         unless (($slot_status == $res->RESERVED) ||
12049:                                                 ($slot_status == $res->RESERVED_LOCATION)) {
12050:                                             $locked_file = 1;
12051:                                         }
12052:                                     }
12053:                                 } else {
12054:                                     $locked_file = 1;
12055:                                 }
12056:                             } else {
12057:                                 $locked_file = 1;
12058:                             }
12059:                         }
12060:                    }
12061:                 } else {
12062:                     my @info = split(/\&/,$rest);
12063:                     my $currsize = $info[6]/1000;
12064:                     if ($currsize < $filesize) {
12065:                         my $extra = $filesize - $currsize;
12066:                         if (($current_disk_usage + $extra) > $disk_quota) {
12067:                             my $msg = '<p class="LC_warning">'.
12068:                                       &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.',
12069:                                           '<span class="LC_filename">'.$fname.'</span>',$filesize,$currsize).'</p>'.
12070:                                       '<p>'.&mt('Disk quota is [_1] kilobytes. Your current disk usage is [_2] kilobytes.',
12071:                                                    $disk_quota,$current_disk_usage).'</p>';
12072:                             return ('will_exceed_quota',$msg);
12073:                         }
12074:                     }
12075:                 }
12076:             }
12077:         }
12078:     }
12079:     if (($current_disk_usage + $filesize) > $disk_quota){
12080:         my $msg = '<p class="LC_warning">'.
12081:                 &mt('Unable to upload [_1]. (size = [_2] kilobytes). Disk quota will be exceeded.','<span class="LC_filename">'.$fname.'</span>',$filesize).'</p>'.
12082:                   '<p>'.&mt('Disk quota is [_1] kilobytes. Your current disk usage is [_2] kilobytes.',$disk_quota,$current_disk_usage).'</p>';
12083:         return ('will_exceed_quota',$msg);
12084:     } elsif ($found_file) {
12085:         if ($locked_file) {
12086:             my $msg = '<p class="LC_warning">';
12087:             $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>');
12088:             $msg .= '</p>';
12089:             $msg .= &mt('You will be able to rename or delete existing [_1] after a grade has been assigned.','<span class="LC_filename">'.$fname.'</span>');
12090:             return ('file_locked',$msg);
12091:         } else {
12092:             my $msg = '<p class="LC_error">';
12093:             $msg .= &mt(' A file by that name: [_1] was found in [_2].','<span class="LC_filename">'.$fname.'</span>',$port_path.$env{'form.currentpath'});
12094:             $msg .= '</p>';
12095:             return ('existingfile',$msg);
12096:         }
12097:     }
12098: }
12099: 
12100: sub check_for_traversal {
12101:     my ($path,$url,$toplevel) = @_;
12102:     my @parts=split(/\//,$path);
12103:     my $cleanpath;
12104:     my $fullpath = $url;
12105:     for (my $i=0;$i<@parts;$i++) {
12106:         next if ($parts[$i] eq '.');
12107:         if ($parts[$i] eq '..') {
12108:             $fullpath =~ s{([^/]+/)$}{};
12109:         } else {
12110:             $fullpath .= $parts[$i].'/';
12111:         }
12112:     }
12113:     if ($fullpath =~ /^\Q$url\E(.*)$/) {
12114:         $cleanpath = $1;
12115:     } elsif ($fullpath =~ /^\Q$toplevel\E(.*)$/) {
12116:         my $curr_toprel = $1;
12117:         my @parts = split(/\//,$curr_toprel);
12118:         my ($url_toprel) = ($url =~ /^\Q$toplevel\E(.*)$/);
12119:         my @urlparts = split(/\//,$url_toprel);
12120:         my $doubledots;
12121:         my $startdiff = -1;
12122:         for (my $i=0; $i<@urlparts; $i++) {
12123:             if ($startdiff == -1) {
12124:                 unless ($urlparts[$i] eq $parts[$i]) {
12125:                     $startdiff = $i;
12126:                     $doubledots .= '../';
12127:                 }
12128:             } else {
12129:                 $doubledots .= '../';
12130:             }
12131:         }
12132:         if ($startdiff > -1) {
12133:             $cleanpath = $doubledots;
12134:             for (my $i=$startdiff; $i<@parts; $i++) {
12135:                 $cleanpath .= $parts[$i].'/';
12136:             }
12137:         }
12138:     }
12139:     $cleanpath =~ s{(/)$}{};
12140:     return $cleanpath;
12141: }
12142: 
12143: sub is_archive_file {
12144:     my ($mimetype) = @_;
12145:     if (($mimetype eq 'application/octet-stream') ||
12146:         ($mimetype eq 'application/x-stuffit') ||
12147:         ($mimetype =~ m{^application/(x\-)?(compressed|tar|zip|tgz|gz|gtar|gzip|gunzip|bz|bz2|bzip2)})) {
12148:         return 1;
12149:     }
12150:     return;
12151: }
12152: 
12153: sub decompress_form {
12154:     my ($mimetype,$archiveurl,$action,$noextract,$hiddenelements,$dirlist) = @_;
12155:     my %lt = &Apache::lonlocal::texthash (
12156:         this => 'This file is an archive file.',
12157:         camt => 'This file is a Camtasia archive file.',
12158:         itsc => 'Its contents are as follows:',
12159:         youm => 'You may wish to extract its contents.',
12160:         extr => 'Extract contents',
12161:         auto => 'LON-CAPA can process the files automatically, or you can decide how each should be handled.',
12162:         proa => 'Process automatically?',
12163:         yes  => 'Yes',
12164:         no   => 'No',
12165:         fold => 'Title for folder containing movie',
12166:         movi => 'Title for page containing embedded movie', 
12167:     );
12168:     my $fileloc = &Apache::lonnet::filelocation(undef,$archiveurl);
12169:     my ($is_camtasia,$topdir,%toplevel,@paths);
12170:     my $info = &list_archive_contents($fileloc,\@paths);
12171:     if (@paths) {
12172:         foreach my $path (@paths) {
12173:             $path =~ s{^/}{};
12174:             if ($path =~ m{^([^/]+)/$}) {
12175:                 $topdir = $1;
12176:             }
12177:             if ($path =~ m{^([^/]+)/}) {
12178:                 $toplevel{$1} = $path;
12179:             } else {
12180:                 $toplevel{$path} = $path;
12181:             }
12182:         }
12183:     }
12184:     if ($mimetype =~ m{^application/(x\-)?(compressed|zip)}) {
12185:         my @camtasia6 = ("$topdir/","$topdir/index.html",
12186:                         "$topdir/media/",
12187:                         "$topdir/media/$topdir.mp4",
12188:                         "$topdir/media/FirstFrame.png",
12189:                         "$topdir/media/player.swf",
12190:                         "$topdir/media/swfobject.js",
12191:                         "$topdir/media/expressInstall.swf");
12192:         my @camtasia8_1 = ("$topdir/","$topdir/$topdir.html",
12193:                          "$topdir/$topdir.mp4",
12194:                          "$topdir/$topdir\_config.xml",
12195:                          "$topdir/$topdir\_controller.swf",
12196:                          "$topdir/$topdir\_embed.css",
12197:                          "$topdir/$topdir\_First_Frame.png",
12198:                          "$topdir/$topdir\_player.html",
12199:                          "$topdir/$topdir\_Thumbnails.png",
12200:                          "$topdir/playerProductInstall.swf",
12201:                          "$topdir/scripts/",
12202:                          "$topdir/scripts/config_xml.js",
12203:                          "$topdir/scripts/handlebars.js",
12204:                          "$topdir/scripts/jquery-1.7.1.min.js",
12205:                          "$topdir/scripts/jquery-ui-1.8.15.custom.min.js",
12206:                          "$topdir/scripts/modernizr.js",
12207:                          "$topdir/scripts/player-min.js",
12208:                          "$topdir/scripts/swfobject.js",
12209:                          "$topdir/skins/",
12210:                          "$topdir/skins/configuration_express.xml",
12211:                          "$topdir/skins/express_show/",
12212:                          "$topdir/skins/express_show/player-min.css",
12213:                          "$topdir/skins/express_show/spritesheet.png");
12214:         my @camtasia8_4 = ("$topdir/","$topdir/$topdir.html",
12215:                          "$topdir/$topdir.mp4",
12216:                          "$topdir/$topdir\_config.xml",
12217:                          "$topdir/$topdir\_controller.swf",
12218:                          "$topdir/$topdir\_embed.css",
12219:                          "$topdir/$topdir\_First_Frame.png",
12220:                          "$topdir/$topdir\_player.html",
12221:                          "$topdir/$topdir\_Thumbnails.png",
12222:                          "$topdir/playerProductInstall.swf",
12223:                          "$topdir/scripts/",
12224:                          "$topdir/scripts/config_xml.js",
12225:                          "$topdir/scripts/techsmith-smart-player.min.js",
12226:                          "$topdir/skins/",
12227:                          "$topdir/skins/configuration_express.xml",
12228:                          "$topdir/skins/express_show/",
12229:                          "$topdir/skins/express_show/spritesheet.min.css",
12230:                          "$topdir/skins/express_show/spritesheet.png",
12231:                          "$topdir/skins/express_show/techsmith-smart-player.min.css");
12232:         my @diffs = &compare_arrays(\@paths,\@camtasia6);
12233:         if (@diffs == 0) {
12234:             $is_camtasia = 6;
12235:         } else {
12236:             @diffs = &compare_arrays(\@paths,\@camtasia8_1);
12237:             if (@diffs == 0) {
12238:                 $is_camtasia = 8;
12239:             } else {
12240:                 @diffs = &compare_arrays(\@paths,\@camtasia8_4);
12241:                 if (@diffs == 0) {
12242:                     $is_camtasia = 8;
12243:                 }
12244:             }
12245:         }
12246:     }
12247:     my $output;
12248:     if ($is_camtasia) {
12249:         $output = <<"ENDCAM";
12250: <script type="text/javascript" language="Javascript">
12251: // <![CDATA[
12252: 
12253: function camtasiaToggle() {
12254:     for (var i=0; i<document.uploaded_decompress.autoextract_camtasia.length; i++) {
12255:         if (document.uploaded_decompress.autoextract_camtasia[i].checked) {
12256:             if (document.uploaded_decompress.autoextract_camtasia[i].value == $is_camtasia) {
12257:                 document.getElementById('camtasia_titles').style.display='block';
12258:             } else {
12259:                 document.getElementById('camtasia_titles').style.display='none';
12260:             }
12261:         }
12262:     }
12263:     return;
12264: }
12265: 
12266: // ]]>
12267: </script>
12268: <p>$lt{'camt'}</p>
12269: ENDCAM
12270:     } else {
12271:         $output = '<p>'.$lt{'this'};
12272:         if ($info eq '') {
12273:             $output .= ' '.$lt{'youm'}.'</p>'."\n";
12274:         } else {
12275:             $output .= ' '.$lt{'itsc'}.'</p>'."\n".
12276:                        '<div><pre>'.$info.'</pre></div>';
12277:         }
12278:     }
12279:     $output .= '<form name="uploaded_decompress" action="'.$action.'" method="post">'."\n";
12280:     my $duplicates;
12281:     my $num = 0;
12282:     if (ref($dirlist) eq 'ARRAY') {
12283:         foreach my $item (@{$dirlist}) {
12284:             if (ref($item) eq 'ARRAY') {
12285:                 if (exists($toplevel{$item->[0]})) {
12286:                     $duplicates .= 
12287:                         &start_data_table_row().
12288:                         '<td><label><input type="radio" name="archive_overwrite_'.$num.'" '.
12289:                         'value="0" checked="checked" />'.&mt('No').'</label>'.
12290:                         '&nbsp;<label><input type="radio" name="archive_overwrite_'.$num.'" '.
12291:                         'value="1" />'.&mt('Yes').'</label>'.
12292:                         '<input type="hidden" name="archive_overwrite_name_'.$num.'" value="'.$item->[0].'" /></td>'."\n".
12293:                         '<td>'.$item->[0].'</td>';
12294:                     if ($item->[2]) {
12295:                         $duplicates .= '<td>'.&mt('Directory').'</td>';
12296:                     } else {
12297:                         $duplicates .= '<td>'.&mt('File').'</td>';
12298:                     }
12299:                     $duplicates .= '<td>'.$item->[3].'</td>'.
12300:                                    '<td>'.
12301:                                    &Apache::lonlocal::locallocaltime($item->[4]).
12302:                                    '</td>'.
12303:                                    &end_data_table_row();
12304:                     $num ++;
12305:                 }
12306:             }
12307:         }
12308:     }
12309:     my $itemcount;
12310:     if (@paths > 0) {
12311:         $itemcount = scalar(@paths);
12312:     } else {
12313:         $itemcount = 1;
12314:     }
12315:     if ($is_camtasia) {
12316:         $output .= $lt{'auto'}.'<br />'.
12317:                    '<span class="LC_nobreak">'.$lt{'proa'}.'<label>'.
12318:                    '<input type="radio" name="autoextract_camtasia" value="'.$is_camtasia.'" onclick="javascript:camtasiaToggle();" checked="checked" />'.
12319:                    $lt{'yes'}.'</label>&nbsp;<label>'.
12320:                    '<input type="radio" name="autoextract_camtasia" value="0" onclick="javascript:camtasiaToggle();" />'.
12321:                    $lt{'no'}.'</label></span><br />'.
12322:                    '<div id="camtasia_titles" style="display:block">'.
12323:                    &Apache::lonhtmlcommon::start_pick_box().
12324:                    &Apache::lonhtmlcommon::row_title($lt{'fold'}).
12325:                    '<input type="textbox" name="camtasia_foldername" value="'.$env{'form.comment'}.'" />'."\n".
12326:                    &Apache::lonhtmlcommon::row_closure().
12327:                    &Apache::lonhtmlcommon::row_title($lt{'movi'}).
12328:                    '<input type="textbox" name="camtasia_moviename" value="" />'."\n".
12329:                    &Apache::lonhtmlcommon::row_closure(1).
12330:                    &Apache::lonhtmlcommon::end_pick_box().
12331:                    '</div>';
12332:     }
12333:     $output .= 
12334:         '<input type="hidden" name="archive_overwrite_total" value="'.$num.'" />'.
12335:         '<input type="hidden" name="archive_itemcount" value="'.$itemcount.'" />'.
12336:         "\n";
12337:     if ($duplicates ne '') {
12338:         $output .= '<p><span class="LC_warning">'.
12339:                    &mt('Warning: decompression of the archive will overwrite the following items which already exist:').'</span><br />'.  
12340:                    &start_data_table().
12341:                    &start_data_table_header_row().
12342:                    '<th>'.&mt('Overwrite?').'</th>'.
12343:                    '<th>'.&mt('Name').'</th>'.
12344:                    '<th>'.&mt('Type').'</th>'.
12345:                    '<th>'.&mt('Size').'</th>'.
12346:                    '<th>'.&mt('Last modified').'</th>'.
12347:                    &end_data_table_header_row().
12348:                    $duplicates.
12349:                    &end_data_table().
12350:                    '</p>';
12351:     }
12352:     $output .= '<input type="hidden" name="archiveurl" value="'.$archiveurl.'" />'."\n";
12353:     if (ref($hiddenelements) eq 'HASH') {
12354:         foreach my $hidden (sort(keys(%{$hiddenelements}))) {
12355:             $output .= '<input type="hidden" name="'.$hidden.'" value="'.$hiddenelements->{$hidden}.'" />'."\n";
12356:         }
12357:     }
12358:     $output .= <<"END";
12359: <br />
12360: <input type="submit" name="decompress" value="$lt{'extr'}" />
12361: </form>
12362: $noextract
12363: END
12364:     return $output;
12365: }
12366: 
12367: sub decompression_utility {
12368:     my ($program) = @_;
12369:     my @utilities = ('tar','gunzip','bunzip2','unzip'); 
12370:     my $location;
12371:     if (grep(/^\Q$program\E$/,@utilities)) { 
12372:         foreach my $dir ('/bin/','/usr/bin/','/usr/local/bin/','/sbin/',
12373:                          '/usr/sbin/') {
12374:             if (-x $dir.$program) {
12375:                 $location = $dir.$program;
12376:                 last;
12377:             }
12378:         }
12379:     }
12380:     return $location;
12381: }
12382: 
12383: sub list_archive_contents {
12384:     my ($file,$pathsref) = @_;
12385:     my (@cmd,$output);
12386:     my $needsregexp;
12387:     if ($file =~ /\.zip$/) {
12388:         @cmd = (&decompression_utility('unzip'),"-l");
12389:         $needsregexp = 1;
12390:     } elsif (($file =~ m/\.tar\.gz$/) ||
12391:              ($file =~ /\.tgz$/)) {
12392:         @cmd = (&decompression_utility('tar'),"-ztf");
12393:     } elsif ($file =~ /\.tar\.bz2$/) {
12394:         @cmd = (&decompression_utility('tar'),"-jtf");
12395:     } elsif ($file =~ m|\.tar$|) {
12396:         @cmd = (&decompression_utility('tar'),"-tf");
12397:     }
12398:     if (@cmd) {
12399:         undef($!);
12400:         undef($@);
12401:         if (open(my $fh,"-|", @cmd, $file)) {
12402:             while (my $line = <$fh>) {
12403:                 $output .= $line;
12404:                 chomp($line);
12405:                 my $item;
12406:                 if ($needsregexp) {
12407:                     ($item) = ($line =~ /^\s*\d+\s+[\d\-]+\s+[\d:]+\s*(.+)$/); 
12408:                 } else {
12409:                     $item = $line;
12410:                 }
12411:                 if ($item ne '') {
12412:                     unless (grep(/^\Q$item\E$/,@{$pathsref})) {
12413:                         push(@{$pathsref},$item);
12414:                     } 
12415:                 }
12416:             }
12417:             close($fh);
12418:         }
12419:     }
12420:     return $output;
12421: }
12422: 
12423: sub decompress_uploaded_file {
12424:     my ($file,$dir) = @_;
12425:     &Apache::lonnet::appenv({'cgi.file' => $file});
12426:     &Apache::lonnet::appenv({'cgi.dir' => $dir});
12427:     my $result = &Apache::lonnet::ssi_body('/cgi-bin/decompress.pl');
12428:     my ($handle) = ($env{'user.environment'} =~m{/([^/]+)\.id$});
12429:     my $lonidsdir = $Apache::lonnet::perlvar{'lonIDsDir'};
12430:     &Apache::lonnet::transfer_profile_to_env($lonidsdir,$handle,1);
12431:     my $decompressed = $env{'cgi.decompressed'};
12432:     &Apache::lonnet::delenv('cgi.file');
12433:     &Apache::lonnet::delenv('cgi.dir');
12434:     &Apache::lonnet::delenv('cgi.decompressed');
12435:     return ($decompressed,$result);
12436: }
12437: 
12438: sub process_decompression {
12439:     my ($docudom,$docuname,$file,$destination,$dir_root,$hiddenelem) = @_;
12440:     my ($dir,$error,$warning,$output);
12441:     if ($file !~ /\.(zip|tar|bz2|gz|tar.gz|tar.bz2|tgz)$/i) {
12442:         $error = &mt('Filename not a supported archive file type.').
12443:                  '<br />'.&mt('Filename should end with one of: [_1].',
12444:                               '.zip, .tar, .bz2, .gz, .tar.gz, .tar.bz2, .tgz');
12445:     } else {
12446:         my $docuhome = &Apache::lonnet::homeserver($docuname,$docudom);
12447:         if ($docuhome eq 'no_host') {
12448:             $error = &mt('Could not determine home server for course.');
12449:         } else {
12450:             my @ids=&Apache::lonnet::current_machine_ids();
12451:             my $currdir = "$dir_root/$destination";
12452:             if (grep(/^\Q$docuhome\E$/,@ids)) {
12453:                 $dir = &LONCAPA::propath($docudom,$docuname).
12454:                        "$dir_root/$destination";
12455:             } else {
12456:                 $dir = $Apache::lonnet::perlvar{'lonDocRoot'}.
12457:                        "$dir_root/$docudom/$docuname/$destination";
12458:                 unless (&Apache::lonnet::repcopy_userfile("$dir/$file") eq 'ok') {
12459:                     $error = &mt('Archive file not found.');
12460:                 }
12461:             }
12462:             my (@to_overwrite,@to_skip);
12463:             if ($env{'form.archive_overwrite_total'} > 0) {
12464:                 my $total = $env{'form.archive_overwrite_total'};
12465:                 for (my $i=0; $i<$total; $i++) {
12466:                     if ($env{'form.archive_overwrite_'.$i} == 1) {
12467:                         push(@to_overwrite,$env{'form.archive_overwrite_name_'.$i});
12468:                     } elsif ($env{'form.archive_overwrite_'.$i} == 0) {
12469:                         push(@to_skip,$env{'form.archive_overwrite_name_'.$i});
12470:                     }
12471:                 }
12472:             }
12473:             my $numskip = scalar(@to_skip);
12474:             if (($numskip > 0) && 
12475:                 ($numskip == $env{'form.archive_itemcount'})) {
12476:                 $warning = &mt('All items in the archive file already exist, and no overwriting of existing files has been requested.');         
12477:             } elsif ($dir eq '') {
12478:                 $error = &mt('Directory containing archive file unavailable.');
12479:             } elsif (!$error) {
12480:                 my ($decompressed,$display);
12481:                 if ($numskip > 0) {
12482:                     my $tempdir = time.'_'.$$.int(rand(10000));
12483:                     mkdir("$dir/$tempdir",0755);
12484:                     system("mv $dir/$file $dir/$tempdir/$file");
12485:                     ($decompressed,$display) = 
12486:                         &decompress_uploaded_file($file,"$dir/$tempdir");
12487:                     foreach my $item (@to_skip) {
12488:                         if (($item ne '') && ($item !~ /\.\./)) {
12489:                             if (-f "$dir/$tempdir/$item") { 
12490:                                 unlink("$dir/$tempdir/$item");
12491:                             } elsif (-d "$dir/$tempdir/$item") {
12492:                                 system("rm -rf $dir/$tempdir/$item");
12493:                             }
12494:                         }
12495:                     }
12496:                     system("mv $dir/$tempdir/* $dir");
12497:                     rmdir("$dir/$tempdir");   
12498:                 } else {
12499:                     ($decompressed,$display) = 
12500:                         &decompress_uploaded_file($file,$dir);
12501:                 }
12502:                 if ($decompressed eq 'ok') {
12503:                     $output = '<p class="LC_info">'.
12504:                               &mt('Files extracted successfully from archive.').
12505:                               '</p>'."\n";
12506:                     my ($warning,$result,@contents);
12507:                     my ($newdirlistref,$newlisterror) =
12508:                         &Apache::lonnet::dirlist($currdir,$docudom,
12509:                                                  $docuname,1);
12510:                     my (%is_dir,%changes,@newitems);
12511:                     my $dirptr = 16384;
12512:                     if (ref($newdirlistref) eq 'ARRAY') {
12513:                         foreach my $dir_line (@{$newdirlistref}) {
12514:                             my ($item,undef,undef,$testdir)=split(/\&/,$dir_line,5);
12515:                             unless (($item =~ /^\.+$/) || ($item eq $file) || 
12516:                                     ((@to_skip > 0) && (grep(/^\Q$item\E$/,@to_skip)))) {
12517:                                 push(@newitems,$item);
12518:                                 if ($dirptr&$testdir) {
12519:                                     $is_dir{$item} = 1;
12520:                                 }
12521:                                 $changes{$item} = 1;
12522:                             }
12523:                         }
12524:                     }
12525:                     if (keys(%changes) > 0) {
12526:                         foreach my $item (sort(@newitems)) {
12527:                             if ($changes{$item}) {
12528:                                 push(@contents,$item);
12529:                             }
12530:                         }
12531:                     }
12532:                     if (@contents > 0) {
12533:                         my $wantform;
12534:                         unless ($env{'form.autoextract_camtasia'}) {
12535:                             $wantform = 1;
12536:                         }
12537:                         my (%children,%parent,%dirorder,%titles);
12538:                         my ($count,$datatable) = &get_extracted($docudom,$docuname,
12539:                                                                 $currdir,\%is_dir,
12540:                                                                 \%children,\%parent,
12541:                                                                 \@contents,\%dirorder,
12542:                                                                 \%titles,$wantform);
12543:                         if ($datatable ne '') {
12544:                             $output .= &archive_options_form('decompressed',$datatable,
12545:                                                              $count,$hiddenelem);
12546:                             my $startcount = 6;
12547:                             $output .= &archive_javascript($startcount,$count,
12548:                                                            \%titles,\%children);
12549:                         }
12550:                         if ($env{'form.autoextract_camtasia'}) {
12551:                             my $version = $env{'form.autoextract_camtasia'};
12552:                             my %displayed;
12553:                             my $total = 1;
12554:                             $env{'form.archive_directory'} = [];
12555:                             foreach my $i (sort { $a <=> $b } keys(%dirorder)) {
12556:                                 my $path = join('/',map { $titles{$_}; } @{$dirorder{$i}});
12557:                                 $path =~ s{/$}{};
12558:                                 my $item;
12559:                                 if ($path ne '') {
12560:                                     $item = "$path/$titles{$i}";
12561:                                 } else {
12562:                                     $item = $titles{$i};
12563:                                 }
12564:                                 $env{'form.archive_content_'.$i} = "$dir_root/$destination/$item";
12565:                                 if ($item eq $contents[0]) {
12566:                                     push(@{$env{'form.archive_directory'}},$i);
12567:                                     $env{'form.archive_'.$i} = 'display';
12568:                                     $env{'form.archive_title_'.$i} = $env{'form.camtasia_foldername'};
12569:                                     $displayed{'folder'} = $i;
12570:                                 } elsif ((($item eq "$contents[0]/index.html") && ($version == 6)) ||
12571:                                          (($item eq "$contents[0]/$contents[0]".'.html') && ($version == 8))) { 
12572:                                     $env{'form.archive_'.$i} = 'display';
12573:                                     $env{'form.archive_title_'.$i} = $env{'form.camtasia_moviename'};
12574:                                     $displayed{'web'} = $i;
12575:                                 } else {
12576:                                     if ((($item eq "$contents[0]/media") && ($version == 6)) ||
12577:                                         ((($item eq "$contents[0]/scripts") || ($item eq "$contents[0]/skins") ||
12578:                                              ($item eq "$contents[0]/skins/express_show")) && ($version == 8))) {
12579:                                         push(@{$env{'form.archive_directory'}},$i);
12580:                                     }
12581:                                     $env{'form.archive_'.$i} = 'dependency';
12582:                                 }
12583:                                 $total ++;
12584:                             }
12585:                             for (my $i=1; $i<$total; $i++) {
12586:                                 next if ($i == $displayed{'web'});
12587:                                 next if ($i == $displayed{'folder'});
12588:                                 $env{'form.archive_dependent_on_'.$i} = $displayed{'web'};
12589:                             }
12590:                             $env{'form.phase'} = 'decompress_cleanup';
12591:                             $env{'form.archivedelete'} = 1;
12592:                             $env{'form.archive_count'} = $total-1;
12593:                             $output .=
12594:                                 &process_extracted_files('coursedocs',$docudom,
12595:                                                          $docuname,$destination,
12596:                                                          $dir_root,$hiddenelem);
12597:                         }
12598:                     } else {
12599:                         $warning = &mt('No new items extracted from archive file.');
12600:                     }
12601:                 } else {
12602:                     $output = $display;
12603:                     $error = &mt('An error occurred during extraction from the archive file.');
12604:                 }
12605:             }
12606:         }
12607:     }
12608:     if ($error) {
12609:         $output .= '<p class="LC_error">'.&mt('Not extracted.').'<br />'.
12610:                    $error.'</p>'."\n";
12611:     }
12612:     if ($warning) {
12613:         $output .= '<p class="LC_warning">'.$warning.'</p>'."\n";
12614:     }
12615:     return $output;
12616: }
12617: 
12618: sub get_extracted {
12619:     my ($docudom,$docuname,$currdir,$is_dir,$children,$parent,$contents,$dirorder,
12620:         $titles,$wantform) = @_;
12621:     my $count = 0;
12622:     my $depth = 0;
12623:     my $datatable;
12624:     my @hierarchy;
12625:     return unless ((ref($is_dir) eq 'HASH') && (ref($children) eq 'HASH') &&
12626:                    (ref($parent) eq 'HASH') && (ref($contents) eq 'ARRAY') &&
12627:                    (ref($dirorder) eq 'HASH') && (ref($titles) eq 'HASH'));
12628:     foreach my $item (@{$contents}) {
12629:         $count ++;
12630:         @{$dirorder->{$count}} = @hierarchy;
12631:         $titles->{$count} = $item;
12632:         &archive_hierarchy($depth,$count,$parent,$children);
12633:         if ($wantform) {
12634:             $datatable .= &archive_row($is_dir->{$item},$item,
12635:                                        $currdir,$depth,$count);
12636:         }
12637:         if ($is_dir->{$item}) {
12638:             $depth ++;
12639:             push(@hierarchy,$count);
12640:             $parent->{$depth} = $count;
12641:             $datatable .=
12642:                 &recurse_extracted_archive("$currdir/$item",$docudom,$docuname,
12643:                                            \$depth,\$count,\@hierarchy,$dirorder,
12644:                                            $children,$parent,$titles,$wantform);
12645:             $depth --;
12646:             pop(@hierarchy);
12647:         }
12648:     }
12649:     return ($count,$datatable);
12650: }
12651: 
12652: sub recurse_extracted_archive {
12653:     my ($currdir,$docudom,$docuname,$depth,$count,$hierarchy,$dirorder,
12654:         $children,$parent,$titles,$wantform) = @_;
12655:     my $result='';
12656:     unless ((ref($depth)) && (ref($count)) && (ref($hierarchy) eq 'ARRAY') &&
12657:             (ref($children) eq 'HASH') && (ref($parent) eq 'HASH') &&
12658:             (ref($dirorder) eq 'HASH')) {
12659:         return $result;
12660:     }
12661:     my $dirptr = 16384;
12662:     my ($newdirlistref,$newlisterror) =
12663:         &Apache::lonnet::dirlist($currdir,$docudom,$docuname,1);
12664:     if (ref($newdirlistref) eq 'ARRAY') {
12665:         foreach my $dir_line (@{$newdirlistref}) {
12666:             my ($item,undef,undef,$testdir)=split(/\&/,$dir_line,5);
12667:             unless ($item =~ /^\.+$/) {
12668:                 $$count ++;
12669:                 @{$dirorder->{$$count}} = @{$hierarchy};
12670:                 $titles->{$$count} = $item;
12671:                 &archive_hierarchy($$depth,$$count,$parent,$children);
12672: 
12673:                 my $is_dir;
12674:                 if ($dirptr&$testdir) {
12675:                     $is_dir = 1;
12676:                 }
12677:                 if ($wantform) {
12678:                     $result .= &archive_row($is_dir,$item,$currdir,$$depth,$$count);
12679:                 }
12680:                 if ($is_dir) {
12681:                     $$depth ++;
12682:                     push(@{$hierarchy},$$count);
12683:                     $parent->{$$depth} = $$count;
12684:                     $result .=
12685:                         &recurse_extracted_archive("$currdir/$item",$docudom,
12686:                                                    $docuname,$depth,$count,
12687:                                                    $hierarchy,$dirorder,$children,
12688:                                                    $parent,$titles,$wantform);
12689:                     $$depth --;
12690:                     pop(@{$hierarchy});
12691:                 }
12692:             }
12693:         }
12694:     }
12695:     return $result;
12696: }
12697: 
12698: sub archive_hierarchy {
12699:     my ($depth,$count,$parent,$children) =@_;
12700:     if ((ref($parent) eq 'HASH') && (ref($children) eq 'HASH')) {
12701:         if (exists($parent->{$depth})) {
12702:              $children->{$parent->{$depth}} .= $count.':';
12703:         }
12704:     }
12705:     return;
12706: }
12707: 
12708: sub archive_row {
12709:     my ($is_dir,$item,$currdir,$depth,$count) = @_;
12710:     my ($name) = ($item =~ m{([^/]+)$});
12711:     my %choices = &Apache::lonlocal::texthash (
12712:                                        'display'    => 'Add as file',
12713:                                        'dependency' => 'Include as dependency',
12714:                                        'discard'    => 'Discard',
12715:                                       );
12716:     if ($is_dir) {
12717:         $choices{'display'} = &mt('Add as folder'); 
12718:     }
12719:     my $output = &start_data_table_row().'<td align="right">'.$count.'</td>'."\n";
12720:     my $offset = 0;
12721:     foreach my $action ('display','dependency','discard') {
12722:         $offset ++;
12723:         if ($action ne 'display') {
12724:             $offset ++;
12725:         }  
12726:         $output .= '<td><span class="LC_nobreak">'.
12727:                    '<label><input type="radio" name="archive_'.$count.
12728:                    '" id="archive_'.$action.'_'.$count.'" value="'.$action.'"';
12729:         my $text = $choices{$action};
12730:         if ($is_dir) {
12731:             $output .= ' onclick="javascript:propagateCheck(this.form,'."'$count'".');"';
12732:             if ($action eq 'display') {
12733:                 $text = &mt('Add as folder');
12734:             }
12735:         } else {
12736:             $output .= ' onclick="javascript:dependencyCheck(this.form,'."$count,$offset".');"';
12737: 
12738:         }
12739:         $output .= ' />&nbsp;'.$choices{$action}.'</label></span>';
12740:         if ($action eq 'dependency') {
12741:             $output .= '<div id="arc_depon_'.$count.'" style="display:none;">'."\n".
12742:                        &mt('Used by:').'&nbsp;<select name="archive_dependent_on_'.$count.'" '.
12743:                        'onchange="propagateSelect(this.form,'."$count,$offset".')">'."\n".
12744:                        '<option value=""></option>'."\n".
12745:                        '</select>'."\n".
12746:                        '</div>';
12747:         } elsif ($action eq 'display') {
12748:             $output .= '<div id="arc_title_'.$count.'" style="display:none;">'."\n".
12749:                        &mt('Title:').'&nbsp;<input type="text" name="archive_title_'.$count.'" id="archive_title_'.$count.'" />'."\n".
12750:                        '</div>';
12751:         }
12752:         $output .= '</td>';
12753:     }
12754:     $output .= '<td><input type="hidden" name="archive_content_'.$count.'" value="'.
12755:                &HTML::Entities::encode("$currdir/$item",'"<>&').'" />'.('&nbsp;' x 2);
12756:     for (my $i=0; $i<$depth; $i++) {
12757:         $output .= ('<img src="/adm/lonIcons/whitespace1.gif" class="LC_docs_spacer" alt="" />' x2)."\n";
12758:     }
12759:     if ($is_dir) {
12760:         $output .= '<img src="/adm/lonIcons/navmap.folder.open.gif" alt="" />&nbsp;'."\n".
12761:                    '<input type="hidden" name="archive_directory" value="'.$count.'" />'."\n";
12762:     } else {
12763:         $output .= '<input type="hidden" name="archive_file" value="'.$count.'" />'."\n";
12764:     }
12765:     $output .= '&nbsp;'.$name.'</td>'."\n".
12766:                &end_data_table_row();
12767:     return $output;
12768: }
12769: 
12770: sub archive_options_form {
12771:     my ($form,$display,$count,$hiddenelem) = @_;
12772:     my %lt = &Apache::lonlocal::texthash(
12773:                perm => 'Permanently remove archive file?',
12774:                hows => 'How should each extracted item be incorporated in the course?',
12775:                cont => 'Content actions for all',
12776:                addf => 'Add as folder/file',
12777:                incd => 'Include as dependency for a displayed file',
12778:                disc => 'Discard',
12779:                no   => 'No',
12780:                yes  => 'Yes',
12781:                save => 'Save',
12782:     );
12783:     my $output = <<"END";
12784: <form name="$form" method="post" action="">
12785: <p><span class="LC_nobreak">$lt{'perm'}&nbsp;
12786: <label>
12787:   <input type="radio" name="archivedelete" value="0" checked="checked" />$lt{'no'}
12788: </label>
12789: &nbsp;
12790: <label>
12791:   <input type="radio" name="archivedelete" value="1" />$lt{'yes'}</label>
12792: </span>
12793: </p>
12794: <input type="hidden" name="phase" value="decompress_cleanup" />
12795: <br />$lt{'hows'}
12796: <div class="LC_columnSection">
12797:   <fieldset>
12798:     <legend>$lt{'cont'}</legend>
12799:     <input type="button" value="$lt{'addf'}" onclick="javascript:checkAll(document.$form,'display');" /> 
12800:     &nbsp;&nbsp;<input type="button" value="$lt{'incd'}" onclick="javascript:checkAll(document.$form,'dependency');" />
12801:     &nbsp;&nbsp;<input type="button" value="$lt{'disc'}" onclick="javascript:checkAll(document.$form,'discard');" />
12802:   </fieldset>
12803: </div>
12804: END
12805:     return $output.
12806:            &start_data_table()."\n".
12807:            $display."\n".
12808:            &end_data_table()."\n".
12809:            '<input type="hidden" name="archive_count" value="'.$count.'" />'.
12810:            $hiddenelem.
12811:            '<br /><input type="submit" name="archive_submit" value="'.$lt{'save'}.'" />'.
12812:            '</form>';
12813: }
12814: 
12815: sub archive_javascript {
12816:     my ($startcount,$numitems,$titles,$children) = @_;
12817:     return unless ((ref($titles) eq 'HASH') && (ref($children) eq 'HASH'));
12818:     my $maintitle = $env{'form.comment'};
12819:     my $scripttag = <<START;
12820: <script type="text/javascript">
12821: // <![CDATA[
12822: 
12823: function checkAll(form,prefix) {
12824:     var idstr =  new RegExp("^archive_"+prefix+"_\\\\d+\$");
12825:     for (var i=0; i < form.elements.length; i++) {
12826:         var id = form.elements[i].id;
12827:         if ((id != '') && (id != undefined)) {
12828:             if (idstr.test(id)) {
12829:                 if (form.elements[i].type == 'radio') {
12830:                     form.elements[i].checked = true;
12831:                     var nostart = i-$startcount;
12832:                     var offset = nostart%7;
12833:                     var count = (nostart-offset)/7;    
12834:                     dependencyCheck(form,count,offset);
12835:                 }
12836:             }
12837:         }
12838:     }
12839: }
12840: 
12841: function propagateCheck(form,count) {
12842:     if (count > 0) {
12843:         var startelement = $startcount + ((count-1) * 7);
12844:         for (var j=1; j<6; j++) {
12845:             if ((j != 2) && (j != 4)) {
12846:                 var item = startelement + j; 
12847:                 if (form.elements[item].type == 'radio') {
12848:                     if (form.elements[item].checked) {
12849:                         containerCheck(form,count,j);
12850:                         break;
12851:                     }
12852:                 }
12853:             }
12854:         }
12855:     }
12856: }
12857: 
12858: numitems = $numitems
12859: var titles = new Array(numitems);
12860: var parents = new Array(numitems);
12861: for (var i=0; i<numitems; i++) {
12862:     parents[i] = new Array;
12863: }
12864: var maintitle = '$maintitle';
12865: 
12866: START
12867: 
12868:     foreach my $container (sort { $a <=> $b } (keys(%{$children}))) {
12869:         my @contents = split(/:/,$children->{$container});
12870:         for (my $i=0; $i<@contents; $i ++) {
12871:             $scripttag .= 'parents['.$container.']['.$i.'] = '.$contents[$i]."\n";
12872:         }
12873:     }
12874: 
12875:     foreach my $key (sort { $a <=> $b } (keys(%{$titles}))) {
12876:         $scripttag .= "titles[$key] = '".$titles->{$key}."';\n";
12877:     }
12878: 
12879:     $scripttag .= <<END;
12880: 
12881: function containerCheck(form,count,offset) {
12882:     if (count > 0) {
12883:         dependencyCheck(form,count,offset);
12884:         var item = (offset+$startcount)+7*(count-1);
12885:         form.elements[item].checked = true;
12886:         if(Object.prototype.toString.call(parents[count]) === '[object Array]') {
12887:             if (parents[count].length > 0) {
12888:                 for (var j=0; j<parents[count].length; j++) {
12889:                     containerCheck(form,parents[count][j],offset);
12890:                 }
12891:             }
12892:         }
12893:     }
12894: }
12895: 
12896: function dependencyCheck(form,count,offset) {
12897:     if (count > 0) {
12898:         var chosen = (offset+$startcount)+7*(count-1);
12899:         var depitem = $startcount + ((count-1) * 7) + 4;
12900:         var currtype = form.elements[depitem].type;
12901:         if (form.elements[chosen].value == 'dependency') {
12902:             document.getElementById('arc_depon_'+count).style.display='block'; 
12903:             form.elements[depitem].options.length = 0;
12904:             form.elements[depitem].options[0] = new Option('Select','',true,true);
12905:             for (var i=1; i<=numitems; i++) {
12906:                 if (i == count) {
12907:                     continue;
12908:                 }
12909:                 var startelement = $startcount + (i-1) * 7;
12910:                 for (var j=1; j<6; j++) {
12911:                     if ((j != 2) && (j!= 4)) {
12912:                         var item = startelement + j;
12913:                         if (form.elements[item].type == 'radio') {
12914:                             if (form.elements[item].checked) {
12915:                                 if (form.elements[item].value == 'display') {
12916:                                     var n = form.elements[depitem].options.length;
12917:                                     form.elements[depitem].options[n] = new Option(titles[i],i,false,false);
12918:                                 }
12919:                             }
12920:                         }
12921:                     }
12922:                 }
12923:             }
12924:         } else {
12925:             document.getElementById('arc_depon_'+count).style.display='none';
12926:             form.elements[depitem].options.length = 0;
12927:             form.elements[depitem].options[0] = new Option('Select','',true,true);
12928:         }
12929:         titleCheck(form,count,offset);
12930:     }
12931: }
12932: 
12933: function propagateSelect(form,count,offset) {
12934:     if (count > 0) {
12935:         var item = (1+offset+$startcount)+7*(count-1);
12936:         var picked = form.elements[item].options[form.elements[item].selectedIndex].value; 
12937:         if (Object.prototype.toString.call(parents[count]) === '[object Array]') {
12938:             if (parents[count].length > 0) {
12939:                 for (var j=0; j<parents[count].length; j++) {
12940:                     containerSelect(form,parents[count][j],offset,picked);
12941:                 }
12942:             }
12943:         }
12944:     }
12945: }
12946: 
12947: function containerSelect(form,count,offset,picked) {
12948:     if (count > 0) {
12949:         var item = (offset+$startcount)+7*(count-1);
12950:         if (form.elements[item].type == 'radio') {
12951:             if (form.elements[item].value == 'dependency') {
12952:                 if (form.elements[item+1].type == 'select-one') {
12953:                     for (var i=0; i<form.elements[item+1].options.length; i++) {
12954:                         if (form.elements[item+1].options[i].value == picked) {
12955:                             form.elements[item+1].selectedIndex = i;
12956:                             break;
12957:                         }
12958:                     }
12959:                 }
12960:                 if (Object.prototype.toString.call(parents[count]) === '[object Array]') {
12961:                     if (parents[count].length > 0) {
12962:                         for (var j=0; j<parents[count].length; j++) {
12963:                             containerSelect(form,parents[count][j],offset,picked);
12964:                         }
12965:                     }
12966:                 }
12967:             }
12968:         }
12969:     }
12970: }
12971: 
12972: function titleCheck(form,count,offset) {
12973:     if (count > 0) {
12974:         var chosen = (offset+$startcount)+7*(count-1);
12975:         var depitem = $startcount + ((count-1) * 7) + 2;
12976:         var currtype = form.elements[depitem].type;
12977:         if (form.elements[chosen].value == 'display') {
12978:             document.getElementById('arc_title_'+count).style.display='block';
12979:             if ((count==1) && ((parents[count].length > 0) || (numitems == 1))) {
12980:                 document.getElementById('archive_title_'+count).value=maintitle;
12981:             }
12982:         } else {
12983:             document.getElementById('arc_title_'+count).style.display='none';
12984:             if (currtype == 'text') { 
12985:                 document.getElementById('archive_title_'+count).value='';
12986:             }
12987:         }
12988:     }
12989:     return;
12990: }
12991: 
12992: // ]]>
12993: </script>
12994: END
12995:     return $scripttag;
12996: }
12997: 
12998: sub process_extracted_files {
12999:     my ($context,$docudom,$docuname,$destination,$dir_root,$hiddenelem) = @_;
13000:     my $numitems = $env{'form.archive_count'};
13001:     return unless ($numitems);
13002:     my @ids=&Apache::lonnet::current_machine_ids();
13003:     my ($prefix,$pathtocheck,$dir,$ishome,$error,$warning,%toplevelitems,%is_dir,
13004:         %folders,%containers,%mapinner,%prompttofetch);
13005:     my $docuhome = &Apache::lonnet::homeserver($docuname,$docudom);
13006:     if (grep(/^\Q$docuhome\E$/,@ids)) {
13007:         $prefix = &LONCAPA::propath($docudom,$docuname);
13008:         $pathtocheck = "$dir_root/$destination";
13009:         $dir = $dir_root;
13010:         $ishome = 1;
13011:     } else {
13012:         $prefix = $Apache::lonnet::perlvar{'lonDocRoot'};
13013:         $pathtocheck = "$dir_root/$docudom/$docuname/$destination";
13014:         $dir = "$dir_root/$docudom/$docuname";    
13015:     }
13016:     my $currdir = "$dir_root/$destination";
13017:     (my $docstype,$mapinner{'0'}) = ($destination =~ m{^(docs|supplemental)/(\w+)/});
13018:     if ($env{'form.folderpath'}) {
13019:         my @items = split('&',$env{'form.folderpath'});
13020:         $folders{'0'} = $items[-2];
13021:         if ($env{'form.folderpath'} =~ /\:1$/) {
13022:             $containers{'0'}='page';
13023:         } else {  
13024:             $containers{'0'}='sequence';
13025:         }
13026:     }
13027:     my @archdirs = &get_env_multiple('form.archive_directory');
13028:     if ($numitems) {
13029:         for (my $i=1; $i<=$numitems; $i++) {
13030:             my $path = $env{'form.archive_content_'.$i};
13031:             if ($path =~ m{^\Q$pathtocheck\E/([^/]+)$}) {
13032:                 my $item = $1;
13033:                 $toplevelitems{$item} = $i;
13034:                 if (grep(/^\Q$i\E$/,@archdirs)) {
13035:                     $is_dir{$item} = 1;
13036:                 }
13037:             }
13038:         }
13039:     }
13040:     my ($output,%children,%parent,%titles,%dirorder,$result);
13041:     if (keys(%toplevelitems) > 0) {
13042:         my @contents = sort(keys(%toplevelitems));
13043:         (my $count,undef) = &get_extracted($docudom,$docuname,$currdir,\%is_dir,\%children,
13044:                                            \%parent,\@contents,\%dirorder,\%titles);
13045:     }
13046:     my (%referrer,%orphaned,%todelete,%todeletedir,%newdest,%newseqid);
13047:     if ($numitems) {
13048:         for (my $i=1; $i<=$numitems; $i++) {
13049:             next if ($env{'form.archive_'.$i} eq 'dependency');
13050:             my $path = $env{'form.archive_content_'.$i};
13051:             if ($path =~ /^\Q$pathtocheck\E/) {
13052:                 if ($env{'form.archive_'.$i} eq 'discard') {
13053:                     if ($prefix ne '' && $path ne '') {
13054:                         if (-e $prefix.$path) {
13055:                             if ((@archdirs > 0) && 
13056:                                 (grep(/^\Q$i\E$/,@archdirs))) {
13057:                                 $todeletedir{$prefix.$path} = 1;
13058:                             } else {
13059:                                 $todelete{$prefix.$path} = 1;
13060:                             }
13061:                         }
13062:                     }
13063:                 } elsif ($env{'form.archive_'.$i} eq 'display') {
13064:                     my ($docstitle,$title,$url,$outer);
13065:                     ($title) = ($path =~ m{/([^/]+)$});
13066:                     $docstitle = $env{'form.archive_title_'.$i};
13067:                     if ($docstitle eq '') {
13068:                         $docstitle = $title;
13069:                     }
13070:                     $outer = 0;
13071:                     if (ref($dirorder{$i}) eq 'ARRAY') {
13072:                         if (@{$dirorder{$i}} > 0) {
13073:                             foreach my $item (reverse(@{$dirorder{$i}})) {
13074:                                 if ($env{'form.archive_'.$item} eq 'display') {
13075:                                     $outer = $item;
13076:                                     last;
13077:                                 }
13078:                             }
13079:                         }
13080:                     }
13081:                     my ($errtext,$fatal) = 
13082:                         &LONCAPA::map::mapread('/uploaded/'.$docudom.'/'.$docuname.
13083:                                                '/'.$folders{$outer}.'.'.
13084:                                                $containers{$outer});
13085:                     next if ($fatal);
13086:                     if ((@archdirs > 0) && (grep(/^\Q$i\E$/,@archdirs))) {
13087:                         if ($context eq 'coursedocs') {
13088:                             $mapinner{$i} = time;
13089:                             $folders{$i} = 'default_'.$mapinner{$i};
13090:                             $containers{$i} = 'sequence';
13091:                             my $url = '/uploaded/'.$docudom.'/'.$docuname.'/'.
13092:                                       $folders{$i}.'.'.$containers{$i};
13093:                             my $newidx = &LONCAPA::map::getresidx();
13094:                             $LONCAPA::map::resources[$newidx]=
13095:                                 $docstitle.':'.$url.':false:normal:res';
13096:                             push(@LONCAPA::map::order,$newidx);
13097:                             my ($outtext,$errtext) =
13098:                                 &LONCAPA::map::storemap('/uploaded/'.$docudom.'/'.
13099:                                                         $docuname.'/'.$folders{$outer}.
13100:                                                         '.'.$containers{$outer},1,1);
13101:                             $newseqid{$i} = $newidx;
13102:                             unless ($errtext) {
13103:                                 $result .=  '<li>'.&mt('Folder: [_1] added to course',$docstitle).'</li>'."\n";
13104:                             }
13105:                         }
13106:                     } else {
13107:                         if ($context eq 'coursedocs') {
13108:                             my $newidx=&LONCAPA::map::getresidx();
13109:                             my $url = '/uploaded/'.$docudom.'/'.$docuname.'/'.
13110:                                       $docstype.'/'.$mapinner{$outer}.'/'.$newidx.'/'.
13111:                                       $title;
13112:                             if (!-e "$prefix$dir/$docstype/$mapinner{$outer}") {
13113:                                 mkdir("$prefix$dir/$docstype/$mapinner{$outer}",0755);
13114:                             }
13115:                             if (!-e "$prefix$dir/$docstype/$mapinner{$outer}/$newidx") {
13116:                                 mkdir("$prefix$dir/$docstype/$mapinner{$outer}/$newidx");
13117:                             }
13118:                             if (-e "$prefix$dir/$docstype/$mapinner{$outer}/$newidx") {
13119:                                 system("mv $prefix$path $prefix$dir/$docstype/$mapinner{$outer}/$newidx/$title");
13120:                                 $newdest{$i} = "$prefix$dir/$docstype/$mapinner{$outer}/$newidx";
13121:                                 unless ($ishome) {
13122:                                     my $fetch = "$newdest{$i}/$title";
13123:                                     $fetch =~ s/^\Q$prefix$dir\E//;
13124:                                     $prompttofetch{$fetch} = 1;
13125:                                 }
13126:                             }
13127:                             $LONCAPA::map::resources[$newidx]=
13128:                                 $docstitle.':'.$url.':false:normal:res';
13129:                             push(@LONCAPA::map::order, $newidx);
13130:                             my ($outtext,$errtext)=
13131:                                 &LONCAPA::map::storemap('/uploaded/'.$docudom.'/'.
13132:                                                         $docuname.'/'.$folders{$outer}.
13133:                                                         '.'.$containers{$outer},1,1);
13134:                             unless ($errtext) {
13135:                                 if (-e "$prefix$dir/$docstype/$mapinner{$outer}/$newidx/$title") {
13136:                                     $result .= '<li>'.&mt('File: [_1] added to course',$docstitle).'</li>'."\n";
13137:                                 }
13138:                             }
13139:                         }
13140:                     }
13141:                 }
13142:             } else {
13143:                 $warning .= &mt('Item extracted from archive: [_1] has unexpected path.',$path).'<br />'; 
13144:             }
13145:         }
13146:         for (my $i=1; $i<=$numitems; $i++) {
13147:             next unless ($env{'form.archive_'.$i} eq 'dependency');
13148:             my $path = $env{'form.archive_content_'.$i};
13149:             if ($path =~ /^\Q$pathtocheck\E/) {
13150:                 my ($title) = ($path =~ m{/([^/]+)$});
13151:                 $referrer{$i} = $env{'form.archive_dependent_on_'.$i};
13152:                 if ($env{'form.archive_'.$referrer{$i}} eq 'display') {
13153:                     if (ref($dirorder{$i}) eq 'ARRAY') {
13154:                         my ($itemidx,$fullpath,$relpath);
13155:                         if (ref($dirorder{$referrer{$i}}) eq 'ARRAY') {
13156:                             my $container = $dirorder{$referrer{$i}}->[-1];
13157:                             for (my $j=0; $j<@{$dirorder{$i}}; $j++) {
13158:                                 if ($dirorder{$i}->[$j] eq $container) {
13159:                                     $itemidx = $j;
13160:                                 }
13161:                             }
13162:                         }
13163:                         if ($itemidx eq '') {
13164:                             $itemidx =  0;
13165:                         } 
13166:                         if (grep(/^\Q$referrer{$i}\E$/,@archdirs)) {
13167:                             if ($mapinner{$referrer{$i}}) {
13168:                                 $fullpath = "$prefix$dir/$docstype/$mapinner{$referrer{$i}}";
13169:                                 for (my $j=$itemidx; $j<@{$dirorder{$i}}; $j++) {
13170:                                     if (grep(/^\Q$dirorder{$i}->[$j]\E$/,@archdirs)) {
13171:                                         unless (defined($newseqid{$dirorder{$i}->[$j]})) {
13172:                                             $fullpath .= '/'.$titles{$dirorder{$i}->[$j]};
13173:                                             $relpath .= '/'.$titles{$dirorder{$i}->[$j]};
13174:                                             if (!-e $fullpath) {
13175:                                                 mkdir($fullpath,0755);
13176:                                             }
13177:                                         }
13178:                                     } else {
13179:                                         last;
13180:                                     }
13181:                                 }
13182:                             }
13183:                         } elsif ($newdest{$referrer{$i}}) {
13184:                             $fullpath = $newdest{$referrer{$i}};
13185:                             for (my $j=$itemidx; $j<@{$dirorder{$i}}; $j++) {
13186:                                 if ($env{'form.archive_'.$dirorder{$i}->[$j]} eq 'discard') {
13187:                                     $orphaned{$i} = $env{'form.archive_'.$dirorder{$i}->[$j]};
13188:                                     last;
13189:                                 } elsif (grep(/^\Q$dirorder{$i}->[$j]\E$/,@archdirs)) {
13190:                                     unless (defined($newseqid{$dirorder{$i}->[$j]})) {
13191:                                         $fullpath .= '/'.$titles{$dirorder{$i}->[$j]};
13192:                                         $relpath .= '/'.$titles{$dirorder{$i}->[$j]};
13193:                                         if (!-e $fullpath) {
13194:                                             mkdir($fullpath,0755);
13195:                                         }
13196:                                     }
13197:                                 } else {
13198:                                     last;
13199:                                 }
13200:                             }
13201:                         }
13202:                         if ($fullpath ne '') {
13203:                             if (-e "$prefix$path") {
13204:                                 system("mv $prefix$path $fullpath/$title");
13205:                             }
13206:                             if (-e "$fullpath/$title") {
13207:                                 my $showpath;
13208:                                 if ($relpath ne '') {
13209:                                     $showpath = "$relpath/$title";
13210:                                 } else {
13211:                                     $showpath = "/$title";
13212:                                 } 
13213:                                 $result .= '<li>'.&mt('[_1] included as a dependency',$showpath).'</li>'."\n";
13214:                             } 
13215:                             unless ($ishome) {
13216:                                 my $fetch = "$fullpath/$title";
13217:                                 $fetch =~ s/^\Q$prefix$dir\E//; 
13218:                                 $prompttofetch{$fetch} = 1;
13219:                             }
13220:                         }
13221:                     }
13222:                 } elsif ($env{'form.archive_'.$referrer{$i}} eq 'discard') {
13223:                     $warning .= &mt('[_1] is a dependency of [_2], which was discarded.',
13224:                                     $path,$env{'form.archive_content_'.$referrer{$i}}).'<br />';
13225:                 }
13226:             } else {
13227:                 $warning .= &mt('Item extracted from archive: [_1] has unexpected path.',$path).'<br />'; 
13228:             }
13229:         }
13230:         if (keys(%todelete)) {
13231:             foreach my $key (keys(%todelete)) {
13232:                 unlink($key);
13233:             }
13234:         }
13235:         if (keys(%todeletedir)) {
13236:             foreach my $key (keys(%todeletedir)) {
13237:                 rmdir($key);
13238:             }
13239:         }
13240:         foreach my $dir (sort(keys(%is_dir))) {
13241:             if (($pathtocheck ne '') && ($dir ne ''))  {
13242:                 &cleanup_empty_dirs($prefix."$pathtocheck/$dir");
13243:             }
13244:         }
13245:         if ($result ne '') {
13246:             $output .= '<ul>'."\n".
13247:                        $result."\n".
13248:                        '</ul>';
13249:         }
13250:         unless ($ishome) {
13251:             my $replicationfail;
13252:             foreach my $item (keys(%prompttofetch)) {
13253:                 my $fetchresult= &Apache::lonnet::reply('fetchuserfile:'.$item,$docuhome);
13254:                 unless ($fetchresult eq 'ok') {
13255:                     $replicationfail .= '<li>'.$item.'</li>'."\n";
13256:                 }
13257:             }
13258:             if ($replicationfail) {
13259:                 $output .= '<p class="LC_error">'.
13260:                            &mt('Course home server failed to retrieve:').'<ul>'.
13261:                            $replicationfail.
13262:                            '</ul></p>';
13263:             }
13264:         }
13265:     } else {
13266:         $warning = &mt('No items found in archive.');
13267:     }
13268:     if ($error) {
13269:         $output .= '<p class="LC_error">'.&mt('Not extracted.').'<br />'.
13270:                    $error.'</p>'."\n";
13271:     }
13272:     if ($warning) {
13273:         $output .= '<p class="LC_warning">'.$warning.'</p>'."\n";
13274:     }
13275:     return $output;
13276: }
13277: 
13278: sub cleanup_empty_dirs {
13279:     my ($path) = @_;
13280:     if (($path ne '') && (-d $path)) {
13281:         if (opendir(my $dirh,$path)) {
13282:             my @dircontents = grep(!/^\./,readdir($dirh));
13283:             my $numitems = 0;
13284:             foreach my $item (@dircontents) {
13285:                 if (-d "$path/$item") {
13286:                     &cleanup_empty_dirs("$path/$item");
13287:                     if (-e "$path/$item") {
13288:                         $numitems ++;
13289:                     }
13290:                 } else {
13291:                     $numitems ++;
13292:                 }
13293:             }
13294:             if ($numitems == 0) {
13295:                 rmdir($path);
13296:             }
13297:             closedir($dirh);
13298:         }
13299:     }
13300:     return;
13301: }
13302: 
13303: =pod
13304: 
13305: =item * &get_folder_hierarchy()
13306: 
13307: Provides hierarchy of names of folders/sub-folders containing the current
13308: item,
13309: 
13310: Inputs: 3
13311:      - $navmap - navmaps object
13312: 
13313:      - $map - url for map (either the trigger itself, or map containing
13314:                            the resource, which is the trigger).
13315: 
13316:      - $showitem - 1 => show title for map itself; 0 => do not show.
13317: 
13318: Outputs: 1 @pathitems - array of folder/subfolder names.
13319: 
13320: =cut
13321: 
13322: sub get_folder_hierarchy {
13323:     my ($navmap,$map,$showitem) = @_;
13324:     my @pathitems;
13325:     if (ref($navmap)) {
13326:         my $mapres = $navmap->getResourceByUrl($map);
13327:         if (ref($mapres)) {
13328:             my $pcslist = $mapres->map_hierarchy();
13329:             if ($pcslist ne '') {
13330:                 my @pcs = split(/,/,$pcslist);
13331:                 foreach my $pc (@pcs) {
13332:                     if ($pc == 1) {
13333:                         push(@pathitems,&mt('Main Content'));
13334:                     } else {
13335:                         my $res = $navmap->getByMapPc($pc);
13336:                         if (ref($res)) {
13337:                             my $title = $res->compTitle();
13338:                             $title =~ s/\W+/_/g;
13339:                             if ($title ne '') {
13340:                                 push(@pathitems,$title);
13341:                             }
13342:                         }
13343:                     }
13344:                 }
13345:             }
13346:             if ($showitem) {
13347:                 if ($mapres->{ID} eq '0.0') {
13348:                     push(@pathitems,&mt('Main Content'));
13349:                 } else {
13350:                     my $maptitle = $mapres->compTitle();
13351:                     $maptitle =~ s/\W+/_/g;
13352:                     if ($maptitle ne '') {
13353:                         push(@pathitems,$maptitle);
13354:                     }
13355:                 }
13356:             }
13357:         }
13358:     }
13359:     return @pathitems;
13360: }
13361: 
13362: =pod
13363: 
13364: =item * &get_turnedin_filepath()
13365: 
13366: Determines path in a user's portfolio file for storage of files uploaded
13367: to a specific essayresponse or dropbox item.
13368: 
13369: Inputs: 3 required + 1 optional.
13370: $symb is symb for resource, $uname and $udom are for current user (required).
13371: $caller is optional (can be "submission", if routine is called when storing
13372: an upoaded file when "Submit Answer" button was pressed).
13373: 
13374: Returns array containing $path and $multiresp. 
13375: $path is path in portfolio.  $multiresp is 1 if this resource contains more
13376: than one file upload item.  Callers of routine should append partid as a 
13377: subdirectory to $path in cases where $multiresp is 1.
13378: 
13379: Called by: homework/essayresponse.pm and homework/structuretags.pm
13380: 
13381: =cut
13382: 
13383: sub get_turnedin_filepath {
13384:     my ($symb,$uname,$udom,$caller) = @_;
13385:     my ($map,$resid,$resurl)=&Apache::lonnet::decode_symb($symb);
13386:     my $turnindir;
13387:     my %userhash = &Apache::lonnet::userenvironment($udom,$uname,'turnindir');
13388:     $turnindir = $userhash{'turnindir'};
13389:     my ($path,$multiresp);
13390:     if ($turnindir eq '') {
13391:         if ($caller eq 'submission') {
13392:             $turnindir = &mt('turned in');
13393:             $turnindir =~ s/\W+/_/g;
13394:             my %newhash = (
13395:                             'turnindir' => $turnindir,
13396:                           );
13397:             &Apache::lonnet::put('environment',\%newhash,$udom,$uname);
13398:         }
13399:     }
13400:     if ($turnindir ne '') {
13401:         $path = '/'.$turnindir.'/';
13402:         my ($multipart,$turnin,@pathitems);
13403:         my $navmap = Apache::lonnavmaps::navmap->new();
13404:         if (defined($navmap)) {
13405:             my $mapres = $navmap->getResourceByUrl($map);
13406:             if (ref($mapres)) {
13407:                 my $pcslist = $mapres->map_hierarchy();
13408:                 if ($pcslist ne '') {
13409:                     foreach my $pc (split(/,/,$pcslist)) {
13410:                         my $res = $navmap->getByMapPc($pc);
13411:                         if (ref($res)) {
13412:                             my $title = $res->compTitle();
13413:                             $title =~ s/\W+/_/g;
13414:                             if ($title ne '') {
13415:                                 if (($pc > 1) && (length($title) > 12)) {
13416:                                     $title = substr($title,0,12);
13417:                                 }
13418:                                 push(@pathitems,$title);
13419:                             }
13420:                         }
13421:                     }
13422:                 }
13423:                 my $maptitle = $mapres->compTitle();
13424:                 $maptitle =~ s/\W+/_/g;
13425:                 if ($maptitle ne '') {
13426:                     if (length($maptitle) > 12) {
13427:                         $maptitle = substr($maptitle,0,12);
13428:                     }
13429:                     push(@pathitems,$maptitle);
13430:                 }
13431:                 unless ($env{'request.state'} eq 'construct') {
13432:                     my $res = $navmap->getBySymb($symb);
13433:                     if (ref($res)) {
13434:                         my $partlist = $res->parts();
13435:                         my $totaluploads = 0;
13436:                         if (ref($partlist) eq 'ARRAY') {
13437:                             foreach my $part (@{$partlist}) {
13438:                                 my @types = $res->responseType($part);
13439:                                 my @ids = $res->responseIds($part);
13440:                                 for (my $i=0; $i < scalar(@ids); $i++) {
13441:                                     if ($types[$i] eq 'essay') {
13442:                                         my $partid = $part.'_'.$ids[$i];
13443:                                         if (&Apache::lonnet::EXT("resource.$partid.uploadedfiletypes") ne '') {
13444:                                             $totaluploads ++;
13445:                                         }
13446:                                     }
13447:                                 }
13448:                             }
13449:                             if ($totaluploads > 1) {
13450:                                 $multiresp = 1;
13451:                             }
13452:                         }
13453:                     }
13454:                 }
13455:             } else {
13456:                 return;
13457:             }
13458:         } else {
13459:             return;
13460:         }
13461:         my $restitle=&Apache::lonnet::gettitle($symb);
13462:         $restitle =~ s/\W+/_/g;
13463:         if ($restitle eq '') {
13464:             $restitle = ($resurl =~ m{/[^/]+$});
13465:             if ($restitle eq '') {
13466:                 $restitle = time;
13467:             }
13468:         }
13469:         if (length($restitle) > 12) {
13470:             $restitle = substr($restitle,0,12);
13471:         }
13472:         push(@pathitems,$restitle);
13473:         $path .= join('/',@pathitems);
13474:     }
13475:     return ($path,$multiresp);
13476: }
13477: 
13478: =pod
13479: 
13480: =back
13481: 
13482: =head1 CSV Upload/Handling functions
13483: 
13484: =over 4
13485: 
13486: =item * &upfile_store($r)
13487: 
13488: Store uploaded file, $r should be the HTTP Request object,
13489: needs $env{'form.upfile'}
13490: returns $datatoken to be put into hidden field
13491: 
13492: =cut
13493: 
13494: sub upfile_store {
13495:     my $r=shift;
13496:     $env{'form.upfile'}=~s/\r/\n/gs;
13497:     $env{'form.upfile'}=~s/\f/\n/gs;
13498:     $env{'form.upfile'}=~s/\n+/\n/gs;
13499:     $env{'form.upfile'}=~s/\n+$//gs;
13500: 
13501:     my $datatoken=$env{'user.name'}.'_'.$env{'user.domain'}.
13502: 	'_enroll_'.$env{'request.course.id'}.'_'.time.'_'.$$;
13503:     {
13504:         my $datafile = $r->dir_config('lonDaemons').
13505:                            '/tmp/'.$datatoken.'.tmp';
13506:         if ( open(my $fh,">$datafile") ) {
13507:             print $fh $env{'form.upfile'};
13508:             close($fh);
13509:         }
13510:     }
13511:     return $datatoken;
13512: }
13513: 
13514: =pod
13515: 
13516: =item * &load_tmp_file($r)
13517: 
13518: Load uploaded file from tmp, $r should be the HTTP Request object,
13519: needs $env{'form.datatoken'},
13520: sets $env{'form.upfile'} to the contents of the file
13521: 
13522: =cut
13523: 
13524: sub load_tmp_file {
13525:     my $r=shift;
13526:     my @studentdata=();
13527:     {
13528:         my $studentfile = $r->dir_config('lonDaemons').
13529:                               '/tmp/'.$env{'form.datatoken'}.'.tmp';
13530:         if ( open(my $fh,"<$studentfile") ) {
13531:             @studentdata=<$fh>;
13532:             close($fh);
13533:         }
13534:     }
13535:     $env{'form.upfile'}=join('',@studentdata);
13536: }
13537: 
13538: =pod
13539: 
13540: =item * &upfile_record_sep()
13541: 
13542: Separate uploaded file into records
13543: returns array of records,
13544: needs $env{'form.upfile'} and $env{'form.upfiletype'}
13545: 
13546: =cut
13547: 
13548: sub upfile_record_sep {
13549:     if ($env{'form.upfiletype'} eq 'xml') {
13550:     } else {
13551: 	my @records;
13552: 	foreach my $line (split(/\n/,$env{'form.upfile'})) {
13553: 	    if ($line=~/^\s*$/) { next; }
13554: 	    push(@records,$line);
13555: 	}
13556: 	return @records;
13557:     }
13558: }
13559: 
13560: =pod
13561: 
13562: =item * &record_sep($record)
13563: 
13564: Separate a record into fields $record should be an item from the upfile_record_sep(), needs $env{'form.upfiletype'}
13565: 
13566: =cut
13567: 
13568: sub takeleft {
13569:     my $index=shift;
13570:     return substr('0000'.$index,-4,4);
13571: }
13572: 
13573: sub record_sep {
13574:     my $record=shift;
13575:     my %components=();
13576:     if ($env{'form.upfiletype'} eq 'xml') {
13577:     } elsif ($env{'form.upfiletype'} eq 'space') {
13578:         my $i=0;
13579:         foreach my $field (split(/\s+/,$record)) {
13580:             $field=~s/^(\"|\')//;
13581:             $field=~s/(\"|\')$//;
13582:             $components{&takeleft($i)}=$field;
13583:             $i++;
13584:         }
13585:     } elsif ($env{'form.upfiletype'} eq 'tab') {
13586:         my $i=0;
13587:         foreach my $field (split(/\t/,$record)) {
13588:             $field=~s/^(\"|\')//;
13589:             $field=~s/(\"|\')$//;
13590:             $components{&takeleft($i)}=$field;
13591:             $i++;
13592:         }
13593:     } else {
13594:         my $separator=',';
13595:         if ($env{'form.upfiletype'} eq 'semisv') {
13596:             $separator=';';
13597:         }
13598:         my $i=0;
13599: # the character we are looking for to indicate the end of a quote or a record 
13600:         my $looking_for=$separator;
13601: # do not add the characters to the fields
13602:         my $ignore=0;
13603: # we just encountered a separator (or the beginning of the record)
13604:         my $just_found_separator=1;
13605: # store the field we are working on here
13606:         my $field='';
13607: # work our way through all characters in record
13608:         foreach my $character ($record=~/(.)/g) {
13609:             if ($character eq $looking_for) {
13610:                if ($character ne $separator) {
13611: # Found the end of a quote, again looking for separator
13612:                   $looking_for=$separator;
13613:                   $ignore=1;
13614:                } else {
13615: # Found a separator, store away what we got
13616:                   $components{&takeleft($i)}=$field;
13617: 	          $i++;
13618:                   $just_found_separator=1;
13619:                   $ignore=0;
13620:                   $field='';
13621:                }
13622:                next;
13623:             }
13624: # single or double quotation marks after a separator indicate beginning of a quote
13625: # we are now looking for the end of the quote and need to ignore separators
13626:             if ((($character eq '"') || ($character eq "'")) && ($just_found_separator))  {
13627:                $looking_for=$character;
13628:                next;
13629:             }
13630: # ignore would be true after we reached the end of a quote
13631:             if ($ignore) { next; }
13632:             if (($just_found_separator) && ($character=~/\s/)) { next; }
13633:             $field.=$character;
13634:             $just_found_separator=0; 
13635:         }
13636: # catch the very last entry, since we never encountered the separator
13637:         $components{&takeleft($i)}=$field;
13638:     }
13639:     return %components;
13640: }
13641: 
13642: ######################################################
13643: ######################################################
13644: 
13645: =pod
13646: 
13647: =item * &upfile_select_html()
13648: 
13649: Return HTML code to select a file from the users machine and specify 
13650: the file type.
13651: 
13652: =cut
13653: 
13654: ######################################################
13655: ######################################################
13656: sub upfile_select_html {
13657:     my %Types = (
13658:                  csv   => &mt('CSV (comma separated values, spreadsheet)'),
13659:                  semisv => &mt('Semicolon separated values'),
13660:                  space => &mt('Space separated'),
13661:                  tab   => &mt('Tabulator separated'),
13662: #                 xml   => &mt('HTML/XML'),
13663:                  );
13664:     my $Str = '<input type="file" name="upfile" size="50" />'.
13665:         '<br />'.&mt('Type').': <select name="upfiletype">';
13666:     foreach my $type (sort(keys(%Types))) {
13667:         $Str .= '<option value="'.$type.'" >'.$Types{$type}."</option>\n";
13668:     }
13669:     $Str .= "</select>\n";
13670:     return $Str;
13671: }
13672: 
13673: sub get_samples {
13674:     my ($records,$toget) = @_;
13675:     my @samples=({});
13676:     my $got=0;
13677:     foreach my $rec (@$records) {
13678: 	my %temp = &record_sep($rec);
13679: 	if (! grep(/\S/, values(%temp))) { next; }
13680: 	if (%temp) {
13681: 	    $samples[$got]=\%temp;
13682: 	    $got++;
13683: 	    if ($got == $toget) { last; }
13684: 	}
13685:     }
13686:     return \@samples;
13687: }
13688: 
13689: ######################################################
13690: ######################################################
13691: 
13692: =pod
13693: 
13694: =item * &csv_print_samples($r,$records)
13695: 
13696: Prints a table of sample values from each column uploaded $r is an
13697: Apache Request ref, $records is an arrayref from
13698: &Apache::loncommon::upfile_record_sep
13699: 
13700: =cut
13701: 
13702: ######################################################
13703: ######################################################
13704: sub csv_print_samples {
13705:     my ($r,$records) = @_;
13706:     my $samples = &get_samples($records,5);
13707: 
13708:     $r->print(&mt('Samples').'<br />'.&start_data_table().
13709:               &start_data_table_header_row());
13710:     foreach my $sample (sort({$a <=> $b} keys(%{ $samples->[0] }))) { 
13711:         $r->print('<th>'.&mt('Column [_1]',($sample+1)).'</th>'); }
13712:     $r->print(&end_data_table_header_row());
13713:     foreach my $hash (@$samples) {
13714: 	$r->print(&start_data_table_row());
13715: 	foreach my $sample (sort({$a <=> $b} keys(%{ $samples->[0] }))) {
13716: 	    $r->print('<td>');
13717: 	    if (defined($$hash{$sample})) { $r->print($$hash{$sample}); }
13718: 	    $r->print('</td>');
13719: 	}
13720: 	$r->print(&end_data_table_row());
13721:     }
13722:     $r->print(&end_data_table().'<br />'."\n");
13723: }
13724: 
13725: ######################################################
13726: ######################################################
13727: 
13728: =pod
13729: 
13730: =item * &csv_print_select_table($r,$records,$d)
13731: 
13732: Prints a table to create associations between values and table columns.
13733: 
13734: $r is an Apache Request ref,
13735: $records is an arrayref from &Apache::loncommon::upfile_record_sep,
13736: $d is an array of 2 element arrays (internal name, displayed name,defaultcol)
13737: 
13738: =cut
13739: 
13740: ######################################################
13741: ######################################################
13742: sub csv_print_select_table {
13743:     my ($r,$records,$d) = @_;
13744:     my $i=0;
13745:     my $samples = &get_samples($records,1);
13746:     $r->print(&mt('Associate columns with student attributes.')."\n".
13747: 	      &start_data_table().&start_data_table_header_row().
13748:               '<th>'.&mt('Attribute').'</th>'.
13749:               '<th>'.&mt('Column').'</th>'.
13750:               &end_data_table_header_row()."\n");
13751:     foreach my $array_ref (@$d) {
13752: 	my ($value,$display,$defaultcol)=@{ $array_ref };
13753: 	$r->print(&start_data_table_row().'<td>'.$display.'</td>');
13754: 
13755: 	$r->print('<td><select name="f'.$i.'"'.
13756: 		  ' onchange="javascript:flip(this.form,'.$i.');">');
13757: 	$r->print('<option value="none"></option>');
13758: 	foreach my $sample (sort({$a <=> $b} keys(%{ $samples->[0] }))) {
13759: 	    $r->print('<option value="'.$sample.'"'.
13760:                       ($sample eq $defaultcol ? ' selected="selected" ' : '').
13761:                       '>'.&mt('Column [_1]',($sample+1)).'</option>');
13762: 	}
13763: 	$r->print('</select></td>'.&end_data_table_row()."\n");
13764: 	$i++;
13765:     }
13766:     $r->print(&end_data_table());
13767:     $i--;
13768:     return $i;
13769: }
13770: 
13771: ######################################################
13772: ######################################################
13773: 
13774: =pod
13775: 
13776: =item * &csv_samples_select_table($r,$records,$d)
13777: 
13778: Prints a table of sample values from the upload and can make associate samples to internal names.
13779: 
13780: $r is an Apache Request ref,
13781: $records is an arrayref from &Apache::loncommon::upfile_record_sep,
13782: $d is an array of 2 element arrays (internal name, displayed name)
13783: 
13784: =cut
13785: 
13786: ######################################################
13787: ######################################################
13788: sub csv_samples_select_table {
13789:     my ($r,$records,$d) = @_;
13790:     my $i=0;
13791:     #
13792:     my $max_samples = 5;
13793:     my $samples = &get_samples($records,$max_samples);
13794:     $r->print(&start_data_table().
13795:               &start_data_table_header_row().'<th>'.
13796:               &mt('Field').'</th><th>'.&mt('Samples').'</th>'.
13797:               &end_data_table_header_row());
13798: 
13799:     foreach my $key (sort(keys(%{ $samples->[0] }))) {
13800: 	$r->print(&start_data_table_row().'<td><select name="f'.$i.'"'.
13801: 		  ' onchange="javascript:flip(this.form,'.$i.');">');
13802: 	foreach my $option (@$d) {
13803: 	    my ($value,$display,$defaultcol)=@{ $option };
13804: 	    $r->print('<option value="'.$value.'"'.
13805:                       ($i eq $defaultcol ? ' selected="selected" ':'').'>'.
13806:                       $display.'</option>');
13807: 	}
13808: 	$r->print('</select></td><td>');
13809: 	foreach my $line (0..($max_samples-1)) {
13810: 	    if (defined($samples->[$line]{$key})) { 
13811: 		$r->print($samples->[$line]{$key}."<br />\n"); 
13812: 	    }
13813: 	}
13814: 	$r->print('</td>'.&end_data_table_row());
13815: 	$i++;
13816:     }
13817:     $r->print(&end_data_table());
13818:     $i--;
13819:     return($i);
13820: }
13821: 
13822: ######################################################
13823: ######################################################
13824: 
13825: =pod
13826: 
13827: =item * &clean_excel_name($name)
13828: 
13829: Returns a replacement for $name which does not contain any illegal characters.
13830: 
13831: =cut
13832: 
13833: ######################################################
13834: ######################################################
13835: sub clean_excel_name {
13836:     my ($name) = @_;
13837:     $name =~ s/[:\*\?\/\\]//g;
13838:     if (length($name) > 31) {
13839:         $name = substr($name,0,31);
13840:     }
13841:     return $name;
13842: }
13843: 
13844: =pod
13845: 
13846: =item * &check_if_partid_hidden($id,$symb,$udom,$uname)
13847: 
13848: Returns either 1 or undef
13849: 
13850: 1 if the part is to be hidden, undef if it is to be shown
13851: 
13852: Arguments are:
13853: 
13854: $id the id of the part to be checked
13855: $symb, optional the symb of the resource to check
13856: $udom, optional the domain of the user to check for
13857: $uname, optional the username of the user to check for
13858: 
13859: =cut
13860: 
13861: sub check_if_partid_hidden {
13862:     my ($id,$symb,$udom,$uname) = @_;
13863:     my $hiddenparts=&Apache::lonnet::EXT('resource.0.hiddenparts',
13864: 					 $symb,$udom,$uname);
13865:     my $truth=1;
13866:     #if the string starts with !, then the list is the list to show not hide
13867:     if ($hiddenparts=~s/^\s*!//) { $truth=undef; }
13868:     my @hiddenlist=split(/,/,$hiddenparts);
13869:     foreach my $checkid (@hiddenlist) {
13870: 	if ($checkid =~ /^\s*\Q$id\E\s*$/) { return $truth; }
13871:     }
13872:     return !$truth;
13873: }
13874: 
13875: 
13876: ############################################################
13877: ############################################################
13878: 
13879: =pod
13880: 
13881: =back 
13882: 
13883: =head1 cgi-bin script and graphing routines
13884: 
13885: =over 4
13886: 
13887: =item * &get_cgi_id()
13888: 
13889: Inputs: none
13890: 
13891: Returns an id which can be used to pass environment variables
13892: to various cgi-bin scripts.  These environment variables will
13893: be removed from the users environment after a given time by
13894: the routine &Apache::lonnet::transfer_profile_to_env.
13895: 
13896: =cut
13897: 
13898: ############################################################
13899: ############################################################
13900: my $uniq=0;
13901: sub get_cgi_id {
13902:     $uniq=($uniq+1)%100000;
13903:     return (time.'_'.$$.'_'.$uniq);
13904: }
13905: 
13906: ############################################################
13907: ############################################################
13908: 
13909: =pod
13910: 
13911: =item * &DrawBarGraph()
13912: 
13913: Facilitates the plotting of data in a (stacked) bar graph.
13914: Puts plot definition data into the users environment in order for 
13915: graph.png to plot it.  Returns an <img> tag for the plot.
13916: The bars on the plot are labeled '1','2',...,'n'.
13917: 
13918: Inputs:
13919: 
13920: =over 4
13921: 
13922: =item $Title: string, the title of the plot
13923: 
13924: =item $xlabel: string, text describing the X-axis of the plot
13925: 
13926: =item $ylabel: string, text describing the Y-axis of the plot
13927: 
13928: =item $Max: scalar, the maximum Y value to use in the plot
13929: If $Max is < any data point, the graph will not be rendered.
13930: 
13931: =item $colors: array ref holding the colors to be used for the data sets when
13932: they are plotted.  If undefined, default values will be used.
13933: 
13934: =item $labels: array ref holding the labels to use on the x-axis for the bars.
13935: 
13936: =item @Values: An array of array references.  Each array reference holds data
13937: to be plotted in a stacked bar chart.
13938: 
13939: =item If the final element of @Values is a hash reference the key/value
13940: pairs will be added to the graph definition.
13941: 
13942: =back
13943: 
13944: Returns:
13945: 
13946: An <img> tag which references graph.png and the appropriate identifying
13947: information for the plot.
13948: 
13949: =cut
13950: 
13951: ############################################################
13952: ############################################################
13953: sub DrawBarGraph {
13954:     my ($Title,$xlabel,$ylabel,$Max,$colors,$labels,@Values)=@_;
13955:     #
13956:     if (! defined($colors)) {
13957:         $colors = ['#33ff00', 
13958:                   '#0033cc', '#990000', '#aaaa66', '#663399', '#ff9933',
13959:                   '#66ccff', '#ff9999', '#cccc33', '#660000', '#33cc66',
13960:                   ]; 
13961:     }
13962:     my $extra_settings = {};
13963:     if (ref($Values[-1]) eq 'HASH') {
13964:         $extra_settings = pop(@Values);
13965:     }
13966:     #
13967:     my $identifier = &get_cgi_id();
13968:     my $id = 'cgi.'.$identifier;        
13969:     if (! @Values || ref($Values[0]) ne 'ARRAY') {
13970:         return '';
13971:     }
13972:     #
13973:     my @Labels;
13974:     if (defined($labels)) {
13975:         @Labels = @$labels;
13976:     } else {
13977:         for (my $i=0;$i<@{$Values[0]};$i++) {
13978:             push (@Labels,$i+1);
13979:         }
13980:     }
13981:     #
13982:     my $NumBars = scalar(@{$Values[0]});
13983:     if ($NumBars < scalar(@Labels)) { $NumBars = scalar(@Labels); }
13984:     my %ValuesHash;
13985:     my $NumSets=1;
13986:     foreach my $array (@Values) {
13987:         next if (! ref($array));
13988:         $ValuesHash{$id.'.data.'.$NumSets++} = 
13989:             join(',',@$array);
13990:     }
13991:     #
13992:     my ($height,$width,$xskip,$bar_width) = (200,120,1,15);
13993:     if ($NumBars < 3) {
13994:         $width = 120+$NumBars*32;
13995:         $xskip = 1;
13996:         $bar_width = 30;
13997:     } elsif ($NumBars < 5) {
13998:         $width = 120+$NumBars*20;
13999:         $xskip = 1;
14000:         $bar_width = 20;
14001:     } elsif ($NumBars < 10) {
14002:         $width = 120+$NumBars*15;
14003:         $xskip = 1;
14004:         $bar_width = 15;
14005:     } elsif ($NumBars <= 25) {
14006:         $width = 120+$NumBars*11;
14007:         $xskip = 5;
14008:         $bar_width = 8;
14009:     } elsif ($NumBars <= 50) {
14010:         $width = 120+$NumBars*8;
14011:         $xskip = 5;
14012:         $bar_width = 4;
14013:     } else {
14014:         $width = 120+$NumBars*8;
14015:         $xskip = 5;
14016:         $bar_width = 4;
14017:     }
14018:     #
14019:     $Max = 1 if ($Max < 1);
14020:     if ( int($Max) < $Max ) {
14021:         $Max++;
14022:         $Max = int($Max);
14023:     }
14024:     $Title  = '' if (! defined($Title));
14025:     $xlabel = '' if (! defined($xlabel));
14026:     $ylabel = '' if (! defined($ylabel));
14027:     $ValuesHash{$id.'.title'}    = &escape($Title);
14028:     $ValuesHash{$id.'.xlabel'}   = &escape($xlabel);
14029:     $ValuesHash{$id.'.ylabel'}   = &escape($ylabel);
14030:     $ValuesHash{$id.'.y_max_value'} = $Max;
14031:     $ValuesHash{$id.'.NumBars'}  = $NumBars;
14032:     $ValuesHash{$id.'.NumSets'}  = $NumSets;
14033:     $ValuesHash{$id.'.PlotType'} = 'bar';
14034:     $ValuesHash{$id.'.Colors'}   = join(',',@{$colors});
14035:     $ValuesHash{$id.'.height'}   = $height;
14036:     $ValuesHash{$id.'.width'}    = $width;
14037:     $ValuesHash{$id.'.xskip'}    = $xskip;
14038:     $ValuesHash{$id.'.bar_width'} = $bar_width;
14039:     $ValuesHash{$id.'.labels'} = join(',',@Labels);
14040:     #
14041:     # Deal with other parameters
14042:     while (my ($key,$value) = each(%$extra_settings)) {
14043:         $ValuesHash{$id.'.'.$key} = $value;
14044:     }
14045:     #
14046:     &Apache::lonnet::appenv(\%ValuesHash);
14047:     return '<img src="/cgi-bin/graph.png?'.$identifier.'" border="1" />';
14048: }
14049: 
14050: ############################################################
14051: ############################################################
14052: 
14053: =pod
14054: 
14055: =item * &DrawXYGraph()
14056: 
14057: Facilitates the plotting of data in an XY graph.
14058: Puts plot definition data into the users environment in order for 
14059: graph.png to plot it.  Returns an <img> tag for the plot.
14060: 
14061: Inputs:
14062: 
14063: =over 4
14064: 
14065: =item $Title: string, the title of the plot
14066: 
14067: =item $xlabel: string, text describing the X-axis of the plot
14068: 
14069: =item $ylabel: string, text describing the Y-axis of the plot
14070: 
14071: =item $Max: scalar, the maximum Y value to use in the plot
14072: If $Max is < any data point, the graph will not be rendered.
14073: 
14074: =item $colors: Array ref containing the hex color codes for the data to be 
14075: plotted in.  If undefined, default values will be used.
14076: 
14077: =item $Xlabels: Array ref containing the labels to be used for the X-axis.
14078: 
14079: =item $Ydata: Array ref containing Array refs.  
14080: Each of the contained arrays will be plotted as a separate curve.
14081: 
14082: =item %Values: hash indicating or overriding any default values which are 
14083: passed to graph.png.  
14084: Possible values are: width, xskip, x_ticks, x_tick_offset, among others.
14085: 
14086: =back
14087: 
14088: Returns:
14089: 
14090: An <img> tag which references graph.png and the appropriate identifying
14091: information for the plot.
14092: 
14093: =cut
14094: 
14095: ############################################################
14096: ############################################################
14097: sub DrawXYGraph {
14098:     my ($Title,$xlabel,$ylabel,$Max,$colors,$Xlabels,$Ydata,%Values)=@_;
14099:     #
14100:     # Create the identifier for the graph
14101:     my $identifier = &get_cgi_id();
14102:     my $id = 'cgi.'.$identifier;
14103:     #
14104:     $Title  = '' if (! defined($Title));
14105:     $xlabel = '' if (! defined($xlabel));
14106:     $ylabel = '' if (! defined($ylabel));
14107:     my %ValuesHash = 
14108:         (
14109:          $id.'.title'  => &escape($Title),
14110:          $id.'.xlabel' => &escape($xlabel),
14111:          $id.'.ylabel' => &escape($ylabel),
14112:          $id.'.y_max_value'=> $Max,
14113:          $id.'.labels'     => join(',',@$Xlabels),
14114:          $id.'.PlotType'   => 'XY',
14115:          );
14116:     #
14117:     if (defined($colors) && ref($colors) eq 'ARRAY') {
14118:         $ValuesHash{$id.'.Colors'}   = join(',',@{$colors});
14119:     }
14120:     #
14121:     if (! ref($Ydata) || ref($Ydata) ne 'ARRAY') {
14122:         return '';
14123:     }
14124:     my $NumSets=1;
14125:     foreach my $array (@{$Ydata}){
14126:         next if (! ref($array));
14127:         $ValuesHash{$id.'.data.'.$NumSets++} = join(',',@$array);
14128:     }
14129:     $ValuesHash{$id.'.NumSets'} = $NumSets-1;
14130:     #
14131:     # Deal with other parameters
14132:     while (my ($key,$value) = each(%Values)) {
14133:         $ValuesHash{$id.'.'.$key} = $value;
14134:     }
14135:     #
14136:     &Apache::lonnet::appenv(\%ValuesHash);
14137:     return '<img src="/cgi-bin/graph.png?'.$identifier.'" border="1" />';
14138: }
14139: 
14140: ############################################################
14141: ############################################################
14142: 
14143: =pod
14144: 
14145: =item * &DrawXYYGraph()
14146: 
14147: Facilitates the plotting of data in an XY graph with two Y axes.
14148: Puts plot definition data into the users environment in order for 
14149: graph.png to plot it.  Returns an <img> tag for the plot.
14150: 
14151: Inputs:
14152: 
14153: =over 4
14154: 
14155: =item $Title: string, the title of the plot
14156: 
14157: =item $xlabel: string, text describing the X-axis of the plot
14158: 
14159: =item $ylabel: string, text describing the Y-axis of the plot
14160: 
14161: =item $colors: Array ref containing the hex color codes for the data to be 
14162: plotted in.  If undefined, default values will be used.
14163: 
14164: =item $Xlabels: Array ref containing the labels to be used for the X-axis.
14165: 
14166: =item $Ydata1: The first data set
14167: 
14168: =item $Min1: The minimum value of the left Y-axis
14169: 
14170: =item $Max1: The maximum value of the left Y-axis
14171: 
14172: =item $Ydata2: The second data set
14173: 
14174: =item $Min2: The minimum value of the right Y-axis
14175: 
14176: =item $Max2: The maximum value of the left Y-axis
14177: 
14178: =item %Values: hash indicating or overriding any default values which are 
14179: passed to graph.png.  
14180: Possible values are: width, xskip, x_ticks, x_tick_offset, among others.
14181: 
14182: =back
14183: 
14184: Returns:
14185: 
14186: An <img> tag which references graph.png and the appropriate identifying
14187: information for the plot.
14188: 
14189: =cut
14190: 
14191: ############################################################
14192: ############################################################
14193: sub DrawXYYGraph {
14194:     my ($Title,$xlabel,$ylabel,$colors,$Xlabels,$Ydata1,$Min1,$Max1,
14195:                                         $Ydata2,$Min2,$Max2,%Values)=@_;
14196:     #
14197:     # Create the identifier for the graph
14198:     my $identifier = &get_cgi_id();
14199:     my $id = 'cgi.'.$identifier;
14200:     #
14201:     $Title  = '' if (! defined($Title));
14202:     $xlabel = '' if (! defined($xlabel));
14203:     $ylabel = '' if (! defined($ylabel));
14204:     my %ValuesHash = 
14205:         (
14206:          $id.'.title'  => &escape($Title),
14207:          $id.'.xlabel' => &escape($xlabel),
14208:          $id.'.ylabel' => &escape($ylabel),
14209:          $id.'.labels' => join(',',@$Xlabels),
14210:          $id.'.PlotType' => 'XY',
14211:          $id.'.NumSets' => 2,
14212:          $id.'.two_axes' => 1,
14213:          $id.'.y1_max_value' => $Max1,
14214:          $id.'.y1_min_value' => $Min1,
14215:          $id.'.y2_max_value' => $Max2,
14216:          $id.'.y2_min_value' => $Min2,
14217:          );
14218:     #
14219:     if (defined($colors) && ref($colors) eq 'ARRAY') {
14220:         $ValuesHash{$id.'.Colors'}   = join(',',@{$colors});
14221:     }
14222:     #
14223:     if (! ref($Ydata1) || ref($Ydata1) ne 'ARRAY' ||
14224:         ! ref($Ydata2) || ref($Ydata2) ne 'ARRAY'){
14225:         return '';
14226:     }
14227:     my $NumSets=1;
14228:     foreach my $array ($Ydata1,$Ydata2){
14229:         next if (! ref($array));
14230:         $ValuesHash{$id.'.data.'.$NumSets++} = join(',',@$array);
14231:     }
14232:     #
14233:     # Deal with other parameters
14234:     while (my ($key,$value) = each(%Values)) {
14235:         $ValuesHash{$id.'.'.$key} = $value;
14236:     }
14237:     #
14238:     &Apache::lonnet::appenv(\%ValuesHash);
14239:     return '<img src="/cgi-bin/graph.png?'.$identifier.'" border="1" />';
14240: }
14241: 
14242: ############################################################
14243: ############################################################
14244: 
14245: =pod
14246: 
14247: =back 
14248: 
14249: =head1 Statistics helper routines?  
14250: 
14251: Bad place for them but what the hell.
14252: 
14253: =over 4
14254: 
14255: =item * &chartlink()
14256: 
14257: Returns a link to the chart for a specific student.  
14258: 
14259: Inputs:
14260: 
14261: =over 4
14262: 
14263: =item $linktext: The text of the link
14264: 
14265: =item $sname: The students username
14266: 
14267: =item $sdomain: The students domain
14268: 
14269: =back
14270: 
14271: =back
14272: 
14273: =cut
14274: 
14275: ############################################################
14276: ############################################################
14277: sub chartlink {
14278:     my ($linktext, $sname, $sdomain) = @_;
14279:     my $link = '<a href="/adm/statistics?reportSelected=student_assessment'.
14280:         '&amp;SelectedStudent='.&escape($sname.':'.$sdomain).
14281:         '&amp;chartoutputmode='.HTML::Entities::encode('html, with all links').
14282:        '">'.$linktext.'</a>';
14283: }
14284: 
14285: #######################################################
14286: #######################################################
14287: 
14288: =pod
14289: 
14290: =head1 Course Environment Routines
14291: 
14292: =over 4
14293: 
14294: =item * &restore_course_settings()
14295: 
14296: =item * &store_course_settings()
14297: 
14298: Restores/Store indicated form parameters from the course environment.
14299: Will not overwrite existing values of the form parameters.
14300: 
14301: Inputs: 
14302: a scalar describing the data (e.g. 'chart', 'problem_analysis')
14303: 
14304: a hash ref describing the data to be stored.  For example:
14305:    
14306: %Save_Parameters = ('Status' => 'scalar',
14307:     'chartoutputmode' => 'scalar',
14308:     'chartoutputdata' => 'scalar',
14309:     'Section' => 'array',
14310:     'Group' => 'array',
14311:     'StudentData' => 'array',
14312:     'Maps' => 'array');
14313: 
14314: Returns: both routines return nothing
14315: 
14316: =back
14317: 
14318: =cut
14319: 
14320: #######################################################
14321: #######################################################
14322: sub store_course_settings {
14323:     return &store_settings($env{'request.course.id'},@_);
14324: }
14325: 
14326: sub store_settings {
14327:     # save to the environment
14328:     # appenv the same items, just to be safe
14329:     my $udom  = $env{'user.domain'};
14330:     my $uname = $env{'user.name'};
14331:     my ($context,$prefix,$Settings) = @_;
14332:     my %SaveHash;
14333:     my %AppHash;
14334:     while (my ($setting,$type) = each(%$Settings)) {
14335:         my $basename = join('.','internal',$context,$prefix,$setting);
14336:         my $envname = 'environment.'.$basename;
14337:         if (exists($env{'form.'.$setting})) {
14338:             # Save this value away
14339:             if ($type eq 'scalar' &&
14340:                 (! exists($env{$envname}) || 
14341:                  $env{$envname} ne $env{'form.'.$setting})) {
14342:                 $SaveHash{$basename} = $env{'form.'.$setting};
14343:                 $AppHash{$envname}   = $env{'form.'.$setting};
14344:             } elsif ($type eq 'array') {
14345:                 my $stored_form;
14346:                 if (ref($env{'form.'.$setting})) {
14347:                     $stored_form = join(',',
14348:                                         map {
14349:                                             &escape($_);
14350:                                         } sort(@{$env{'form.'.$setting}}));
14351:                 } else {
14352:                     $stored_form = 
14353:                         &escape($env{'form.'.$setting});
14354:                 }
14355:                 # Determine if the array contents are the same.
14356:                 if ($stored_form ne $env{$envname}) {
14357:                     $SaveHash{$basename} = $stored_form;
14358:                     $AppHash{$envname}   = $stored_form;
14359:                 }
14360:             }
14361:         }
14362:     }
14363:     my $put_result = &Apache::lonnet::put('environment',\%SaveHash,
14364:                                           $udom,$uname);
14365:     if ($put_result !~ /^(ok|delayed)/) {
14366:         &Apache::lonnet::logthis('unable to save form parameters, '.
14367:                                  'got error:'.$put_result);
14368:     }
14369:     # Make sure these settings stick around in this session, too
14370:     &Apache::lonnet::appenv(\%AppHash);
14371:     return;
14372: }
14373: 
14374: sub restore_course_settings {
14375:     return &restore_settings($env{'request.course.id'},@_);
14376: }
14377: 
14378: sub restore_settings {
14379:     my ($context,$prefix,$Settings) = @_;
14380:     while (my ($setting,$type) = each(%$Settings)) {
14381:         next if (exists($env{'form.'.$setting}));
14382:         my $envname = 'environment.internal.'.$context.'.'.$prefix.
14383:             '.'.$setting;
14384:         if (exists($env{$envname})) {
14385:             if ($type eq 'scalar') {
14386:                 $env{'form.'.$setting} = $env{$envname};
14387:             } elsif ($type eq 'array') {
14388:                 $env{'form.'.$setting} = [ 
14389:                                            map { 
14390:                                                &unescape($_); 
14391:                                            } split(',',$env{$envname})
14392:                                            ];
14393:             }
14394:         }
14395:     }
14396: }
14397: 
14398: #######################################################
14399: #######################################################
14400: 
14401: =pod
14402: 
14403: =head1 Domain E-mail Routines  
14404: 
14405: =over 4
14406: 
14407: =item * &build_recipient_list()
14408: 
14409: Build recipient lists for following types of e-mail:
14410: (a) Error Reports, (b) Package Updates, (c) lonstatus warnings/errors
14411: (d) Help requests, (e) Course requests needing approval, (f) loncapa
14412: module change checking, student/employee ID conflict checks, as
14413: generated by lonerrorhandler.pm, CHECKRPMS, loncron,
14414: lonsupportreq.pm, loncoursequeueadmin.pm, searchcat.pl respectively.
14415: 
14416: Inputs:
14417: defmail (scalar - email address of default recipient), 
14418: mailing type (scalar: errormail, packagesmail, helpdeskmail,
14419: requestsmail, updatesmail, or idconflictsmail).
14420: 
14421: defdom (domain for which to retrieve configuration settings),
14422: 
14423: origmail (scalar - email address of recipient from loncapa.conf, 
14424: i.e., predates configuration by DC via domainprefs.pm 
14425: 
14426: Returns: comma separated list of addresses to which to send e-mail.
14427: 
14428: =back
14429: 
14430: =cut
14431: 
14432: ############################################################
14433: ############################################################
14434: sub build_recipient_list {
14435:     my ($defmail,$mailing,$defdom,$origmail) = @_;
14436:     my @recipients;
14437:     my $otheremails;
14438:     my %domconfig =
14439:          &Apache::lonnet::get_dom('configuration',['contacts'],$defdom);
14440:     if (ref($domconfig{'contacts'}) eq 'HASH') {
14441:         if (exists($domconfig{'contacts'}{$mailing})) {
14442:             if (ref($domconfig{'contacts'}{$mailing}) eq 'HASH') {
14443:                 my @contacts = ('adminemail','supportemail');
14444:                 foreach my $item (@contacts) {
14445:                     if ($domconfig{'contacts'}{$mailing}{$item}) {
14446:                         my $addr = $domconfig{'contacts'}{$item}; 
14447:                         if (!grep(/^\Q$addr\E$/,@recipients)) {
14448:                             push(@recipients,$addr);
14449:                         }
14450:                     }
14451:                     $otheremails = $domconfig{'contacts'}{$mailing}{'others'};
14452:                 }
14453:             }
14454:         } elsif ($origmail ne '') {
14455:             push(@recipients,$origmail);
14456:         }
14457:     } elsif ($origmail ne '') {
14458:         push(@recipients,$origmail);
14459:     }
14460:     if (defined($defmail)) {
14461:         if ($defmail ne '') {
14462:             push(@recipients,$defmail);
14463:         }
14464:     }
14465:     if ($otheremails) {
14466:         my @others;
14467:         if ($otheremails =~ /,/) {
14468:             @others = split(/,/,$otheremails);
14469:         } else {
14470:             push(@others,$otheremails);
14471:         }
14472:         foreach my $addr (@others) {
14473:             if (!grep(/^\Q$addr\E$/,@recipients)) {
14474:                 push(@recipients,$addr);
14475:             }
14476:         }
14477:     }
14478:     my $recipientlist = join(',',@recipients); 
14479:     return $recipientlist;
14480: }
14481: 
14482: ############################################################
14483: ############################################################
14484: 
14485: =pod
14486: 
14487: =over 4
14488: 
14489: =item * &mime_email()
14490: 
14491: Sends an email with a possible attachment
14492: 
14493: Inputs:
14494: 
14495: =over 4
14496: 
14497: from -              Sender's email address
14498: 
14499: to -                Email address of recipient
14500: 
14501: subject -           Subject of email
14502: 
14503: body -              Body of email
14504: 
14505: cc_string -         Carbon copy email address
14506: 
14507: bcc -               Blind carbon copy email address
14508: 
14509: type -              File type of attachment
14510: 
14511: attachment_path -   Path of file to be attached
14512: 
14513: file_name -         Name of file to be attached
14514: 
14515: attachment_text -   The body of an attachment of type "TEXT"
14516: 
14517: =back
14518: 
14519: =back
14520: 
14521: =cut
14522: 
14523: ############################################################
14524: ############################################################
14525: 
14526: sub mime_email {
14527:     my ($from, $to, $subject, $body, $cc_string, $bcc, $attachment_path, 
14528:         $file_name, $attachment_text) = @_;
14529:     my $msg = MIME::Lite->new(
14530:              From    => $from,
14531:              To      => $to,
14532:              Subject => $subject,
14533:              Type    =>'TEXT',
14534:              Data    => $body,
14535:              );
14536:     if ($cc_string ne '') {
14537:         $msg->add("Cc" => $cc_string);
14538:     }
14539:     if ($bcc ne '') {
14540:         $msg->add("Bcc" => $bcc);
14541:     }
14542:     $msg->attr("content-type"         => "text/plain");
14543:     $msg->attr("content-type.charset" => "UTF-8");
14544:     # Attach file if given
14545:     if ($attachment_path) {
14546:         unless ($file_name) {
14547:             if ($attachment_path =~ m-/([^/]+)$-) { $file_name = $1; }
14548:         }
14549:         my ($type, $encoding) = MIME::Types::by_suffix($attachment_path);
14550:         $msg->attach(Type     => $type,
14551:                      Path     => $attachment_path,
14552:                      Filename => $file_name
14553:                      );
14554:     # Otherwise attach text if given
14555:     } elsif ($attachment_text) {
14556:         $msg->attach(Type => 'TEXT',
14557:                      Data => $attachment_text);
14558:     }
14559:     # Send it
14560:     $msg->send('sendmail');
14561: }
14562: 
14563: ############################################################
14564: ############################################################
14565: 
14566: =pod
14567: 
14568: =head1 Course Catalog Routines
14569: 
14570: =over 4
14571: 
14572: =item * &gather_categories()
14573: 
14574: Converts category definitions - keys of categories hash stored in  
14575: coursecategories in configuration.db on the primary library server in a 
14576: domain - to an array.  Also generates javascript and idx hash used to 
14577: generate Domain Coordinator interface for editing Course Categories.
14578: 
14579: Inputs:
14580: 
14581: categories (reference to hash of category definitions).
14582: 
14583: cats (reference to array of arrays/hashes which encapsulates hierarchy of
14584:       categories and subcategories).
14585: 
14586: idx (reference to hash of counters used in Domain Coordinator interface for 
14587:       editing Course Categories).
14588: 
14589: jsarray (reference to array of categories used to create Javascript arrays for
14590:          Domain Coordinator interface for editing Course Categories).
14591: 
14592: Returns: nothing
14593: 
14594: Side effects: populates cats, idx and jsarray. 
14595: 
14596: =cut
14597: 
14598: sub gather_categories {
14599:     my ($categories,$cats,$idx,$jsarray) = @_;
14600:     my %counters;
14601:     my $num = 0;
14602:     foreach my $item (keys(%{$categories})) {
14603:         my ($cat,$container,$depth) = map { &unescape($_); } split(/:/,$item);
14604:         if ($container eq '' && $depth == 0) {
14605:             $cats->[$depth][$categories->{$item}] = $cat;
14606:         } else {
14607:             $cats->[$depth]{$container}[$categories->{$item}] = $cat;
14608:         }
14609:         my ($escitem,$tail) = split(/:/,$item,2);
14610:         if ($counters{$tail} eq '') {
14611:             $counters{$tail} = $num;
14612:             $num ++;
14613:         }
14614:         if (ref($idx) eq 'HASH') {
14615:             $idx->{$item} = $counters{$tail};
14616:         }
14617:         if (ref($jsarray) eq 'ARRAY') {
14618:             push(@{$jsarray->[$counters{$tail}]},$item);
14619:         }
14620:     }
14621:     return;
14622: }
14623: 
14624: =pod
14625: 
14626: =item * &extract_categories()
14627: 
14628: Used to generate breadcrumb trails for course categories.
14629: 
14630: Inputs:
14631: 
14632: categories (reference to hash of category definitions).
14633: 
14634: cats (reference to array of arrays/hashes which encapsulates hierarchy of
14635:       categories and subcategories).
14636: 
14637: trails (reference to array of breacrumb trails for each category).
14638: 
14639: allitems (reference to hash - key is category key 
14640:          (format: escaped(name):escaped(parent category):depth in hierarchy).
14641: 
14642: idx (reference to hash of counters used in Domain Coordinator interface for
14643:       editing Course Categories).
14644: 
14645: jsarray (reference to array of categories used to create Javascript arrays for
14646:          Domain Coordinator interface for editing Course Categories).
14647: 
14648: subcats (reference to hash of arrays containing all subcategories within each 
14649:          category, -recursive)
14650: 
14651: Returns: nothing
14652: 
14653: Side effects: populates trails and allitems hash references.
14654: 
14655: =cut
14656: 
14657: sub extract_categories {
14658:     my ($categories,$cats,$trails,$allitems,$idx,$jsarray,$subcats) = @_;
14659:     if (ref($categories) eq 'HASH') {
14660:         &gather_categories($categories,$cats,$idx,$jsarray);
14661:         if (ref($cats->[0]) eq 'ARRAY') {
14662:             for (my $i=0; $i<@{$cats->[0]}; $i++) {
14663:                 my $name = $cats->[0][$i];
14664:                 my $item = &escape($name).'::0';
14665:                 my $trailstr;
14666:                 if ($name eq 'instcode') {
14667:                     $trailstr = &mt('Official courses (with institutional codes)');
14668:                 } elsif ($name eq 'communities') {
14669:                     $trailstr = &mt('Communities');
14670:                 } elsif ($name eq 'placement') {
14671:                     $trailstr = &mt('Placement Tests');
14672:                 } else {
14673:                     $trailstr = $name;
14674:                 }
14675:                 if ($allitems->{$item} eq '') {
14676:                     push(@{$trails},$trailstr);
14677:                     $allitems->{$item} = scalar(@{$trails})-1;
14678:                 }
14679:                 my @parents = ($name);
14680:                 if (ref($cats->[1]{$name}) eq 'ARRAY') {
14681:                     for (my $j=0; $j<@{$cats->[1]{$name}}; $j++) {
14682:                         my $category = $cats->[1]{$name}[$j];
14683:                         if (ref($subcats) eq 'HASH') {
14684:                             push(@{$subcats->{$item}},&escape($category).':'.&escape($name).':1');
14685:                         }
14686:                         &recurse_categories($cats,2,$category,$trails,$allitems,\@parents,$subcats);
14687:                     }
14688:                 } else {
14689:                     if (ref($subcats) eq 'HASH') {
14690:                         $subcats->{$item} = [];
14691:                     }
14692:                 }
14693:             }
14694:         }
14695:     }
14696:     return;
14697: }
14698: 
14699: =pod
14700: 
14701: =item * &recurse_categories()
14702: 
14703: Recursively used to generate breadcrumb trails for course categories.
14704: 
14705: Inputs:
14706: 
14707: cats (reference to array of arrays/hashes which encapsulates hierarchy of
14708:       categories and subcategories).
14709: 
14710: depth (current depth in hierarchy of categories and sub-categories - 0 indexed).
14711: 
14712: category (current course category, for which breadcrumb trail is being generated).
14713: 
14714: trails (reference to array of breadcrumb trails for each category).
14715: 
14716: allitems (reference to hash - key is category key
14717:          (format: escaped(name):escaped(parent category):depth in hierarchy).
14718: 
14719: parents (array containing containers directories for current category, 
14720:          back to top level). 
14721: 
14722: Returns: nothing
14723: 
14724: Side effects: populates trails and allitems hash references
14725: 
14726: =cut
14727: 
14728: sub recurse_categories {
14729:     my ($cats,$depth,$category,$trails,$allitems,$parents,$subcats) = @_;
14730:     my $shallower = $depth - 1;
14731:     if (ref($cats->[$depth]{$category}) eq 'ARRAY') {
14732:         for (my $k=0; $k<@{$cats->[$depth]{$category}}; $k++) {
14733:             my $name = $cats->[$depth]{$category}[$k];
14734:             my $item = &escape($category).':'.&escape($parents->[-1]).':'.$shallower;
14735:             my $trailstr = join(' -&gt; ',(@{$parents},$category));
14736:             if ($allitems->{$item} eq '') {
14737:                 push(@{$trails},$trailstr);
14738:                 $allitems->{$item} = scalar(@{$trails})-1;
14739:             }
14740:             my $deeper = $depth+1;
14741:             push(@{$parents},$category);
14742:             if (ref($subcats) eq 'HASH') {
14743:                 my $subcat = &escape($name).':'.$category.':'.$depth;
14744:                 for (my $j=@{$parents}; $j>=0; $j--) {
14745:                     my $higher;
14746:                     if ($j > 0) {
14747:                         $higher = &escape($parents->[$j]).':'.
14748:                                   &escape($parents->[$j-1]).':'.$j;
14749:                     } else {
14750:                         $higher = &escape($parents->[$j]).'::'.$j;
14751:                     }
14752:                     push(@{$subcats->{$higher}},$subcat);
14753:                 }
14754:             }
14755:             &recurse_categories($cats,$deeper,$name,$trails,$allitems,$parents,
14756:                                 $subcats);
14757:             pop(@{$parents});
14758:         }
14759:     } else {
14760:         my $item = &escape($category).':'.&escape($parents->[-1]).':'.$shallower;
14761:         my $trailstr = join(' -&gt; ',(@{$parents},$category));
14762:         if ($allitems->{$item} eq '') {
14763:             push(@{$trails},$trailstr);
14764:             $allitems->{$item} = scalar(@{$trails})-1;
14765:         }
14766:     }
14767:     return;
14768: }
14769: 
14770: =pod
14771: 
14772: =item * &assign_categories_table()
14773: 
14774: Create a datatable for display of hierarchical categories in a domain,
14775: with checkboxes to allow a course to be categorized. 
14776: 
14777: Inputs:
14778: 
14779: cathash - reference to hash of categories defined for the domain (from
14780:           configuration.db)
14781: 
14782: currcat - scalar with an & separated list of categories assigned to a course. 
14783: 
14784: type    - scalar contains course type (Course or Community).
14785: 
14786: Returns: $output (markup to be displayed) 
14787: 
14788: =cut
14789: 
14790: sub assign_categories_table {
14791:     my ($cathash,$currcat,$type) = @_;
14792:     my $output;
14793:     if (ref($cathash) eq 'HASH') {
14794:         my (@cats,@trails,%allitems,%idx,@jsarray,@path,$maxdepth);
14795:         &extract_categories($cathash,\@cats,\@trails,\%allitems,\%idx,\@jsarray);
14796:         $maxdepth = scalar(@cats);
14797:         if (@cats > 0) {
14798:             my $itemcount = 0;
14799:             if (ref($cats[0]) eq 'ARRAY') {
14800:                 my @currcategories;
14801:                 if ($currcat ne '') {
14802:                     @currcategories = split('&',$currcat);
14803:                 }
14804:                 my $table;
14805:                 for (my $i=0; $i<@{$cats[0]}; $i++) {
14806:                     my $parent = $cats[0][$i];
14807:                     next if ($parent eq 'instcode');
14808:                     if ($type eq 'Community') {
14809:                         next unless ($parent eq 'communities');
14810:                     } elsif ($type eq 'Placement') {
14811:                         next unless ($parent eq 'placement');
14812:                     } else {
14813:                         next if (($parent eq 'communities') || ($parent eq 'placement'));
14814:                     }
14815:                     my $css_class = $itemcount%2?' class="LC_odd_row"':'';
14816:                     my $item = &escape($parent).'::0';
14817:                     my $checked = '';
14818:                     if (@currcategories > 0) {
14819:                         if (grep(/^\Q$item\E$/,@currcategories)) {
14820:                             $checked = ' checked="checked"';
14821:                         }
14822:                     }
14823:                     my $parent_title = $parent;
14824:                     if ($parent eq 'communities') {
14825:                         $parent_title = &mt('Communities');
14826:                     } elsif ($parent eq 'placement') {
14827:                         $parent_title = &mt('Placement Tests');
14828:                     }
14829:                     $table .= '<tr '.$css_class.'><td><span class="LC_nobreak">'.
14830:                               '<input type="checkbox" name="usecategory" value="'.
14831:                               $item.'"'.$checked.' />'.$parent_title.'</span>'.
14832:                               '<input type="hidden" name="catname" value="'.$parent.'" /></td>';
14833:                     my $depth = 1;
14834:                     push(@path,$parent);
14835:                     $table .= &assign_category_rows($itemcount,\@cats,$depth,$parent,\@path,\@currcategories);
14836:                     pop(@path);
14837:                     $table .= '</tr><tr><td colspan="'.$maxdepth.'" class="LC_row_separator"></td></tr>';
14838:                     $itemcount ++;
14839:                 }
14840:                 if ($itemcount) {
14841:                     $output = &Apache::loncommon::start_data_table().
14842:                               $table.
14843:                               &Apache::loncommon::end_data_table();
14844:                 }
14845:             }
14846:         }
14847:     }
14848:     return $output;
14849: }
14850: 
14851: =pod
14852: 
14853: =item * &assign_category_rows()
14854: 
14855: Create a datatable row for display of nested categories in a domain,
14856: with checkboxes to allow a course to be categorized,called recursively.
14857: 
14858: Inputs:
14859: 
14860: itemcount - track row number for alternating colors
14861: 
14862: cats - reference to array of arrays/hashes which encapsulates hierarchy of
14863:       categories and subcategories.
14864: 
14865: depth - current depth in hierarchy of categories and sub-categories - 0 indexed.
14866: 
14867: parent - parent of current category item
14868: 
14869: path - Array containing all categories back up through the hierarchy from the
14870:        current category to the top level.
14871: 
14872: currcategories - reference to array of current categories assigned to the course
14873: 
14874: Returns: $output (markup to be displayed).
14875: 
14876: =cut
14877: 
14878: sub assign_category_rows {
14879:     my ($itemcount,$cats,$depth,$parent,$path,$currcategories) = @_;
14880:     my ($text,$name,$item,$chgstr);
14881:     if (ref($cats) eq 'ARRAY') {
14882:         my $maxdepth = scalar(@{$cats});
14883:         if (ref($cats->[$depth]) eq 'HASH') {
14884:             if (ref($cats->[$depth]{$parent}) eq 'ARRAY') {
14885:                 my $numchildren = @{$cats->[$depth]{$parent}};
14886:                 my $css_class = $itemcount%2?' class="LC_odd_row"':'';
14887:                 $text .= '<td><table class="LC_data_table">';
14888:                 for (my $j=0; $j<$numchildren; $j++) {
14889:                     $name = $cats->[$depth]{$parent}[$j];
14890:                     $item = &escape($name).':'.&escape($parent).':'.$depth;
14891:                     my $deeper = $depth+1;
14892:                     my $checked = '';
14893:                     if (ref($currcategories) eq 'ARRAY') {
14894:                         if (@{$currcategories} > 0) {
14895:                             if (grep(/^\Q$item\E$/,@{$currcategories})) {
14896:                                 $checked = ' checked="checked"';
14897:                             }
14898:                         }
14899:                     }
14900:                     $text .= '<tr><td><span class="LC_nobreak"><label>'.
14901:                              '<input type="checkbox" name="usecategory" value="'.
14902:                              $item.'"'.$checked.' />'.$name.'</label></span>'.
14903:                              '<input type="hidden" name="catname" value="'.$name.'" />'.
14904:                              '</td><td>';
14905:                     if (ref($path) eq 'ARRAY') {
14906:                         push(@{$path},$name);
14907:                         $text .= &assign_category_rows($itemcount,$cats,$deeper,$name,$path,$currcategories);
14908:                         pop(@{$path});
14909:                     }
14910:                     $text .= '</td></tr>';
14911:                 }
14912:                 $text .= '</table></td>';
14913:             }
14914:         }
14915:     }
14916:     return $text;
14917: }
14918: 
14919: =pod
14920: 
14921: =back
14922: 
14923: =cut
14924: 
14925: ############################################################
14926: ############################################################
14927: 
14928: 
14929: sub commit_customrole {
14930:     my ($udom,$uname,$url,$three,$four,$five,$start,$end,$context) = @_;
14931:     my $output = &mt('Assigning custom role').' "'.$five.'" by '.$four.':'.$three.' in '.$url.
14932:                          ($start?', '.&mt('starting').' '.localtime($start):'').
14933:                          ($end?', ending '.localtime($end):'').': <b>'.
14934:               &Apache::lonnet::assigncustomrole(
14935:                  $udom,$uname,$url,$three,$four,$five,$end,$start,undef,undef,$context).
14936:                  '</b><br />';
14937:     return $output;
14938: }
14939: 
14940: sub commit_standardrole {
14941:     my ($udom,$uname,$url,$three,$start,$end,$one,$two,$sec,$context,$credits) = @_;
14942:     my ($output,$logmsg,$linefeed);
14943:     if ($context eq 'auto') {
14944:         $linefeed = "\n";
14945:     } else {
14946:         $linefeed = "<br />\n";
14947:     }  
14948:     if ($three eq 'st') {
14949:         my $result = &commit_studentrole(\$logmsg,$udom,$uname,$url,$three,$start,$end,
14950:                                          $one,$two,$sec,$context,$credits);
14951:         if (($result =~ /^error/) || ($result eq 'not_in_class') || 
14952:             ($result eq 'unknown_course') || ($result eq 'refused')) {
14953:             $output = $logmsg.' '.&mt('Error: ').$result."\n"; 
14954:         } else {
14955:             $output = $logmsg.$linefeed.&mt('Assigning').' '.$three.' in '.$url.
14956:                ($start?', '.&mt('starting').' '.localtime($start):'').
14957:                ($end?', '.&mt('ending').' '.localtime($end):'').': ';
14958:             if ($context eq 'auto') {
14959:                 $output .= $result.$linefeed.&mt('Add to classlist').': ok';
14960:             } else {
14961:                $output .= '<b>'.$result.'</b>'.$linefeed.
14962:                &mt('Add to classlist').': <b>ok</b>';
14963:             }
14964:             $output .= $linefeed;
14965:         }
14966:     } else {
14967:         $output = &mt('Assigning').' '.$three.' in '.$url.
14968:                ($start?', '.&mt('starting').' '.localtime($start):'').
14969:                ($end?', '.&mt('ending').' '.localtime($end):'').': ';
14970:         my $result = &Apache::lonnet::assignrole($udom,$uname,$url,$three,$end,$start,'','',$context);
14971:         if ($context eq 'auto') {
14972:             $output .= $result.$linefeed;
14973:         } else {
14974:             $output .= '<b>'.$result.'</b>'.$linefeed;
14975:         }
14976:     }
14977:     return $output;
14978: }
14979: 
14980: sub commit_studentrole {
14981:     my ($logmsg,$udom,$uname,$url,$three,$start,$end,$one,$two,$sec,$context,
14982:         $credits) = @_;
14983:     my ($result,$linefeed,$oldsecurl,$newsecurl);
14984:     if ($context eq 'auto') {
14985:         $linefeed = "\n";
14986:     } else {
14987:         $linefeed = '<br />'."\n";
14988:     }
14989:     if (defined($one) && defined($two)) {
14990:         my $cid=$one.'_'.$two;
14991:         my $oldsec=&Apache::lonnet::getsection($udom,$uname,$cid);
14992:         my $secchange = 0;
14993:         my $expire_role_result;
14994:         my $modify_section_result;
14995:         if ($oldsec ne '-1') { 
14996:             if ($oldsec ne $sec) {
14997:                 $secchange = 1;
14998:                 my $now = time;
14999:                 my $uurl='/'.$cid;
15000:                 $uurl=~s/\_/\//g;
15001:                 if ($oldsec) {
15002:                     $uurl.='/'.$oldsec;
15003:                 }
15004:                 $oldsecurl = $uurl;
15005:                 $expire_role_result = 
15006:                     &Apache::lonnet::assignrole($udom,$uname,$uurl,'st',$now,'','',$context);
15007:                 if ($env{'request.course.sec'} ne '') { 
15008:                     if ($expire_role_result eq 'refused') {
15009:                         my @roles = ('st');
15010:                         my @statuses = ('previous');
15011:                         my @roledoms = ($one);
15012:                         my $withsec = 1;
15013:                         my %roleshash = 
15014:                             &Apache::lonnet::get_my_roles($uname,$udom,'userroles',
15015:                                               \@statuses,\@roles,\@roledoms,$withsec);
15016:                         if (defined ($roleshash{$two.':'.$one.':st:'.$oldsec})) {
15017:                             my ($oldstart,$oldend) = 
15018:                                 split(':',$roleshash{$two.':'.$one.':st:'.$oldsec});
15019:                             if ($oldend > 0 && $oldend <= $now) {
15020:                                 $expire_role_result = 'ok';
15021:                             }
15022:                         }
15023:                     }
15024:                 }
15025:                 $result = $expire_role_result;
15026:             }
15027:         }
15028:         if (($expire_role_result eq 'ok') || ($secchange == 0)) {
15029:             $modify_section_result = 
15030:                 &Apache::lonnet::modify_student_enrollment($udom,$uname,undef,undef,
15031:                                                            undef,undef,undef,$sec,
15032:                                                            $end,$start,'','',$cid,
15033:                                                            '',$context,$credits);
15034:             if ($modify_section_result =~ /^ok/) {
15035:                 if ($secchange == 1) {
15036:                     if ($sec eq '') {
15037:                         $$logmsg .= &mt('Section for [_1] switched from (possibly expired) old section: [_2] to student role without a section.',$uname,$oldsec).$linefeed;
15038:                     } else {
15039:                         $$logmsg .= &mt('Section for [_1] switched from (possibly expired) old section: [_2] to new section: [_3].',$uname,$oldsec,$sec).$linefeed;
15040:                     }
15041:                 } elsif ($oldsec eq '-1') {
15042:                     if ($sec eq '') {
15043:                         $$logmsg .= &mt('New student role without a section for [_1] in course [_2].',$uname,$cid).$linefeed;
15044:                     } else {
15045:                         $$logmsg .= &mt('New student role for [_1] in section [_2] in course [_3].',$uname,$sec,$cid).$linefeed;
15046:                     }
15047:                 } else {
15048:                     if ($sec eq '') {
15049:                         $$logmsg .= &mt('Student [_1] assigned to course [_2] without a section.',$uname,$cid).$linefeed;
15050:                     } else {
15051:                         $$logmsg .= &mt('Student [_1] assigned to section [_2] in course [_3].',$uname,$sec,$cid).$linefeed;
15052:                     }
15053:                 }
15054:             } else {
15055:                 if ($secchange) { 
15056:                     $$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;
15057:                 } else {
15058:                     $$logmsg .= &mt('Error when attempting to modify role for [_1] for section: "[_2]" in course [_3] -error:',$uname,$sec,$cid).' '.$modify_section_result.$linefeed;
15059:                 }
15060:             }
15061:             $result = $modify_section_result;
15062:         } elsif ($secchange == 1) {
15063:             if ($oldsec eq '') {
15064:                 $$logmsg .= &mt('Error when attempting to expire existing role without a section for [_1] in course [_2] -error: ',$uname,$cid).' '.$expire_role_result.$linefeed;
15065:             } else {
15066:                 $$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;
15067:             }
15068:             if ($expire_role_result eq 'refused') {
15069:                 my $newsecurl = '/'.$cid;
15070:                 $newsecurl =~ s/\_/\//g;
15071:                 if ($sec ne '') {
15072:                     $newsecurl.='/'.$sec;
15073:                 }
15074:                 if (&Apache::lonnet::allowed('cst',$newsecurl) && !(&Apache::lonnet::allowed('cst',$oldsecurl))) {
15075:                     if ($sec eq '') {
15076:                         $$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;
15077:                     } else {
15078:                         $$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;
15079:                     }
15080:                 }
15081:             }
15082:         }
15083:     } else {
15084:         $$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;
15085:         $result = "error: incomplete course id\n";
15086:     }
15087:     return $result;
15088: }
15089: 
15090: sub show_role_extent {
15091:     my ($scope,$context,$role) = @_;
15092:     $scope =~ s{^/}{};
15093:     my @courseroles = &Apache::lonuserutils::roles_by_context('course',1);
15094:     push(@courseroles,'co');
15095:     my @authorroles = &Apache::lonuserutils::roles_by_context('author');
15096:     if (($context eq 'course') || (grep(/^\Q$role\E/,@courseroles))) {
15097:         $scope =~ s{/}{_};
15098:         return '<span class="LC_cusr_emph">'.$env{'course.'.$scope.'.description'}.'</span>';
15099:     } elsif (($context eq 'author') || (grep(/^\Q$role\E/,@authorroles))) {
15100:         my ($audom,$auname) = split(/\//,$scope);
15101:         return &mt('[_1] Author Space','<span class="LC_cusr_emph">'.
15102:                    &Apache::loncommon::plainname($auname,$audom).'</span>');
15103:     } else {
15104:         $scope =~ s{/$}{};
15105:         return &mt('Domain: [_1]','<span class="LC_cusr_emph">'.
15106:                    &Apache::lonnet::domain($scope,'description').'</span>');
15107:     }
15108: }
15109: 
15110: ############################################################
15111: ############################################################
15112: 
15113: sub check_clone {
15114:     my ($args,$linefeed) = @_;
15115:     my $cloneid='/'.$args->{'clonedomain'}.'/'.$args->{'clonecourse'};
15116:     my ($clonecrsudom,$clonecrsunum)= &LONCAPA::split_courseid($cloneid);
15117:     my $clonehome=&Apache::lonnet::homeserver($clonecrsunum,$clonecrsudom);
15118:     my $clonemsg;
15119:     my $can_clone = 0;
15120:     my $lctype = lc($args->{'crstype'});
15121:     if ($lctype ne 'community') {
15122:         $lctype = 'course';
15123:     }
15124:     if ($clonehome eq 'no_host') {
15125:         if ($args->{'crstype'} eq 'Community') {
15126:             $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'});
15127:         } else {
15128:             $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'});
15129:         }     
15130:     } else {
15131: 	my %clonedesc = &Apache::lonnet::coursedescription($cloneid,{'one_time' => 1});
15132:         if ($args->{'crstype'} eq 'Community') {
15133:             if ($clonedesc{'type'} ne 'Community') {
15134:                  $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'});
15135:                 return ($can_clone, $clonemsg, $cloneid, $clonehome);
15136:             }
15137:         }
15138: 	if (($env{'request.role.domain'} eq $args->{'clonedomain'}) && 
15139:             (&Apache::lonnet::allowed('ccc',$env{'request.role.domain'}))) {
15140: 	    $can_clone = 1;
15141: 	} else {
15142: 	    my %clonehash = &Apache::lonnet::get('environment',['cloners','internal.coursecode'],
15143: 						 $args->{'clonedomain'},$args->{'clonecourse'});
15144:             if ($clonehash{'cloners'} eq '') {
15145:                 my %domdefs = &Apache::lonnet::get_domain_defaults($args->{'course_domain'});
15146:                 if ($domdefs{'canclone'}) {
15147:                     unless ($domdefs{'canclone'} eq 'none') {
15148:                         if ($domdefs{'canclone'} eq 'domain') {
15149:                             if ($args->{'ccdomain'} eq $args->{'clonedomain'}) {
15150:                                 $can_clone = 1;
15151:                             }
15152:                         } elsif (($clonehash{'internal.coursecode'}) && ($args->{'crscode'}) && 
15153:                                  ($args->{'clonedomain'} eq  $args->{'course_domain'})) {
15154:                             if (&Apache::lonnet::default_instcode_cloning($args->{'clonedomain'},$domdefs{'canclone'},
15155:                                                                           $clonehash{'internal.coursecode'},$args->{'crscode'})) {
15156:                                 $can_clone = 1;
15157:                             }
15158:                         }
15159:                     }
15160:                 }
15161:             } else {
15162: 	        my @cloners = split(/,/,$clonehash{'cloners'});
15163:                 if (grep(/^\*$/,@cloners)) {
15164:                     $can_clone = 1;
15165:                 } elsif (grep(/^\*\:\Q$args->{'ccdomain'}\E$/,@cloners)) {
15166:                     $can_clone = 1;
15167:                 } elsif (grep(/^\Q$args->{'ccuname'}\E:\Q$args->{'ccdomain'}\E$/,@cloners)) {
15168:                     $can_clone = 1;
15169:                 }
15170:                 unless ($can_clone) {
15171:                     if (($clonehash{'internal.coursecode'}) && ($args->{'crscode'}) && 
15172:                         ($args->{'clonedomain'} eq  $args->{'course_domain'})) {
15173:                         my (%gotdomdefaults,%gotcodedefaults);
15174:                         foreach my $cloner (@cloners) {
15175:                             if (($cloner ne '*') && ($cloner !~ /^\*\:$match_domain$/) &&
15176:                                 ($cloner !~ /^$match_username\:$match_domain$/) && ($cloner ne '')) {
15177:                                 my (%codedefaults,@code_order);
15178:                                 if (ref($gotcodedefaults{$args->{'clonedomain'}}) eq 'HASH') {
15179:                                     if (ref($gotcodedefaults{$args->{'clonedomain'}}{'defaults'}) eq 'HASH') {
15180:                                         %codedefaults = %{$gotcodedefaults{$args->{'clonedomain'}}{'defaults'}};
15181:                                     }
15182:                                     if (ref($gotcodedefaults{$args->{'clonedomain'}}{'order'}) eq 'ARRAY') {
15183:                                         @code_order = @{$gotcodedefaults{$args->{'clonedomain'}}{'order'}};
15184:                                     }
15185:                                 } else {
15186:                                     &Apache::lonnet::auto_instcode_defaults($args->{'clonedomain'},
15187:                                                                             \%codedefaults,
15188:                                                                             \@code_order);
15189:                                     $gotcodedefaults{$args->{'clonedomain'}}{'defaults'} = \%codedefaults;
15190:                                     $gotcodedefaults{$args->{'clonedomain'}}{'order'} = \@code_order;
15191:                                 }
15192:                                 if (@code_order > 0) {
15193:                                     if (&Apache::lonnet::check_instcode_cloning(\%codedefaults,\@code_order,
15194:                                                                                 $cloner,$clonehash{'internal.coursecode'},
15195:                                                                                 $args->{'crscode'})) {
15196:                                         $can_clone = 1;
15197:                                         last;
15198:                                     }
15199:                                 }
15200:                             }
15201:                         }
15202:                     }
15203:                 }
15204:             }
15205:             unless ($can_clone) {
15206:                 my $ccrole = 'cc';
15207:                 if ($args->{'crstype'} eq 'Community') {
15208:                     $ccrole = 'co';
15209:                 }
15210: 	        my %roleshash =
15211: 		    &Apache::lonnet::get_my_roles($args->{'ccuname'},
15212: 					          $args->{'ccdomain'},
15213:                                                   'userroles',['active'],[$ccrole],
15214: 					          [$args->{'clonedomain'}]);
15215: 	        if ($roleshash{$args->{'clonecourse'}.':'.$args->{'clonedomain'}.':'.$ccrole}) {
15216:                     $can_clone = 1;
15217:                 } elsif (&Apache::lonnet::is_course_owner($args->{'clonedomain'},$args->{'clonecourse'},
15218:                                                           $args->{'ccuname'},$args->{'ccdomain'})) {
15219:                     $can_clone = 1;
15220:                 }
15221:             }
15222:             unless ($can_clone) {
15223:                 if ($args->{'crstype'} eq 'Community') {
15224:                     $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'});
15225:                 } else {
15226:                     $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'});
15227:                 }
15228: 	    }
15229:         }
15230:     }
15231:     return ($can_clone, $clonemsg, $cloneid, $clonehome);
15232: }
15233: 
15234: sub construct_course {
15235:     my ($args,$logmsg,$courseid,$crsudom,$crsunum,$udom,$uname,$context,$cnum,$category,$coderef) = @_;
15236:     my $outcome;
15237:     my $linefeed =  '<br />'."\n";
15238:     if ($context eq 'auto') {
15239:         $linefeed = "\n";
15240:     }
15241: 
15242: #
15243: # Are we cloning?
15244: #
15245:     my ($can_clone, $clonemsg, $cloneid, $clonehome);
15246:     if (($args->{'clonecourse'}) && ($args->{'clonedomain'})) {
15247: 	($can_clone, $clonemsg, $cloneid, $clonehome) = &check_clone($args,$linefeed);
15248: 	if ($context ne 'auto') {
15249:             if ($clonemsg ne '') {
15250: 	        $clonemsg = '<span class="LC_error">'.$clonemsg.'</span>';
15251:             }
15252: 	}
15253: 	$outcome .= $clonemsg.$linefeed;
15254: 
15255:         if (!$can_clone) {
15256: 	    return (0,$outcome);
15257: 	}
15258:     }
15259: 
15260: #
15261: # Open course
15262: #
15263:     my $showncrstype;
15264:     if ($args->{'crstype'} eq 'Placement') {
15265:         $showncrstype = 'placement test'; 
15266:     } else {  
15267:         $showncrstype = lc($args->{'crstype'});
15268:     }
15269:     my %cenv=();
15270:     $$courseid=&Apache::lonnet::createcourse($args->{'course_domain'},
15271:                                              $args->{'cdescr'},
15272:                                              $args->{'curl'},
15273:                                              $args->{'course_home'},
15274:                                              $args->{'nonstandard'},
15275:                                              $args->{'crscode'},
15276:                                              $args->{'ccuname'}.':'.
15277:                                              $args->{'ccdomain'},
15278:                                              $args->{'crstype'},
15279:                                              $cnum,$context,$category);
15280: 
15281:     # Note: The testing routines depend on this being output; see 
15282:     # Utils::Course. This needs to at least be output as a comment
15283:     # if anyone ever decides to not show this, and Utils::Course::new
15284:     # will need to be suitably modified.
15285:     $outcome .= &mt('New LON-CAPA [_1] ID: [_2]',$showncrstype,$$courseid).$linefeed;
15286:     if ($$courseid =~ /^error:/) {
15287:         return (0,$outcome);
15288:     }
15289: 
15290: #
15291: # Check if created correctly
15292: #
15293:     ($$crsudom,$$crsunum)= &LONCAPA::split_courseid($$courseid);
15294:     my $crsuhome=&Apache::lonnet::homeserver($$crsunum,$$crsudom);
15295:     if ($crsuhome eq 'no_host') {
15296:         $outcome .= &mt('Course creation failed, unrecognized course home server.').$linefeed;
15297:         return (0,$outcome);
15298:     }
15299:     $outcome .= &mt('Created on').': '.$crsuhome.$linefeed;
15300: 
15301: #
15302: # Do the cloning
15303: #   
15304:     if ($can_clone && $cloneid) {
15305: 	$clonemsg = &mt('Cloning [_1] from [_2]',$showncrstype,$clonehome);
15306: 	if ($context ne 'auto') {
15307: 	    $clonemsg = '<span class="LC_success">'.$clonemsg.'</span>';
15308: 	}
15309: 	$outcome .= $clonemsg.$linefeed;
15310: 	my %oldcenv=&Apache::lonnet::dump('environment',$$crsudom,$$crsunum);
15311: # Copy all files
15312: 	&Apache::lonclonecourse::copycoursefiles($cloneid,$$courseid,$args->{'datemode'},$args->{'dateshift'});
15313: # Restore URL
15314: 	$cenv{'url'}=$oldcenv{'url'};
15315: # Restore title
15316: 	$cenv{'description'}=$oldcenv{'description'};
15317: # Restore creation date, creator and creation context.
15318:         $cenv{'internal.created'}=$oldcenv{'internal.created'};
15319:         $cenv{'internal.creator'}=$oldcenv{'internal.creator'};
15320:         $cenv{'internal.creationcontext'}=$oldcenv{'internal.creationcontext'};
15321: # Mark as cloned
15322: 	$cenv{'clonedfrom'}=$cloneid;
15323: # Need to clone grading mode
15324:         my %newenv=&Apache::lonnet::get('environment',['grading'],$$crsudom,$$crsunum);
15325:         $cenv{'grading'}=$newenv{'grading'};
15326: # Do not clone these environment entries
15327:         &Apache::lonnet::del('environment',
15328:                   ['default_enrollment_start_date',
15329:                    'default_enrollment_end_date',
15330:                    'question.email',
15331:                    'policy.email',
15332:                    'comment.email',
15333:                    'pch.users.denied',
15334:                    'plc.users.denied',
15335:                    'hidefromcat',
15336:                    'checkforpriv',
15337:                    'categories',
15338:                    'internal.uniquecode'],
15339:                    $$crsudom,$$crsunum);
15340:         if ($args->{'textbook'}) {
15341:             $cenv{'internal.textbook'} = $args->{'textbook'};
15342:         }
15343:     }
15344: 
15345: #
15346: # Set environment (will override cloned, if existing)
15347: #
15348:     my @sections = ();
15349:     my @xlists = ();
15350:     if ($args->{'crstype'}) {
15351:         $cenv{'type'}=$args->{'crstype'};
15352:     }
15353:     if ($args->{'crsid'}) {
15354:         $cenv{'courseid'}=$args->{'crsid'};
15355:     }
15356:     if ($args->{'crscode'}) {
15357:         $cenv{'internal.coursecode'}=$args->{'crscode'};
15358:     }
15359:     if ($args->{'crsquota'} ne '') {
15360:         $cenv{'internal.coursequota'}=$args->{'crsquota'};
15361:     } else {
15362:         $cenv{'internal.coursequota'}=$args->{'crsquota'} = 20;
15363:     }
15364:     if ($args->{'ccuname'}) {
15365:         $cenv{'internal.courseowner'} = $args->{'ccuname'}.
15366:                                         ':'.$args->{'ccdomain'};
15367:     } else {
15368:         $cenv{'internal.courseowner'} = $args->{'curruser'};
15369:     }
15370:     if ($args->{'defaultcredits'}) {
15371:         $cenv{'internal.defaultcredits'} = $args->{'defaultcredits'};
15372:     }
15373:     my @badclasses = (); # Used to accumulate sections/crosslistings that did not pass classlist access check for course owner.
15374:     if ($args->{'crssections'}) {
15375:         $cenv{'internal.sectionnums'} = '';
15376:         if ($args->{'crssections'} =~ m/,/) {
15377:             @sections = split/,/,$args->{'crssections'};
15378:         } else {
15379:             $sections[0] = $args->{'crssections'};
15380:         }
15381:         if (@sections > 0) {
15382:             foreach my $item (@sections) {
15383:                 my ($sec,$gp) = split/:/,$item;
15384:                 my $class = $args->{'crscode'}.$sec;
15385:                 my $addcheck = &Apache::lonnet::auto_new_course($$crsunum,$$crsudom,$class,$cenv{'internal.courseowner'});
15386:                 $cenv{'internal.sectionnums'} .= $item.',';
15387:                 unless ($addcheck eq 'ok') {
15388:                     push @badclasses, $class;
15389:                 }
15390:             }
15391:             $cenv{'internal.sectionnums'} =~ s/,$//;
15392:         }
15393:     }
15394: # do not hide course coordinator from staff listing, 
15395: # even if privileged
15396:     $cenv{'nothideprivileged'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
15397: # add course coordinator's domain to domains to check for privileged users
15398: # if different to course domain
15399:     if ($$crsudom ne $args->{'ccdomain'}) {
15400:         $cenv{'checkforpriv'} = $args->{'ccdomain'};
15401:     }
15402: # add crosslistings
15403:     if ($args->{'crsxlist'}) {
15404:         $cenv{'internal.crosslistings'}='';
15405:         if ($args->{'crsxlist'} =~ m/,/) {
15406:             @xlists = split/,/,$args->{'crsxlist'};
15407:         } else {
15408:             $xlists[0] = $args->{'crsxlist'};
15409:         }
15410:         if (@xlists > 0) {
15411:             foreach my $item (@xlists) {
15412:                 my ($xl,$gp) = split/:/,$item;
15413:                 my $addcheck =  &Apache::lonnet::auto_new_course($$crsunum,$$crsudom,$xl,$cenv{'internal.courseowner'});
15414:                 $cenv{'internal.crosslistings'} .= $item.',';
15415:                 unless ($addcheck eq 'ok') {
15416:                     push @badclasses, $xl;
15417:                 }
15418:             }
15419:             $cenv{'internal.crosslistings'} =~ s/,$//;
15420:         }
15421:     }
15422:     if ($args->{'autoadds'}) {
15423:         $cenv{'internal.autoadds'}=$args->{'autoadds'};
15424:     }
15425:     if ($args->{'autodrops'}) {
15426:         $cenv{'internal.autodrops'}=$args->{'autodrops'};
15427:     }
15428: # check for notification of enrollment changes
15429:     my @notified = ();
15430:     if ($args->{'notify_owner'}) {
15431:         if ($args->{'ccuname'} ne '') {
15432:             push(@notified,$args->{'ccuname'}.':'.$args->{'ccdomain'});
15433:         }
15434:     }
15435:     if ($args->{'notify_dc'}) {
15436:         if ($uname ne '') { 
15437:             push(@notified,$uname.':'.$udom);
15438:         }
15439:     }
15440:     if (@notified > 0) {
15441:         my $notifylist;
15442:         if (@notified > 1) {
15443:             $notifylist = join(',',@notified);
15444:         } else {
15445:             $notifylist = $notified[0];
15446:         }
15447:         $cenv{'internal.notifylist'} = $notifylist;
15448:     }
15449:     if (@badclasses > 0) {
15450:         my %lt=&Apache::lonlocal::texthash(
15451:                 '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',
15452:                 'dnhr' => 'does not have rights to access enrollment in these classes',
15453:                 'adby' => 'as determined by the policies of your institution on access to official classlists'
15454:         );
15455:         my $badclass_msg = $cenv{'internal.courseowner'}.') - '.$lt{'dnhr'}.
15456:                            ' ('.$lt{'adby'}.')';
15457:         if ($context eq 'auto') {
15458:             $outcome .= $badclass_msg.$linefeed;
15459:             $outcome .= '<div class="LC_warning">'.$badclass_msg.$linefeed.'<ul>'."\n";
15460:             foreach my $item (@badclasses) {
15461:                 if ($context eq 'auto') {
15462:                     $outcome .= " - $item\n";
15463:                 } else {
15464:                     $outcome .= "<li>$item</li>\n";
15465:                 }
15466:             }
15467:             if ($context eq 'auto') {
15468:                 $outcome .= $linefeed;
15469:             } else {
15470:                 $outcome .= "</ul><br /><br /></div>\n";
15471:             }
15472:         } 
15473:     }
15474:     if ($args->{'no_end_date'}) {
15475:         $args->{'endaccess'} = 0;
15476:     }
15477:     $cenv{'internal.autostart'}=$args->{'enrollstart'};
15478:     $cenv{'internal.autoend'}=$args->{'enrollend'};
15479:     $cenv{'default_enrollment_start_date'}=$args->{'startaccess'};
15480:     $cenv{'default_enrollment_end_date'}=$args->{'endaccess'};
15481:     if ($args->{'showphotos'}) {
15482:       $cenv{'internal.showphotos'}=$args->{'showphotos'};
15483:     }
15484:     $cenv{'internal.authtype'} = $args->{'authtype'};
15485:     $cenv{'internal.autharg'} = $args->{'autharg'}; 
15486:     if ( ($cenv{'internal.authtype'} =~ /^krb/) && ($cenv{'internal.autoadds'} == 1)) {
15487:         if (! defined($cenv{'internal.autharg'}) || $cenv{'internal.autharg'}  eq '') {
15488:             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'); 
15489:             if ($context eq 'auto') {
15490:                 $outcome .= $krb_msg;
15491:             } else {
15492:                 $outcome .= '<span class="LC_error">'.$krb_msg.'</span>';
15493:             }
15494:             $outcome .= $linefeed;
15495:         }
15496:     }
15497:     if (($args->{'ccdomain'}) && ($args->{'ccuname'})) {
15498:        if ($args->{'setpolicy'}) {
15499:            $cenv{'policy.email'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
15500:        }
15501:        if ($args->{'setcontent'}) {
15502:            $cenv{'question.email'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
15503:        }
15504:        if ($args->{'setcomment'}) {
15505:            $cenv{'comment.email'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
15506:        }
15507:     }
15508:     if ($args->{'reshome'}) {
15509: 	$cenv{'reshome'}=$args->{'reshome'}.'/';
15510: 	$cenv{'reshome'}=~s/\/+$/\//;
15511:     }
15512: #
15513: # course has keyed access
15514: #
15515:     if ($args->{'setkeys'}) {
15516:        $cenv{'keyaccess'}='yes';
15517:     }
15518: # if specified, key authority is not course, but user
15519: # only active if keyaccess is yes
15520:     if ($args->{'keyauth'}) {
15521: 	my ($user,$domain) = split(':',$args->{'keyauth'});
15522: 	$user = &LONCAPA::clean_username($user);
15523: 	$domain = &LONCAPA::clean_username($domain);
15524: 	if ($user ne '' && $domain ne '') {
15525: 	    $cenv{'keyauth'}=$user.':'.$domain;
15526: 	}
15527:     }
15528: 
15529: #
15530: #  generate and store uniquecode (available to course requester), if course should have one.
15531: #
15532:     if ($args->{'uniquecode'}) {
15533:         my ($code,$error) = &make_unique_code($$crsudom,$$crsunum);
15534:         if ($code) {
15535:             $cenv{'internal.uniquecode'} = $code;
15536:             my %crsinfo =
15537:                 &Apache::lonnet::courseiddump($$crsudom,'.',1,'.','.',$$crsunum,undef,undef,'.');
15538:             if (ref($crsinfo{$$crsudom.'_'.$$crsunum}) eq 'HASH') {
15539:                 $crsinfo{$$crsudom.'_'.$$crsunum}{'uniquecode'} = $code;
15540:                 my $putres = &Apache::lonnet::courseidput($$crsudom,\%crsinfo,$crsuhome,'notime');
15541:             } 
15542:             if (ref($coderef)) {
15543:                 $$coderef = $code;
15544:             }
15545:         }
15546:     }
15547: 
15548:     if ($args->{'disresdis'}) {
15549:         $cenv{'pch.roles.denied'}='st';
15550:     }
15551:     if ($args->{'disablechat'}) {
15552:         $cenv{'plc.roles.denied'}='st';
15553:     }
15554: 
15555:     # Record we've not yet viewed the Course Initialization Helper for this 
15556:     # course
15557:     $cenv{'course.helper.not.run'} = 1;
15558:     #
15559:     # Use new Randomseed
15560:     #
15561:     $cenv{'rndseed'}=&Apache::lonnet::latest_rnd_algorithm_id();;
15562:     $cenv{'receiptalg'}=&Apache::lonnet::latest_receipt_algorithm_id();;
15563:     #
15564:     # The encryption code and receipt prefix for this course
15565:     #
15566:     $cenv{'internal.encseed'}=$Apache::lonnet::perlvar{'lonReceipt'}.$$.time.int(rand(9999));
15567:     $cenv{'internal.encpref'}=100+int(9*rand(99));
15568:     #
15569:     # By default, use standard grading
15570:     if (!defined($cenv{'grading'})) { $cenv{'grading'} = 'standard'; }
15571: 
15572:     $outcome .= $linefeed.&mt('Setting environment').': '.                 
15573:           &Apache::lonnet::put('environment',\%cenv,$$crsudom,$$crsunum).$linefeed;
15574: #
15575: # Open all assignments
15576: #
15577:     if ($args->{'openall'}) {
15578:        my $storeunder=$$crsudom.'_'.$$crsunum.'.0.opendate';
15579:        my %storecontent = ($storeunder         => time,
15580:                            $storeunder.'.type' => 'date_start');
15581:        
15582:        $outcome .= &mt('Opening all assignments').': '.&Apache::lonnet::cput
15583:                  ('resourcedata',\%storecontent,$$crsudom,$$crsunum).$linefeed;
15584:    }
15585: #
15586: # Set first page
15587: #
15588:     unless (($args->{'nonstandard'}) || ($args->{'firstres'} eq 'blank')
15589: 	    || ($cloneid)) {
15590: 	use LONCAPA::map;
15591: 	$outcome .= &mt('Setting first resource').': ';
15592: 
15593: 	my $map = '/uploaded/'.$$crsudom.'/'.$$crsunum.'/default.sequence';
15594:         my ($errtext,$fatal)=&LONCAPA::map::mapread($map);
15595: 
15596:         $outcome .= ($fatal?$errtext:'read ok').' - ';
15597:         my $title; my $url;
15598:         if ($args->{'firstres'} eq 'syl') {
15599: 	    $title=&mt('Syllabus');
15600:             $url='/public/'.$$crsudom.'/'.$$crsunum.'/syllabus';
15601:         } else {
15602:             $title=&mt('Table of Contents');
15603:             $url='/adm/navmaps';
15604:         }
15605: 
15606:         $LONCAPA::map::resources[1]=$title.':'.$url.':false:start:res';
15607: 	(my $outtext,$errtext) = &LONCAPA::map::storemap($map,1);
15608: 
15609: 	if ($errtext) { $fatal=2; }
15610:         $outcome .= ($fatal?$errtext:'write ok').$linefeed;
15611:     }
15612: 
15613: # 
15614: # Set params for Placement Tests
15615: #
15616:     if ($args->{'crstype'} eq 'Placement') {
15617:        my %storecontent; 
15618:        my $prefix=$$crsudom.'_'.$$crsunum.'.0.';
15619:        my %defaults = (
15620:                         buttonshide   => { value => 'yes',
15621:                                            type => 'string_yesno',},
15622:                         type          => { value => 'randomizetry',
15623:                                            type  => 'string_questiontype',},
15624:                         maxtries      => { value => 1,
15625:                                            type => 'int_pos',},
15626:                         problemstatus => { value => 'no',
15627:                                            type  => 'string_problemstatus',},
15628:                       );
15629:        foreach my $key (keys(%defaults)) {
15630:            $storecontent{$prefix.$key} = $defaults{$key}{'value'};
15631:            $storecontent{$prefix.$key.'.type'} = $defaults{$key}{'type'};
15632:        }
15633:        &Apache::lonnet::cput
15634:                  ('resourcedata',\%storecontent,$$crsudom,$$crsunum); 
15635:     }
15636: 
15637:     return (1,$outcome);
15638: }
15639: 
15640: sub make_unique_code {
15641:     my ($cdom,$cnum) = @_;
15642:     # get lock on uniquecodes db
15643:     my $lockhash = {
15644:                       $cnum."\0".'uniquecodes' => $env{'user.name'}.
15645:                                                   ':'.$env{'user.domain'},
15646:                    };
15647:     my $tries = 0;
15648:     my $gotlock = &Apache::lonnet::newput_dom('uniquecodes',$lockhash,$cdom);
15649:     my ($code,$error);
15650:   
15651:     while (($gotlock ne 'ok') && ($tries<3)) {
15652:         $tries ++;
15653:         sleep 1;
15654:         $gotlock = &Apache::lonnet::newput_dom('uniquecodes',$lockhash,$cdom);
15655:     }
15656:     if ($gotlock eq 'ok') {
15657:         my %currcodes = &Apache::lonnet::dump_dom('uniquecodes',$cdom);
15658:         my $gotcode;
15659:         my $attempts = 0;
15660:         while ((!$gotcode) && ($attempts < 100)) {
15661:             $code = &generate_code();
15662:             if (!exists($currcodes{$code})) {
15663:                 $gotcode = 1;
15664:                 unless (&Apache::lonnet::newput_dom('uniquecodes',{ $code => $cnum },$cdom) eq 'ok') {
15665:                     $error = 'nostore';
15666:                 }
15667:             }
15668:             $attempts ++;
15669:         }
15670:         my @del_lock = ($cnum."\0".'uniquecodes');
15671:         my $dellockoutcome = &Apache::lonnet::del_dom('uniquecodes',\@del_lock,$cdom);
15672:     } else {
15673:         $error = 'nolock';
15674:     }
15675:     return ($code,$error);
15676: }
15677: 
15678: sub generate_code {
15679:     my $code;
15680:     my @letts = qw(B C D G H J K M N P Q R S T V W X Z);
15681:     for (my $i=0; $i<6; $i++) {
15682:         my $lettnum = int (rand 2);
15683:         my $item = '';
15684:         if ($lettnum) {
15685:             $item = $letts[int( rand(18) )];
15686:         } else {
15687:             $item = 1+int( rand(8) );
15688:         }
15689:         $code .= $item;
15690:     }
15691:     return $code;
15692: }
15693: 
15694: ############################################################
15695: ############################################################
15696: 
15697: # Community, Course and Placement Test
15698: sub course_type {
15699:     my ($cid) = @_;
15700:     if (!defined($cid)) {
15701:         $cid = $env{'request.course.id'};
15702:     }
15703:     if (defined($env{'course.'.$cid.'.type'})) {
15704:         return $env{'course.'.$cid.'.type'};
15705:     } else {
15706:         return 'Course';
15707:     }
15708: }
15709: 
15710: sub group_term {
15711:     my $crstype = &course_type();
15712:     my %names = (
15713:                   'Course' => 'group',
15714:                   'Community' => 'group',
15715:                   'Placement' => 'group',
15716:                 );
15717:     return $names{$crstype};
15718: }
15719: 
15720: sub course_types {
15721:     my @types = ('official','unofficial','community','textbook','placement');
15722:     my %typename = (
15723:                          official   => 'Official course',
15724:                          unofficial => 'Unofficial course',
15725:                          community  => 'Community',
15726:                          textbook   => 'Textbook course',
15727:                          placement  => 'Placement test',
15728:                    );
15729:     return (\@types,\%typename);
15730: }
15731: 
15732: sub icon {
15733:     my ($file)=@_;
15734:     my $curfext = lc((split(/\./,$file))[-1]);
15735:     my $iconname=$Apache::lonnet::perlvar{'lonIconsURL'}.'/unknown.gif';
15736:     my $embstyle = &Apache::loncommon::fileembstyle($curfext);
15737:     if (!(!defined($embstyle) || $embstyle eq 'unk' || $embstyle eq 'hdn')) {
15738: 	if (-e  $Apache::lonnet::perlvar{'lonDocRoot'}.'/'.
15739: 	          $Apache::lonnet::perlvar{'lonIconsURL'}.'/'.
15740: 	            $curfext.".gif") {
15741: 	    $iconname=$Apache::lonnet::perlvar{'lonIconsURL'}.'/'.
15742: 		$curfext.".gif";
15743: 	}
15744:     }
15745:     return &lonhttpdurl($iconname);
15746: } 
15747: 
15748: sub lonhttpdurl {
15749: #
15750: # Had been used for "small fry" static images on separate port 8080.
15751: # Modify here if lightweight http functionality desired again.
15752: # Currently eliminated due to increasing firewall issues.
15753: #
15754:     my ($url)=@_;
15755:     return $url;
15756: }
15757: 
15758: sub connection_aborted {
15759:     my ($r)=@_;
15760:     $r->print(" ");$r->rflush();
15761:     my $c = $r->connection;
15762:     return $c->aborted();
15763: }
15764: 
15765: #    Escapes strings that may have embedded 's that will be put into
15766: #    strings as 'strings'.
15767: sub escape_single {
15768:     my ($input) = @_;
15769:     $input =~ s/\\/\\\\/g;	# Escape the \'s..(must be first)>
15770:     $input =~ s/\'/\\\'/g;	# Esacpe the 's....
15771:     return $input;
15772: }
15773: 
15774: #  Same as escape_single, but escape's "'s  This 
15775: #  can be used for  "strings"
15776: sub escape_double {
15777:     my ($input) = @_;
15778:     $input =~ s/\\/\\\\/g;	# Escape the /'s..(must be first)>
15779:     $input =~ s/\"/\\\"/g;	# Esacpe the "s....
15780:     return $input;
15781: }
15782:  
15783: #   Escapes the last element of a full URL.
15784: sub escape_url {
15785:     my ($url)   = @_;
15786:     my @urlslices = split(/\//, $url,-1);
15787:     my $lastitem = &escape(pop(@urlslices));
15788:     return &HTML::Entities::encode(join('/',@urlslices),"'").'/'.$lastitem;
15789: }
15790: 
15791: sub compare_arrays {
15792:     my ($arrayref1,$arrayref2) = @_;
15793:     my (@difference,%count);
15794:     @difference = ();
15795:     %count = ();
15796:     if ((ref($arrayref1) eq 'ARRAY') && (ref($arrayref2) eq 'ARRAY')) {
15797:         foreach my $element (@{$arrayref1}, @{$arrayref2}) { $count{$element}++; }
15798:         foreach my $element (keys(%count)) {
15799:             if ($count{$element} == 1) {
15800:                 push(@difference,$element);
15801:             }
15802:         }
15803:     }
15804:     return @difference;
15805: }
15806: 
15807: # -------------------------------------------------------- Initialize user login
15808: sub init_user_environment {
15809:     my ($r, $username, $domain, $authhost, $form, $args) = @_;
15810:     my $lonids=$Apache::lonnet::perlvar{'lonIDsDir'};
15811: 
15812:     my $public=($username eq 'public' && $domain eq 'public');
15813: 
15814: # See if old ID present, if so, remove
15815: 
15816:     my ($filename,$cookie,$userroles,$firstaccenv,$timerintenv);
15817:     my $now=time;
15818: 
15819:     if ($public) {
15820: 	my $max_public=100;
15821: 	my $oldest;
15822: 	my $oldest_time=0;
15823: 	for(my $next=1;$next<=$max_public;$next++) {
15824: 	    if (-e $lonids."/publicuser_$next.id") {
15825: 		my $mtime=(stat($lonids."/publicuser_$next.id"))[9];
15826: 		if ($mtime<$oldest_time || !$oldest_time) {
15827: 		    $oldest_time=$mtime;
15828: 		    $oldest=$next;
15829: 		}
15830: 	    } else {
15831: 		$cookie="publicuser_$next";
15832: 		last;
15833: 	    }
15834: 	}
15835: 	if (!$cookie) { $cookie="publicuser_$oldest"; }
15836:     } else {
15837: 	# if this isn't a robot, kill any existing non-robot sessions
15838: 	if (!$args->{'robot'}) {
15839: 	    opendir(DIR,$lonids);
15840: 	    while ($filename=readdir(DIR)) {
15841: 		if ($filename=~/^$username\_\d+\_$domain\_$authhost\.id$/) {
15842: 		    unlink($lonids.'/'.$filename);
15843: 		}
15844: 	    }
15845: 	    closedir(DIR);
15846: # If there is a undeleted lockfile for the user's paste buffer remove it.
15847:             my $namespace = 'nohist_courseeditor';
15848:             my $lockingkey = 'paste'."\0".'locked_num';
15849:             my %lockhash = &Apache::lonnet::get($namespace,[$lockingkey],
15850:                                                 $domain,$username);
15851:             if (exists($lockhash{$lockingkey})) {
15852:                 my $delresult = &Apache::lonnet::del($namespace,[$lockingkey],$domain,$username);
15853:                 unless ($delresult eq 'ok') {
15854:                     &Apache::lonnet::logthis("Failed to delete paste buffer locking key in $namespace for ".$username.":".$domain." Result was: $delresult");
15855:                 }
15856:             }
15857: 	}
15858: # Give them a new cookie
15859: 	my $id = ($args->{'robot'} ? 'robot'.$args->{'robot'}
15860: 		                   : $now.$$.int(rand(10000)));
15861: 	$cookie="$username\_$id\_$domain\_$authhost";
15862:     
15863: # Initialize roles
15864: 
15865: 	($userroles,$firstaccenv,$timerintenv) = 
15866:             &Apache::lonnet::rolesinit($domain,$username,$authhost);
15867:     }
15868: # ------------------------------------ Check browser type and MathML capability
15869: 
15870:     my ($httpbrowser,$clientbrowser,$clientversion,$clientmathml,$clientunicode,
15871:         $clientos,$clientmobile,$clientinfo,$clientosversion) = &decode_user_agent($r);
15872: 
15873: # ------------------------------------------------------------- Get environment
15874: 
15875:     my %userenv = &Apache::lonnet::dump('environment',$domain,$username);
15876:     my ($tmp) = keys(%userenv);
15877:     if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
15878:     } else {
15879: 	undef(%userenv);
15880:     }
15881:     if (($userenv{'interface'}) && (!$form->{'interface'})) {
15882: 	$form->{'interface'}=$userenv{'interface'};
15883:     }
15884:     if ($userenv{'texengine'} eq 'ttm') { $clientmathml=1; }
15885: 
15886: # --------------- Do not trust query string to be put directly into environment
15887:     foreach my $option ('interface','localpath','localres') {
15888:         $form->{$option}=~s/[\n\r\=]//gs;
15889:     }
15890: # --------------------------------------------------------- Write first profile
15891: 
15892:     {
15893: 	my %initial_env = 
15894: 	    ("user.name"          => $username,
15895: 	     "user.domain"        => $domain,
15896: 	     "user.home"          => $authhost,
15897: 	     "browser.type"       => $clientbrowser,
15898: 	     "browser.version"    => $clientversion,
15899: 	     "browser.mathml"     => $clientmathml,
15900: 	     "browser.unicode"    => $clientunicode,
15901: 	     "browser.os"         => $clientos,
15902:              "browser.mobile"     => $clientmobile,
15903:              "browser.info"       => $clientinfo,
15904:              "browser.osversion"  => $clientosversion,
15905: 	     "server.domain"      => $Apache::lonnet::perlvar{'lonDefDomain'},
15906: 	     "request.course.fn"  => '',
15907: 	     "request.course.uri" => '',
15908: 	     "request.course.sec" => '',
15909: 	     "request.role"       => 'cm',
15910: 	     "request.role.adv"   => $env{'user.adv'},
15911: 	     "request.host"       => $ENV{'REMOTE_ADDR'},);
15912: 
15913:         if ($form->{'localpath'}) {
15914: 	    $initial_env{"browser.localpath"}  = $form->{'localpath'};
15915: 	    $initial_env{"browser.localres"}   = $form->{'localres'};
15916:         }
15917: 	
15918: 	if ($form->{'interface'}) {
15919: 	    $form->{'interface'}=~s/\W//gs;
15920: 	    $initial_env{"browser.interface"} = $form->{'interface'};
15921: 	    $env{'browser.interface'}=$form->{'interface'};
15922: 	}
15923: 
15924:         if ($form->{'iptoken'}) {
15925:             my $lonhost = $r->dir_config('lonHostID');
15926:             $initial_env{"user.noloadbalance"} = $lonhost;
15927:             $env{'user.noloadbalance'} = $lonhost;
15928:         }
15929: 
15930:         my %is_adv = ( is_adv => $env{'user.adv'} );
15931:         my %domdef;
15932:         unless ($domain eq 'public') {
15933:             %domdef = &Apache::lonnet::get_domain_defaults($domain);
15934:         }
15935: 
15936:         foreach my $tool ('aboutme','blog','webdav','portfolio') {
15937:             $userenv{'availabletools.'.$tool} = 
15938:                 &Apache::lonnet::usertools_access($username,$domain,$tool,'reload',
15939:                                                   undef,\%userenv,\%domdef,\%is_adv);
15940:         }
15941: 
15942:         foreach my $crstype ('official','unofficial','community','textbook','placement') {
15943:             $userenv{'canrequest.'.$crstype} =
15944:                 &Apache::lonnet::usertools_access($username,$domain,$crstype,
15945:                                                   'reload','requestcourses',
15946:                                                   \%userenv,\%domdef,\%is_adv);
15947:         }
15948: 
15949:         $userenv{'canrequest.author'} =
15950:             &Apache::lonnet::usertools_access($username,$domain,'requestauthor',
15951:                                         'reload','requestauthor',
15952:                                         \%userenv,\%domdef,\%is_adv);
15953:         my %reqauthor = &Apache::lonnet::get('requestauthor',['author_status','author'],
15954:                                              $domain,$username);
15955:         my $reqstatus = $reqauthor{'author_status'};
15956:         if ($reqstatus eq 'approval' || $reqstatus eq 'approved') { 
15957:             if (ref($reqauthor{'author'}) eq 'HASH') {
15958:                 $userenv{'requestauthorqueued'} = $reqstatus.':'.
15959:                                                   $reqauthor{'author'}{'timestamp'};
15960:             }
15961:         }
15962: 
15963: 	$env{'user.environment'} = "$lonids/$cookie.id";
15964: 
15965: 	if (tie(my %disk_env,'GDBM_File',"$lonids/$cookie.id",
15966: 		 &GDBM_WRCREAT(),0640)) {
15967: 	    &_add_to_env(\%disk_env,\%initial_env);
15968: 	    &_add_to_env(\%disk_env,\%userenv,'environment.');
15969: 	    &_add_to_env(\%disk_env,$userroles);
15970:             if (ref($firstaccenv) eq 'HASH') {
15971:                 &_add_to_env(\%disk_env,$firstaccenv);
15972:             }
15973:             if (ref($timerintenv) eq 'HASH') {
15974:                 &_add_to_env(\%disk_env,$timerintenv);
15975:             }
15976: 	    if (ref($args->{'extra_env'})) {
15977: 		&_add_to_env(\%disk_env,$args->{'extra_env'});
15978: 	    }
15979: 	    untie(%disk_env);
15980: 	} else {
15981: 	    &Apache::lonnet::logthis("<span style=\"color:blue;\">WARNING: ".
15982: 			   'Could not create environment storage in lonauth: '.$!.'</span>');
15983: 	    return 'error: '.$!;
15984: 	}
15985:     }
15986:     $env{'request.role'}='cm';
15987:     $env{'request.role.adv'}=$env{'user.adv'};
15988:     $env{'browser.type'}=$clientbrowser;
15989: 
15990:     return $cookie;
15991: 
15992: }
15993: 
15994: sub _add_to_env {
15995:     my ($idf,$env_data,$prefix) = @_;
15996:     if (ref($env_data) eq 'HASH') {
15997:         while (my ($key,$value) = each(%$env_data)) {
15998: 	    $idf->{$prefix.$key} = $value;
15999: 	    $env{$prefix.$key}   = $value;
16000:         }
16001:     }
16002: }
16003: 
16004: # --- Get the symbolic name of a problem and the url
16005: sub get_symb {
16006:     my ($request,$silent) = @_;
16007:     (my $url=$env{'form.url'}) =~ s-^https?\://($ENV{'SERVER_NAME'}|$ENV{'HTTP_HOST'})--;
16008:     my $symb=($env{'form.symb'} ne '' ? $env{'form.symb'} : (&Apache::lonnet::symbread($url)));
16009:     if ($symb eq '') {
16010:         if (!$silent) {
16011:             if (ref($request)) { 
16012:                 $request->print("Unable to handle ambiguous references:$url:.");
16013:             }
16014:             return ();
16015:         }
16016:     }
16017:     &Apache::lonenc::check_decrypt(\$symb);
16018:     return ($symb);
16019: }
16020: 
16021: # --------------------------------------------------------------Get annotation
16022: 
16023: sub get_annotation {
16024:     my ($symb,$enc) = @_;
16025: 
16026:     my $key = $symb;
16027:     if (!$enc) {
16028:         $key =
16029:             &Apache::lonnet::clutter((&Apache::lonnet::decode_symb($symb))[2]);
16030:     }
16031:     my %annotation=&Apache::lonnet::get('nohist_annotations',[$key]);
16032:     return $annotation{$key};
16033: }
16034: 
16035: sub clean_symb {
16036:     my ($symb,$delete_enc) = @_;
16037: 
16038:     &Apache::lonenc::check_decrypt(\$symb);
16039:     my $enc = $env{'request.enc'};
16040:     if ($delete_enc) {
16041:         delete($env{'request.enc'});
16042:     }
16043: 
16044:     return ($symb,$enc);
16045: }
16046: 
16047: ############################################################
16048: ############################################################
16049: 
16050: =pod
16051: 
16052: =head1 Routines for building display used to search for courses
16053: 
16054: 
16055: =over 4
16056: 
16057: =item * &build_filters()
16058: 
16059: Create markup for a table used to set filters to use when selecting
16060: courses in a domain.  Used by lonpickcourse.pm, lonmodifycourse.pm
16061: and quotacheck.pl
16062: 
16063: 
16064: Inputs:
16065: 
16066: filterlist - anonymous array of fields to include as potential filters 
16067: 
16068: crstype - course type
16069: 
16070: roleelement - fifth arg in selectcourse_link() populates fifth arg in javascript: opencrsbrowser() function, used
16071:               to pop-open a course selector (will contain "extra element"). 
16072: 
16073: multelement - if multiple course selections will be allowed, this will be a hidden form element: name: multiple; value: 1
16074: 
16075: filter - anonymous hash of criteria and their values
16076: 
16077: action - form action
16078: 
16079: numfiltersref - ref to scalar (count of number of elements in institutional codes -- e.g., 4 for year, semester, department, and number)
16080: 
16081: caller - caller context (e.g., set to 'modifycourse' when routine is called from lonmodifycourse.pm)
16082: 
16083: cloneruname - username of owner of new course who wants to clone
16084: 
16085: clonerudom - domain of owner of new course who wants to clone
16086: 
16087: typeelem - text to use for left column in row containing course type (i.e., Course, Community or Course/Community) 
16088: 
16089: codetitlesref - reference to array of titles of components in institutional codes (official courses)
16090: 
16091: codedom - domain
16092: 
16093: formname - value of form element named "form". 
16094: 
16095: fixeddom - domain, if fixed.
16096: 
16097: prevphase - value to assign to form element named "phase" when going back to the previous screen  
16098: 
16099: cnameelement - name of form element in form on opener page which will receive title of selected course 
16100: 
16101: cnumelement - name of form element in form on opener page which will receive courseID  of selected course
16102: 
16103: cdomelement - name of form element in form on opener page which will receive domain of selected course
16104: 
16105: setroles - includes access constraint identifier when setting a roles-based condition for acces to a portfolio file
16106: 
16107: clonetext - hidden form elements containing list of courses cloneable by intended course owner when DC creates a course
16108: 
16109: clonewarning - warning message about missing information for intended course owner when DC creates a course
16110: 
16111: 
16112: Returns: $output - HTML for display of search criteria, and hidden form elements.
16113: 
16114: 
16115: Side Effects: None
16116: 
16117: =cut
16118: 
16119: # ---------------------------------------------- search for courses based on last activity etc.
16120: 
16121: sub build_filters {
16122:     my ($filterlist,$crstype,$roleelement,$multelement,$filter,$action,
16123:         $numtitlesref,$caller,$cloneruname,$clonerudom,$typeelement,
16124:         $codetitlesref,$codedom,$formname,$fixeddom,$prevphase,
16125:         $cnameelement,$cnumelement,$cdomelement,$setroles,
16126:         $clonetext,$clonewarning) = @_;
16127:     my ($list,$jscript);
16128:     my $onchange = 'javascript:updateFilters(this)';
16129:     my ($domainselectform,$sincefilterform,$createdfilterform,
16130:         $ownerdomselectform,$persondomselectform,$instcodeform,
16131:         $typeselectform,$instcodetitle);
16132:     if ($formname eq '') {
16133:         $formname = $caller;
16134:     }
16135:     foreach my $item (@{$filterlist}) {
16136:         unless (($item eq 'descriptfilter') || ($item eq 'instcodefilter') ||
16137:                 ($item eq 'sincefilter') || ($item eq 'createdfilter')) {
16138:             if ($item eq 'domainfilter') {
16139:                 $filter->{$item} = &LONCAPA::clean_domain($filter->{$item});
16140:             } elsif ($item eq 'coursefilter') {
16141:                 $filter->{$item} = &LONCAPA::clean_courseid($filter->{$item});
16142:             } elsif ($item eq 'ownerfilter') {
16143:                 $filter->{$item} = &LONCAPA::clean_username($filter->{$item});
16144:             } elsif ($item eq 'ownerdomfilter') {
16145:                 $filter->{'ownerdomfilter'} =
16146:                     &LONCAPA::clean_domain($filter->{$item});
16147:                 $ownerdomselectform = &select_dom_form($filter->{'ownerdomfilter'},
16148:                                                        'ownerdomfilter',1);
16149:             } elsif ($item eq 'personfilter') {
16150:                 $filter->{$item} = &LONCAPA::clean_username($filter->{$item});
16151:             } elsif ($item eq 'persondomfilter') {
16152:                 $persondomselectform = &select_dom_form($filter->{'persondomfilter'},
16153:                                                         'persondomfilter',1);
16154:             } else {
16155:                 $filter->{$item} =~ s/\W//g;
16156:             }
16157:             if (!$filter->{$item}) {
16158:                 $filter->{$item} = '';
16159:             }
16160:         }
16161:         if ($item eq 'domainfilter') {
16162:             my $allow_blank = 1;
16163:             if ($formname eq 'portform') {
16164:                 $allow_blank=0;
16165:             } elsif ($formname eq 'studentform') {
16166:                 $allow_blank=0;
16167:             }
16168:             if ($fixeddom) {
16169:                 $domainselectform = '<input type="hidden" name="domainfilter"'.
16170:                                     ' value="'.$codedom.'" />'.
16171:                                     &Apache::lonnet::domain($codedom,'description');
16172:             } else {
16173:                 $domainselectform = &select_dom_form($filter->{$item},
16174:                                                      'domainfilter',
16175:                                                       $allow_blank,'',$onchange);
16176:             }
16177:         } else {
16178:             $list->{$item} = &HTML::Entities::encode($filter->{$item},'<>&"');
16179:         }
16180:     }
16181: 
16182:     # last course activity filter and selection
16183:     $sincefilterform = &timebased_select_form('sincefilter',$filter);
16184: 
16185:     # course created filter and selection
16186:     if (exists($filter->{'createdfilter'})) {
16187:         $createdfilterform = &timebased_select_form('createdfilter',$filter);
16188:     }
16189: 
16190:     my $prefix = $crstype;
16191:     if ($crstype eq 'Placement') {
16192:         $prefix = 'Placement Test'
16193:     }
16194:     my %lt = &Apache::lonlocal::texthash(
16195:                 'cac' => "$prefix Activity",
16196:                 'ccr' => "$prefix Created",
16197:                 'cde' => "$prefix Title",
16198:                 'cdo' => "$prefix Domain",
16199:                 'ins' => 'Institutional Code',
16200:                 'inc' => 'Institutional Categorization',
16201:                 'cow' => "$prefix Owner/Co-owner",
16202:                 'cop' => "$prefix Personnel Includes",
16203:                 'cog' => 'Type',
16204:              );
16205: 
16206:     if (($formname eq 'ccrs') || ($formname eq 'requestcrs')) {
16207:         my $typeval = 'Course';
16208:         if ($crstype eq 'Community') {
16209:             $typeval = 'Community';
16210:         } elsif ($crstype eq 'Placement') {
16211:             $typeval = 'Placement';
16212:         }
16213:         $typeselectform = '<input type="hidden" name="type" value="'.$typeval.'" />';
16214:     } else {
16215:         $typeselectform =  '<select name="type" size="1"';
16216:         if ($onchange) {
16217:             $typeselectform .= ' onchange="'.$onchange.'"';
16218:         }
16219:         $typeselectform .= '>'."\n";
16220:         foreach my $posstype ('Course','Community','Placement') {
16221:             my $shown;
16222:             if ($posstype eq 'Placement') {
16223:                 $shown = &mt('Placement Test');
16224:             } else {
16225:                 $shown = &mt($posstype);
16226:             }
16227:             $typeselectform.='<option value="'.$posstype.'"'.
16228:                 ($posstype eq $crstype ? ' selected="selected" ' : ''). ">".$shown."</option>\n";
16229:         }
16230:         $typeselectform.="</select>";
16231:     }
16232: 
16233:     my ($cloneableonlyform,$cloneabletitle);
16234:     if (exists($filter->{'cloneableonly'})) {
16235:         my $cloneableon = '';
16236:         my $cloneableoff = ' checked="checked"';
16237:         if ($filter->{'cloneableonly'}) {
16238:             $cloneableon = $cloneableoff;
16239:             $cloneableoff = '';
16240:         }
16241:         $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>';
16242:         if ($formname eq 'ccrs') {
16243:             $cloneabletitle = &mt('Cloneable for [_1]',$cloneruname.':'.$clonerudom);
16244:         } else {
16245:             $cloneabletitle = &mt('Cloneable by you');
16246:         }
16247:     }
16248:     my $officialjs;
16249:     if ($crstype eq 'Course') {
16250:         if (exists($filter->{'instcodefilter'})) {
16251: #            if (($fixeddom) || ($formname eq 'requestcrs') ||
16252: #                ($formname eq 'modifycourse') || ($formname eq 'filterpicker')) {
16253:             if ($codedom) { 
16254:                 $officialjs = 1;
16255:                 ($instcodeform,$jscript,$$numtitlesref) =
16256:                     &Apache::courseclassifier::instcode_selectors($codedom,'filterpicker',
16257:                                                                   $officialjs,$codetitlesref);
16258:                 if ($jscript) {
16259:                     $jscript = '<script type="text/javascript">'."\n".
16260:                                '// <![CDATA['."\n".
16261:                                $jscript."\n".
16262:                                '// ]]>'."\n".
16263:                                '</script>'."\n";
16264:                 }
16265:             }
16266:             if ($instcodeform eq '') {
16267:                 $instcodeform =
16268:                     '<input type="text" name="instcodefilter" size="10" value="'.
16269:                     $list->{'instcodefilter'}.'" />';
16270:                 $instcodetitle = $lt{'ins'};
16271:             } else {
16272:                 $instcodetitle = $lt{'inc'};
16273:             }
16274:             if ($fixeddom) {
16275:                 $instcodetitle .= '<br />('.$codedom.')';
16276:             }
16277:         }
16278:     }
16279:     my $output = qq|
16280: <form method="post" name="filterpicker" action="$action">
16281: <input type="hidden" name="form" value="$formname" />
16282: |;
16283:     if ($formname eq 'modifycourse') {
16284:         $output .= '<input type="hidden" name="phase" value="courselist" />'."\n".
16285:                    '<input type="hidden" name="prevphase" value="'.
16286:                    $prevphase.'" />'."\n";
16287:     } elsif ($formname eq 'quotacheck') {
16288:         $output .= qq|
16289: <input type="hidden" name="sortby" value="" />
16290: <input type="hidden" name="sortorder" value="" />
16291: |;
16292:     } else {
16293:         my $name_input;
16294:         if ($cnameelement ne '') {
16295:             $name_input = '<input type="hidden" name="cnameelement" value="'.
16296:                           $cnameelement.'" />';
16297:         }
16298:         $output .= qq|
16299: <input type="hidden" name="cnumelement" value="$cnumelement" />
16300: <input type="hidden" name="cdomelement" value="$cdomelement" />
16301: $name_input
16302: $roleelement
16303: $multelement
16304: $typeelement
16305: |;
16306:         if ($formname eq 'portform') {
16307:             $output .= '<input type="hidden" name="setroles" value="'.$setroles.'" />'."\n";
16308:         }
16309:     }
16310:     if ($fixeddom) {
16311:         $output .= '<input type="hidden" name="fixeddom" value="'.$fixeddom.'" />'."\n";
16312:     }
16313:     $output .= "<br />\n".&Apache::lonhtmlcommon::start_pick_box();
16314:     if ($sincefilterform) {
16315:         $output .= &Apache::lonhtmlcommon::row_title($lt{'cac'})
16316:                   .$sincefilterform
16317:                   .&Apache::lonhtmlcommon::row_closure();
16318:     }
16319:     if ($createdfilterform) {
16320:         $output .= &Apache::lonhtmlcommon::row_title($lt{'ccr'})
16321:                   .$createdfilterform
16322:                   .&Apache::lonhtmlcommon::row_closure();
16323:     }
16324:     if ($domainselectform) {
16325:         $output .= &Apache::lonhtmlcommon::row_title($lt{'cdo'})
16326:                   .$domainselectform
16327:                   .&Apache::lonhtmlcommon::row_closure();
16328:     }
16329:     if ($typeselectform) {
16330:         if (($formname eq 'ccrs') || ($formname eq 'requestcrs')) {
16331:             $output .= $typeselectform;
16332:         } else {
16333:             $output .= &Apache::lonhtmlcommon::row_title($lt{'cog'})
16334:                       .$typeselectform
16335:                       .&Apache::lonhtmlcommon::row_closure();
16336:         }
16337:     }
16338:     if ($instcodeform) {
16339:         $output .= &Apache::lonhtmlcommon::row_title($instcodetitle)
16340:                   .$instcodeform
16341:                   .&Apache::lonhtmlcommon::row_closure();
16342:     }
16343:     if (exists($filter->{'ownerfilter'})) {
16344:         $output .= &Apache::lonhtmlcommon::row_title($lt{'cow'}).
16345:                    '<table><tr><td>'.&mt('Username').'<br />'.
16346:                    '<input type="text" name="ownerfilter" size="20" value="'.
16347:                    $list->{'ownerfilter'}.'" /></td><td>'.&mt('Domain').'<br />'.
16348:                    $ownerdomselectform.'</td></tr></table>'.
16349:                    &Apache::lonhtmlcommon::row_closure();
16350:     }
16351:     if (exists($filter->{'personfilter'})) {
16352:         $output .= &Apache::lonhtmlcommon::row_title($lt{'cop'}).
16353:                    '<table><tr><td>'.&mt('Username').'<br />'.
16354:                    '<input type="text" name="personfilter" size="20" value="'.
16355:                    $list->{'personfilter'}.'" /></td><td>'.&mt('Domain').'<br />'.
16356:                    $persondomselectform.'</td></tr></table>'.
16357:                    &Apache::lonhtmlcommon::row_closure();
16358:     }
16359:     if (exists($filter->{'coursefilter'})) {
16360:         $output .= &Apache::lonhtmlcommon::row_title(&mt('LON-CAPA course ID'))
16361:                   .'<input type="text" name="coursefilter" size="25" value="'
16362:                   .$list->{'coursefilter'}.'" />'
16363:                   .&Apache::lonhtmlcommon::row_closure();
16364:     }
16365:     if ($cloneableonlyform) {
16366:         $output .= &Apache::lonhtmlcommon::row_title($cloneabletitle).
16367:                    $cloneableonlyform.&Apache::lonhtmlcommon::row_closure();
16368:     }
16369:     if (exists($filter->{'descriptfilter'})) {
16370:         $output .= &Apache::lonhtmlcommon::row_title($lt{'cde'})
16371:                   .'<input type="text" name="descriptfilter" size="40" value="'
16372:                   .$list->{'descriptfilter'}.'" />'
16373:                   .&Apache::lonhtmlcommon::row_closure(1);
16374:     }
16375:     $output .= &Apache::lonhtmlcommon::end_pick_box().'<p>'.$clonetext."\n".
16376:                '<input type="hidden" name="updater" value="" />'."\n".
16377:                '<input type="submit" name="gosearch" value="'.
16378:                &mt('Search').'" /></p>'."\n".'</form>'."\n".'<hr />'."\n";
16379:     return $jscript.$clonewarning.$output;
16380: }
16381: 
16382: =pod 
16383: 
16384: =item * &timebased_select_form()
16385: 
16386: Create markup for a dropdown list used to select a time-based
16387: filter e.g., Course Activity, Course Created, when searching for courses
16388: or communities
16389: 
16390: Inputs:
16391: 
16392: item - name of form element (sincefilter or createdfilter)
16393: 
16394: filter - anonymous hash of criteria and their values
16395: 
16396: Returns: HTML for a select box contained a blank, then six time selections,
16397:          with value set in incoming form variables currently selected. 
16398: 
16399: Side Effects: None
16400: 
16401: =cut
16402: 
16403: sub timebased_select_form {
16404:     my ($item,$filter) = @_;
16405:     if (ref($filter) eq 'HASH') {
16406:         $filter->{$item} =~ s/[^\d-]//g;
16407:         if (!$filter->{$item}) { $filter->{$item}=-1; }
16408:         return &select_form(
16409:                             $filter->{$item},
16410:                             $item,
16411:                             {      '-1' => '',
16412:                                 '86400' => &mt('today'),
16413:                                '604800' => &mt('last week'),
16414:                               '2592000' => &mt('last month'),
16415:                               '7776000' => &mt('last three months'),
16416:                              '15552000' => &mt('last six months'),
16417:                              '31104000' => &mt('last year'),
16418:                     'select_form_order' =>
16419:                            ['-1','86400','604800','2592000','7776000',
16420:                             '15552000','31104000']});
16421:     }
16422: }
16423: 
16424: =pod
16425: 
16426: =item * &js_changer()
16427: 
16428: Create script tag containing Javascript used to submit course search form
16429: when course type or domain is changed, and also to hide 'Searching ...' on
16430: page load completion for page showing search result.
16431: 
16432: Inputs: None
16433: 
16434: Returns: markup containing updateFilters() and hideSearching() javascript functions. 
16435: 
16436: Side Effects: None
16437: 
16438: =cut
16439: 
16440: sub js_changer {
16441:     return <<ENDJS;
16442: <script type="text/javascript">
16443: // <![CDATA[
16444: function updateFilters(caller) {
16445:     if (typeof(caller) != "undefined") {
16446:         document.filterpicker.updater.value = caller.name;
16447:     }
16448:     document.filterpicker.submit();
16449: }
16450: 
16451: function hideSearching() {
16452:     if (document.getElementById('searching')) {
16453:         document.getElementById('searching').style.display = 'none';
16454:     }
16455:     return;
16456: }
16457: 
16458: // ]]>
16459: </script>
16460: 
16461: ENDJS
16462: }
16463: 
16464: =pod
16465: 
16466: =item * &search_courses()
16467: 
16468: Process selected filters form course search form and pass to lonnet::courseiddump
16469: to retrieve a hash for which keys are courseIDs which match the selected filters.
16470: 
16471: Inputs:
16472: 
16473: dom - domain being searched 
16474: 
16475: type - course type ('Course' or 'Community' or '.' if any).
16476: 
16477: filter - anonymous hash of criteria and their values
16478: 
16479: numtitles - for institutional codes - number of categories
16480: 
16481: cloneruname - optional username of new course owner
16482: 
16483: clonerudom - optional domain of new course owner
16484: 
16485: domcloner - optional "domcloner" flag; has value=1 if user has ccc priv in domain being filtered by, 
16486:             (used when DC is using course creation form)
16487: 
16488: codetitles - reference to array of titles of components in institutional codes (official courses).
16489: 
16490: cc_clone - escaped comma separated list of courses for which course cloner has active CC role
16491:            (and so can clone automatically)
16492: 
16493: reqcrsdom - domain of new course, where search_courses is used to identify potential courses to clone
16494: 
16495: reqinstcode - institutional code of new course, where search_courses is used to identify potential 
16496:               courses to clone 
16497: 
16498: Returns: %courses - hash of courses satisfying search criteria, keys = course IDs, values are corresponding colon-separated escaped description, institutional code, owner and type.
16499: 
16500: 
16501: Side Effects: None
16502: 
16503: =cut
16504: 
16505: 
16506: sub search_courses {
16507:     my ($dom,$type,$filter,$numtitles,$cloneruname,$clonerudom,$domcloner,$codetitles,
16508:         $cc_clone,$reqcrsdom,$reqinstcode) = @_;
16509:     my (%courses,%showcourses,$cloner);
16510:     if (($filter->{'ownerfilter'} ne '') ||
16511:         ($filter->{'ownerdomfilter'} ne '')) {
16512:         $filter->{'combownerfilter'} = $filter->{'ownerfilter'}.':'.
16513:                                        $filter->{'ownerdomfilter'};
16514:     }
16515:     foreach my $item ('descriptfilter','coursefilter','combownerfilter') {
16516:         if (!$filter->{$item}) {
16517:             $filter->{$item}='.';
16518:         }
16519:     }
16520:     my $now = time;
16521:     my $timefilter =
16522:        ($filter->{'sincefilter'}==-1?1:$now-$filter->{'sincefilter'});
16523:     my ($createdbefore,$createdafter);
16524:     if (($filter->{'createdfilter'} ne '') && ($filter->{'createdfilter'} !=-1)) {
16525:         $createdbefore = $now;
16526:         $createdafter = $now-$filter->{'createdfilter'};
16527:     }
16528:     my ($instcodefilter,$regexpok);
16529:     if ($numtitles) {
16530:         if ($env{'form.official'} eq 'on') {
16531:             $instcodefilter =
16532:                 &Apache::courseclassifier::instcode_search_str($dom,$numtitles,$codetitles);
16533:             $regexpok = 1;
16534:         } elsif ($env{'form.official'} eq 'off') {
16535:             $instcodefilter = &Apache::courseclassifier::instcode_search_str($dom,$numtitles,$codetitles);
16536:             unless ($instcodefilter eq '') {
16537:                 $regexpok = -1;
16538:             }
16539:         }
16540:     } else {
16541:         $instcodefilter = $filter->{'instcodefilter'};
16542:     }
16543:     if ($instcodefilter eq '') { $instcodefilter = '.'; }
16544:     if ($type eq '') { $type = '.'; }
16545: 
16546:     if (($clonerudom ne '') && ($cloneruname ne '')) {
16547:         $cloner = $cloneruname.':'.$clonerudom;
16548:     }
16549:     %courses = &Apache::lonnet::courseiddump($dom,
16550:                                              $filter->{'descriptfilter'},
16551:                                              $timefilter,
16552:                                              $instcodefilter,
16553:                                              $filter->{'combownerfilter'},
16554:                                              $filter->{'coursefilter'},
16555:                                              undef,undef,$type,$regexpok,undef,undef,
16556:                                              undef,undef,$cloner,$cc_clone,
16557:                                              $filter->{'cloneableonly'},
16558:                                              $createdbefore,$createdafter,undef,
16559:                                              $domcloner,undef,$reqcrsdom,$reqinstcode);
16560:     if (($filter->{'personfilter'} ne '') && ($filter->{'persondomfilter'} ne '')) {
16561:         my $ccrole;
16562:         if ($type eq 'Community') {
16563:             $ccrole = 'co';
16564:         } else {
16565:             $ccrole = 'cc';
16566:         }
16567:         my %rolehash = &Apache::lonnet::get_my_roles($filter->{'personfilter'},
16568:                                                      $filter->{'persondomfilter'},
16569:                                                      'userroles',undef,
16570:                                                      [$ccrole,'in','ad','ep','ta','cr'],
16571:                                                      $dom);
16572:         foreach my $role (keys(%rolehash)) {
16573:             my ($cnum,$cdom,$courserole) = split(':',$role);
16574:             my $cid = $cdom.'_'.$cnum;
16575:             if (exists($courses{$cid})) {
16576:                 if (ref($courses{$cid}) eq 'HASH') {
16577:                     if (ref($courses{$cid}{roles}) eq 'ARRAY') {
16578:                         if (!grep(/^\Q$courserole\E$/,@{$courses{$cid}{roles}})) {
16579:                             push (@{$courses{$cid}{roles}},$courserole);
16580:                         }
16581:                     } else {
16582:                         $courses{$cid}{roles} = [$courserole];
16583:                     }
16584:                     $showcourses{$cid} = $courses{$cid};
16585:                 }
16586:             }
16587:         }
16588:         %courses = %showcourses;
16589:     }
16590:     return %courses;
16591: }
16592: 
16593: =pod
16594: 
16595: =back
16596: 
16597: =head1 Routines for version requirements for current course.
16598: 
16599: =over 4
16600: 
16601: =item * &check_release_required()
16602: 
16603: Compares required LON-CAPA version with version on server, and
16604: if required version is newer looks for a server with the required version.
16605: 
16606: Looks first at servers in user's owen domain; if none suitable, looks at
16607: servers in course's domain are permitted to host sessions for user's domain.
16608: 
16609: Inputs:
16610: 
16611: $loncaparev - Version on current server (format: Major.Minor.Subrelease-datestamp)
16612: 
16613: $courseid - Course ID of current course
16614: 
16615: $rolecode - User's current role in course (for switchserver query string).
16616: 
16617: $required - LON-CAPA version needed by course (format: Major.Minor).
16618: 
16619: 
16620: Returns:
16621: 
16622: $switchserver - query string tp append to /adm/switchserver call (if 
16623:                 current server's LON-CAPA version is too old. 
16624: 
16625: $warning - Message is displayed if no suitable server could be found.
16626: 
16627: =cut
16628: 
16629: sub check_release_required {
16630:     my ($loncaparev,$courseid,$rolecode,$required) = @_;
16631:     my ($switchserver,$warning);
16632:     if ($required ne '') {
16633:         my ($reqdmajor,$reqdminor) = ($required =~ /^(\d+)\.(\d+)$/);
16634:         my ($major,$minor) = ($loncaparev =~ /^\'?(\d+)\.(\d+)\.[\w.\-]+\'?$/);
16635:         if ($reqdmajor ne '' && $reqdminor ne '') {
16636:             my $otherserver;
16637:             if (($major eq '' && $minor eq '') ||
16638:                 (($reqdmajor > $major) || (($reqdmajor == $major) && ($reqdminor > $minor)))) {
16639:                 my ($userdomserver) = &Apache::lonnet::choose_server($env{'user.domain'},undef,$required,1);
16640:                 my $switchlcrev =
16641:                     &Apache::lonnet::get_server_loncaparev($env{'user.domain'},
16642:                                                            $userdomserver);
16643:                 my ($swmajor,$swminor) = ($switchlcrev =~ /^\'?(\d+)\.(\d+)\.[\w.\-]+\'?$/);
16644:                 if (($swmajor eq '' && $swminor eq '') || ($reqdmajor > $swmajor) ||
16645:                     (($reqdmajor == $swmajor) && ($reqdminor > $swminor))) {
16646:                     my $cdom = $env{'course.'.$courseid.'.domain'};
16647:                     if ($cdom ne $env{'user.domain'}) {
16648:                         my ($coursedomserver,$coursehostname) = &Apache::lonnet::choose_server($cdom,undef,$required,1);
16649:                         my $serverhomeID = &Apache::lonnet::get_server_homeID($coursehostname);
16650:                         my $serverhomedom = &Apache::lonnet::host_domain($serverhomeID);
16651:                         my %defdomdefaults = &Apache::lonnet::get_domain_defaults($serverhomedom);
16652:                         my %udomdefaults = &Apache::lonnet::get_domain_defaults($env{'user.domain'});
16653:                         my $remoterev = &Apache::lonnet::get_server_loncaparev($serverhomedom,$coursedomserver);
16654:                         my $canhost =
16655:                             &Apache::lonnet::can_host_session($env{'user.domain'},
16656:                                                               $coursedomserver,
16657:                                                               $remoterev,
16658:                                                               $udomdefaults{'remotesessions'},
16659:                                                               $defdomdefaults{'hostedsessions'});
16660: 
16661:                         if ($canhost) {
16662:                             $otherserver = $coursedomserver;
16663:                         } else {
16664:                             $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.");
16665:                         }
16666:                     } else {
16667:                         $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).");
16668:                     }
16669:                 } else {
16670:                     $otherserver = $userdomserver;
16671:                 }
16672:             }
16673:             if ($otherserver ne '') {
16674:                 $switchserver = 'otherserver='.$otherserver.'&amp;role='.$rolecode;
16675:             }
16676:         }
16677:     }
16678:     return ($switchserver,$warning);
16679: }
16680: 
16681: =pod
16682: 
16683: =item * &check_release_result()
16684: 
16685: Inputs:
16686: 
16687: $switchwarning - Warning message if no suitable server found to host session.
16688: 
16689: $switchserver - query string to append to /adm/switchserver containing lonHostID
16690:                 and current role.
16691: 
16692: Returns: HTML to display with information about requirement to switch server.
16693:          Either displaying warning with link to Roles/Courses screen or
16694:          display link to switchserver.
16695: 
16696: =cut
16697: 
16698: sub check_release_result {
16699:     my ($switchwarning,$switchserver) = @_;
16700:     my $output = &start_page('Selected course unavailable on this server').
16701:                  '<p class="LC_warning">';
16702:     if ($switchwarning) {
16703:         $output .= $switchwarning.'<br /><a href="/adm/roles">';
16704:         if (&show_course()) {
16705:             $output .= &mt('Display courses');
16706:         } else {
16707:             $output .= &mt('Display roles');
16708:         }
16709:         $output .= '</a>';
16710:     } elsif ($switchserver) {
16711:         $output .= &mt('This course requires a newer version of LON-CAPA than is installed on this server.').
16712:                    '<br />'.
16713:                    '<a href="/adm/switchserver?'.$switchserver.'">'.
16714:                    &mt('Switch Server').
16715:                    '</a>';
16716:     }
16717:     $output .= '</p>'.&end_page();
16718:     return $output;
16719: }
16720: 
16721: =pod
16722: 
16723: =item * &needs_coursereinit()
16724: 
16725: Determine if course contents stored for user's session needs to be
16726: refreshed, because content has changed since "Big Hash" last tied.
16727: 
16728: Check for change is made if time last checked is more than 10 minutes ago
16729: (by default).
16730: 
16731: Inputs:
16732: 
16733: $loncaparev - Version on current server (format: Major.Minor.Subrelease-datestamp)
16734: 
16735: $interval (optional) - Time which may elapse (in s) between last check for content
16736:                        change in current course. (default: 600 s).  
16737: 
16738: Returns: an array; first element is:
16739: 
16740: =over 4
16741: 
16742: 'switch' - if content updates mean user's session
16743:            needs to be switched to a server running a newer LON-CAPA version
16744:  
16745: 'update' - if course session needs to be refreshed (i.e., Big Hash needs to be reloaded)
16746:            on current server hosting user's session                
16747: 
16748: ''       - if no action required.
16749: 
16750: =back
16751: 
16752: If first item element is 'switch':
16753: 
16754: second item is $switchwarning - Warning message if no suitable server found to host session. 
16755: 
16756: third item is $switchserver - query string to append to /adm/switchserver containing lonHostID
16757:                               and current role. 
16758: 
16759: otherwise: no other elements returned.
16760: 
16761: =back
16762: 
16763: =cut
16764: 
16765: sub needs_coursereinit {
16766:     my ($loncaparev,$interval) = @_;
16767:     return() unless ($env{'request.course.id'} && $env{'request.course.tied'});
16768:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
16769:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
16770:     my $now = time;
16771:     if ($interval eq '') {
16772:         $interval = 600;
16773:     }
16774:     if (($now-$env{'request.course.timechecked'})>$interval) {
16775:         my $lastchange = &Apache::lonnet::get_coursechange($cdom,$cnum);
16776:         &Apache::lonnet::appenv({'request.course.timechecked'=>$now});
16777:         if ($lastchange > $env{'request.course.tied'}) {
16778:             my %curr_reqd_hash = &Apache::lonnet::userenvironment($cdom,$cnum,'internal.releaserequired');
16779:             if ($curr_reqd_hash{'internal.releaserequired'} ne '') {
16780:                 my $required = $env{'course.'.$cdom.'_'.$cnum.'.internal.releaserequired'};
16781:                 if ($curr_reqd_hash{'internal.releaserequired'} ne $required) {
16782:                     &Apache::lonnet::appenv({'course.'.$cdom.'_'.$cnum.'.internal.releaserequired' =>
16783:                                              $curr_reqd_hash{'internal.releaserequired'}});
16784:                     my ($switchserver,$switchwarning) =
16785:                         &check_release_required($loncaparev,$cdom.'_'.$cnum,$env{'request.role'},
16786:                                                 $curr_reqd_hash{'internal.releaserequired'});
16787:                     if ($switchwarning ne '' || $switchserver ne '') {
16788:                         return ('switch',$switchwarning,$switchserver);
16789:                     }
16790:                 }
16791:             }
16792:             return ('update');
16793:         }
16794:     }
16795:     return ();
16796: }
16797: 
16798: sub update_content_constraints {
16799:     my ($cdom,$cnum,$chome,$cid) = @_;
16800:     my %curr_reqd_hash = &Apache::lonnet::userenvironment($cdom,$cnum,'internal.releaserequired');
16801:     my ($reqdmajor,$reqdminor) = split(/\./,$curr_reqd_hash{'internal.releaserequired'});
16802:     my %checkresponsetypes;
16803:     foreach my $key (keys(%Apache::lonnet::needsrelease)) {
16804:         my ($item,$name,$value) = split(/:/,$key);
16805:         if ($item eq 'resourcetag') {
16806:             if ($name eq 'responsetype') {
16807:                 $checkresponsetypes{$value} = $Apache::lonnet::needsrelease{$key}
16808:             }
16809:         }
16810:     }
16811:     my $navmap = Apache::lonnavmaps::navmap->new();
16812:     if (defined($navmap)) {
16813:         my %allresponses;
16814:         foreach my $res ($navmap->retrieveResources(undef,sub { $_[0]->is_problem() },1,0)) {
16815:             my %responses = $res->responseTypes();
16816:             foreach my $key (keys(%responses)) {
16817:                 next unless(exists($checkresponsetypes{$key}));
16818:                 $allresponses{$key} += $responses{$key};
16819:             }
16820:         }
16821:         foreach my $key (keys(%allresponses)) {
16822:             my ($major,$minor) = split(/\./,$checkresponsetypes{$key});
16823:             if (($major > $reqdmajor) || ($major == $reqdmajor && $minor > $reqdminor)) {
16824:                 ($reqdmajor,$reqdminor) = ($major,$minor);
16825:             }
16826:         }
16827:         undef($navmap);
16828:     }
16829:     unless (($reqdmajor eq '') && ($reqdminor eq '')) {
16830:         &Apache::lonnet::update_released_required($reqdmajor.'.'.$reqdminor,$cdom,$cnum,$chome,$cid);
16831:     }
16832:     return;
16833: }
16834: 
16835: sub allmaps_incourse {
16836:     my ($cdom,$cnum,$chome,$cid) = @_;
16837:     if ($cdom eq '' || $cnum eq '' || $chome eq '' || $cid eq '') {
16838:         $cid = $env{'request.course.id'};
16839:         $cdom = $env{'course.'.$cid.'.domain'};
16840:         $cnum = $env{'course.'.$cid.'.num'};
16841:         $chome = $env{'course.'.$cid.'.home'};
16842:     }
16843:     my %allmaps = ();
16844:     my $lastchange =
16845:         &Apache::lonnet::get_coursechange($cdom,$cnum);
16846:     if ($lastchange > $env{'request.course.tied'}) {
16847:         my ($furl,$ferr) = &Apache::lonuserstate::readmap("$cdom/$cnum");
16848:         unless ($ferr) {
16849:             &update_content_constraints($cdom,$cnum,$chome,$cid);
16850:         }
16851:     }
16852:     my $navmap = Apache::lonnavmaps::navmap->new();
16853:     if (defined($navmap)) {
16854:         foreach my $res ($navmap->retrieveResources(undef,sub { $_[0]->is_map() },1,0,1)) {
16855:             $allmaps{$res->src()} = 1;
16856:         }
16857:     }
16858:     return \%allmaps;
16859: }
16860: 
16861: sub parse_supplemental_title {
16862:     my ($title) = @_;
16863: 
16864:     my ($foldertitle,$renametitle);
16865:     if ($title =~ /&amp;&amp;&amp;/) {
16866:         $title = &HTML::Entites::decode($title);
16867:     }
16868:     if ($title =~ m/^(\d+)___&&&___($match_username)___&&&___($match_domain)___&&&___(.*)$/) {
16869:         $renametitle=$4;
16870:         my ($time,$uname,$udom) = ($1,$2,$3);
16871:         $foldertitle=&Apache::lontexconvert::msgtexconverted($4);
16872:         my $name =  &plainname($uname,$udom);
16873:         $name = &HTML::Entities::encode($name,'"<>&\'');
16874:         $renametitle = &HTML::Entities::encode($renametitle,'"<>&\'');
16875:         $title='<i>'.&Apache::lonlocal::locallocaltime($time).'</i> '.
16876:             $name.': <br />'.$foldertitle;
16877:     }
16878:     if (wantarray) {
16879:         return ($title,$foldertitle,$renametitle);
16880:     }
16881:     return $title;
16882: }
16883: 
16884: sub recurse_supplemental {
16885:     my ($cnum,$cdom,$suppmap,$numfiles,$errors) = @_;
16886:     if ($suppmap) {
16887:         my ($errtext,$fatal) = &LONCAPA::map::mapread('/uploaded/'.$cdom.'/'.$cnum.'/'.$suppmap);
16888:         if ($fatal) {
16889:             $errors ++;
16890:         } else {
16891:             if ($#LONCAPA::map::resources > 0) {
16892:                 foreach my $res (@LONCAPA::map::resources) {
16893:                     my ($title,$src,$ext,$type,$status)=split(/\:/,$res);
16894:                     if (($src ne '') && ($status eq 'res')) {
16895:                         if ($src =~ m{^\Q/uploaded/$cdom/$cnum/\E(supplemental_\d+\.sequence)$}) {
16896:                             ($numfiles,$errors) = &recurse_supplemental($cnum,$cdom,$1,$numfiles,$errors);
16897:                         } else {
16898:                             $numfiles ++;
16899:                         }
16900:                     }
16901:                 }
16902:             }
16903:         }
16904:     }
16905:     return ($numfiles,$errors);
16906: }
16907: 
16908: sub symb_to_docspath {
16909:     my ($symb) = @_;
16910:     return unless ($symb);
16911:     my ($mapurl,$id,$resurl) = &Apache::lonnet::decode_symb($symb);
16912:     if ($resurl=~/\.(sequence|page)$/) {
16913:         $mapurl=$resurl;
16914:     } elsif ($resurl eq 'adm/navmaps') {
16915:         $mapurl=$env{'course.'.$env{'request.course.id'}.'.url'};
16916:     }
16917:     my $mapresobj;
16918:     my $navmap = Apache::lonnavmaps::navmap->new();
16919:     if (ref($navmap)) {
16920:         $mapresobj = $navmap->getResourceByUrl($mapurl);
16921:     }
16922:     $mapurl=~s{^.*/([^/]+)\.(\w+)$}{$1};
16923:     my $type=$2;
16924:     my $path;
16925:     if (ref($mapresobj)) {
16926:         my $pcslist = $mapresobj->map_hierarchy();
16927:         if ($pcslist ne '') {
16928:             foreach my $pc (split(/,/,$pcslist)) {
16929:                 next if ($pc <= 1);
16930:                 my $res = $navmap->getByMapPc($pc);
16931:                 if (ref($res)) {
16932:                     my $thisurl = $res->src();
16933:                     $thisurl=~s{^.*/([^/]+)\.\w+$}{$1};
16934:                     my $thistitle = $res->title();
16935:                     $path .= '&'.
16936:                              &Apache::lonhtmlcommon::entity_encode($thisurl).'&'.
16937:                              &escape($thistitle).
16938:                              ':'.$res->randompick().
16939:                              ':'.$res->randomout().
16940:                              ':'.$res->encrypted().
16941:                              ':'.$res->randomorder().
16942:                              ':'.$res->is_page();
16943:                 }
16944:             }
16945:         }
16946:         $path =~ s/^\&//;
16947:         my $maptitle = $mapresobj->title();
16948:         if ($mapurl eq 'default') {
16949:             $maptitle = 'Main Content';
16950:         }
16951:         $path .= (($path ne '')? '&' : '').
16952:                  &Apache::lonhtmlcommon::entity_encode($mapurl).'&'.
16953:                  &escape($maptitle).
16954:                  ':'.$mapresobj->randompick().
16955:                  ':'.$mapresobj->randomout().
16956:                  ':'.$mapresobj->encrypted().
16957:                  ':'.$mapresobj->randomorder().
16958:                  ':'.$mapresobj->is_page();
16959:     } else {
16960:         my $maptitle = &Apache::lonnet::gettitle($mapurl);
16961:         my $ispage = (($type eq 'page')? 1 : '');
16962:         if ($mapurl eq 'default') {
16963:             $maptitle = 'Main Content';
16964:         }
16965:         $path = &Apache::lonhtmlcommon::entity_encode($mapurl).'&'.
16966:                 &escape($maptitle).':::::'.$ispage;
16967:     }
16968:     unless ($mapurl eq 'default') {
16969:         $path = 'default&'.
16970:                 &escape('Main Content').
16971:                 ':::::&'.$path;
16972:     }
16973:     return $path;
16974: }
16975: 
16976: sub captcha_display {
16977:     my ($context,$lonhost) = @_;
16978:     my ($output,$error);
16979:     my ($captcha,$pubkey,$privkey,$version) = 
16980:         &get_captcha_config($context,$lonhost);
16981:     if ($captcha eq 'original') {
16982:         $output = &create_captcha();
16983:         unless ($output) {
16984:             $error = 'captcha';
16985:         }
16986:     } elsif ($captcha eq 'recaptcha') {
16987:         $output = &create_recaptcha($pubkey,$version);
16988:         unless ($output) {
16989:             $error = 'recaptcha';
16990:         }
16991:     }
16992:     return ($output,$error,$captcha,$version);
16993: }
16994: 
16995: sub captcha_response {
16996:     my ($context,$lonhost) = @_;
16997:     my ($captcha_chk,$captcha_error);
16998:     my ($captcha,$pubkey,$privkey,$version) = &get_captcha_config($context,$lonhost);
16999:     if ($captcha eq 'original') {
17000:         ($captcha_chk,$captcha_error) = &check_captcha();
17001:     } elsif ($captcha eq 'recaptcha') {
17002:         $captcha_chk = &check_recaptcha($privkey,$version);
17003:     } else {
17004:         $captcha_chk = 1;
17005:     }
17006:     return ($captcha_chk,$captcha_error);
17007: }
17008: 
17009: sub get_captcha_config {
17010:     my ($context,$lonhost) = @_;
17011:     my ($captcha,$pubkey,$privkey,$version,$hashtocheck);
17012:     my $hostname = &Apache::lonnet::hostname($lonhost);
17013:     my $serverhomeID = &Apache::lonnet::get_server_homeID($hostname);
17014:     my $serverhomedom = &Apache::lonnet::host_domain($serverhomeID);
17015:     if ($context eq 'usercreation') {
17016:         my %domconfig = &Apache::lonnet::get_dom('configuration',[$context],$serverhomedom);
17017:         if (ref($domconfig{$context}) eq 'HASH') {
17018:             $hashtocheck = $domconfig{$context}{'cancreate'};
17019:             if (ref($hashtocheck) eq 'HASH') {
17020:                 if ($hashtocheck->{'captcha'} eq 'recaptcha') {
17021:                     if (ref($hashtocheck->{'recaptchakeys'}) eq 'HASH') {
17022:                         $pubkey = $hashtocheck->{'recaptchakeys'}{'public'};
17023:                         $privkey = $hashtocheck->{'recaptchakeys'}{'private'};
17024:                     }
17025:                     if ($privkey && $pubkey) {
17026:                         $captcha = 'recaptcha';
17027:                         $version = $hashtocheck->{'recaptchaversion'};
17028:                         if ($version ne '2') {
17029:                             $version = 1;
17030:                         }
17031:                     } else {
17032:                         $captcha = 'original';
17033:                     }
17034:                 } elsif ($hashtocheck->{'captcha'} ne 'notused') {
17035:                     $captcha = 'original';
17036:                 }
17037:             }
17038:         } else {
17039:             $captcha = 'captcha';
17040:         }
17041:     } elsif ($context eq 'login') {
17042:         my %domconfhash = &Apache::loncommon::get_domainconf($serverhomedom);
17043:         if ($domconfhash{$serverhomedom.'.login.captcha'} eq 'recaptcha') {
17044:             $pubkey = $domconfhash{$serverhomedom.'.login.recaptchakeys_public'};
17045:             $privkey = $domconfhash{$serverhomedom.'.login.recaptchakeys_private'};
17046:             if ($privkey && $pubkey) {
17047:                 $captcha = 'recaptcha';
17048:                 $version = $domconfhash{$serverhomedom.'.login.recaptchaversion'};
17049:                 if ($version ne '2') {
17050:                     $version = 1; 
17051:                 }
17052:             } else {
17053:                 $captcha = 'original';
17054:             }
17055:         } elsif ($domconfhash{$serverhomedom.'.login.captcha'} eq 'original') {
17056:             $captcha = 'original';
17057:         }
17058:     }
17059:     return ($captcha,$pubkey,$privkey,$version);
17060: }
17061: 
17062: sub create_captcha {
17063:     my %captcha_params = &captcha_settings();
17064:     my ($output,$maxtries,$tries) = ('',10,0);
17065:     while ($tries < $maxtries) {
17066:         $tries ++;
17067:         my $captcha = Authen::Captcha->new (
17068:                                            output_folder => $captcha_params{'output_dir'},
17069:                                            data_folder   => $captcha_params{'db_dir'},
17070:                                           );
17071:         my $md5sum = $captcha->generate_code($captcha_params{'numchars'});
17072: 
17073:         if (-e $Apache::lonnet::perlvar{'lonCaptchaDir'}.'/'.$md5sum.'.png') {
17074:             $output = '<input type="hidden" name="crypt" value="'.$md5sum.'" />'."\n".
17075:                       &mt('Type in the letters/numbers shown below').'&nbsp;'.
17076:                       '<input type="text" size="5" name="code" value="" autocomplete="off" />'.
17077:                       '<br />'.
17078:                       '<img src="'.$captcha_params{'www_output_dir'}.'/'.$md5sum.'.png" alt="captcha" />';
17079:             last;
17080:         }
17081:     }
17082:     return $output;
17083: }
17084: 
17085: sub captcha_settings {
17086:     my %captcha_params = (
17087:                            output_dir     => $Apache::lonnet::perlvar{'lonCaptchaDir'},
17088:                            www_output_dir => "/captchaspool",
17089:                            db_dir         => $Apache::lonnet::perlvar{'lonCaptchaDb'},
17090:                            numchars       => '5',
17091:                          );
17092:     return %captcha_params;
17093: }
17094: 
17095: sub check_captcha {
17096:     my ($captcha_chk,$captcha_error);
17097:     my $code = $env{'form.code'};
17098:     my $md5sum = $env{'form.crypt'};
17099:     my %captcha_params = &captcha_settings();
17100:     my $captcha = Authen::Captcha->new(
17101:                       output_folder => $captcha_params{'output_dir'},
17102:                       data_folder   => $captcha_params{'db_dir'},
17103:                   );
17104:     $captcha_chk = $captcha->check_code($code,$md5sum);
17105:     my %captcha_hash = (
17106:                         0       => 'Code not checked (file error)',
17107:                        -1      => 'Failed: code expired',
17108:                        -2      => 'Failed: invalid code (not in database)',
17109:                        -3      => 'Failed: invalid code (code does not match crypt)',
17110:     );
17111:     if ($captcha_chk != 1) {
17112:         $captcha_error = $captcha_hash{$captcha_chk}
17113:     }
17114:     return ($captcha_chk,$captcha_error);
17115: }
17116: 
17117: sub create_recaptcha {
17118:     my ($pubkey,$version) = @_;
17119:     if ($version >= 2) {
17120:         return '<div class="g-recaptcha" data-sitekey="'.$pubkey.'"></div>';
17121:     } else {
17122:         my $use_ssl;
17123:         if ($ENV{'SERVER_PORT'} == 443) {
17124:             $use_ssl = 1;
17125:         }
17126:         my $captcha = Captcha::reCAPTCHA->new;
17127:         return $captcha->get_options_setter({theme => 'white'})."\n".
17128:                $captcha->get_html($pubkey,undef,$use_ssl).
17129:                &mt('If the text is hard to read, [_1] will replace them.',
17130:                    '<img src="/res/adm/pages/refresh.gif" alt="reCAPTCHA refresh" />').
17131:                '<br /><br />';
17132:     }
17133: }
17134: 
17135: sub check_recaptcha {
17136:     my ($privkey,$version) = @_;
17137:     my $captcha_chk;
17138:     if ($version >= 2) {
17139:         my $ua = LWP::UserAgent->new;
17140:         $ua->timeout(10);
17141:         my %info = (
17142:                      secret   => $privkey, 
17143:                      response => $env{'form.g-recaptcha-response'},
17144:                      remoteip => $ENV{'REMOTE_ADDR'},
17145:                    );
17146:         my $response = $ua->post('https://www.google.com/recaptcha/api/siteverify',\%info);
17147:         if ($response->is_success)  {
17148:             my $data = JSON::DWIW->from_json($response->decoded_content);
17149:             if (ref($data) eq 'HASH') {
17150:                 if ($data->{'success'}) {
17151:                     $captcha_chk = 1;
17152:                 }
17153:             }
17154:         }
17155:     } else {
17156:         my $captcha = Captcha::reCAPTCHA->new;
17157:         my $captcha_result =
17158:             $captcha->check_answer(
17159:                                     $privkey,
17160:                                     $ENV{'REMOTE_ADDR'},
17161:                                     $env{'form.recaptcha_challenge_field'},
17162:                                     $env{'form.recaptcha_response_field'},
17163:                                   );
17164:         if ($captcha_result->{is_valid}) {
17165:             $captcha_chk = 1;
17166:         }
17167:     }
17168:     return $captcha_chk;
17169: }
17170: 
17171: sub emailusername_info {
17172:     my @fields = ('firstname','lastname','institution','web','location','officialemail','id');
17173:     my %titles = &Apache::lonlocal::texthash (
17174:                      lastname      => 'Last Name',
17175:                      firstname     => 'First Name',
17176:                      institution   => 'School/college/university',
17177:                      location      => "School's city, state/province, country",
17178:                      web           => "School's web address",
17179:                      officialemail => 'E-mail address at institution (if different)',
17180:                      id            => 'Student/Employee ID',
17181:                  );
17182:     return (\@fields,\%titles);
17183: }
17184: 
17185: sub cleanup_html {
17186:     my ($incoming) = @_;
17187:     my $outgoing;
17188:     if ($incoming ne '') {
17189:         $outgoing = $incoming;
17190:         $outgoing =~ s/;/&#059;/g;
17191:         $outgoing =~ s/\#/&#035;/g;
17192:         $outgoing =~ s/\&/&#038;/g;
17193:         $outgoing =~ s/</&#060;/g;
17194:         $outgoing =~ s/>/&#062;/g;
17195:         $outgoing =~ s/\(/&#040/g;
17196:         $outgoing =~ s/\)/&#041;/g;
17197:         $outgoing =~ s/"/&#034;/g;
17198:         $outgoing =~ s/'/&#039;/g;
17199:         $outgoing =~ s/\$/&#036;/g;
17200:         $outgoing =~ s{/}{&#047;}g;
17201:         $outgoing =~ s/=/&#061;/g;
17202:         $outgoing =~ s/\\/&#092;/g
17203:     }
17204:     return $outgoing;
17205: }
17206: 
17207: # Checks for critical messages and returns a redirect url if one exists.
17208: # $interval indicates how often to check for messages.
17209: sub critical_redirect {
17210:     my ($interval) = @_;
17211:     if ((time-$env{'user.criticalcheck.time'})>$interval) {
17212:         my @what=&Apache::lonnet::dump('critical', $env{'user.domain'}, 
17213:                                         $env{'user.name'});
17214:         &Apache::lonnet::appenv({'user.criticalcheck.time'=>time});
17215:         my $redirecturl;
17216:         if ($what[0]) {
17217: 	    if (($what[0] ne 'con_lost') && ($what[0]!~/^error\:/)) {
17218: 	        $redirecturl='/adm/email?critical=display';
17219: 	        my $url=&Apache::lonnet::absolute_url().$redirecturl;
17220:                 return (1, $url);
17221:             }
17222:         }
17223:     } 
17224:     return ();
17225: }
17226: 
17227: # Use:
17228: #   my $answer=reply("encrypt:passwd:$udom:$uname:$upass",$tryserver);
17229: #
17230: ##################################################
17231: #          password associated functions         #
17232: ##################################################
17233: sub des_keys {
17234:     # Make a new key for DES encryption.
17235:     # Each key has two parts which are returned separately.
17236:     # Please note:  Each key must be passed through the &hex function
17237:     # before it is output to the web browser.  The hex versions cannot
17238:     # be used to decrypt.
17239:     my @hexstr=('0','1','2','3','4','5','6','7',
17240:                 '8','9','a','b','c','d','e','f');
17241:     my $lkey='';
17242:     for (0..7) {
17243:         $lkey.=$hexstr[rand(15)];
17244:     }
17245:     my $ukey='';
17246:     for (0..7) {
17247:         $ukey.=$hexstr[rand(15)];
17248:     }
17249:     return ($lkey,$ukey);
17250: }
17251: 
17252: sub des_decrypt {
17253:     my ($key,$cyphertext) = @_;
17254:     my $keybin=pack("H16",$key);
17255:     my $cypher;
17256:     if ($Crypt::DES::VERSION>=2.03) {
17257:         $cypher=new Crypt::DES $keybin;
17258:     } else {
17259:         $cypher=new DES $keybin;
17260:     }
17261:     my $plaintext='';
17262:     my $cypherlength = length($cyphertext);
17263:     my $numchunks = int($cypherlength/32);
17264:     for (my $j=0; $j<$numchunks; $j++) {
17265:         my $start = $j*32;
17266:         my $cypherblock = substr($cyphertext,$start,32);
17267:         my $chunk =
17268:             $cypher->decrypt(unpack("a8",pack("H16",substr($cypherblock,0,16))));
17269:         $chunk .=
17270:             $cypher->decrypt(unpack("a8",pack("H16",substr($cypherblock,16,16))));
17271:         $chunk=substr($chunk,1,ord(substr($chunk,0,1)) );
17272:         $plaintext .= $chunk;
17273:     }
17274:     return $plaintext;
17275: }
17276: 
17277: 1;
17278: __END__;
17279: 

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