File:  [LON-CAPA] / loncom / interface / loncommon.pm
Revision 1.1190: download - view: text, annotated - select for diffs
Tue May 20 20:19:08 2014 UTC (10 years ago) by musolffc
Branches: MAIN
CVS tags: HEAD
New function: critical_redirect()
Accepts an interval parameter indicating how often to check for critical
messages.  If critical messages have not been checked for within the given
interval, a check will be made and a redirect url to the critical message
will be returned if it exists.

    1: # The LearningOnline Network with CAPA
    2: # a pile of common routines
    3: #
    4: # $Id: loncommon.pm,v 1.1190 2014/05/20 20:19:08 musolffc Exp $
    5: #
    6: # Copyright Michigan State University Board of Trustees
    7: #
    8: # This file is part of the LearningOnline Network with CAPA (LON-CAPA).
    9: #
   10: # LON-CAPA is free software; you can redistribute it and/or modify
   11: # it under the terms of the GNU General Public License as published by
   12: # the Free Software Foundation; either version 2 of the License, or
   13: # (at your option) any later version.
   14: #
   15: # LON-CAPA is distributed in the hope that it will be useful,
   16: # but WITHOUT ANY WARRANTY; without even the implied warranty of
   17: # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   18: # GNU General Public License for more details.
   19: #
   20: # You should have received a copy of the GNU General Public License
   21: # along with LON-CAPA; if not, write to the Free Software
   22: # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
   23: #
   24: # /home/httpd/html/adm/gpl.txt
   25: #
   26: # http://www.lon-capa.org/
   27: #
   28: 
   29: # Makes a table out of the previous attempts
   30: # Inputs result_from_symbread, user, domain, course_id
   31: # Reads in non-network-related .tab files
   32: 
   33: # POD header:
   34: 
   35: =pod
   36: 
   37: =head1 NAME
   38: 
   39: Apache::loncommon - pile of common routines
   40: 
   41: =head1 SYNOPSIS
   42: 
   43: Common routines for manipulating connections, student answers,
   44:     domains, common Javascript fragments, etc.
   45: 
   46: =head1 OVERVIEW
   47: 
   48: A collection of commonly used subroutines that don't have a natural
   49: home anywhere else. This collection helps remove
   50: redundancy from other modules and increase efficiency of memory usage.
   51: 
   52: =cut 
   53: 
   54: # End of POD header
   55: package Apache::loncommon;
   56: 
   57: use strict;
   58: use Apache::lonnet;
   59: use GDBM_File;
   60: use POSIX qw(strftime mktime);
   61: use Apache::lonmenu();
   62: use Apache::lonenc();
   63: use Apache::lonlocal;
   64: use Apache::lonnet();
   65: use HTML::Entities;
   66: use Apache::lonhtmlcommon();
   67: use Apache::loncoursedata();
   68: use Apache::lontexconvert();
   69: use Apache::lonclonecourse();
   70: use Apache::lonuserutils();
   71: use Apache::lonuserstate();
   72: use Apache::courseclassifier();
   73: use LONCAPA qw(:DEFAULT :match);
   74: use DateTime::TimeZone;
   75: use DateTime::Locale::Catalog;
   76: use Text::Aspell;
   77: use Authen::Captcha;
   78: use Captcha::reCAPTCHA;
   79: use Crypt::DES;
   80: use DynaLoader; # for Crypt::DES version
   81: 
   82: # ---------------------------------------------- Designs
   83: use vars qw(%defaultdesign);
   84: 
   85: my $readit;
   86: 
   87: 
   88: ##
   89: ## Global Variables
   90: ##
   91: 
   92: 
   93: # ----------------------------------------------- SSI with retries:
   94: #
   95: 
   96: =pod
   97: 
   98: =head1 Server Side include with retries:
   99: 
  100: =over 4
  101: 
  102: =item * &ssi_with_retries(resource,retries form)
  103: 
  104: Performs an ssi with some number of retries.  Retries continue either
  105: until the result is ok or until the retry count supplied by the
  106: caller is exhausted.  
  107: 
  108: Inputs:
  109: 
  110: =over 4
  111: 
  112: resource   - Identifies the resource to insert.
  113: 
  114: retries    - Count of the number of retries allowed.
  115: 
  116: form       - Hash that identifies the rendering options.
  117: 
  118: =back
  119: 
  120: Returns:
  121: 
  122: =over 4
  123: 
  124: content    - The content of the response.  If retries were exhausted this is empty.
  125: 
  126: response   - The response from the last attempt (which may or may not have been successful.
  127: 
  128: =back
  129: 
  130: =back
  131: 
  132: =cut
  133: 
  134: sub ssi_with_retries {
  135:     my ($resource, $retries, %form) = @_;
  136: 
  137: 
  138:     my $ok = 0;			# True if we got a good response.
  139:     my $content;
  140:     my $response;
  141: 
  142:     # Try to get the ssi done. within the retries count:
  143: 
  144:     do {
  145: 	($content, $response) = &Apache::lonnet::ssi($resource, %form);
  146: 	$ok      = $response->is_success;
  147:         if (!$ok) {
  148:             &Apache::lonnet::logthis("Failed ssi_with_retries on $resource: ".$response->is_success.', '.$response->code.', '.$response->message);
  149:         }
  150: 	$retries--;
  151:     } while (!$ok && ($retries > 0));
  152: 
  153:     if (!$ok) {
  154: 	$content = '';		# On error return an empty content.
  155:     }
  156:     return ($content, $response);
  157: 
  158: }
  159: 
  160: 
  161: 
  162: # ----------------------------------------------- Filetypes/Languages/Copyright
  163: my %language;
  164: my %supported_language;
  165: my %supported_codes;
  166: my %latex_language;		# For choosing hyphenation in <transl..>
  167: my %latex_language_bykey;	# for choosing hyphenation from metadata
  168: my %cprtag;
  169: my %scprtag;
  170: my %fe; my %fd; my %fm;
  171: my %category_extensions;
  172: 
  173: # ---------------------------------------------- Thesaurus variables
  174: #
  175: # %Keywords:
  176: #      A hash used by &keyword to determine if a word is considered a keyword.
  177: # $thesaurus_db_file 
  178: #      Scalar containing the full path to the thesaurus database.
  179: 
  180: my %Keywords;
  181: my $thesaurus_db_file;
  182: 
  183: #
  184: # Initialize values from language.tab, copyright.tab, filetypes.tab,
  185: # thesaurus.tab, and filecategories.tab.
  186: #
  187: BEGIN {
  188:     # Variable initialization
  189:     $thesaurus_db_file = $Apache::lonnet::perlvar{'lonTabDir'}."/thesaurus.db";
  190:     #
  191:     unless ($readit) {
  192: # ------------------------------------------------------------------- languages
  193:     {
  194:         my $langtabfile = $Apache::lonnet::perlvar{'lonTabDir'}.
  195:                                    '/language.tab';
  196:         if ( open(my $fh,"<$langtabfile") ) {
  197:             while (my $line = <$fh>) {
  198:                 next if ($line=~/^\#/);
  199:                 chomp($line);
  200:                 my ($key,$code,$country,$three,$enc,$val,$sup,$latex)=(split(/\t/,$line));
  201:                 $language{$key}=$val.' - '.$enc;
  202:                 if ($sup) {
  203:                     $supported_language{$key}=$sup;
  204: 		    $supported_codes{$key}   = $code;
  205:                 }
  206: 		if ($latex) {
  207: 		    $latex_language_bykey{$key} = $latex;
  208: 		    $latex_language{$code} = $latex;
  209: 		}
  210:             }
  211:             close($fh);
  212:         }
  213:     }
  214: # ------------------------------------------------------------------ copyrights
  215:     {
  216:         my $copyrightfile = $Apache::lonnet::perlvar{'lonIncludes'}.
  217:                                   '/copyright.tab';
  218:         if ( open (my $fh,"<$copyrightfile") ) {
  219:             while (my $line = <$fh>) {
  220:                 next if ($line=~/^\#/);
  221:                 chomp($line);
  222:                 my ($key,$val)=(split(/\s+/,$line,2));
  223:                 $cprtag{$key}=$val;
  224:             }
  225:             close($fh);
  226:         }
  227:     }
  228: # ----------------------------------------------------------- source copyrights
  229:     {
  230:         my $sourcecopyrightfile = $Apache::lonnet::perlvar{'lonIncludes'}.
  231:                                   '/source_copyright.tab';
  232:         if ( open (my $fh,"<$sourcecopyrightfile") ) {
  233:             while (my $line = <$fh>) {
  234:                 next if ($line =~ /^\#/);
  235:                 chomp($line);
  236:                 my ($key,$val)=(split(/\s+/,$line,2));
  237:                 $scprtag{$key}=$val;
  238:             }
  239:             close($fh);
  240:         }
  241:     }
  242: 
  243: # -------------------------------------------------------------- default domain designs
  244:     my $designdir=$Apache::lonnet::perlvar{'lonTabDir'}.'/lonDomColors';
  245:     my $designfile = $designdir.'/default.tab';
  246:     if ( open (my $fh,"<$designfile") ) {
  247:         while (my $line = <$fh>) {
  248:             next if ($line =~ /^\#/);
  249:             chomp($line);
  250:             my ($key,$val)=(split(/\=/,$line));
  251:             if ($val) { $defaultdesign{$key}=$val; }
  252:         }
  253:         close($fh);
  254:     }
  255: 
  256: # ------------------------------------------------------------- file categories
  257:     {
  258:         my $categoryfile = $Apache::lonnet::perlvar{'lonTabDir'}.
  259:                                   '/filecategories.tab';
  260:         if ( open (my $fh,"<$categoryfile") ) {
  261: 	    while (my $line = <$fh>) {
  262: 		next if ($line =~ /^\#/);
  263: 		chomp($line);
  264:                 my ($extension,$category)=(split(/\s+/,$line,2));
  265:                 push @{$category_extensions{lc($category)}},$extension;
  266:             }
  267:             close($fh);
  268:         }
  269: 
  270:     }
  271: # ------------------------------------------------------------------ file types
  272:     {
  273:         my $typesfile = $Apache::lonnet::perlvar{'lonTabDir'}.
  274:                '/filetypes.tab';
  275:         if ( open (my $fh,"<$typesfile") ) {
  276:             while (my $line = <$fh>) {
  277: 		next if ($line =~ /^\#/);
  278: 		chomp($line);
  279:                 my ($ending,$emb,$mime,$descr)=split(/\s+/,$line,4);
  280:                 if ($descr ne '') {
  281:                     $fe{$ending}=lc($emb);
  282:                     $fd{$ending}=$descr;
  283:                     if ($mime ne 'unk') { $fm{$ending}=$mime; }
  284:                 }
  285:             }
  286:             close($fh);
  287:         }
  288:     }
  289:     &Apache::lonnet::logthis(
  290:              "<span style='color:yellow;'>INFO: Read file types</span>");
  291:     $readit=1;
  292:     }  # end of unless($readit) 
  293:     
  294: }
  295: 
  296: ###############################################################
  297: ##           HTML and Javascript Helper Functions            ##
  298: ###############################################################
  299: 
  300: =pod 
  301: 
  302: =head1 HTML and Javascript Functions
  303: 
  304: =over 4
  305: 
  306: =item * &browser_and_searcher_javascript()
  307: 
  308: X<browsing, javascript>X<searching, javascript>Returns a string
  309: containing javascript with two functions, C<openbrowser> and
  310: C<opensearcher>. Returned string does not contain E<lt>scriptE<gt>
  311: tags.
  312: 
  313: =item * &openbrowser(formname,elementname,only,omit) [javascript]
  314: 
  315: inputs: formname, elementname, only, omit
  316: 
  317: formname and elementname indicate the name of the html form and name of
  318: the element that the results of the browsing selection are to be placed in. 
  319: 
  320: Specifying 'only' will restrict the browser to displaying only files
  321: with the given extension.  Can be a comma separated list.
  322: 
  323: Specifying 'omit' will restrict the browser to NOT displaying files
  324: with the given extension.  Can be a comma separated list.
  325: 
  326: =item * &opensearcher(formname,elementname) [javascript]
  327: 
  328: Inputs: formname, elementname
  329: 
  330: formname and elementname specify the name of the html form and the name
  331: of the element the selection from the search results will be placed in.
  332: 
  333: =cut
  334: 
  335: sub browser_and_searcher_javascript {
  336:     my ($mode)=@_;
  337:     if (!defined($mode)) { $mode='edit'; }
  338:     my $resurl=&escape_single(&lastresurl());
  339:     return <<END;
  340: // <!-- BEGIN LON-CAPA Internal
  341:     var editbrowser = null;
  342:     function openbrowser(formname,elementname,only,omit,titleelement) {
  343:         var url = '$resurl/?';
  344:         if (editbrowser == null) {
  345:             url += 'launch=1&';
  346:         }
  347:         url += 'catalogmode=interactive&';
  348:         url += 'mode=$mode&';
  349:         url += 'inhibitmenu=yes&';
  350:         url += 'form=' + formname + '&';
  351:         if (only != null) {
  352:             url += 'only=' + only + '&';
  353:         } else {
  354:             url += 'only=&';
  355: 	}
  356:         if (omit != null) {
  357:             url += 'omit=' + omit + '&';
  358:         } else {
  359:             url += 'omit=&';
  360: 	}
  361:         if (titleelement != null) {
  362:             url += 'titleelement=' + titleelement + '&';
  363:         } else {
  364: 	    url += 'titleelement=&';
  365: 	}
  366:         url += 'element=' + elementname + '';
  367:         var title = 'Browser';
  368:         var options = 'scrollbars=1,resizable=1,menubar=0,toolbar=1,location=1';
  369:         options += ',width=700,height=600';
  370:         editbrowser = open(url,title,options,'1');
  371:         editbrowser.focus();
  372:     }
  373:     var editsearcher;
  374:     function opensearcher(formname,elementname,titleelement) {
  375:         var url = '/adm/searchcat?';
  376:         if (editsearcher == null) {
  377:             url += 'launch=1&';
  378:         }
  379:         url += 'catalogmode=interactive&';
  380:         url += 'mode=$mode&';
  381:         url += 'form=' + formname + '&';
  382:         if (titleelement != null) {
  383:             url += 'titleelement=' + titleelement + '&';
  384:         } else {
  385: 	    url += 'titleelement=&';
  386: 	}
  387:         url += 'element=' + elementname + '';
  388:         var title = 'Search';
  389:         var options = 'scrollbars=1,resizable=1,menubar=0,toolbar=1,location=1';
  390:         options += ',width=700,height=600';
  391:         editsearcher = open(url,title,options,'1');
  392:         editsearcher.focus();
  393:     }
  394: // END LON-CAPA Internal -->
  395: END
  396: }
  397: 
  398: sub lastresurl {
  399:     if ($env{'environment.lastresurl'}) {
  400: 	return $env{'environment.lastresurl'}
  401:     } else {
  402: 	return '/res';
  403:     }
  404: }
  405: 
  406: sub storeresurl {
  407:     my $resurl=&Apache::lonnet::clutter(shift);
  408:     unless ($resurl=~/^\/res/) { return 0; }
  409:     $resurl=~s/\/$//;
  410:     &Apache::lonnet::put('environment',{'lastresurl' => $resurl});
  411:     &Apache::lonnet::appenv({'environment.lastresurl' => $resurl});
  412:     return 1;
  413: }
  414: 
  415: sub studentbrowser_javascript {
  416:    unless (
  417:             (($env{'request.course.id'}) && 
  418:              (&Apache::lonnet::allowed('srm',$env{'request.course.id'})
  419: 	      || &Apache::lonnet::allowed('srm',$env{'request.course.id'}.
  420: 					  '/'.$env{'request.course.sec'})
  421: 	      ))
  422:          || ($env{'request.role'}=~/^(au|dc|su)/)
  423:           ) { return ''; }  
  424:    return (<<'ENDSTDBRW');
  425: <script type="text/javascript" language="Javascript">
  426: // <![CDATA[
  427:     var stdeditbrowser;
  428:     function openstdbrowser(formname,uname,udom,clicker,roleflag,ignorefilter,courseadvonly) {
  429:         var url = '/adm/pickstudent?';
  430:         var filter;
  431: 	if (!ignorefilter) {
  432: 	    eval('filter=document.'+formname+'.'+uname+'.value;');
  433: 	}
  434:         if (filter != null) {
  435:            if (filter != '') {
  436:                url += 'filter='+filter+'&';
  437: 	   }
  438:         }
  439:         url += 'form=' + formname + '&unameelement='+uname+
  440:                                     '&udomelement='+udom+
  441:                                     '&clicker='+clicker;
  442: 	if (roleflag) { url+="&roles=1"; }
  443:         if (courseadvonly) { url+="&courseadvonly=1"; }
  444:         var title = 'Student_Browser';
  445:         var options = 'scrollbars=1,resizable=1,menubar=0';
  446:         options += ',width=700,height=600';
  447:         stdeditbrowser = open(url,title,options,'1');
  448:         stdeditbrowser.focus();
  449:     }
  450: // ]]>
  451: </script>
  452: ENDSTDBRW
  453: }
  454: 
  455: sub resourcebrowser_javascript {
  456:    unless ($env{'request.course.id'}) { return ''; }
  457:    return (<<'ENDRESBRW');
  458: <script type="text/javascript" language="Javascript">
  459: // <![CDATA[
  460:     var reseditbrowser;
  461:     function openresbrowser(formname,reslink) {
  462:         var url = '/adm/pickresource?form='+formname+'&reslink='+reslink;
  463:         var title = 'Resource_Browser';
  464:         var options = 'scrollbars=1,resizable=1,menubar=0';
  465:         options += ',width=700,height=500';
  466:         reseditbrowser = open(url,title,options,'1');
  467:         reseditbrowser.focus();
  468:     }
  469: // ]]>
  470: </script>
  471: ENDRESBRW
  472: }
  473: 
  474: sub selectstudent_link {
  475:    my ($form,$unameele,$udomele,$courseadvonly,$clickerid)=@_;
  476:    my $callargs = "'".&Apache::lonhtmlcommon::entity_encode($form)."','".
  477:                       &Apache::lonhtmlcommon::entity_encode($unameele)."','".
  478:                       &Apache::lonhtmlcommon::entity_encode($udomele)."'";
  479:    if ($env{'request.course.id'}) {  
  480:        if (!&Apache::lonnet::allowed('srm',$env{'request.course.id'})
  481: 	   && !&Apache::lonnet::allowed('srm',$env{'request.course.id'}.
  482: 					'/'.$env{'request.course.sec'})) {
  483: 	   return '';
  484:        }
  485:        $callargs.=",'".&Apache::lonhtmlcommon::entity_encode($clickerid)."'";
  486:        if ($courseadvonly)  {
  487:            $callargs .= ",'',1,1";
  488:        }
  489:        return '<span class="LC_nobreak">'.
  490:               '<a href="javascript:openstdbrowser('.$callargs.');">'.
  491:               &mt('Select User').'</a></span>';
  492:    }
  493:    if ($env{'request.role'}=~/^(au|dc|su)/) {
  494:        $callargs .= ",'',1"; 
  495:        return '<span class="LC_nobreak">'.
  496:               '<a href="javascript:openstdbrowser('.$callargs.');">'.
  497:               &mt('Select User').'</a></span>';
  498:    }
  499:    return '';
  500: }
  501: 
  502: sub selectresource_link {
  503:    my ($form,$reslink,$arg)=@_;
  504:    
  505:    my $callargs = "'".&Apache::lonhtmlcommon::entity_encode($form)."','".
  506:                       &Apache::lonhtmlcommon::entity_encode($reslink)."'";
  507:    unless ($env{'request.course.id'}) { return $arg; }
  508:    return '<span class="LC_nobreak">'.
  509:               '<a href="javascript:openresbrowser('.$callargs.');">'.
  510:               $arg.'</a></span>';
  511: }
  512: 
  513: 
  514: 
  515: sub authorbrowser_javascript {
  516:     return <<"ENDAUTHORBRW";
  517: <script type="text/javascript" language="JavaScript">
  518: // <![CDATA[
  519: var stdeditbrowser;
  520: 
  521: function openauthorbrowser(formname,udom) {
  522:     var url = '/adm/pickauthor?';
  523:     url += 'form='+formname+'&roledom='+udom;
  524:     var title = 'Author_Browser';
  525:     var options = 'scrollbars=1,resizable=1,menubar=0';
  526:     options += ',width=700,height=600';
  527:     stdeditbrowser = open(url,title,options,'1');
  528:     stdeditbrowser.focus();
  529: }
  530: 
  531: // ]]>
  532: </script>
  533: ENDAUTHORBRW
  534: }
  535: 
  536: sub coursebrowser_javascript {
  537:     my ($domainfilter,$sec_element,$formname,$role_element,$crstype,
  538:         $credits_element) = @_;
  539:     my $wintitle = 'Course_Browser';
  540:     if ($crstype eq 'Community') {
  541:         $wintitle = 'Community_Browser';
  542:     }
  543:     my $id_functions = &javascript_index_functions();
  544:     my $output = '
  545: <script type="text/javascript" language="JavaScript">
  546: // <![CDATA[
  547:     var stdeditbrowser;'."\n";
  548: 
  549:     $output .= <<"ENDSTDBRW";
  550:     function opencrsbrowser(formname,uname,udom,desc,extra_element,multflag,type,type_elem) {
  551:         var url = '/adm/pickcourse?';
  552:         var formid = getFormIdByName(formname);
  553:         var domainfilter = getDomainFromSelectbox(formname,udom);
  554:         if (domainfilter != null) {
  555:            if (domainfilter != '') {
  556:                url += 'domainfilter='+domainfilter+'&';
  557: 	   }
  558:         }
  559:         url += 'form=' + formname + '&cnumelement='+uname+
  560: 	                            '&cdomelement='+udom+
  561:                                     '&cnameelement='+desc;
  562:         if (extra_element !=null && extra_element != '') {
  563:             if (formname == 'rolechoice' || formname == 'studentform') {
  564:                 url += '&roleelement='+extra_element;
  565:                 if (domainfilter == null || domainfilter == '') {
  566:                     url += '&domainfilter='+extra_element;
  567:                 }
  568:             }
  569:             else {
  570:                 if (formname == 'portform') {
  571:                     url += '&setroles='+extra_element;
  572:                 } else {
  573:                     if (formname == 'rules') {
  574:                         url += '&fixeddom='+extra_element; 
  575:                     }
  576:                 }
  577:             }     
  578:         }
  579:         if (type != null && type != '') {
  580:             url += '&type='+type;
  581:         }
  582:         if (type_elem != null && type_elem != '') {
  583:             url += '&typeelement='+type_elem;
  584:         }
  585:         if (formname == 'ccrs') {
  586:             var ownername = document.forms[formid].ccuname.value;
  587:             var ownerdom =  document.forms[formid].ccdomain.options[document.forms[formid].ccdomain.selectedIndex].value;
  588:             url += '&cloner='+ownername+':'+ownerdom;
  589:         }
  590:         if (multflag !=null && multflag != '') {
  591:             url += '&multiple='+multflag;
  592:         }
  593:         var title = '$wintitle';
  594:         var options = 'scrollbars=1,resizable=1,menubar=0';
  595:         options += ',width=700,height=600';
  596:         stdeditbrowser = open(url,title,options,'1');
  597:         stdeditbrowser.focus();
  598:     }
  599: $id_functions
  600: ENDSTDBRW
  601:     if (($sec_element ne '') || ($role_element ne '') || ($credits_element ne '')) {
  602:         $output .= &setsec_javascript($sec_element,$formname,$role_element,
  603:                                       $credits_element);
  604:     }
  605:     $output .= '
  606: // ]]>
  607: </script>';
  608:     return $output;
  609: }
  610: 
  611: sub javascript_index_functions {
  612:     return <<"ENDJS";
  613: 
  614: function getFormIdByName(formname) {
  615:     for (var i=0;i<document.forms.length;i++) {
  616:         if (document.forms[i].name == formname) {
  617:             return i;
  618:         }
  619:     }
  620:     return -1;
  621: }
  622: 
  623: function getIndexByName(formid,item) {
  624:     for (var i=0;i<document.forms[formid].elements.length;i++) {
  625:         if (document.forms[formid].elements[i].name == item) {
  626:             return i;
  627:         }
  628:     }
  629:     return -1;
  630: }
  631: 
  632: function getDomainFromSelectbox(formname,udom) {
  633:     var userdom;
  634:     var formid = getFormIdByName(formname);
  635:     if (formid > -1) {
  636:         var domid = getIndexByName(formid,udom);
  637:         if (domid > -1) {
  638:             if (document.forms[formid].elements[domid].type == 'select-one') {
  639:                 userdom=document.forms[formid].elements[domid].options[document.forms[formid].elements[domid].selectedIndex].value;
  640:             }
  641:             if (document.forms[formid].elements[domid].type == 'hidden') {
  642:                 userdom=document.forms[formid].elements[domid].value;
  643:             }
  644:         }
  645:     }
  646:     return userdom;
  647: }
  648: 
  649: ENDJS
  650: 
  651: }
  652: 
  653: sub javascript_array_indexof {
  654:     return <<ENDJS;
  655: <script type="text/javascript" language="JavaScript">
  656: // <![CDATA[
  657: 
  658: if (!Array.prototype.indexOf) {
  659:     Array.prototype.indexOf = function (searchElement /*, fromIndex */ ) {
  660:         "use strict";
  661:         if (this === void 0 || this === null) {
  662:             throw new TypeError();
  663:         }
  664:         var t = Object(this);
  665:         var len = t.length >>> 0;
  666:         if (len === 0) {
  667:             return -1;
  668:         }
  669:         var n = 0;
  670:         if (arguments.length > 0) {
  671:             n = Number(arguments[1]);
  672:             if (n !== n) { // shortcut for verifying if it is NaN
  673:                 n = 0;
  674:             } else if (n !== 0 && n !== (1 / 0) && n !== -(1 / 0)) {
  675:                 n = (n > 0 || -1) * Math.floor(Math.abs(n));
  676:             }
  677:         }
  678:         if (n >= len) {
  679:             return -1;
  680:         }
  681:         var k = n >= 0 ? n : Math.max(len - Math.abs(n), 0);
  682:         for (; k < len; k++) {
  683:             if (k in t && t[k] === searchElement) {
  684:                 return k;
  685:             }
  686:         }
  687:         return -1;
  688:     }
  689: }
  690: 
  691: // ]]>
  692: </script>
  693: 
  694: ENDJS
  695: 
  696: }
  697: 
  698: sub userbrowser_javascript {
  699:     my $id_functions = &javascript_index_functions();
  700:     return <<"ENDUSERBRW";
  701: 
  702: function openuserbrowser(formname,uname,udom,ulast,ufirst,uemail,hideudom,crsdom,caller) {
  703:     var url = '/adm/pickuser?';
  704:     var userdom = getDomainFromSelectbox(formname,udom);
  705:     if (userdom != null) {
  706:        if (userdom != '') {
  707:            url += 'srchdom='+userdom+'&';
  708:        }
  709:     }
  710:     url += 'form=' + formname + '&unameelement='+uname+
  711:                                 '&udomelement='+udom+
  712:                                 '&ulastelement='+ulast+
  713:                                 '&ufirstelement='+ufirst+
  714:                                 '&uemailelement='+uemail+
  715:                                 '&hideudomelement='+hideudom+
  716:                                 '&coursedom='+crsdom;
  717:     if ((caller != null) && (caller != undefined)) {
  718:         url += '&caller='+caller;
  719:     }
  720:     var title = 'User_Browser';
  721:     var options = 'scrollbars=1,resizable=1,menubar=0';
  722:     options += ',width=700,height=600';
  723:     var stdeditbrowser = open(url,title,options,'1');
  724:     stdeditbrowser.focus();
  725: }
  726: 
  727: function fix_domain (formname,udom,origdom,uname) {
  728:     var formid = getFormIdByName(formname);
  729:     if (formid > -1) {
  730:         var unameid = getIndexByName(formid,uname);
  731:         var domid = getIndexByName(formid,udom);
  732:         var hidedomid = getIndexByName(formid,origdom);
  733:         if (hidedomid > -1) {
  734:             var fixeddom = document.forms[formid].elements[hidedomid].value;
  735:             var unameval = document.forms[formid].elements[unameid].value;
  736:             if ((fixeddom != '') && (fixeddom != undefined) && (fixeddom != null) && (unameval != '') && (unameval != undefined) && (unameval != null)) {
  737:                 if (domid > -1) {
  738:                     var slct = document.forms[formid].elements[domid];
  739:                     if (slct.type == 'select-one') {
  740:                         var i;
  741:                         for (i=0;i<slct.length;i++) {
  742:                             if (slct.options[i].value==fixeddom) { slct.selectedIndex=i; }
  743:                         }
  744:                     }
  745:                     if (slct.type == 'hidden') {
  746:                         slct.value = fixeddom;
  747:                     }
  748:                 }
  749:             }
  750:         }
  751:     }
  752:     return;
  753: }
  754: 
  755: $id_functions
  756: ENDUSERBRW
  757: }
  758: 
  759: sub setsec_javascript {
  760:     my ($sec_element,$formname,$role_element,$credits_element) = @_;
  761:     my (@courserolenames,@communityrolenames,$rolestr,$courserolestr,
  762:         $communityrolestr);
  763:     if ($role_element ne '') {
  764:         my @allroles = ('st','ta','ep','in','ad');
  765:         foreach my $crstype ('Course','Community') {
  766:             if ($crstype eq 'Community') {
  767:                 foreach my $role (@allroles) {
  768:                     push(@communityrolenames,&Apache::lonnet::plaintext($role,$crstype));
  769:                 }
  770:                 push(@communityrolenames,&Apache::lonnet::plaintext('co'));
  771:             } else {
  772:                 foreach my $role (@allroles) {
  773:                     push(@courserolenames,&Apache::lonnet::plaintext($role,$crstype));
  774:                 }
  775:                 push(@courserolenames,&Apache::lonnet::plaintext('cc'));
  776:             }
  777:         }
  778:         $rolestr = '"'.join('","',@allroles).'"';
  779:         $courserolestr = '"'.join('","',@courserolenames).'"';
  780:         $communityrolestr = '"'.join('","',@communityrolenames).'"';
  781:     }
  782:     my $setsections = qq|
  783: function setSect(sectionlist) {
  784:     var sectionsArray = new Array();
  785:     if ((sectionlist != '') && (typeof sectionlist != "undefined")) {
  786:         sectionsArray = sectionlist.split(",");
  787:     }
  788:     var numSections = sectionsArray.length;
  789:     document.$formname.$sec_element.length = 0;
  790:     if (numSections == 0) {
  791:         document.$formname.$sec_element.multiple=false;
  792:         document.$formname.$sec_element.size=1;
  793:         document.$formname.$sec_element.options[0] = new Option('No existing sections','',false,false)
  794:     } else {
  795:         if (numSections == 1) {
  796:             document.$formname.$sec_element.multiple=false;
  797:             document.$formname.$sec_element.size=1;
  798:             document.$formname.$sec_element.options[0] = new Option('Select','',true,true);
  799:             document.$formname.$sec_element.options[1] = new Option('No section','',false,false)
  800:             document.$formname.$sec_element.options[2] = new Option(sectionsArray[0],sectionsArray[0],false,false);
  801:         } else {
  802:             for (var i=0; i<numSections; i++) {
  803:                 document.$formname.$sec_element.options[i] = new Option(sectionsArray[i],sectionsArray[i],false,false)
  804:             }
  805:             document.$formname.$sec_element.multiple=true
  806:             if (numSections < 3) {
  807:                 document.$formname.$sec_element.size=numSections;
  808:             } else {
  809:                 document.$formname.$sec_element.size=3;
  810:             }
  811:             document.$formname.$sec_element.options[0].selected = false
  812:         }
  813:     }
  814: }
  815: 
  816: function setRole(crstype) {
  817: |;
  818:     if ($role_element eq '') {
  819:         $setsections .= '    return;
  820: }
  821: ';
  822:     } else {
  823:         $setsections .= qq|
  824:     var elementLength = document.$formname.$role_element.length;
  825:     var allroles = Array($rolestr);
  826:     var courserolenames = Array($courserolestr);
  827:     var communityrolenames = Array($communityrolestr);
  828:     if (elementLength != undefined) {
  829:         if (document.$formname.$role_element.options[5].value == 'cc') {
  830:             if (crstype == 'Course') {
  831:                 return;
  832:             } else {
  833:                 allroles[5] = 'co';
  834:                 for (var i=0; i<6; i++) {
  835:                     document.$formname.$role_element.options[i].value = allroles[i];
  836:                     document.$formname.$role_element.options[i].text = communityrolenames[i];
  837:                 }
  838:             }
  839:         } else {
  840:             if (crstype == 'Community') {
  841:                 return;
  842:             } else {
  843:                 allroles[5] = 'cc';
  844:                 for (var i=0; i<6; i++) {
  845:                     document.$formname.$role_element.options[i].value = allroles[i];
  846:                     document.$formname.$role_element.options[i].text = courserolenames[i];
  847:                 }
  848:             }
  849:         }
  850:     }
  851:     return;
  852: }
  853: |;
  854:     }
  855:     if ($credits_element) {
  856:         $setsections .= qq|
  857: function setCredits(defaultcredits) {
  858:     document.$formname.$credits_element.value = defaultcredits;
  859:     return;
  860: }
  861: |;
  862:     }
  863:     return $setsections;
  864: }
  865: 
  866: sub selectcourse_link {
  867:    my ($form,$unameele,$udomele,$desc,$extra_element,$multflag,$selecttype,
  868:        $typeelement) = @_;
  869:    my $type = $selecttype;
  870:    my $linktext = &mt('Select Course');
  871:    if ($selecttype eq 'Community') {
  872:        $linktext = &mt('Select Community');
  873:    } elsif ($selecttype eq 'Course/Community') {
  874:        $linktext = &mt('Select Course/Community');
  875:        $type = '';
  876:    } elsif ($selecttype eq 'Select') {
  877:        $linktext = &mt('Select');
  878:        $type = '';
  879:    }
  880:    return '<span class="LC_nobreak">'
  881:          ."<a href='"
  882:          .'javascript:opencrsbrowser("'.$form.'","'.$unameele
  883:          .'","'.$udomele.'","'.$desc.'","'.$extra_element
  884:          .'","'.$multflag.'","'.$type.'","'.$typeelement.'");'
  885:          ."'>".$linktext.'</a>'
  886:          .'</span>';
  887: }
  888: 
  889: sub selectauthor_link {
  890:    my ($form,$udom)=@_;
  891:    return '<a href="javascript:openauthorbrowser('."'$form','$udom'".');">'.
  892:           &mt('Select Author').'</a>';
  893: }
  894: 
  895: sub selectuser_link {
  896:     my ($form,$unameelem,$domelem,$lastelem,$firstelem,$emailelem,$hdomelem,
  897:         $coursedom,$linktext,$caller) = @_;
  898:     return '<a href="javascript:openuserbrowser('."'$form','$unameelem','$domelem',".
  899:            "'$lastelem','$firstelem','$emailelem','$hdomelem','$coursedom','$caller'".
  900:            ');">'.$linktext.'</a>';
  901: }
  902: 
  903: sub check_uncheck_jscript {
  904:     my $jscript = <<"ENDSCRT";
  905: function checkAll(field) {
  906:     if (field.length > 0) {
  907:         for (i = 0; i < field.length; i++) {
  908:             if (!field[i].disabled) { 
  909:                 field[i].checked = true;
  910:             }
  911:         }
  912:     } else {
  913:         if (!field.disabled) { 
  914:             field.checked = true;
  915:         }
  916:     }
  917: }
  918:  
  919: function uncheckAll(field) {
  920:     if (field.length > 0) {
  921:         for (i = 0; i < field.length; i++) {
  922:             field[i].checked = false ;
  923:         }
  924:     } else {
  925:         field.checked = false ;
  926:     }
  927: }
  928: ENDSCRT
  929:     return $jscript;
  930: }
  931: 
  932: sub select_timezone {
  933:    my ($name,$selected,$onchange,$includeempty)=@_;
  934:    my $output='<select name="'.$name.'" '.$onchange.'>'."\n";
  935:    if ($includeempty) {
  936:        $output .= '<option value=""';
  937:        if (($selected eq '') || ($selected eq 'local')) {
  938:            $output .= ' selected="selected" ';
  939:        }
  940:        $output .= '> </option>';
  941:    }
  942:    my @timezones = DateTime::TimeZone->all_names;
  943:    foreach my $tzone (@timezones) {
  944:        $output.= '<option value="'.$tzone.'"';
  945:        if ($tzone eq $selected) {
  946:            $output.=' selected="selected"';
  947:        }
  948:        $output.=">$tzone</option>\n";
  949:    }
  950:    $output.="</select>";
  951:    return $output;
  952: }
  953: 
  954: sub select_datelocale {
  955:     my ($name,$selected,$onchange,$includeempty)=@_;
  956:     my $output='<select name="'.$name.'" '.$onchange.'>'."\n";
  957:     if ($includeempty) {
  958:         $output .= '<option value=""';
  959:         if ($selected eq '') {
  960:             $output .= ' selected="selected" ';
  961:         }
  962:         $output .= '> </option>';
  963:     }
  964:     my (@possibles,%locale_names);
  965:     my @locales = DateTime::Locale::Catalog::Locales;
  966:     foreach my $locale (@locales) {
  967:         if (ref($locale) eq 'HASH') {
  968:             my $id = $locale->{'id'};
  969:             if ($id ne '') {
  970:                 my $en_terr = $locale->{'en_territory'};
  971:                 my $native_terr = $locale->{'native_territory'};
  972:                 my @languages = &Apache::lonlocal::preferred_languages();
  973:                 if (grep(/^en$/,@languages) || !@languages) {
  974:                     if ($en_terr ne '') {
  975:                         $locale_names{$id} = '('.$en_terr.')';
  976:                     } elsif ($native_terr ne '') {
  977:                         $locale_names{$id} = $native_terr;
  978:                     }
  979:                 } else {
  980:                     if ($native_terr ne '') {
  981:                         $locale_names{$id} = $native_terr.' ';
  982:                     } elsif ($en_terr ne '') {
  983:                         $locale_names{$id} = '('.$en_terr.')';
  984:                     }
  985:                 }
  986:                 push (@possibles,$id);
  987:             }
  988:         }
  989:     }
  990:     foreach my $item (sort(@possibles)) {
  991:         $output.= '<option value="'.$item.'"';
  992:         if ($item eq $selected) {
  993:             $output.=' selected="selected"';
  994:         }
  995:         $output.=">$item";
  996:         if ($locale_names{$item} ne '') {
  997:             $output.="  $locale_names{$item}</option>\n";
  998:         }
  999:         $output.="</option>\n";
 1000:     }
 1001:     $output.="</select>";
 1002:     return $output;
 1003: }
 1004: 
 1005: sub select_language {
 1006:     my ($name,$selected,$includeempty) = @_;
 1007:     my %langchoices;
 1008:     if ($includeempty) {
 1009:         %langchoices = ('' => 'No language preference');
 1010:     }
 1011:     foreach my $id (&languageids()) {
 1012:         my $code = &supportedlanguagecode($id);
 1013:         if ($code) {
 1014:             $langchoices{$code} = &plainlanguagedescription($id);
 1015:         }
 1016:     }
 1017:     %langchoices = &Apache::lonlocal::texthash(%langchoices);
 1018:     return &select_form($selected,$name,\%langchoices);
 1019: }
 1020: 
 1021: =pod
 1022: 
 1023: 
 1024: =item * &list_languages()
 1025: 
 1026: Returns an array reference that is suitable for use in language prompters.
 1027: Each array element is itself a two element array.  The first element
 1028: is the language code.  The second element a descsriptiuon of the 
 1029: language itself.  This is suitable for use in e.g.
 1030: &Apache::edit::select_arg (once dereferenced that is).
 1031: 
 1032: =cut 
 1033: 
 1034: sub list_languages {
 1035:     my @lang_choices;
 1036: 
 1037:     foreach my $id (&languageids()) {
 1038: 	my $code = &supportedlanguagecode($id);
 1039: 	if ($code) {
 1040: 	    my $selector    = $supported_codes{$id};
 1041: 	    my $description = &plainlanguagedescription($id);
 1042: 	    push (@lang_choices, [$selector, $description]);
 1043: 	}
 1044:     }
 1045:     return \@lang_choices;
 1046: }
 1047: 
 1048: =pod
 1049: 
 1050: =item * &linked_select_forms(...)
 1051: 
 1052: linked_select_forms returns a string containing a <script></script> block
 1053: and html for two <select> menus.  The select menus will be linked in that
 1054: changing the value of the first menu will result in new values being placed
 1055: in the second menu.  The values in the select menu will appear in alphabetical
 1056: order unless a defined order is provided.
 1057: 
 1058: linked_select_forms takes the following ordered inputs:
 1059: 
 1060: =over 4
 1061: 
 1062: =item * $formname, the name of the <form> tag
 1063: 
 1064: =item * $middletext, the text which appears between the <select> tags
 1065: 
 1066: =item * $firstdefault, the default value for the first menu
 1067: 
 1068: =item * $firstselectname, the name of the first <select> tag
 1069: 
 1070: =item * $secondselectname, the name of the second <select> tag
 1071: 
 1072: =item * $hashref, a reference to a hash containing the data for the menus.
 1073: 
 1074: =item * $menuorder, the order of values in the first menu
 1075: 
 1076: =item * $onchangefirst, additional javascript call to execute for an onchange
 1077:         event for the first <select> tag
 1078: 
 1079: =item * $onchangesecond, additional javascript call to execute for an onchange
 1080:         event for the second <select> tag
 1081: 
 1082: =back 
 1083: 
 1084: Below is an example of such a hash.  Only the 'text', 'default', and 
 1085: 'select2' keys must appear as stated.  keys(%menu) are the possible 
 1086: values for the first select menu.  The text that coincides with the 
 1087: first menu value is given in $menu{$choice1}->{'text'}.  The values 
 1088: and text for the second menu are given in the hash pointed to by 
 1089: $menu{$choice1}->{'select2'}.  
 1090: 
 1091:  my %menu = ( A1 => { text =>"Choice A1" ,
 1092:                        default => "B3",
 1093:                        select2 => { 
 1094:                            B1 => "Choice B1",
 1095:                            B2 => "Choice B2",
 1096:                            B3 => "Choice B3",
 1097:                            B4 => "Choice B4"
 1098:                            },
 1099:                        order => ['B4','B3','B1','B2'],
 1100:                    },
 1101:                A2 => { text =>"Choice A2" ,
 1102:                        default => "C2",
 1103:                        select2 => { 
 1104:                            C1 => "Choice C1",
 1105:                            C2 => "Choice C2",
 1106:                            C3 => "Choice C3"
 1107:                            },
 1108:                        order => ['C2','C1','C3'],
 1109:                    },
 1110:                A3 => { text =>"Choice A3" ,
 1111:                        default => "D6",
 1112:                        select2 => { 
 1113:                            D1 => "Choice D1",
 1114:                            D2 => "Choice D2",
 1115:                            D3 => "Choice D3",
 1116:                            D4 => "Choice D4",
 1117:                            D5 => "Choice D5",
 1118:                            D6 => "Choice D6",
 1119:                            D7 => "Choice D7"
 1120:                            },
 1121:                        order => ['D4','D3','D2','D1','D7','D6','D5'],
 1122:                    }
 1123:                );
 1124: 
 1125: =cut
 1126: 
 1127: sub linked_select_forms {
 1128:     my ($formname,
 1129:         $middletext,
 1130:         $firstdefault,
 1131:         $firstselectname,
 1132:         $secondselectname, 
 1133:         $hashref,
 1134:         $menuorder,
 1135:         $onchangefirst,
 1136:         $onchangesecond
 1137:         ) = @_;
 1138:     my $second = "document.$formname.$secondselectname";
 1139:     my $first = "document.$formname.$firstselectname";
 1140:     # output the javascript to do the changing
 1141:     my $result = '';
 1142:     $result.='<script type="text/javascript" language="JavaScript">'."\n";
 1143:     $result.="// <![CDATA[\n";
 1144:     $result.="var select2data = new Object();\n";
 1145:     $" = '","';
 1146:     my $debug = '';
 1147:     foreach my $s1 (sort(keys(%$hashref))) {
 1148:         $result.="select2data.d_$s1 = new Object();\n";        
 1149:         $result.="select2data.d_$s1.def = new String('".
 1150:             $hashref->{$s1}->{'default'}."');\n";
 1151:         $result.="select2data.d_$s1.values = new Array(";
 1152:         my @s2values = sort(keys( %{ $hashref->{$s1}->{'select2'} } ));
 1153:         if (ref($hashref->{$s1}->{'order'}) eq 'ARRAY') {
 1154:             @s2values = @{$hashref->{$s1}->{'order'}};
 1155:         }
 1156:         $result.="\"@s2values\");\n";
 1157:         $result.="select2data.d_$s1.texts = new Array(";        
 1158:         my @s2texts;
 1159:         foreach my $value (@s2values) {
 1160:             push @s2texts, $hashref->{$s1}->{'select2'}->{$value};
 1161:         }
 1162:         $result.="\"@s2texts\");\n";
 1163:     }
 1164:     $"=' ';
 1165:     $result.= <<"END";
 1166: 
 1167: function select1_changed() {
 1168:     // Determine new choice
 1169:     var newvalue = "d_" + $first.value;
 1170:     // update select2
 1171:     var values     = select2data[newvalue].values;
 1172:     var texts      = select2data[newvalue].texts;
 1173:     var select2def = select2data[newvalue].def;
 1174:     var i;
 1175:     // out with the old
 1176:     for (i = 0; i < $second.options.length; i++) {
 1177:         $second.options[i] = null;
 1178:     }
 1179:     // in with the nuclear
 1180:     for (i=0;i<values.length; i++) {
 1181:         $second.options[i] = new Option(values[i]);
 1182:         $second.options[i].value = values[i];
 1183:         $second.options[i].text = texts[i];
 1184:         if (values[i] == select2def) {
 1185:             $second.options[i].selected = true;
 1186:         }
 1187:     }
 1188: }
 1189: // ]]>
 1190: </script>
 1191: END
 1192:     # output the initial values for the selection lists
 1193:     $result .= "<select size=\"1\" name=\"$firstselectname\" onchange=\"select1_changed();$onchangefirst\">\n";
 1194:     my @order = sort(keys(%{$hashref}));
 1195:     if (ref($menuorder) eq 'ARRAY') {
 1196:         @order = @{$menuorder};
 1197:     }
 1198:     foreach my $value (@order) {
 1199:         $result.="    <option value=\"$value\" ";
 1200:         $result.=" selected=\"selected\" " if ($value eq $firstdefault);
 1201:         $result.=">".&mt($hashref->{$value}->{'text'})."</option>\n";
 1202:     }
 1203:     $result .= "</select>\n";
 1204:     my %select2 = %{$hashref->{$firstdefault}->{'select2'}};
 1205:     $result .= $middletext;
 1206:     $result .= "<select size=\"1\" name=\"$secondselectname\"";
 1207:     if ($onchangesecond) {
 1208:         $result .= ' onchange="'.$onchangesecond.'"';
 1209:     }
 1210:     $result .= ">\n";
 1211:     my $seconddefault = $hashref->{$firstdefault}->{'default'};
 1212:     
 1213:     my @secondorder = sort(keys(%select2));
 1214:     if (ref($hashref->{$firstdefault}->{'order'}) eq 'ARRAY') {
 1215:         @secondorder = @{$hashref->{$firstdefault}->{'order'}};
 1216:     }
 1217:     foreach my $value (@secondorder) {
 1218:         $result.="    <option value=\"$value\" ";        
 1219:         $result.=" selected=\"selected\" " if ($value eq $seconddefault);
 1220:         $result.=">".&mt($select2{$value})."</option>\n";
 1221:     }
 1222:     $result .= "</select>\n";
 1223:     #    return $debug;
 1224:     return $result;
 1225: }   #  end of sub linked_select_forms {
 1226: 
 1227: =pod
 1228: 
 1229: =item * &help_open_topic($topic,$text,$stayOnPage,$width,$height,$imgid)
 1230: 
 1231: Returns a string corresponding to an HTML link to the given help
 1232: $topic, where $topic corresponds to the name of a .tex file in
 1233: /home/httpd/html/adm/help/tex, with underscores replaced by
 1234: spaces. 
 1235: 
 1236: $text will optionally be linked to the same topic, allowing you to
 1237: link text in addition to the graphic. If you do not want to link
 1238: text, but wish to specify one of the later parameters, pass an
 1239: empty string. 
 1240: 
 1241: $stayOnPage is a value that will be interpreted as a boolean. If true,
 1242: the link will not open a new window. If false, the link will open
 1243: a new window using Javascript. (Default is false.) 
 1244: 
 1245: $width and $height are optional numerical parameters that will
 1246: override the width and height of the popped up window, which may
 1247: be useful for certain help topics with big pictures included.
 1248: 
 1249: $imgid is the id of the img tag used for the help icon. This may be
 1250: used in a javascript call to switch the image src.  See 
 1251: lonhtmlcommon::htmlareaselectactive() for an example.
 1252: 
 1253: =cut
 1254: 
 1255: sub help_open_topic {
 1256:     my ($topic, $text, $stayOnPage, $width, $height, $imgid) = @_;
 1257:     $text = "" if (not defined $text);
 1258:     $stayOnPage = 0 if (not defined $stayOnPage);
 1259:     $width = 500 if (not defined $width);
 1260:     $height = 400 if (not defined $height);
 1261:     my $filename = $topic;
 1262:     $filename =~ s/ /_/g;
 1263: 
 1264:     my $template = "";
 1265:     my $link;
 1266:     
 1267:     $topic=~s/\W/\_/g;
 1268: 
 1269:     if (!$stayOnPage) {
 1270: 	$link = "javascript:openMyModal('/adm/help/${filename}.hlp',$width,$height,'yes');";
 1271:     } elsif ($stayOnPage eq 'popup') {
 1272:         $link = "javascript:void(open('/adm/help/${filename}.hlp', 'Help_for_$topic', 'menubar=0,toolbar=1,scrollbars=1,width=$width,height=$height,resizable=yes'))";
 1273:     } else {
 1274: 	$link = "/adm/help/${filename}.hlp";
 1275:     }
 1276: 
 1277:     # Add the text
 1278:     if ($text ne "") {	
 1279: 	$template.='<span class="LC_help_open_topic">'
 1280:                   .'<a target="_top" href="'.$link.'">'
 1281:                   .$text.'</a>';
 1282:     }
 1283: 
 1284:     # (Always) Add the graphic
 1285:     my $title = &mt('Online Help');
 1286:     my $helpicon=&lonhttpdurl("/adm/help/help.png");
 1287:     if ($imgid ne '') {
 1288:         $imgid = ' id="'.$imgid.'"';
 1289:     }
 1290:     $template.=' <a target="_top" href="'.$link.'" title="'.$title.'">'
 1291:               .'<img src="'.$helpicon.'" border="0"'
 1292:               .' alt="'.&mt('Help: [_1]',$topic).'"'
 1293:               .' title="'.$title.'" style="vertical-align:middle;"'.$imgid 
 1294:               .' /></a>';
 1295:     if ($text ne "") {	
 1296:         $template.='</span>';
 1297:     }
 1298:     return $template;
 1299: 
 1300: }
 1301: 
 1302: # This is a quicky function for Latex cheatsheet editing, since it 
 1303: # appears in at least four places
 1304: sub helpLatexCheatsheet {
 1305:     my ($topic,$text,$not_author,$stayOnPage) = @_;
 1306:     my $out;
 1307:     my $addOther = '';
 1308:     if ($topic) {
 1309: 	$addOther = '<span>'.&help_open_topic($topic,&mt($text),$stayOnPage, undef, 600).'</span> ';
 1310:     }
 1311:     $out = '<span>' # Start cheatsheet
 1312: 	  .$addOther
 1313:           .'<span>'
 1314: 	  .&help_open_topic('Greek_Symbols',&mt('Greek Symbols'),$stayOnPage,undef,600)
 1315: 	  .'</span> <span>'
 1316: 	  .&help_open_topic('Other_Symbols',&mt('Other Symbols'),$stayOnPage,undef,600)
 1317: 	  .'</span>';
 1318:     unless ($not_author) {
 1319:         $out .= '<span>'
 1320:                .&help_open_topic('Authoring_Output_Tags',&mt('Output Tags'),$stayOnPage,undef,600)
 1321:                .'</span> <span>'
 1322:                .&help_open_topic('Authoring_Multilingual_Problems',&mt('How to create problems in different languages'),$stayOnPage,undef,600)
 1323: 	       .'</span>';
 1324:     }
 1325:     $out .= '</span>'; # End cheatsheet
 1326:     return $out;
 1327: }
 1328: 
 1329: sub general_help {
 1330:     my $helptopic='Student_Intro';
 1331:     if ($env{'request.role'}=~/^(ca|au)/) {
 1332: 	$helptopic='Authoring_Intro';
 1333:     } elsif ($env{'request.role'}=~/^(cc|co)/) {
 1334: 	$helptopic='Course_Coordination_Intro';
 1335:     } elsif ($env{'request.role'}=~/^dc/) {
 1336:         $helptopic='Domain_Coordination_Intro';
 1337:     }
 1338:     return $helptopic;
 1339: }
 1340: 
 1341: sub update_help_link {
 1342:     my ($topic,$component_help,$faq,$bug,$stayOnPage) = @_;
 1343:     my $origurl = $ENV{'REQUEST_URI'};
 1344:     $origurl=~s|^/~|/priv/|;
 1345:     my $timestamp = time;
 1346:     foreach my $datum (\$topic,\$component_help,\$faq,\$bug,\$origurl) {
 1347:         $$datum = &escape($$datum);
 1348:     }
 1349: 
 1350:     my $banner_link = "/adm/helpmenu?page=banner&amp;topic=$topic&amp;component_help=$component_help&amp;faq=$faq&amp;bug=$bug&amp;origurl=$origurl&amp;stamp=$timestamp&amp;stayonpage=$stayOnPage";
 1351:     my $output .= <<"ENDOUTPUT";
 1352: <script type="text/javascript">
 1353: // <![CDATA[
 1354: banner_link = '$banner_link';
 1355: // ]]>
 1356: </script>
 1357: ENDOUTPUT
 1358:     return $output;
 1359: }
 1360: 
 1361: # now just updates the help link and generates a blue icon
 1362: sub help_open_menu {
 1363:     my ($topic,$component_help,$faq,$bug,$stayOnPage,$width,$height,$text) 
 1364: 	= @_;    
 1365:     $stayOnPage = 1;
 1366:     my $output;
 1367:     if ($component_help) {
 1368: 	if (!$text) {
 1369: 	    $output=&help_open_topic($component_help,undef,$stayOnPage,
 1370: 				       $width,$height);
 1371: 	} else {
 1372: 	    my $help_text;
 1373: 	    $help_text=&unescape($topic);
 1374: 	    $output='<table><tr><td>'.
 1375: 		&help_open_topic($component_help,$help_text,$stayOnPage,
 1376: 				 $width,$height).'</td></tr></table>';
 1377: 	}
 1378:     }
 1379:     my $banner_link = &update_help_link($topic,$component_help,$faq,$bug,$stayOnPage);
 1380:     return $output.$banner_link;
 1381: }
 1382: 
 1383: sub top_nav_help {
 1384:     my ($text) = @_;
 1385:     $text = &mt($text);
 1386:     my $stay_on_page = 1;
 1387: 
 1388:     my ($link,$banner_link);
 1389:     unless ($env{'request.noversionuri'} =~ m{^/adm/helpmenu}) {
 1390:         $link = ($stay_on_page) ? "javascript:helpMenu('display')"
 1391: 	                         : "javascript:helpMenu('open')";
 1392:         $banner_link = &update_help_link(undef,undef,undef,undef,$stay_on_page);
 1393:     }
 1394:     my $title = &mt('Get help');
 1395:     if ($link) {
 1396:         return <<"END";
 1397: $banner_link
 1398: <a href="$link" title="$title">$text</a>
 1399: END
 1400:     } else {
 1401:         return '&nbsp;'.$text.'&nbsp;';
 1402:     }
 1403: }
 1404: 
 1405: sub help_menu_js {
 1406:     my ($httphost) = @_;
 1407:     my $stayOnPage = 1;
 1408:     my $width = 620;
 1409:     my $height = 600;
 1410:     my $helptopic=&general_help();
 1411:     my $details_link = $httphost.'/adm/help/'.$helptopic.'.hlp';
 1412:     my $nothing=&Apache::lonhtmlcommon::javascript_nothing();
 1413:     my $start_page =
 1414:         &Apache::loncommon::start_page('Help Menu', undef,
 1415: 				       {'frameset'    => 1,
 1416: 					'js_ready'    => 1,
 1417:                                         'use_absolute' => $httphost,
 1418: 					'add_entries' => {
 1419: 					    'border' => '0', 
 1420: 					    'rows'   => "110,*",},});
 1421:     my $end_page =
 1422:         &Apache::loncommon::end_page({'frameset' => 1,
 1423: 				      'js_ready' => 1,});
 1424: 
 1425:     my $template .= <<"ENDTEMPLATE";
 1426: <script type="text/javascript">
 1427: // <![CDATA[
 1428: // <!-- BEGIN LON-CAPA Internal
 1429: var banner_link = '';
 1430: function helpMenu(target) {
 1431:     var caller = this;
 1432:     if (target == 'open') {
 1433:         var newWindow = null;
 1434:         try {
 1435:             newWindow =  window.open($nothing,"helpmenu","HEIGHT=$height,WIDTH=$width,resizable=yes,scrollbars=yes" )
 1436:         }
 1437:         catch(error) {
 1438:             writeHelp(caller);
 1439:             return;
 1440:         }
 1441:         if (newWindow) {
 1442:             caller = newWindow;
 1443:         }
 1444:     }
 1445:     writeHelp(caller);
 1446:     return;
 1447: }
 1448: function writeHelp(caller) {
 1449:     caller.document.writeln('$start_page\\n<frame name="bannerframe" src="'+banner_link+'" marginwidth="0" marginheight="0" frameborder="0">\\n');
 1450:     caller.document.writeln('<frame name="bodyframe" src="$details_link" marginwidth="0" marginheight="0" frameborder="0">\\n$end_page');
 1451:     caller.document.close();
 1452:     caller.focus();
 1453: }
 1454: // END LON-CAPA Internal -->
 1455: // ]]>
 1456: </script>
 1457: ENDTEMPLATE
 1458:     return $template;
 1459: }
 1460: 
 1461: sub help_open_bug {
 1462:     my ($topic, $text, $stayOnPage, $width, $height) = @_;
 1463:     unless ($env{'user.adv'}) { return ''; }
 1464:     unless ($Apache::lonnet::perlvar{'BugzillaHost'}) { return ''; }
 1465:     $text = "" if (not defined $text);
 1466: 	$stayOnPage=1;
 1467:     $width = 600 if (not defined $width);
 1468:     $height = 600 if (not defined $height);
 1469: 
 1470:     $topic=~s/\W+/\+/g;
 1471:     my $link='';
 1472:     my $template='';
 1473:     my $url=$Apache::lonnet::perlvar{'BugzillaHost'}.'enter_bug.cgi?product=LON-CAPA&amp;bug_file_loc='.
 1474: 	&escape($ENV{'REQUEST_URI'}).'&amp;component='.$topic;
 1475:     if (!$stayOnPage)
 1476:     {
 1477: 	$link = "javascript:void(open('$url', 'Bugzilla', 'menubar=0,toolbar=1,scrollbars=1,width=$width,height=$height,resizable=yes'))";
 1478:     }
 1479:     else
 1480:     {
 1481: 	$link = $url;
 1482:     }
 1483:     # Add the text
 1484:     if ($text ne "")
 1485:     {
 1486: 	$template .= 
 1487:   "<table bgcolor='#AA3333' cellspacing='1' cellpadding='1' border='0'><tr>".
 1488:   "<td bgcolor='#FF5555'><a target=\"_top\" href=\"$link\"><span style=\"color:#FFFFFF;font-size:10pt;\">$text</span></a>";
 1489:     }
 1490: 
 1491:     # Add the graphic
 1492:     my $title = &mt('Report a Bug');
 1493:     my $bugicon=&lonhttpdurl("/adm/lonMisc/smallBug.gif");
 1494:     $template .= <<"ENDTEMPLATE";
 1495:  <a target="_top" href="$link" title="$title"><img src="$bugicon" border="0" alt="(Bug: $topic)" /></a>
 1496: ENDTEMPLATE
 1497:     if ($text ne '') { $template.='</td></tr></table>' };
 1498:     return $template;
 1499: 
 1500: }
 1501: 
 1502: sub help_open_faq {
 1503:     my ($topic, $text, $stayOnPage, $width, $height) = @_;
 1504:     unless ($env{'user.adv'}) { return ''; }
 1505:     unless ($Apache::lonnet::perlvar{'FAQHost'}) { return ''; }
 1506:     $text = "" if (not defined $text);
 1507: 	$stayOnPage=1;
 1508:     $width = 350 if (not defined $width);
 1509:     $height = 400 if (not defined $height);
 1510: 
 1511:     $topic=~s/\W+/\+/g;
 1512:     my $link='';
 1513:     my $template='';
 1514:     my $url=$Apache::lonnet::perlvar{'FAQHost'}.'/fom/cache/'.$topic.'.html';
 1515:     if (!$stayOnPage)
 1516:     {
 1517: 	$link = "javascript:void(open('$url', 'FAQ-O-Matic', 'menubar=0,toolbar=1,scrollbars=1,width=$width,height=$height,resizable=yes'))";
 1518:     }
 1519:     else
 1520:     {
 1521: 	$link = $url;
 1522:     }
 1523: 
 1524:     # Add the text
 1525:     if ($text ne "")
 1526:     {
 1527: 	$template .= 
 1528:   "<table bgcolor='#337733' cellspacing='1' cellpadding='1' border='0'><tr>".
 1529:   "<td bgcolor='#448844'><a target=\"_top\" href=\"$link\"><span style=\"color:#FFFFFF; font-size:10pt;\">$text</span></a>";
 1530:     }
 1531: 
 1532:     # Add the graphic
 1533:     my $title = &mt('View the FAQ');
 1534:     my $faqicon=&lonhttpdurl("/adm/lonMisc/smallFAQ.gif");
 1535:     $template .= <<"ENDTEMPLATE";
 1536:  <a target="_top" href="$link" title="$title"><img src="$faqicon" border="0" alt="(FAQ: $topic)" /></a>
 1537: ENDTEMPLATE
 1538:     if ($text ne '') { $template.='</td></tr></table>' };
 1539:     return $template;
 1540: 
 1541: }
 1542: 
 1543: ###############################################################
 1544: ###############################################################
 1545: 
 1546: =pod
 1547: 
 1548: =item * &change_content_javascript():
 1549: 
 1550: This and the next function allow you to create small sections of an
 1551: otherwise static HTML page that you can update on the fly with
 1552: Javascript, even in Netscape 4.
 1553: 
 1554: The Javascript fragment returned by this function (no E<lt>scriptE<gt> tag)
 1555: must be written to the HTML page once. It will prove the Javascript
 1556: function "change(name, content)". Calling the change function with the
 1557: name of the section 
 1558: you want to update, matching the name passed to C<changable_area>, and
 1559: the new content you want to put in there, will put the content into
 1560: that area.
 1561: 
 1562: B<Note>: Netscape 4 only reserves enough space for the changable area
 1563: to contain room for the original contents. You need to "make space"
 1564: for whatever changes you wish to make, and be B<sure> to check your
 1565: code in Netscape 4. This feature in Netscape 4 is B<not> powerful;
 1566: it's adequate for updating a one-line status display, but little more.
 1567: This script will set the space to 100% width, so you only need to
 1568: worry about height in Netscape 4.
 1569: 
 1570: Modern browsers are much less limiting, and if you can commit to the
 1571: user not using Netscape 4, this feature may be used freely with
 1572: pretty much any HTML.
 1573: 
 1574: =cut
 1575: 
 1576: sub change_content_javascript {
 1577:     # If we're on Netscape 4, we need to use Layer-based code
 1578:     if ($env{'browser.type'} eq 'netscape' &&
 1579: 	$env{'browser.version'} =~ /^4\./) {
 1580: 	return (<<NETSCAPE4);
 1581: 	function change(name, content) {
 1582: 	    doc = document.layers[name+"___escape"].layers[0].document;
 1583: 	    doc.open();
 1584: 	    doc.write(content);
 1585: 	    doc.close();
 1586: 	}
 1587: NETSCAPE4
 1588:     } else {
 1589: 	# Otherwise, we need to use semi-standards-compliant code
 1590: 	# (technically, "innerHTML" isn't standard but the equivalent
 1591: 	# is really scary, and every useful browser supports it
 1592: 	return (<<DOMBASED);
 1593: 	function change(name, content) {
 1594: 	    element = document.getElementById(name);
 1595: 	    element.innerHTML = content;
 1596: 	}
 1597: DOMBASED
 1598:     }
 1599: }
 1600: 
 1601: =pod
 1602: 
 1603: =item * &changable_area($name,$origContent):
 1604: 
 1605: This provides a "changable area" that can be modified on the fly via
 1606: the Javascript code provided in C<change_content_javascript>. $name is
 1607: the name you will use to reference the area later; do not repeat the
 1608: same name on a given HTML page more then once. $origContent is what
 1609: the area will originally contain, which can be left blank.
 1610: 
 1611: =cut
 1612: 
 1613: sub changable_area {
 1614:     my ($name, $origContent) = @_;
 1615: 
 1616:     if ($env{'browser.type'} eq 'netscape' &&
 1617: 	$env{'browser.version'} =~ /^4\./) {
 1618: 	# If this is netscape 4, we need to use the Layer tag
 1619: 	return "<ilayer width='100%' id='${name}___escape' overflow='none'><layer width='100%' id='$name' overflow='none'>$origContent</layer></ilayer>";
 1620:     } else {
 1621: 	return "<span id='$name'>$origContent</span>";
 1622:     }
 1623: }
 1624: 
 1625: =pod
 1626: 
 1627: =item * &viewport_geometry_js 
 1628: 
 1629: Provides javascript object (Geometry) which can provide information about the viewport geometry for the client browser.
 1630: 
 1631: =cut
 1632: 
 1633: 
 1634: sub viewport_geometry_js { 
 1635:     return <<"GEOMETRY";
 1636: var Geometry = {};
 1637: function init_geometry() {
 1638:     if (Geometry.init) { return };
 1639:     Geometry.init=1;
 1640:     if (window.innerHeight) {
 1641:         Geometry.getViewportHeight   = function() { return window.innerHeight; };
 1642:         Geometry.getViewportWidth   = function() { return window.innerWidth; };
 1643:         Geometry.getHorizontalScroll = function() { return window.pageXOffset; };
 1644:         Geometry.getVerticalScroll   = function() { return window.pageYOffset; };
 1645:     }
 1646:     else if (document.documentElement && document.documentElement.clientHeight) {
 1647:         Geometry.getViewportHeight =
 1648:             function() { return document.documentElement.clientHeight; };
 1649:         Geometry.getViewportWidth =
 1650:             function() { return document.documentElement.clientWidth; };
 1651: 
 1652:         Geometry.getHorizontalScroll =
 1653:             function() { return document.documentElement.scrollLeft; };
 1654:         Geometry.getVerticalScroll =
 1655:             function() { return document.documentElement.scrollTop; };
 1656:     }
 1657:     else if (document.body.clientHeight) {
 1658:         Geometry.getViewportHeight =
 1659:             function() { return document.body.clientHeight; };
 1660:         Geometry.getViewportWidth =
 1661:             function() { return document.body.clientWidth; };
 1662:         Geometry.getHorizontalScroll =
 1663:             function() { return document.body.scrollLeft; };
 1664:         Geometry.getVerticalScroll =
 1665:             function() { return document.body.scrollTop; };
 1666:     }
 1667: }
 1668: 
 1669: GEOMETRY
 1670: }
 1671: 
 1672: =pod
 1673: 
 1674: =item * &viewport_size_js()
 1675: 
 1676: Provides a javascript function to set values of two form elements - width and height (elements are passed in as arguments to the javascript function) to the dimensions of the user's browser window. 
 1677: 
 1678: =cut
 1679: 
 1680: sub viewport_size_js {
 1681:     my $geometry = &viewport_geometry_js();
 1682:     return <<"DIMS";
 1683: 
 1684: $geometry
 1685: 
 1686: function getViewportDims(width,height) {
 1687:     init_geometry();
 1688:     width.value = Geometry.getViewportWidth();
 1689:     height.value = Geometry.getViewportHeight();
 1690:     return;
 1691: }
 1692: 
 1693: DIMS
 1694: }
 1695: 
 1696: =pod
 1697: 
 1698: =item * &resize_textarea_js()
 1699: 
 1700: emits the needed javascript to resize a textarea to be as big as possible
 1701: 
 1702: creates a function resize_textrea that takes two IDs first should be
 1703: the id of the element to resize, second should be the id of a div that
 1704: surrounds everything that comes after the textarea, this routine needs
 1705: to be attached to the <body> for the onload and onresize events.
 1706: 
 1707: =back
 1708: 
 1709: =cut
 1710: 
 1711: sub resize_textarea_js {
 1712:     my $geometry = &viewport_geometry_js();
 1713:     return <<"RESIZE";
 1714:     <script type="text/javascript">
 1715: // <![CDATA[
 1716: $geometry
 1717: 
 1718: function getX(element) {
 1719:     var x = 0;
 1720:     while (element) {
 1721: 	x += element.offsetLeft;
 1722: 	element = element.offsetParent;
 1723:     }
 1724:     return x;
 1725: }
 1726: function getY(element) {
 1727:     var y = 0;
 1728:     while (element) {
 1729: 	y += element.offsetTop;
 1730: 	element = element.offsetParent;
 1731:     }
 1732:     return y;
 1733: }
 1734: 
 1735: 
 1736: function resize_textarea(textarea_id,bottom_id) {
 1737:     init_geometry();
 1738:     var textarea        = document.getElementById(textarea_id);
 1739:     //alert(textarea);
 1740: 
 1741:     var textarea_top    = getY(textarea);
 1742:     var textarea_height = textarea.offsetHeight;
 1743:     var bottom          = document.getElementById(bottom_id);
 1744:     var bottom_top      = getY(bottom);
 1745:     var bottom_height   = bottom.offsetHeight;
 1746:     var window_height   = Geometry.getViewportHeight();
 1747:     var fudge           = 23;
 1748:     var new_height      = window_height-fudge-textarea_top-bottom_height;
 1749:     if (new_height < 300) {
 1750: 	new_height = 300;
 1751:     }
 1752:     textarea.style.height=new_height+'px';
 1753: }
 1754: // ]]>
 1755: </script>
 1756: RESIZE
 1757: 
 1758: }
 1759: 
 1760: =pod
 1761: 
 1762: =head1 Excel and CSV file utility routines
 1763: 
 1764: =cut
 1765: 
 1766: ###############################################################
 1767: ###############################################################
 1768: 
 1769: =pod
 1770: 
 1771: =over 4
 1772: 
 1773: =item * &csv_translate($text) 
 1774: 
 1775: Translate $text to allow it to be output as a 'comma separated values' 
 1776: format.
 1777: 
 1778: =cut
 1779: 
 1780: ###############################################################
 1781: ###############################################################
 1782: sub csv_translate {
 1783:     my $text = shift;
 1784:     $text =~ s/\"/\"\"/g;
 1785:     $text =~ s/\n/ /g;
 1786:     return $text;
 1787: }
 1788: 
 1789: ###############################################################
 1790: ###############################################################
 1791: 
 1792: =pod
 1793: 
 1794: =item * &define_excel_formats()
 1795: 
 1796: Define some commonly used Excel cell formats.
 1797: 
 1798: Currently supported formats:
 1799: 
 1800: =over 4
 1801: 
 1802: =item header
 1803: 
 1804: =item bold
 1805: 
 1806: =item h1
 1807: 
 1808: =item h2
 1809: 
 1810: =item h3
 1811: 
 1812: =item h4
 1813: 
 1814: =item i
 1815: 
 1816: =item date
 1817: 
 1818: =back
 1819: 
 1820: Inputs: $workbook
 1821: 
 1822: Returns: $format, a hash reference.
 1823: 
 1824: 
 1825: =cut
 1826: 
 1827: ###############################################################
 1828: ###############################################################
 1829: sub define_excel_formats {
 1830:     my ($workbook) = @_;
 1831:     my $format;
 1832:     $format->{'header'} = $workbook->add_format(bold      => 1, 
 1833:                                                 bottom    => 1,
 1834:                                                 align     => 'center');
 1835:     $format->{'bold'} = $workbook->add_format(bold=>1);
 1836:     $format->{'h1'}   = $workbook->add_format(bold=>1, size=>18);
 1837:     $format->{'h2'}   = $workbook->add_format(bold=>1, size=>16);
 1838:     $format->{'h3'}   = $workbook->add_format(bold=>1, size=>14);
 1839:     $format->{'h4'}   = $workbook->add_format(bold=>1, size=>12);
 1840:     $format->{'i'}    = $workbook->add_format(italic=>1);
 1841:     $format->{'date'} = $workbook->add_format(num_format=>
 1842:                                             'mm/dd/yyyy hh:mm:ss');
 1843:     return $format;
 1844: }
 1845: 
 1846: ###############################################################
 1847: ###############################################################
 1848: 
 1849: =pod
 1850: 
 1851: =item * &create_workbook()
 1852: 
 1853: Create an Excel worksheet.  If it fails, output message on the
 1854: request object and return undefs.
 1855: 
 1856: Inputs: Apache request object
 1857: 
 1858: Returns (undef) on failure, 
 1859:     Excel worksheet object, scalar with filename, and formats 
 1860:     from &Apache::loncommon::define_excel_formats on success
 1861: 
 1862: =cut
 1863: 
 1864: ###############################################################
 1865: ###############################################################
 1866: sub create_workbook {
 1867:     my ($r) = @_;
 1868:         #
 1869:     # Create the excel spreadsheet
 1870:     my $filename = '/prtspool/'.
 1871:         $env{'user.name'}.'_'.$env{'user.domain'}.'_'.
 1872:         time.'_'.rand(1000000000).'.xls';
 1873:     my $workbook  = Spreadsheet::WriteExcel->new('/home/httpd'.$filename);
 1874:     if (! defined($workbook)) {
 1875:         $r->log_error("Error creating excel spreadsheet $filename: $!");
 1876:         $r->print(
 1877:             '<p class="LC_error">'
 1878:            .&mt('Problems occurred in creating the new Excel file.')
 1879:            .' '.&mt('This error has been logged.')
 1880:            .' '.&mt('Please alert your LON-CAPA administrator.')
 1881:            .'</p>'
 1882:         );
 1883:         return (undef);
 1884:     }
 1885:     #
 1886:     $workbook->set_tempdir(LONCAPA::tempdir());
 1887:     #
 1888:     my $format = &Apache::loncommon::define_excel_formats($workbook);
 1889:     return ($workbook,$filename,$format);
 1890: }
 1891: 
 1892: ###############################################################
 1893: ###############################################################
 1894: 
 1895: =pod
 1896: 
 1897: =item * &create_text_file()
 1898: 
 1899: Create a file to write to and eventually make available to the user.
 1900: If file creation fails, outputs an error message on the request object and 
 1901: return undefs.
 1902: 
 1903: Inputs: Apache request object, and file suffix
 1904: 
 1905: Returns (undef) on failure, 
 1906:     Filehandle and filename on success.
 1907: 
 1908: =cut
 1909: 
 1910: ###############################################################
 1911: ###############################################################
 1912: sub create_text_file {
 1913:     my ($r,$suffix) = @_;
 1914:     if (! defined($suffix)) { $suffix = 'txt'; };
 1915:     my $fh;
 1916:     my $filename = '/prtspool/'.
 1917:         $env{'user.name'}.'_'.$env{'user.domain'}.'_'.
 1918:         time.'_'.rand(1000000000).'.'.$suffix;
 1919:     $fh = Apache::File->new('>/home/httpd'.$filename);
 1920:     if (! defined($fh)) {
 1921:         $r->log_error("Couldn't open $filename for output $!");
 1922:         $r->print(
 1923:             '<p class="LC_error">'
 1924:            .&mt('Problems occurred in creating the output file.')
 1925:            .' '.&mt('This error has been logged.')
 1926:            .' '.&mt('Please alert your LON-CAPA administrator.')
 1927:            .'</p>'
 1928:         );
 1929:     }
 1930:     return ($fh,$filename)
 1931: }
 1932: 
 1933: 
 1934: =pod 
 1935: 
 1936: =back
 1937: 
 1938: =cut
 1939: 
 1940: ###############################################################
 1941: ##        Home server <option> list generating code          ##
 1942: ###############################################################
 1943: 
 1944: # ------------------------------------------
 1945: 
 1946: sub domain_select {
 1947:     my ($name,$value,$multiple)=@_;
 1948:     my %domains=map { 
 1949: 	$_ => $_.' '. &Apache::lonnet::domain($_,'description') 
 1950:     } &Apache::lonnet::all_domains();
 1951:     if ($multiple) {
 1952: 	$domains{''}=&mt('Any domain');
 1953: 	$domains{'select_form_order'} = [sort {lc($a) cmp lc($b) } (keys(%domains))];
 1954: 	return &multiple_select_form($name,$value,4,\%domains);
 1955:     } else {
 1956: 	$domains{'select_form_order'} = [sort {lc($a) cmp lc($b) } (keys(%domains))];
 1957: 	return &select_form($name,$value,\%domains);
 1958:     }
 1959: }
 1960: 
 1961: #-------------------------------------------
 1962: 
 1963: =pod
 1964: 
 1965: =head1 Routines for form select boxes
 1966: 
 1967: =over 4
 1968: 
 1969: =item * &multiple_select_form($name,$value,$size,$hash,$order)
 1970: 
 1971: Returns a string containing a <select> element int multiple mode
 1972: 
 1973: 
 1974: Args:
 1975:   $name - name of the <select> element
 1976:   $value - scalar or array ref of values that should already be selected
 1977:   $size - number of rows long the select element is
 1978:   $hash - the elements should be 'option' => 'shown text'
 1979:           (shown text should already have been &mt())
 1980:   $order - (optional) array ref of the order to show the elements in
 1981: 
 1982: =cut
 1983: 
 1984: #-------------------------------------------
 1985: sub multiple_select_form {
 1986:     my ($name,$value,$size,$hash,$order)=@_;
 1987:     my %selected = map { $_ => 1 } ref($value)?@{$value}:($value);
 1988:     my $output='';
 1989:     if (! defined($size)) {
 1990:         $size = 4;
 1991:         if (scalar(keys(%$hash))<4) {
 1992:             $size = scalar(keys(%$hash));
 1993:         }
 1994:     }
 1995:     $output.="\n".'<select name="'.$name.'" size="'.$size.'" multiple="multiple">';
 1996:     my @order;
 1997:     if (ref($order) eq 'ARRAY')  {
 1998:         @order = @{$order};
 1999:     } else {
 2000:         @order = sort(keys(%$hash));
 2001:     }
 2002:     if (exists($$hash{'select_form_order'})) {
 2003:         @order = @{$$hash{'select_form_order'}};
 2004:     }
 2005:         
 2006:     foreach my $key (@order) {
 2007:         $output.='<option value="'.&HTML::Entities::encode($key,'"<>&').'" ';
 2008:         $output.='selected="selected" ' if ($selected{$key});
 2009:         $output.='>'.$hash->{$key}."</option>\n";
 2010:     }
 2011:     $output.="</select>\n";
 2012:     return $output;
 2013: }
 2014: 
 2015: #-------------------------------------------
 2016: 
 2017: =pod
 2018: 
 2019: =item * &select_form($defdom,$name,$hashref,$onchange)
 2020: 
 2021: Returns a string containing a <select name='$name' size='1'> form to 
 2022: allow a user to select options from a ref to a hash containing:
 2023: option_name => displayed text. An optional $onchange can include
 2024: a javascript onchange item, e.g., onchange="this.form.submit();"  
 2025: 
 2026: See lonrights.pm for an example invocation and use.
 2027: 
 2028: =cut
 2029: 
 2030: #-------------------------------------------
 2031: sub select_form {
 2032:     my ($def,$name,$hashref,$onchange) = @_;
 2033:     return unless (ref($hashref) eq 'HASH');
 2034:     if ($onchange) {
 2035:         $onchange = ' onchange="'.$onchange.'"';
 2036:     }
 2037:     my $selectform = "<select name=\"$name\" size=\"1\"$onchange>\n";
 2038:     my @keys;
 2039:     if (exists($hashref->{'select_form_order'})) {
 2040: 	@keys=@{$hashref->{'select_form_order'}};
 2041:     } else {
 2042: 	@keys=sort(keys(%{$hashref}));
 2043:     }
 2044:     foreach my $key (@keys) {
 2045:         $selectform.=
 2046: 	    '<option value="'.&HTML::Entities::encode($key,'"<>&').'" '.
 2047:             ($key eq $def ? 'selected="selected" ' : '').
 2048:                 ">".$hashref->{$key}."</option>\n";
 2049:     }
 2050:     $selectform.="</select>";
 2051:     return $selectform;
 2052: }
 2053: 
 2054: # For display filters
 2055: 
 2056: sub display_filter {
 2057:     my ($context) = @_;
 2058:     if (!$env{'form.show'}) { $env{'form.show'}=10; }
 2059:     if (!$env{'form.displayfilter'}) { $env{'form.displayfilter'}='currentfolder'; }
 2060:     my $phraseinput = 'hidden';
 2061:     my $includeinput = 'hidden';
 2062:     my ($checked,$includetypestext);
 2063:     if ($env{'form.displayfilter'} eq 'containing') {
 2064:         $phraseinput = 'text'; 
 2065:         if ($context eq 'parmslog') {
 2066:             $includeinput = 'checkbox';
 2067:             if ($env{'form.includetypes'}) {
 2068:                 $checked = ' checked="checked"';
 2069:             }
 2070:             $includetypestext = &mt('Include parameter types');
 2071:         }
 2072:     } else {
 2073:         $includetypestext = '&nbsp;';
 2074:     }
 2075:     my ($additional,$secondid,$thirdid);
 2076:     if ($context eq 'parmslog') {
 2077:         $additional = 
 2078:             '<label><input type="'.$includeinput.'" name="includetypes"'. 
 2079:             $checked.' name="includetypes" value="1" id="includetypes" />'.
 2080:             '&nbsp;<span id="includetypestext">'.$includetypestext.'</span>'.
 2081:             '</label>';
 2082:         $secondid = 'includetypes';
 2083:         $thirdid = 'includetypestext';
 2084:     }
 2085:     my $onchange = "javascript:toggleHistoryOptions(this,'containingphrase','$context',
 2086:                                                     '$secondid','$thirdid')";
 2087:     return '<span class="LC_nobreak"><label>'.&mt('Records: [_1]',
 2088: 			       &Apache::lonmeta::selectbox('show',$env{'form.show'},undef,
 2089: 							   (&mt('all'),10,20,50,100,1000,10000))).
 2090: 	   '</label></span> <span class="LC_nobreak">'.
 2091:            &mt('Filter: [_1]',
 2092: 	   &select_form($env{'form.displayfilter'},
 2093: 			'displayfilter',
 2094: 			{'currentfolder' => 'Current folder/page',
 2095: 			 'containing' => 'Containing phrase',
 2096: 			 'none' => 'None'},$onchange)).'&nbsp;'.
 2097: 			 '<input type="'.$phraseinput.'" name="containingphrase" id="containingphrase" size="30" value="'.
 2098:                          &HTML::Entities::encode($env{'form.containingphrase'}).
 2099:                          '" />'.$additional;
 2100: }
 2101: 
 2102: sub display_filter_js {
 2103:     my $includetext = &mt('Include parameter types');
 2104:     return <<"ENDJS";
 2105:   
 2106: function toggleHistoryOptions(setter,firstid,context,secondid,thirdid) {
 2107:     var firstType = 'hidden';
 2108:     if (setter.options[setter.selectedIndex].value == 'containing') {
 2109:         firstType = 'text';
 2110:     }
 2111:     firstObject = document.getElementById(firstid);
 2112:     if (typeof(firstObject) == 'object') {
 2113:         if (firstObject.type != firstType) {
 2114:             changeInputType(firstObject,firstType);
 2115:         }
 2116:     }
 2117:     if (context == 'parmslog') {
 2118:         var secondType = 'hidden';
 2119:         if (firstType == 'text') {
 2120:             secondType = 'checkbox';
 2121:         }
 2122:         secondObject = document.getElementById(secondid);  
 2123:         if (typeof(secondObject) == 'object') {
 2124:             if (secondObject.type != secondType) {
 2125:                 changeInputType(secondObject,secondType);
 2126:             }
 2127:         }
 2128:         var textItem = document.getElementById(thirdid);
 2129:         var currtext = textItem.innerHTML;
 2130:         var newtext;
 2131:         if (firstType == 'text') {
 2132:             newtext = '$includetext';
 2133:         } else {
 2134:             newtext = '&nbsp;';
 2135:         }
 2136:         if (currtext != newtext) {
 2137:             textItem.innerHTML = newtext;
 2138:         }
 2139:     }
 2140:     return;
 2141: }
 2142: 
 2143: function changeInputType(oldObject,newType) {
 2144:     var newObject = document.createElement('input');
 2145:     newObject.type = newType;
 2146:     if (oldObject.size) {
 2147:         newObject.size = oldObject.size;
 2148:     }
 2149:     if (oldObject.value) {
 2150:         newObject.value = oldObject.value;
 2151:     }
 2152:     if (oldObject.name) {
 2153:         newObject.name = oldObject.name;
 2154:     }
 2155:     if (oldObject.id) {
 2156:         newObject.id = oldObject.id;
 2157:     }
 2158:     oldObject.parentNode.replaceChild(newObject,oldObject);
 2159:     return;
 2160: }
 2161: 
 2162: ENDJS
 2163: }
 2164: 
 2165: sub gradeleveldescription {
 2166:     my $gradelevel=shift;
 2167:     my %gradelevels=(0 => 'Not specified',
 2168: 		     1 => 'Grade 1',
 2169: 		     2 => 'Grade 2',
 2170: 		     3 => 'Grade 3',
 2171: 		     4 => 'Grade 4',
 2172: 		     5 => 'Grade 5',
 2173: 		     6 => 'Grade 6',
 2174: 		     7 => 'Grade 7',
 2175: 		     8 => 'Grade 8',
 2176: 		     9 => 'Grade 9',
 2177: 		     10 => 'Grade 10',
 2178: 		     11 => 'Grade 11',
 2179: 		     12 => 'Grade 12',
 2180: 		     13 => 'Grade 13',
 2181: 		     14 => '100 Level',
 2182: 		     15 => '200 Level',
 2183: 		     16 => '300 Level',
 2184: 		     17 => '400 Level',
 2185: 		     18 => 'Graduate Level');
 2186:     return &mt($gradelevels{$gradelevel});
 2187: }
 2188: 
 2189: sub select_level_form {
 2190:     my ($deflevel,$name)=@_;
 2191:     unless ($deflevel) { $deflevel=0; }
 2192:     my $selectform = "<select name=\"$name\" size=\"1\">\n";
 2193:     for (my $i=0; $i<=18; $i++) {
 2194:         $selectform.="<option value=\"$i\" ".
 2195:             ($i==$deflevel ? 'selected="selected" ' : '').
 2196:                 ">".&gradeleveldescription($i)."</option>\n";
 2197:     }
 2198:     $selectform.="</select>";
 2199:     return $selectform;
 2200: }
 2201: 
 2202: #-------------------------------------------
 2203: 
 2204: =pod
 2205: 
 2206: =item * &select_dom_form($defdom,$name,$includeempty,$showdomdesc,$onchange,$incdoms,$excdoms)
 2207: 
 2208: Returns a string containing a <select name='$name' size='1'> form to 
 2209: allow a user to select the domain to preform an operation in.  
 2210: See loncreateuser.pm for an example invocation and use.
 2211: 
 2212: If the $includeempty flag is set, it also includes an empty choice ("no domain
 2213: selected");
 2214: 
 2215: If the $showdomdesc flag is set, the domain name is followed by the domain description.
 2216: 
 2217: 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.
 2218: 
 2219: The optional $incdoms is a reference to an array of domains which will be the only available options.
 2220: 
 2221: The optional $excdoms is a reference to an array of domains which will be excluded from the available options.
 2222: 
 2223: =cut
 2224: 
 2225: #-------------------------------------------
 2226: sub select_dom_form {
 2227:     my ($defdom,$name,$includeempty,$showdomdesc,$onchange,$incdoms,$excdoms) = @_;
 2228:     if ($onchange) {
 2229:         $onchange = ' onchange="'.$onchange.'"';
 2230:     }
 2231:     my (@domains,%exclude);
 2232:     if (ref($incdoms) eq 'ARRAY') {
 2233:         @domains = sort {lc($a) cmp lc($b)} (@{$incdoms});
 2234:     } else {
 2235:         @domains = sort {lc($a) cmp lc($b)} (&Apache::lonnet::all_domains());
 2236:     }
 2237:     if ($includeempty) { @domains=('',@domains); }
 2238:     if (ref($excdoms) eq 'ARRAY') {
 2239:         map { $exclude{$_} = 1; } @{$excdoms}; 
 2240:     }
 2241:     my $selectdomain = "<select name=\"$name\" size=\"1\"$onchange>\n";
 2242:     foreach my $dom (@domains) {
 2243:         next if ($exclude{$dom});
 2244:         $selectdomain.="<option value=\"$dom\" ".
 2245:             ($dom eq $defdom ? 'selected="selected" ' : '').'>'.$dom;
 2246:         if ($showdomdesc) {
 2247:             if ($dom ne '') {
 2248:                 my $domdesc = &Apache::lonnet::domain($dom,'description');
 2249:                 if ($domdesc ne '') {
 2250:                     $selectdomain .= ' ('.$domdesc.')';
 2251:                 }
 2252:             } 
 2253:         }
 2254:         $selectdomain .= "</option>\n";
 2255:     }
 2256:     $selectdomain.="</select>";
 2257:     return $selectdomain;
 2258: }
 2259: 
 2260: #-------------------------------------------
 2261: 
 2262: =pod
 2263: 
 2264: =item * &home_server_form_item($domain,$name,$defaultflag)
 2265: 
 2266: input: 4 arguments (two required, two optional) - 
 2267:     $domain - domain of new user
 2268:     $name - name of form element
 2269:     $default - Value of 'default' causes a default item to be first 
 2270:                             option, and selected by default. 
 2271:     $hide - Value of 'hide' causes hiding of the name of the server, 
 2272:                             if 1 server found, or default, if 0 found.
 2273: output: returns 2 items: 
 2274: (a) form element which contains either:
 2275:    (i) <select name="$name">
 2276:         <option value="$hostid1">$hostid $servers{$hostid}</option>
 2277:         <option value="$hostid2">$hostid $servers{$hostid}</option>       
 2278:        </select>
 2279:        form item if there are multiple library servers in $domain, or
 2280:    (ii) an <input type="hidden" name="$name" value="$hostid" /> form item 
 2281:        if there is only one library server in $domain.
 2282: 
 2283: (b) number of library servers found.
 2284: 
 2285: See loncreateuser.pm for example of use.
 2286: 
 2287: =cut
 2288: 
 2289: #-------------------------------------------
 2290: sub home_server_form_item {
 2291:     my ($domain,$name,$default,$hide) = @_;
 2292:     my %servers = &Apache::lonnet::get_servers($domain,'library');
 2293:     my $result;
 2294:     my $numlib = keys(%servers);
 2295:     if ($numlib > 1) {
 2296:         $result .= '<select name="'.$name.'" />'."\n";
 2297:         if ($default) {
 2298:             $result .= '<option value="default" selected="selected">'.&mt('default').
 2299:                        '</option>'."\n";
 2300:         }
 2301:         foreach my $hostid (sort(keys(%servers))) {
 2302:             $result.= '<option value="'.$hostid.'">'.
 2303: 	              $hostid.' '.$servers{$hostid}."</option>\n";
 2304:         }
 2305:         $result .= '</select>'."\n";
 2306:     } elsif ($numlib == 1) {
 2307:         my $hostid;
 2308:         foreach my $item (keys(%servers)) {
 2309:             $hostid = $item;
 2310:         }
 2311:         $result .= '<input type="hidden" name="'.$name.'" value="'.
 2312:                    $hostid.'" />';
 2313:                    if (!$hide) {
 2314:                        $result .= $hostid.' '.$servers{$hostid};
 2315:                    }
 2316:                    $result .= "\n";
 2317:     } elsif ($default) {
 2318:         $result .= '<input type="hidden" name="'.$name.
 2319:                    '" value="default" />';
 2320:                    if (!$hide) {
 2321:                        $result .= &mt('default');
 2322:                    }
 2323:                    $result .= "\n";
 2324:     }
 2325:     return ($result,$numlib);
 2326: }
 2327: 
 2328: =pod
 2329: 
 2330: =back 
 2331: 
 2332: =cut
 2333: 
 2334: ###############################################################
 2335: ##                  Decoding User Agent                      ##
 2336: ###############################################################
 2337: 
 2338: =pod
 2339: 
 2340: =head1 Decoding the User Agent
 2341: 
 2342: =over 4
 2343: 
 2344: =item * &decode_user_agent()
 2345: 
 2346: Inputs: $r
 2347: 
 2348: Outputs:
 2349: 
 2350: =over 4
 2351: 
 2352: =item * $httpbrowser
 2353: 
 2354: =item * $clientbrowser
 2355: 
 2356: =item * $clientversion
 2357: 
 2358: =item * $clientmathml
 2359: 
 2360: =item * $clientunicode
 2361: 
 2362: =item * $clientos
 2363: 
 2364: =item * $clientmobile
 2365: 
 2366: =item * $clientinfo
 2367: 
 2368: =back
 2369: 
 2370: =back 
 2371: 
 2372: =cut
 2373: 
 2374: ###############################################################
 2375: ###############################################################
 2376: sub decode_user_agent {
 2377:     my ($r)=@_;
 2378:     my @browsertype=split(/\&/,$Apache::lonnet::perlvar{"lonBrowsDet"});
 2379:     my %mathcap=split(/\&/,$$Apache::lonnet::perlvar{"lonMathML"});
 2380:     my $httpbrowser=$ENV{"HTTP_USER_AGENT"};
 2381:     if (!$httpbrowser && $r) { $httpbrowser=$r->header_in('User-Agent'); }
 2382:     my $clientbrowser='unknown';
 2383:     my $clientversion='0';
 2384:     my $clientmathml='';
 2385:     my $clientunicode='0';
 2386:     my $clientmobile=0;
 2387:     for (my $i=0;$i<=$#browsertype;$i++) {
 2388:         my ($bname,$match,$notmatch,$vreg,$minv,$univ)=split(/\:/,$browsertype[$i]);
 2389: 	if (($httpbrowser=~/$match/i)  && ($httpbrowser!~/$notmatch/i)) {
 2390: 	    $clientbrowser=$bname;
 2391:             $httpbrowser=~/$vreg/i;
 2392: 	    $clientversion=$1;
 2393:             $clientmathml=($clientversion>=$minv);
 2394:             $clientunicode=($clientversion>=$univ);
 2395: 	}
 2396:     }
 2397:     my $clientos='unknown';
 2398:     my $clientinfo;
 2399:     if (($httpbrowser=~/linux/i) ||
 2400:         ($httpbrowser=~/unix/i) ||
 2401:         ($httpbrowser=~/ux/i) ||
 2402:         ($httpbrowser=~/solaris/i)) { $clientos='unix'; }
 2403:     if (($httpbrowser=~/vax/i) ||
 2404:         ($httpbrowser=~/vms/i)) { $clientos='vms'; }
 2405:     if ($httpbrowser=~/next/i) { $clientos='next'; }
 2406:     if (($httpbrowser=~/mac/i) ||
 2407:         ($httpbrowser=~/powerpc/i)) { $clientos='mac'; }
 2408:     if ($httpbrowser=~/win/i) { $clientos='win'; }
 2409:     if ($httpbrowser=~/embed/i) { $clientos='pda'; }
 2410:     if ($httpbrowser=~/(Android|iPod|iPad|iPhone|webOS|Blackberry|Windows Phone|Opera m(?:ob|in)|Fennec)/i) {
 2411:         $clientmobile=lc($1);
 2412:     }
 2413:     if ($httpbrowser=~ m{Firefox/(\d+\.\d+)}) {
 2414:         $clientinfo = 'firefox-'.$1;
 2415:     } elsif ($httpbrowser=~ m{chromeframe/(\d+\.\d+)\.}) {
 2416:         $clientinfo = 'chromeframe-'.$1;
 2417:     }
 2418:     return ($httpbrowser,$clientbrowser,$clientversion,$clientmathml,
 2419:             $clientunicode,$clientos,$clientmobile,$clientinfo);
 2420: }
 2421: 
 2422: ###############################################################
 2423: ##    Authentication changing form generation subroutines    ##
 2424: ###############################################################
 2425: ##
 2426: ## All of the authform_xxxxxxx subroutines take their inputs in a
 2427: ## hash, and have reasonable default values.
 2428: ##
 2429: ##    formname = the name given in the <form> tag.
 2430: #-------------------------------------------
 2431: 
 2432: =pod
 2433: 
 2434: =head1 Authentication Routines
 2435: 
 2436: =over 4
 2437: 
 2438: =item * &authform_xxxxxx()
 2439: 
 2440: The authform_xxxxxx subroutines provide javascript and html forms which 
 2441: handle some of the conveniences required for authentication forms.  
 2442: This is not an optimal method, but it works.  
 2443: 
 2444: =over 4
 2445: 
 2446: =item * authform_header
 2447: 
 2448: =item * authform_authorwarning
 2449: 
 2450: =item * authform_nochange
 2451: 
 2452: =item * authform_kerberos
 2453: 
 2454: =item * authform_internal
 2455: 
 2456: =item * authform_filesystem
 2457: 
 2458: =back
 2459: 
 2460: See loncreateuser.pm for invocation and use examples.
 2461: 
 2462: =cut
 2463: 
 2464: #-------------------------------------------
 2465: sub authform_header{  
 2466:     my %in = (
 2467:         formname => 'cu',
 2468:         kerb_def_dom => '',
 2469:         @_,
 2470:     );
 2471:     $in{'formname'} = 'document.' . $in{'formname'};
 2472:     my $result='';
 2473: 
 2474: #---------------------------------------------- Code for upper case translation
 2475:     my $Javascript_toUpperCase;
 2476:     unless ($in{kerb_def_dom}) {
 2477:         $Javascript_toUpperCase =<<"END";
 2478:         switch (choice) {
 2479:            case 'krb': currentform.elements[choicearg].value =
 2480:                currentform.elements[choicearg].value.toUpperCase();
 2481:                break;
 2482:            default:
 2483:         }
 2484: END
 2485:     } else {
 2486:         $Javascript_toUpperCase = "";
 2487:     }
 2488: 
 2489:     my $radioval = "'nochange'";
 2490:     if (defined($in{'curr_authtype'})) {
 2491:         if ($in{'curr_authtype'} ne '') {
 2492:             $radioval = "'".$in{'curr_authtype'}."arg'";
 2493:         }
 2494:     }
 2495:     my $argfield = 'null';
 2496:     if (defined($in{'mode'})) {
 2497:         if ($in{'mode'} eq 'modifycourse')  {
 2498:             if (defined($in{'curr_autharg'})) {
 2499:                 if ($in{'curr_autharg'} ne '') {
 2500:                     $argfield = "'$in{'curr_autharg'}'";
 2501:                 }
 2502:             }
 2503:         }
 2504:     }
 2505: 
 2506:     $result.=<<"END";
 2507: var current = new Object();
 2508: current.radiovalue = $radioval;
 2509: current.argfield = $argfield;
 2510: 
 2511: function changed_radio(choice,currentform) {
 2512:     var choicearg = choice + 'arg';
 2513:     // If a radio button in changed, we need to change the argfield
 2514:     if (current.radiovalue != choice) {
 2515:         current.radiovalue = choice;
 2516:         if (current.argfield != null) {
 2517:             currentform.elements[current.argfield].value = '';
 2518:         }
 2519:         if (choice == 'nochange') {
 2520:             current.argfield = null;
 2521:         } else {
 2522:             current.argfield = choicearg;
 2523:             switch(choice) {
 2524:                 case 'krb': 
 2525:                     currentform.elements[current.argfield].value = 
 2526:                         "$in{'kerb_def_dom'}";
 2527:                 break;
 2528:               default:
 2529:                 break;
 2530:             }
 2531:         }
 2532:     }
 2533:     return;
 2534: }
 2535: 
 2536: function changed_text(choice,currentform) {
 2537:     var choicearg = choice + 'arg';
 2538:     if (currentform.elements[choicearg].value !='') {
 2539:         $Javascript_toUpperCase
 2540:         // clear old field
 2541:         if ((current.argfield != choicearg) && (current.argfield != null)) {
 2542:             currentform.elements[current.argfield].value = '';
 2543:         }
 2544:         current.argfield = choicearg;
 2545:     }
 2546:     set_auth_radio_buttons(choice,currentform);
 2547:     return;
 2548: }
 2549: 
 2550: function set_auth_radio_buttons(newvalue,currentform) {
 2551:     var numauthchoices = currentform.login.length;
 2552:     if (typeof numauthchoices  == "undefined") {
 2553:         return;
 2554:     } 
 2555:     var i=0;
 2556:     while (i < numauthchoices) {
 2557:         if (currentform.login[i].value == newvalue) { break; }
 2558:         i++;
 2559:     }
 2560:     if (i == numauthchoices) {
 2561:         return;
 2562:     }
 2563:     current.radiovalue = newvalue;
 2564:     currentform.login[i].checked = true;
 2565:     return;
 2566: }
 2567: END
 2568:     return $result;
 2569: }
 2570: 
 2571: sub authform_authorwarning {
 2572:     my $result='';
 2573:     $result='<i>'.
 2574:         &mt('As a general rule, only authors or co-authors should be '.
 2575:             'filesystem authenticated '.
 2576:             '(which allows access to the server filesystem).')."</i>\n";
 2577:     return $result;
 2578: }
 2579: 
 2580: sub authform_nochange {
 2581:     my %in = (
 2582:               formname => 'document.cu',
 2583:               kerb_def_dom => 'MSU.EDU',
 2584:               @_,
 2585:           );
 2586:     my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
 2587:     my $result;
 2588:     if (!$authnum) {
 2589:         $result = &mt('Under your current role you are not permitted to change login settings for this user');
 2590:     } else {
 2591:         $result = '<label>'.&mt('[_1] Do not change login data',
 2592:                   '<input type="radio" name="login" value="nochange" '.
 2593:                   'checked="checked" onclick="'.
 2594:             "javascript:changed_radio('nochange',$in{'formname'});".'" />').
 2595: 	    '</label>';
 2596:     }
 2597:     return $result;
 2598: }
 2599: 
 2600: sub authform_kerberos {
 2601:     my %in = (
 2602:               formname => 'document.cu',
 2603:               kerb_def_dom => 'MSU.EDU',
 2604:               kerb_def_auth => 'krb4',
 2605:               @_,
 2606:               );
 2607:     my ($check4,$check5,$krbcheck,$krbarg,$krbver,$result,$authtype,
 2608:         $autharg,$jscall);
 2609:     my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
 2610:     if ($in{'kerb_def_auth'} eq 'krb5') {
 2611:        $check5 = ' checked="checked"';
 2612:     } else {
 2613:        $check4 = ' checked="checked"';
 2614:     }
 2615:     $krbarg = $in{'kerb_def_dom'};
 2616:     if (defined($in{'curr_authtype'})) {
 2617:         if ($in{'curr_authtype'} eq 'krb') {
 2618:             $krbcheck = ' checked="checked"';
 2619:             if (defined($in{'mode'})) {
 2620:                 if ($in{'mode'} eq 'modifyuser') {
 2621:                     $krbcheck = '';
 2622:                 }
 2623:             }
 2624:             if (defined($in{'curr_kerb_ver'})) {
 2625:                 if ($in{'curr_krb_ver'} eq '5') {
 2626:                     $check5 = ' checked="checked"';
 2627:                     $check4 = '';
 2628:                 } else {
 2629:                     $check4 = ' checked="checked"';
 2630:                     $check5 = '';
 2631:                 }
 2632:             }
 2633:             if (defined($in{'curr_autharg'})) {
 2634:                 $krbarg = $in{'curr_autharg'};
 2635:             }
 2636:             if (!$can_assign{'krb4'} && !$can_assign{'krb5'}) {
 2637:                 if (defined($in{'curr_autharg'})) {
 2638:                     $result = 
 2639:     &mt('Currently Kerberos authenticated with domain [_1] Version [_2].',
 2640:         $in{'curr_autharg'},$krbver);
 2641:                 } else {
 2642:                     $result =
 2643:     &mt('Currently Kerberos authenticated, Version [_1].',$krbver);
 2644:                 }
 2645:                 return $result; 
 2646:             }
 2647:         }
 2648:     } else {
 2649:         if ($authnum == 1) {
 2650:             $authtype = '<input type="hidden" name="login" value="krb" />';
 2651:         }
 2652:     }
 2653:     if (!$can_assign{'krb4'} && !$can_assign{'krb5'}) {
 2654:         return;
 2655:     } elsif ($authtype eq '') {
 2656:         if (defined($in{'mode'})) {
 2657:             if ($in{'mode'} eq 'modifycourse') {
 2658:                 if ($authnum == 1) {
 2659:                     $authtype = '<input type="radio" name="login" value="krb" />';
 2660:                 }
 2661:             }
 2662:         }
 2663:     }
 2664:     $jscall = "javascript:changed_radio('krb',$in{'formname'});";
 2665:     if ($authtype eq '') {
 2666:         $authtype = '<input type="radio" name="login" value="krb" '.
 2667:                     'onclick="'.$jscall.'" onchange="'.$jscall.'"'.
 2668:                     $krbcheck.' />';
 2669:     }
 2670:     if (($can_assign{'krb4'} && $can_assign{'krb5'}) ||
 2671:         ($can_assign{'krb4'} && !$can_assign{'krb5'} &&
 2672:          $in{'curr_authtype'} eq 'krb5') ||
 2673:         (!$can_assign{'krb4'} && $can_assign{'krb5'} &&
 2674:          $in{'curr_authtype'} eq 'krb4')) {
 2675:         $result .= &mt
 2676:         ('[_1] Kerberos authenticated with domain [_2] '.
 2677:          '[_3] Version 4 [_4] Version 5 [_5]',
 2678:          '<label>'.$authtype,
 2679:          '</label><input type="text" size="10" name="krbarg" '.
 2680:              'value="'.$krbarg.'" '.
 2681:              'onchange="'.$jscall.'" />',
 2682:          '<label><input type="radio" name="krbver" value="4" '.$check4.' />',
 2683:          '</label><label><input type="radio" name="krbver" value="5" '.$check5.' />',
 2684: 	 '</label>');
 2685:     } elsif ($can_assign{'krb4'}) {
 2686:         $result .= &mt
 2687:         ('[_1] Kerberos authenticated with domain [_2] '.
 2688:          '[_3] Version 4 [_4]',
 2689:          '<label>'.$authtype,
 2690:          '</label><input type="text" size="10" name="krbarg" '.
 2691:              'value="'.$krbarg.'" '.
 2692:              'onchange="'.$jscall.'" />',
 2693:          '<label><input type="hidden" name="krbver" value="4" />',
 2694:          '</label>');
 2695:     } elsif ($can_assign{'krb5'}) {
 2696:         $result .= &mt
 2697:         ('[_1] Kerberos authenticated with domain [_2] '.
 2698:          '[_3] Version 5 [_4]',
 2699:          '<label>'.$authtype,
 2700:          '</label><input type="text" size="10" name="krbarg" '.
 2701:              'value="'.$krbarg.'" '.
 2702:              'onchange="'.$jscall.'" />',
 2703:          '<label><input type="hidden" name="krbver" value="5" />',
 2704:          '</label>');
 2705:     }
 2706:     return $result;
 2707: }
 2708: 
 2709: sub authform_internal {
 2710:     my %in = (
 2711:                 formname => 'document.cu',
 2712:                 kerb_def_dom => 'MSU.EDU',
 2713:                 @_,
 2714:                 );
 2715:     my ($intcheck,$intarg,$result,$authtype,$autharg,$jscall);
 2716:     my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
 2717:     if (defined($in{'curr_authtype'})) {
 2718:         if ($in{'curr_authtype'} eq 'int') {
 2719:             if ($can_assign{'int'}) {
 2720:                 $intcheck = 'checked="checked" ';
 2721:                 if (defined($in{'mode'})) {
 2722:                     if ($in{'mode'} eq 'modifyuser') {
 2723:                         $intcheck = '';
 2724:                     }
 2725:                 }
 2726:                 if (defined($in{'curr_autharg'})) {
 2727:                     $intarg = $in{'curr_autharg'};
 2728:                 }
 2729:             } else {
 2730:                 $result = &mt('Currently internally authenticated.');
 2731:                 return $result;
 2732:             }
 2733:         }
 2734:     } else {
 2735:         if ($authnum == 1) {
 2736:             $authtype = '<input type="hidden" name="login" value="int" />';
 2737:         }
 2738:     }
 2739:     if (!$can_assign{'int'}) {
 2740:         return;
 2741:     } elsif ($authtype eq '') {
 2742:         if (defined($in{'mode'})) {
 2743:             if ($in{'mode'} eq 'modifycourse') {
 2744:                 if ($authnum == 1) {
 2745:                     $authtype = '<input type="radio" name="login" value="int" />';
 2746:                 }
 2747:             }
 2748:         }
 2749:     }
 2750:     $jscall = "javascript:changed_radio('int',$in{'formname'});";
 2751:     if ($authtype eq '') {
 2752:         $authtype = '<input type="radio" name="login" value="int" '.$intcheck.
 2753:                     ' onchange="'.$jscall.'" onclick="'.$jscall.'" />';
 2754:     }
 2755:     $autharg = '<input type="password" size="10" name="intarg" value="'.
 2756:                $intarg.'" onchange="'.$jscall.'" />';
 2757:     $result = &mt
 2758:         ('[_1] Internally authenticated (with initial password [_2])',
 2759:          '<label>'.$authtype,'</label>'.$autharg);
 2760:     $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>';
 2761:     return $result;
 2762: }
 2763: 
 2764: sub authform_local {
 2765:     my %in = (
 2766:               formname => 'document.cu',
 2767:               kerb_def_dom => 'MSU.EDU',
 2768:               @_,
 2769:               );
 2770:     my ($loccheck,$locarg,$result,$authtype,$autharg,$jscall);
 2771:     my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
 2772:     if (defined($in{'curr_authtype'})) {
 2773:         if ($in{'curr_authtype'} eq 'loc') {
 2774:             if ($can_assign{'loc'}) {
 2775:                 $loccheck = 'checked="checked" ';
 2776:                 if (defined($in{'mode'})) {
 2777:                     if ($in{'mode'} eq 'modifyuser') {
 2778:                         $loccheck = '';
 2779:                     }
 2780:                 }
 2781:                 if (defined($in{'curr_autharg'})) {
 2782:                     $locarg = $in{'curr_autharg'};
 2783:                 }
 2784:             } else {
 2785:                 $result = &mt('Currently using local (institutional) authentication.');
 2786:                 return $result;
 2787:             }
 2788:         }
 2789:     } else {
 2790:         if ($authnum == 1) {
 2791:             $authtype = '<input type="hidden" name="login" value="loc" />';
 2792:         }
 2793:     }
 2794:     if (!$can_assign{'loc'}) {
 2795:         return;
 2796:     } elsif ($authtype eq '') {
 2797:         if (defined($in{'mode'})) {
 2798:             if ($in{'mode'} eq 'modifycourse') {
 2799:                 if ($authnum == 1) {
 2800:                     $authtype = '<input type="radio" name="login" value="loc" />';
 2801:                 }
 2802:             }
 2803:         }
 2804:     }
 2805:     $jscall = "javascript:changed_radio('loc',$in{'formname'});";
 2806:     if ($authtype eq '') {
 2807:         $authtype = '<input type="radio" name="login" value="loc" '.
 2808:                     $loccheck.' onchange="'.$jscall.'" onclick="'.
 2809:                     $jscall.'" />';
 2810:     }
 2811:     $autharg = '<input type="text" size="10" name="locarg" value="'.
 2812:                $locarg.'" onchange="'.$jscall.'" />';
 2813:     $result = &mt('[_1] Local Authentication with argument [_2]',
 2814:                   '<label>'.$authtype,'</label>'.$autharg);
 2815:     return $result;
 2816: }
 2817: 
 2818: sub authform_filesystem {
 2819:     my %in = (
 2820:               formname => 'document.cu',
 2821:               kerb_def_dom => 'MSU.EDU',
 2822:               @_,
 2823:               );
 2824:     my ($fsyscheck,$result,$authtype,$autharg,$jscall);
 2825:     my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
 2826:     if (defined($in{'curr_authtype'})) {
 2827:         if ($in{'curr_authtype'} eq 'fsys') {
 2828:             if ($can_assign{'fsys'}) {
 2829:                 $fsyscheck = 'checked="checked" ';
 2830:                 if (defined($in{'mode'})) {
 2831:                     if ($in{'mode'} eq 'modifyuser') {
 2832:                         $fsyscheck = '';
 2833:                     }
 2834:                 }
 2835:             } else {
 2836:                 $result = &mt('Currently Filesystem Authenticated.');
 2837:                 return $result;
 2838:             }           
 2839:         }
 2840:     } else {
 2841:         if ($authnum == 1) {
 2842:             $authtype = '<input type="hidden" name="login" value="fsys" />';
 2843:         }
 2844:     }
 2845:     if (!$can_assign{'fsys'}) {
 2846:         return;
 2847:     } elsif ($authtype eq '') {
 2848:         if (defined($in{'mode'})) {
 2849:             if ($in{'mode'} eq 'modifycourse') {
 2850:                 if ($authnum == 1) {
 2851:                     $authtype = '<input type="radio" name="login" value="fsys" />';
 2852:                 }
 2853:             }
 2854:         }
 2855:     }
 2856:     $jscall = "javascript:changed_radio('fsys',$in{'formname'});";
 2857:     if ($authtype eq '') {
 2858:         $authtype = '<input type="radio" name="login" value="fsys" '.
 2859:                     $fsyscheck.' onchange="'.$jscall.'" onclick="'.
 2860:                     $jscall.'" />';
 2861:     }
 2862:     $autharg = '<input type="text" size="10" name="fsysarg" value=""'.
 2863:                ' onchange="'.$jscall.'" />';
 2864:     $result = &mt
 2865:         ('[_1] Filesystem Authenticated (with initial password [_2])',
 2866:          '<label><input type="radio" name="login" value="fsys" '.
 2867:          $fsyscheck.'onchange="'.$jscall.'" onclick="'.$jscall.'" />',
 2868:          '</label><input type="password" size="10" name="fsysarg" value="" '.
 2869:                   'onchange="'.$jscall.'" />');
 2870:     return $result;
 2871: }
 2872: 
 2873: sub get_assignable_auth {
 2874:     my ($dom) = @_;
 2875:     if ($dom eq '') {
 2876:         $dom = $env{'request.role.domain'};
 2877:     }
 2878:     my %can_assign = (
 2879:                           krb4 => 1,
 2880:                           krb5 => 1,
 2881:                           int  => 1,
 2882:                           loc  => 1,
 2883:                      );
 2884:     my %domconfig = &Apache::lonnet::get_dom('configuration',['usercreation'],$dom);
 2885:     if (ref($domconfig{'usercreation'}) eq 'HASH') {
 2886:         if (ref($domconfig{'usercreation'}{'authtypes'}) eq 'HASH') {
 2887:             my $authhash = $domconfig{'usercreation'}{'authtypes'};
 2888:             my $context;
 2889:             if ($env{'request.role'} =~ /^au/) {
 2890:                 $context = 'author';
 2891:             } elsif ($env{'request.role'} =~ /^dc/) {
 2892:                 $context = 'domain';
 2893:             } elsif ($env{'request.course.id'}) {
 2894:                 $context = 'course';
 2895:             }
 2896:             if ($context) {
 2897:                 if (ref($authhash->{$context}) eq 'HASH') {
 2898:                    %can_assign = %{$authhash->{$context}}; 
 2899:                 }
 2900:             }
 2901:         }
 2902:     }
 2903:     my $authnum = 0;
 2904:     foreach my $key (keys(%can_assign)) {
 2905:         if ($can_assign{$key}) {
 2906:             $authnum ++;
 2907:         }
 2908:     }
 2909:     if ($can_assign{'krb4'} && $can_assign{'krb5'}) {
 2910:         $authnum --;
 2911:     }
 2912:     return ($authnum,%can_assign);
 2913: }
 2914: 
 2915: ###############################################################
 2916: ##    Get Kerberos Defaults for Domain                 ##
 2917: ###############################################################
 2918: ##
 2919: ## Returns default kerberos version and an associated argument
 2920: ## as listed in file domain.tab. If not listed, provides
 2921: ## appropriate default domain and kerberos version.
 2922: ##
 2923: #-------------------------------------------
 2924: 
 2925: =pod
 2926: 
 2927: =item * &get_kerberos_defaults()
 2928: 
 2929: get_kerberos_defaults($target_domain) returns the default kerberos
 2930: version and domain. If not found, it defaults to version 4 and the 
 2931: domain of the server.
 2932: 
 2933: =over 4
 2934: 
 2935: ($def_version, $def_krb_domain) = &get_kerberos_defaults($target_domain);
 2936: 
 2937: =back
 2938: 
 2939: =back
 2940: 
 2941: =cut
 2942: 
 2943: #-------------------------------------------
 2944: sub get_kerberos_defaults {
 2945:     my $domain=shift;
 2946:     my ($krbdef,$krbdefdom);
 2947:     my %domdefaults = &Apache::lonnet::get_domain_defaults($domain);
 2948:     if (($domdefaults{'auth_def'} =~/^krb(4|5)$/) && ($domdefaults{'auth_arg_def'} ne '')) {
 2949:         $krbdef = $domdefaults{'auth_def'};
 2950:         $krbdefdom = $domdefaults{'auth_arg_def'};
 2951:     } else {
 2952:         $ENV{'SERVER_NAME'}=~/(\w+\.\w+)$/;
 2953:         my $krbdefdom=$1;
 2954:         $krbdefdom=~tr/a-z/A-Z/;
 2955:         $krbdef = "krb4";
 2956:     }
 2957:     return ($krbdef,$krbdefdom);
 2958: }
 2959: 
 2960: 
 2961: ###############################################################
 2962: ##                Thesaurus Functions                        ##
 2963: ###############################################################
 2964: 
 2965: =pod
 2966: 
 2967: =head1 Thesaurus Functions
 2968: 
 2969: =over 4
 2970: 
 2971: =item * &initialize_keywords()
 2972: 
 2973: Initializes the package variable %Keywords if it is empty.  Uses the
 2974: package variable $thesaurus_db_file.
 2975: 
 2976: =cut
 2977: 
 2978: ###################################################
 2979: 
 2980: sub initialize_keywords {
 2981:     return 1 if (scalar keys(%Keywords));
 2982:     # If we are here, %Keywords is empty, so fill it up
 2983:     #   Make sure the file we need exists...
 2984:     if (! -e $thesaurus_db_file) {
 2985:         &Apache::lonnet::logthis("Attempt to access $thesaurus_db_file".
 2986:                                  " failed because it does not exist");
 2987:         return 0;
 2988:     }
 2989:     #   Set up the hash as a database
 2990:     my %thesaurus_db;
 2991:     if (! tie(%thesaurus_db,'GDBM_File',
 2992:               $thesaurus_db_file,&GDBM_READER(),0640)){
 2993:         &Apache::lonnet::logthis("Could not tie \%thesaurus_db to ".
 2994:                                  $thesaurus_db_file);
 2995:         return 0;
 2996:     } 
 2997:     #  Get the average number of appearances of a word.
 2998:     my $avecount = $thesaurus_db{'average.count'};
 2999:     #  Put keywords (those that appear > average) into %Keywords
 3000:     while (my ($word,$data)=each (%thesaurus_db)) {
 3001:         my ($count,undef) = split /:/,$data;
 3002:         $Keywords{$word}++ if ($count > $avecount);
 3003:     }
 3004:     untie %thesaurus_db;
 3005:     # Remove special values from %Keywords.
 3006:     foreach my $value ('total.count','average.count') {
 3007:         delete($Keywords{$value}) if (exists($Keywords{$value}));
 3008:   }
 3009:     return 1;
 3010: }
 3011: 
 3012: ###################################################
 3013: 
 3014: =pod
 3015: 
 3016: =item * &keyword($word)
 3017: 
 3018: Returns true if $word is a keyword.  A keyword is a word that appears more 
 3019: than the average number of times in the thesaurus database.  Calls 
 3020: &initialize_keywords
 3021: 
 3022: =cut
 3023: 
 3024: ###################################################
 3025: 
 3026: sub keyword {
 3027:     return if (!&initialize_keywords());
 3028:     my $word=lc(shift());
 3029:     $word=~s/\W//g;
 3030:     return exists($Keywords{$word});
 3031: }
 3032: 
 3033: ###############################################################
 3034: 
 3035: =pod 
 3036: 
 3037: =item * &get_related_words()
 3038: 
 3039: Look up a word in the thesaurus.  Takes a scalar argument and returns
 3040: an array of words.  If the keyword is not in the thesaurus, an empty array
 3041: will be returned.  The order of the words returned is determined by the
 3042: database which holds them.
 3043: 
 3044: Uses global $thesaurus_db_file.
 3045: 
 3046: 
 3047: =cut
 3048: 
 3049: ###############################################################
 3050: sub get_related_words {
 3051:     my $keyword = shift;
 3052:     my %thesaurus_db;
 3053:     if (! -e $thesaurus_db_file) {
 3054:         &Apache::lonnet::logthis("Attempt to access $thesaurus_db_file ".
 3055:                                  "failed because the file does not exist");
 3056:         return ();
 3057:     }
 3058:     if (! tie(%thesaurus_db,'GDBM_File',
 3059:               $thesaurus_db_file,&GDBM_READER(),0640)){
 3060:         return ();
 3061:     } 
 3062:     my @Words=();
 3063:     my $count=0;
 3064:     if (exists($thesaurus_db{$keyword})) {
 3065: 	# The first element is the number of times
 3066: 	# the word appears.  We do not need it now.
 3067: 	my (undef,@RelatedWords) = (split(/:/,$thesaurus_db{$keyword}));
 3068: 	my (undef,$mostfrequentcount)=split(/\,/,$RelatedWords[0]);
 3069: 	my $threshold=$mostfrequentcount/10;
 3070:         foreach my $possibleword (@RelatedWords) {
 3071:             my ($word,$wordcount)=split(/\,/,$possibleword);
 3072:             if ($wordcount>$threshold) {
 3073: 		push(@Words,$word);
 3074:                 $count++;
 3075:                 if ($count>10) { last; }
 3076: 	    }
 3077:         }
 3078:     }
 3079:     untie %thesaurus_db;
 3080:     return @Words;
 3081: }
 3082: ###############################################################
 3083: #
 3084: #  Spell checking
 3085: #
 3086: 
 3087: =pod
 3088: 
 3089: =back
 3090: 
 3091: =head1 Spell checking
 3092: 
 3093: =over 4
 3094: 
 3095: =item * &check_spelling($wordlist $language)
 3096: 
 3097: Takes a string containing words and feeds it to an external
 3098: spellcheck program via a pipeline. Returns a string containing
 3099: them mis-spelled words.
 3100: 
 3101: Parameters:
 3102: 
 3103: =over 4
 3104: 
 3105: =item - $wordlist
 3106: 
 3107: String that will be fed into the spellcheck program.
 3108: 
 3109: =item - $language
 3110: 
 3111: Language string that specifies the language for which the spell
 3112: check will be performed.
 3113: 
 3114: =back
 3115: 
 3116: =back
 3117: 
 3118: Note: This sub assumes that aspell is installed.
 3119: 
 3120: 
 3121: =cut
 3122: 
 3123: 
 3124: sub check_spelling {
 3125:     my ($wordlist, $language) = @_;
 3126:     my @misspellings;
 3127:     
 3128:     # Generate the speller and set the langauge.
 3129:     # if explicitly selected:
 3130: 
 3131:     my $speller = Text::Aspell->new;
 3132:     if ($language) {
 3133: 	$speller->set_option('lang', $language);
 3134:     }
 3135: 
 3136:     # Turn the word list into an array of words by splittingon whitespace
 3137: 
 3138:     my @words = split(/\s+/, $wordlist);
 3139: 
 3140:     foreach my $word (@words) {
 3141: 	if(! $speller->check($word)) {
 3142: 	    push(@misspellings, $word);
 3143: 	}
 3144:     }
 3145:     return join(' ', @misspellings);
 3146:     
 3147: }
 3148: 
 3149: # -------------------------------------------------------------- Plaintext name
 3150: =pod
 3151: 
 3152: =head1 User Name Functions
 3153: 
 3154: =over 4
 3155: 
 3156: =item * &plainname($uname,$udom,$first)
 3157: 
 3158: Takes a users logon name and returns it as a string in
 3159: "first middle last generation" form 
 3160: if $first is set to 'lastname' then it returns it as
 3161: 'lastname generation, firstname middlename' if their is a lastname
 3162: 
 3163: =cut
 3164: 
 3165: 
 3166: ###############################################################
 3167: sub plainname {
 3168:     my ($uname,$udom,$first)=@_;
 3169:     return if (!defined($uname) || !defined($udom));
 3170:     my %names=&getnames($uname,$udom);
 3171:     my $name=&Apache::lonnet::format_name($names{'firstname'},
 3172: 					  $names{'middlename'},
 3173: 					  $names{'lastname'},
 3174: 					  $names{'generation'},$first);
 3175:     $name=~s/^\s+//;
 3176:     $name=~s/\s+$//;
 3177:     $name=~s/\s+/ /g;
 3178:     if ($name !~ /\S/) { $name=$uname.':'.$udom; }
 3179:     return $name;
 3180: }
 3181: 
 3182: # -------------------------------------------------------------------- Nickname
 3183: =pod
 3184: 
 3185: =item * &nickname($uname,$udom)
 3186: 
 3187: Gets a users name and returns it as a string as
 3188: 
 3189: "&quot;nickname&quot;"
 3190: 
 3191: if the user has a nickname or
 3192: 
 3193: "first middle last generation"
 3194: 
 3195: if the user does not
 3196: 
 3197: =cut
 3198: 
 3199: sub nickname {
 3200:     my ($uname,$udom)=@_;
 3201:     return if (!defined($uname) || !defined($udom));
 3202:     my %names=&getnames($uname,$udom);
 3203:     my $name=$names{'nickname'};
 3204:     if ($name) {
 3205:        $name='&quot;'.$name.'&quot;'; 
 3206:     } else {
 3207:        $name=$names{'firstname'}.' '.$names{'middlename'}.' '.
 3208: 	     $names{'lastname'}.' '.$names{'generation'};
 3209:        $name=~s/\s+$//;
 3210:        $name=~s/\s+/ /g;
 3211:     }
 3212:     return $name;
 3213: }
 3214: 
 3215: sub getnames {
 3216:     my ($uname,$udom)=@_;
 3217:     return if (!defined($uname) || !defined($udom));
 3218:     if ($udom eq 'public' && $uname eq 'public') {
 3219: 	return ('lastname' => &mt('Public'));
 3220:     }
 3221:     my $id=$uname.':'.$udom;
 3222:     my ($names,$cached)=&Apache::lonnet::is_cached_new('namescache',$id);
 3223:     if ($cached) {
 3224: 	return %{$names};
 3225:     } else {
 3226: 	my %loadnames=&Apache::lonnet::get('environment',
 3227:                     ['firstname','middlename','lastname','generation','nickname'],
 3228: 					 $udom,$uname);
 3229: 	&Apache::lonnet::do_cache_new('namescache',$id,\%loadnames);
 3230: 	return %loadnames;
 3231:     }
 3232: }
 3233: 
 3234: # -------------------------------------------------------------------- getemails
 3235: 
 3236: =pod
 3237: 
 3238: =item * &getemails($uname,$udom)
 3239: 
 3240: Gets a user's email information and returns it as a hash with keys:
 3241: notification, critnotification, permanentemail
 3242: 
 3243: For notification and critnotification, values are comma-separated lists 
 3244: of e-mail addresses; for permanentemail, value is a single e-mail address.
 3245:  
 3246: 
 3247: =cut
 3248: 
 3249: 
 3250: sub getemails {
 3251:     my ($uname,$udom)=@_;
 3252:     if ($udom eq 'public' && $uname eq 'public') {
 3253: 	return;
 3254:     }
 3255:     if (!$udom) { $udom=$env{'user.domain'}; }
 3256:     if (!$uname) { $uname=$env{'user.name'}; }
 3257:     my $id=$uname.':'.$udom;
 3258:     my ($names,$cached)=&Apache::lonnet::is_cached_new('emailscache',$id);
 3259:     if ($cached) {
 3260: 	return %{$names};
 3261:     } else {
 3262: 	my %loadnames=&Apache::lonnet::get('environment',
 3263:                     			   ['notification','critnotification',
 3264: 					    'permanentemail'],
 3265: 					   $udom,$uname);
 3266: 	&Apache::lonnet::do_cache_new('emailscache',$id,\%loadnames);
 3267: 	return %loadnames;
 3268:     }
 3269: }
 3270: 
 3271: sub flush_email_cache {
 3272:     my ($uname,$udom)=@_;
 3273:     if (!$udom)  { $udom =$env{'user.domain'}; }
 3274:     if (!$uname) { $uname=$env{'user.name'};   }
 3275:     return if ($udom eq 'public' && $uname eq 'public');
 3276:     my $id=$uname.':'.$udom;
 3277:     &Apache::lonnet::devalidate_cache_new('emailscache',$id);
 3278: }
 3279: 
 3280: # -------------------------------------------------------------------- getlangs
 3281: 
 3282: =pod
 3283: 
 3284: =item * &getlangs($uname,$udom)
 3285: 
 3286: Gets a user's language preference and returns it as a hash with key:
 3287: language.
 3288: 
 3289: =cut
 3290: 
 3291: 
 3292: sub getlangs {
 3293:     my ($uname,$udom) = @_;
 3294:     if (!$udom)  { $udom =$env{'user.domain'}; }
 3295:     if (!$uname) { $uname=$env{'user.name'};   }
 3296:     my $id=$uname.':'.$udom;
 3297:     my ($langs,$cached)=&Apache::lonnet::is_cached_new('userlangs',$id);
 3298:     if ($cached) {
 3299:         return %{$langs};
 3300:     } else {
 3301:         my %loadlangs=&Apache::lonnet::get('environment',['languages'],
 3302:                                            $udom,$uname);
 3303:         &Apache::lonnet::do_cache_new('userlangs',$id,\%loadlangs);
 3304:         return %loadlangs;
 3305:     }
 3306: }
 3307: 
 3308: sub flush_langs_cache {
 3309:     my ($uname,$udom)=@_;
 3310:     if (!$udom)  { $udom =$env{'user.domain'}; }
 3311:     if (!$uname) { $uname=$env{'user.name'};   }
 3312:     return if ($udom eq 'public' && $uname eq 'public');
 3313:     my $id=$uname.':'.$udom;
 3314:     &Apache::lonnet::devalidate_cache_new('userlangs',$id);
 3315: }
 3316: 
 3317: # ------------------------------------------------------------------ Screenname
 3318: 
 3319: =pod
 3320: 
 3321: =item * &screenname($uname,$udom)
 3322: 
 3323: Gets a users screenname and returns it as a string
 3324: 
 3325: =cut
 3326: 
 3327: sub screenname {
 3328:     my ($uname,$udom)=@_;
 3329:     if ($uname eq $env{'user.name'} &&
 3330: 	$udom eq $env{'user.domain'}) {return $env{'environment.screenname'};}
 3331:     my %names=&Apache::lonnet::get('environment',['screenname'],$udom,$uname);
 3332:     return $names{'screenname'};
 3333: }
 3334: 
 3335: 
 3336: # ------------------------------------------------------------- Confirm Wrapper
 3337: =pod
 3338: 
 3339: =item * &confirmwrapper($message)
 3340: 
 3341: Wrap messages about completion of operation in box
 3342: 
 3343: =cut
 3344: 
 3345: sub confirmwrapper {
 3346:     my ($message)=@_;
 3347:     if ($message) {
 3348:         return "\n".'<div class="LC_confirm_box">'."\n"
 3349:                .$message."\n"
 3350:                .'</div>'."\n";
 3351:     } else {
 3352:         return $message;
 3353:     }
 3354: }
 3355: 
 3356: # ------------------------------------------------------------- Message Wrapper
 3357: 
 3358: sub messagewrapper {
 3359:     my ($link,$username,$domain,$subject,$text)=@_;
 3360:     return 
 3361:         '<a href="/adm/email?compose=individual&amp;'.
 3362:         'recname='.$username.'&amp;recdom='.$domain.
 3363: 	'&amp;subject='.&escape($subject).'&amp;text='.&escape($text).'" '.
 3364:         'title="'.&mt('Send message').'">'.$link.'</a>';
 3365: }
 3366: 
 3367: # --------------------------------------------------------------- Notes Wrapper
 3368: 
 3369: sub noteswrapper {
 3370:     my ($link,$un,$do)=@_;
 3371:     return 
 3372: "<a href='/adm/email?recordftf=retrieve&amp;recname=$un&amp;recdom=$do'>$link</a>";
 3373: }
 3374: 
 3375: # ------------------------------------------------------------- Aboutme Wrapper
 3376: 
 3377: sub aboutmewrapper {
 3378:     my ($link,$username,$domain,$target,$class)=@_;
 3379:     if (!defined($username)  && !defined($domain)) {
 3380:         return;
 3381:     }
 3382:     return '<a href="/adm/'.$domain.'/'.$username.'/aboutme"'.
 3383: 	($target?' target="'.$target.'"':'').($class?' class="'.$class.'"':'').' title="'.&mt("View this user's personal information page").'">'.$link.'</a>';
 3384: }
 3385: 
 3386: # ------------------------------------------------------------ Syllabus Wrapper
 3387: 
 3388: sub syllabuswrapper {
 3389:     my ($linktext,$coursedir,$domain)=@_;
 3390:     return qq{<a href="/public/$domain/$coursedir/syllabus">$linktext</a>};
 3391: }
 3392: 
 3393: # -----------------------------------------------------------------------------
 3394: 
 3395: sub track_student_link {
 3396:     my ($linktext,$sname,$sdom,$target,$start,$only_body) = @_;
 3397:     my $link ="/adm/trackstudent?";
 3398:     my $title = 'View recent activity';
 3399:     if (defined($sname) && $sname !~ /^\s*$/ &&
 3400:         defined($sdom)  && $sdom  !~ /^\s*$/) {
 3401:         $link .= "selected_student=$sname:$sdom";
 3402:         $title .= ' of this student';
 3403:     } 
 3404:     if (defined($target) && $target !~ /^\s*$/) {
 3405:         $target = qq{target="$target"};
 3406:     } else {
 3407:         $target = '';
 3408:     }
 3409:     if ($start) { $link.='&amp;start='.$start; }
 3410:     if ($only_body) { $link .= '&amp;only_body=1'; }
 3411:     $title = &mt($title);
 3412:     $linktext = &mt($linktext);
 3413:     return qq{<a href="$link" title="$title" $target>$linktext</a>}.
 3414: 	&help_open_topic('View_recent_activity');
 3415: }
 3416: 
 3417: sub slot_reservations_link {
 3418:     my ($linktext,$sname,$sdom,$target) = @_;
 3419:     my $link ="/adm/slotrequest?command=showresv&amp;origin=aboutme";
 3420:     my $title = 'View slot reservation history';
 3421:     if (defined($sname) && $sname !~ /^\s*$/ &&
 3422:         defined($sdom)  && $sdom  !~ /^\s*$/) {
 3423:         $link .= "&amp;uname=$sname&amp;udom=$sdom";
 3424:         $title .= ' of this student';
 3425:     }
 3426:     if (defined($target) && $target !~ /^\s*$/) {
 3427:         $target = qq{target="$target"};
 3428:     } else {
 3429:         $target = '';
 3430:     }
 3431:     $title = &mt($title);
 3432:     $linktext = &mt($linktext);
 3433:     return qq{<a href="$link" title="$title" $target>$linktext</a>};
 3434: # FIXME uncomment when help item created: &help_open_topic('Slot_Reservation_History');
 3435: 
 3436: }
 3437: 
 3438: # ===================================================== Display a student photo
 3439: 
 3440: 
 3441: sub student_image_tag {
 3442:     my ($domain,$user)=@_;
 3443:     my $imgsrc=&Apache::lonnet::studentphoto($domain,$user,'jpg');
 3444:     if (($imgsrc) && ($imgsrc ne '/adm/lonKaputt/lonlogo_broken.gif')) {
 3445: 	return '<img src="'.$imgsrc.'" align="right" />';
 3446:     } else {
 3447: 	return '';
 3448:     }
 3449: }
 3450: 
 3451: =pod
 3452: 
 3453: =back
 3454: 
 3455: =head1 Access .tab File Data
 3456: 
 3457: =over 4
 3458: 
 3459: =item * &languageids() 
 3460: 
 3461: returns list of all language ids
 3462: 
 3463: =cut
 3464: 
 3465: sub languageids {
 3466:     return sort(keys(%language));
 3467: }
 3468: 
 3469: =pod
 3470: 
 3471: =item * &languagedescription() 
 3472: 
 3473: returns description of a specified language id
 3474: 
 3475: =cut
 3476: 
 3477: sub languagedescription {
 3478:     my $code=shift;
 3479:     return  ($supported_language{$code}?'* ':'').
 3480:             $language{$code}.
 3481: 	    ($supported_language{$code}?' ('.&mt('interface available').')':'');
 3482: }
 3483: 
 3484: =pod
 3485: 
 3486: =item * &plainlanguagedescription
 3487: 
 3488: Returns both the plain language description (e.g. 'Creoles and Pidgins, English-based (Other)')
 3489: and the language character encoding (e.g. ISO) separated by a ' - ' string.
 3490: 
 3491: =cut
 3492: 
 3493: sub plainlanguagedescription {
 3494:     my $code=shift;
 3495:     return $language{$code};
 3496: }
 3497: 
 3498: =pod
 3499: 
 3500: =item * &supportedlanguagecode
 3501: 
 3502: Returns the supported language code (e.g. sptutf maps to pt) given a language
 3503: code.
 3504: 
 3505: =cut
 3506: 
 3507: sub supportedlanguagecode {
 3508:     my $code=shift;
 3509:     return $supported_language{$code};
 3510: }
 3511: 
 3512: =pod
 3513: 
 3514: =item * &latexlanguage()
 3515: 
 3516: Given a language key code returns the correspondnig language to use
 3517: to select the correct hyphenation on LaTeX printouts.  This is undef if there
 3518: is no supported hyphenation for the language code.
 3519: 
 3520: =cut
 3521: 
 3522: sub latexlanguage {
 3523:     my $code = shift;
 3524:     return $latex_language{$code};
 3525: }
 3526: 
 3527: =pod
 3528: 
 3529: =item * &latexhyphenation()
 3530: 
 3531: Same as above but what's supplied is the language as it might be stored
 3532: in the metadata.
 3533: 
 3534: =cut
 3535: 
 3536: sub latexhyphenation {
 3537:     my $key = shift;
 3538:     return $latex_language_bykey{$key};
 3539: }
 3540: 
 3541: =pod
 3542: 
 3543: =item * &copyrightids() 
 3544: 
 3545: returns list of all copyrights
 3546: 
 3547: =cut
 3548: 
 3549: sub copyrightids {
 3550:     return sort(keys(%cprtag));
 3551: }
 3552: 
 3553: =pod
 3554: 
 3555: =item * &copyrightdescription() 
 3556: 
 3557: returns description of a specified copyright id
 3558: 
 3559: =cut
 3560: 
 3561: sub copyrightdescription {
 3562:     return &mt($cprtag{shift(@_)});
 3563: }
 3564: 
 3565: =pod
 3566: 
 3567: =item * &source_copyrightids() 
 3568: 
 3569: returns list of all source copyrights
 3570: 
 3571: =cut
 3572: 
 3573: sub source_copyrightids {
 3574:     return sort(keys(%scprtag));
 3575: }
 3576: 
 3577: =pod
 3578: 
 3579: =item * &source_copyrightdescription() 
 3580: 
 3581: returns description of a specified source copyright id
 3582: 
 3583: =cut
 3584: 
 3585: sub source_copyrightdescription {
 3586:     return &mt($scprtag{shift(@_)});
 3587: }
 3588: 
 3589: =pod
 3590: 
 3591: =item * &filecategories() 
 3592: 
 3593: returns list of all file categories
 3594: 
 3595: =cut
 3596: 
 3597: sub filecategories {
 3598:     return sort(keys(%category_extensions));
 3599: }
 3600: 
 3601: =pod
 3602: 
 3603: =item * &filecategorytypes() 
 3604: 
 3605: returns list of file types belonging to a given file
 3606: category
 3607: 
 3608: =cut
 3609: 
 3610: sub filecategorytypes {
 3611:     my ($cat) = @_;
 3612:     return @{$category_extensions{lc($cat)}};
 3613: }
 3614: 
 3615: =pod
 3616: 
 3617: =item * &fileembstyle() 
 3618: 
 3619: returns embedding style for a specified file type
 3620: 
 3621: =cut
 3622: 
 3623: sub fileembstyle {
 3624:     return $fe{lc(shift(@_))};
 3625: }
 3626: 
 3627: sub filemimetype {
 3628:     return $fm{lc(shift(@_))};
 3629: }
 3630: 
 3631: 
 3632: sub filecategoryselect {
 3633:     my ($name,$value)=@_;
 3634:     return &select_form($value,$name,
 3635:                         {'' => &mt('Any category'), map { $_,$_ } sort(keys(%category_extensions))});
 3636: }
 3637: 
 3638: =pod
 3639: 
 3640: =item * &filedescription() 
 3641: 
 3642: returns description for a specified file type
 3643: 
 3644: =cut
 3645: 
 3646: sub filedescription {
 3647:     my $file_description = $fd{lc(shift())};
 3648:     $file_description =~ s:([\[\]]):~$1:g;
 3649:     return &mt($file_description);
 3650: }
 3651: 
 3652: =pod
 3653: 
 3654: =item * &filedescriptionex() 
 3655: 
 3656: returns description for a specified file type with
 3657: extra formatting
 3658: 
 3659: =cut
 3660: 
 3661: sub filedescriptionex {
 3662:     my $ex=shift;
 3663:     my $file_description = $fd{lc($ex)};
 3664:     $file_description =~ s:([\[\]]):~$1:g;
 3665:     return '.'.$ex.' '.&mt($file_description);
 3666: }
 3667: 
 3668: # End of .tab access
 3669: =pod
 3670: 
 3671: =back
 3672: 
 3673: =cut
 3674: 
 3675: # ------------------------------------------------------------------ File Types
 3676: sub fileextensions {
 3677:     return sort(keys(%fe));
 3678: }
 3679: 
 3680: # ----------------------------------------------------------- Display Languages
 3681: # returns a hash with all desired display languages
 3682: #
 3683: 
 3684: sub display_languages {
 3685:     my %languages=();
 3686:     foreach my $lang (&Apache::lonlocal::preferred_languages()) {
 3687: 	$languages{$lang}=1;
 3688:     }
 3689:     &get_unprocessed_cgi($ENV{'QUERY_STRING'},['displaylanguage']);
 3690:     if ($env{'form.displaylanguage'}) {
 3691: 	foreach my $lang (split(/\s*(\,|\;|\:)\s*/,$env{'form.displaylanguage'})) {
 3692: 	    $languages{$lang}=1;
 3693:         }
 3694:     }
 3695:     return %languages;
 3696: }
 3697: 
 3698: sub languages {
 3699:     my ($possible_langs) = @_;
 3700:     my @preferred_langs = &Apache::lonlocal::preferred_languages();
 3701:     if (!ref($possible_langs)) {
 3702: 	if( wantarray ) {
 3703: 	    return @preferred_langs;
 3704: 	} else {
 3705: 	    return $preferred_langs[0];
 3706: 	}
 3707:     }
 3708:     my %possibilities = map { $_ => 1 } (@$possible_langs);
 3709:     my @preferred_possibilities;
 3710:     foreach my $preferred_lang (@preferred_langs) {
 3711: 	if (exists($possibilities{$preferred_lang})) {
 3712: 	    push(@preferred_possibilities, $preferred_lang);
 3713: 	}
 3714:     }
 3715:     if( wantarray ) {
 3716: 	return @preferred_possibilities;
 3717:     }
 3718:     return $preferred_possibilities[0];
 3719: }
 3720: 
 3721: sub user_lang {
 3722:     my ($touname,$toudom,$fromcid) = @_;
 3723:     my @userlangs;
 3724:     if (($fromcid ne '') && ($env{'course.'.$fromcid.'.languages'} ne '')) {
 3725:         @userlangs=(@userlangs,split(/\s*(\,|\;|\:)\s*/,
 3726:                     $env{'course.'.$fromcid.'.languages'}));
 3727:     } else {
 3728:         my %langhash = &getlangs($touname,$toudom);
 3729:         if ($langhash{'languages'} ne '') {
 3730:             @userlangs = split(/\s*(\,|\;|\:)\s*/,$langhash{'languages'});
 3731:         } else {
 3732:             my %domdefs = &Apache::lonnet::get_domain_defaults($toudom);
 3733:             if ($domdefs{'lang_def'} ne '') {
 3734:                 @userlangs = ($domdefs{'lang_def'});
 3735:             }
 3736:         }
 3737:     }
 3738:     my @languages=&Apache::lonlocal::get_genlanguages(@userlangs);
 3739:     my $user_lh = Apache::localize->get_handle(@languages);
 3740:     return $user_lh;
 3741: }
 3742: 
 3743: 
 3744: ###############################################################
 3745: ##               Student Answer Attempts                     ##
 3746: ###############################################################
 3747: 
 3748: =pod
 3749: 
 3750: =head1 Alternate Problem Views
 3751: 
 3752: =over 4
 3753: 
 3754: =item * &get_previous_attempt($symb, $username, $domain, $course,
 3755:     $getattempt, $regexp, $gradesub)
 3756: 
 3757: Return string with previous attempt on problem. Arguments:
 3758: 
 3759: =over 4
 3760: 
 3761: =item * $symb: Problem, including path
 3762: 
 3763: =item * $username: username of the desired student
 3764: 
 3765: =item * $domain: domain of the desired student
 3766: 
 3767: =item * $course: Course ID
 3768: 
 3769: =item * $getattempt: Leave blank for all attempts, otherwise put
 3770:     something
 3771: 
 3772: =item * $regexp: if string matches this regexp, the string will be
 3773:     sent to $gradesub
 3774: 
 3775: =item * $gradesub: routine that processes the string if it matches $regexp
 3776: 
 3777: =back
 3778: 
 3779: The output string is a table containing all desired attempts, if any.
 3780: 
 3781: =cut
 3782: 
 3783: sub get_previous_attempt {
 3784:   my ($symb,$username,$domain,$course,$getattempt,$regexp,$gradesub)=@_;
 3785:   my $prevattempts='';
 3786:   no strict 'refs';
 3787:   if ($symb) {
 3788:     my (%returnhash)=
 3789:       &Apache::lonnet::restore($symb,$course,$domain,$username);
 3790:     if ($returnhash{'version'}) {
 3791:       my %lasthash=();
 3792:       my $version;
 3793:       for ($version=1;$version<=$returnhash{'version'};$version++) {
 3794:         foreach my $key (sort(split(/\:/,$returnhash{$version.':keys'}))) {
 3795: 	  $lasthash{$key}=$returnhash{$version.':'.$key};
 3796:         }
 3797:       }
 3798:       $prevattempts=&start_data_table().&start_data_table_header_row();
 3799:       $prevattempts.='<th>'.&mt('History').'</th>';
 3800:       my (%typeparts,%lasthidden);
 3801:       my $showsurv=&Apache::lonnet::allowed('vas',$env{'request.course.id'});
 3802:       foreach my $key (sort(keys(%lasthash))) {
 3803: 	my ($ign,@parts) = split(/\./,$key);
 3804: 	if ($#parts > 0) {
 3805: 	  my $data=$parts[-1];
 3806:           next if ($data eq 'foilorder');
 3807: 	  pop(@parts);
 3808:           $prevattempts.='<th>'.&mt('Part ').join('.',@parts).'<br />'.$data.'&nbsp;</th>';
 3809:           if ($data eq 'type') {
 3810:               unless ($showsurv) {
 3811:                   my $id = join(',',@parts);
 3812:                   $typeparts{$ign.'.'.$id} = $lasthash{$key};
 3813:                   if (($lasthash{$key} eq 'anonsurvey') || ($lasthash{$key} eq 'anonsurveycred')) {
 3814:                       $lasthidden{$ign.'.'.$id} = 1;
 3815:                   }
 3816:               }
 3817:           } 
 3818: 	} else {
 3819: 	  if ($#parts == 0) {
 3820: 	    $prevattempts.='<th>'.$parts[0].'</th>';
 3821: 	  } else {
 3822: 	    $prevattempts.='<th>'.$ign.'</th>';
 3823: 	  }
 3824: 	}
 3825:       }
 3826:       $prevattempts.=&end_data_table_header_row();
 3827:       if ($getattempt eq '') {
 3828: 	for ($version=1;$version<=$returnhash{'version'};$version++) {
 3829:             my @hidden;
 3830:             if (%typeparts) {
 3831:                 foreach my $id (keys(%typeparts)) {
 3832:                     if (($returnhash{$version.':'.$id.'.type'} eq 'anonsurvey') || ($returnhash{$version.':'.$id.'.type'} eq 'anonsurveycred')) {
 3833:                         push(@hidden,$id);
 3834:                     }
 3835:                 }
 3836:             }
 3837:             $prevattempts.=&start_data_table_row().
 3838:                            '<td>'.&mt('Transaction [_1]',$version).'</td>';
 3839:             if (@hidden) {
 3840:                 foreach my $key (sort(keys(%lasthash))) {
 3841:                     next if ($key =~ /\.foilorder$/);
 3842:                     my $hide;
 3843:                     foreach my $id (@hidden) {
 3844:                         if ($key =~ /^\Q$id\E/) {
 3845:                             $hide = 1;
 3846:                             last;
 3847:                         }
 3848:                     }
 3849:                     if ($hide) {
 3850:                         my ($id,$data) = ($key =~ /^(.+)\.([^.]+)$/);
 3851:                         if (($data eq 'award') || ($data eq 'awarddetail')) {
 3852:                             my $value = &format_previous_attempt_value($key,
 3853:                                              $returnhash{$version.':'.$key});
 3854:                             $prevattempts.='<td>'.$value.'&nbsp;</td>';
 3855:                         } else {
 3856:                             $prevattempts.='<td>&nbsp;</td>';
 3857:                         }
 3858:                     } else {
 3859:                         if ($key =~ /\./) {
 3860:                             my $value = &format_previous_attempt_value($key,
 3861:                                               $returnhash{$version.':'.$key});
 3862:                             $prevattempts.='<td>'.$value.'&nbsp;</td>';
 3863:                         } else {
 3864:                             $prevattempts.='<td>&nbsp;</td>';
 3865:                         }
 3866:                     }
 3867:                 }
 3868:             } else {
 3869: 	        foreach my $key (sort(keys(%lasthash))) {
 3870:                     next if ($key =~ /\.foilorder$/);
 3871: 		    my $value = &format_previous_attempt_value($key,
 3872: 			            $returnhash{$version.':'.$key});
 3873: 		    $prevattempts.='<td>'.$value.'&nbsp;</td>';
 3874: 	        }
 3875:             }
 3876: 	    $prevattempts.=&end_data_table_row();
 3877: 	 }
 3878:       }
 3879:       my @currhidden = keys(%lasthidden);
 3880:       $prevattempts.=&start_data_table_row().'<td>'.&mt('Current').'</td>';
 3881:       foreach my $key (sort(keys(%lasthash))) {
 3882:           next if ($key =~ /\.foilorder$/);
 3883:           if (%typeparts) {
 3884:               my $hidden;
 3885:               foreach my $id (@currhidden) {
 3886:                   if ($key =~ /^\Q$id\E/) {
 3887:                       $hidden = 1;
 3888:                       last;
 3889:                   }
 3890:               }
 3891:               if ($hidden) {
 3892:                   my ($id,$data) = ($key =~ /^(.+)\.([^.]+)$/);
 3893:                   if (($data eq 'award') || ($data eq 'awarddetail')) {
 3894:                       my $value = &format_previous_attempt_value($key,$lasthash{$key});
 3895:                       if ($key =~/$regexp$/ && (defined &$gradesub)) {
 3896:                           $value = &$gradesub($value);
 3897:                       }
 3898:                       $prevattempts.='<td>'. $value.'&nbsp;</td>';
 3899:                   } else {
 3900:                       $prevattempts.='<td>&nbsp;</td>';
 3901:                   }
 3902:               } else {
 3903:                   my $value = &format_previous_attempt_value($key,$lasthash{$key});
 3904:                   if ($key =~/$regexp$/ && (defined &$gradesub)) {
 3905:                       $value = &$gradesub($value);
 3906:                   }
 3907:                   $prevattempts.='<td>'.$value.'&nbsp;</td>';
 3908:               }
 3909:           } else {
 3910: 	      my $value = &format_previous_attempt_value($key,$lasthash{$key});
 3911: 	      if ($key =~/$regexp$/ && (defined &$gradesub)) {
 3912:                   $value = &$gradesub($value);
 3913:               }
 3914: 	     $prevattempts.='<td>'.$value.'&nbsp;</td>';
 3915:           }
 3916:       }
 3917:       $prevattempts.= &end_data_table_row().&end_data_table();
 3918:     } else {
 3919:       $prevattempts=
 3920: 	  &start_data_table().&start_data_table_row().
 3921: 	  '<td>'.&mt('Nothing submitted - no attempts.').'</td>'.
 3922: 	  &end_data_table_row().&end_data_table();
 3923:     }
 3924:   } else {
 3925:     $prevattempts=
 3926: 	  &start_data_table().&start_data_table_row().
 3927: 	  '<td>'.&mt('No data.').'</td>'.
 3928: 	  &end_data_table_row().&end_data_table();
 3929:   }
 3930: }
 3931: 
 3932: sub format_previous_attempt_value {
 3933:     my ($key,$value) = @_;
 3934:     if (($key =~ /timestamp/) || ($key=~/duedate/)) {
 3935:         $value = &Apache::lonlocal::locallocaltime($value);
 3936:     } elsif (ref($value) eq 'ARRAY') {
 3937:         $value = &HTML::Entities::encode('('.join(', ', @{ $value }).')','"<>&');
 3938:     } elsif ($key =~ /answerstring$/) {
 3939:         my %answers = &Apache::lonnet::str2hash($value);
 3940:         my @answer = %answers;
 3941:         %answers = map {&HTML::Entities::encode($_, '"<>&')} @answer;
 3942:         my @anskeys = sort(keys(%answers));
 3943:         if (@anskeys == 1) {
 3944:             my $answer = $answers{$anskeys[0]};
 3945:             if ($answer =~ m{\0}) {
 3946:                 $answer =~ s{\0}{,}g;
 3947:             }
 3948:             my $tag_internal_answer_name = 'INTERNAL';
 3949:             if ($anskeys[0] eq $tag_internal_answer_name) {
 3950:                 $value = $answer; 
 3951:             } else {
 3952:                 $value = $anskeys[0].'='.$answer;
 3953:             }
 3954:         } else {
 3955:             foreach my $ans (@anskeys) {
 3956:                 my $answer = $answers{$ans};
 3957:                 if ($answer =~ m{\0}) {
 3958:                     $answer =~ s{\0}{,}g;
 3959:                 }
 3960:                 $value .=  $ans.'='.$answer.'<br />';;
 3961:             } 
 3962:         }
 3963:     } else {
 3964:         $value = &HTML::Entities::encode(&unescape($value), '"<>&');
 3965:     }
 3966:     return $value;
 3967: }
 3968: 
 3969: 
 3970: sub relative_to_absolute {
 3971:     my ($url,$output)=@_;
 3972:     my $parser=HTML::TokeParser->new(\$output);
 3973:     my $token;
 3974:     my $thisdir=$url;
 3975:     my @rlinks=();
 3976:     while ($token=$parser->get_token) {
 3977: 	if ($token->[0] eq 'S') {
 3978: 	    if ($token->[1] eq 'a') {
 3979: 		if ($token->[2]->{'href'}) {
 3980: 		    $rlinks[$#rlinks+1]=$token->[2]->{'href'};
 3981: 		}
 3982: 	    } elsif ($token->[1] eq 'img' || $token->[1] eq 'embed' ) {
 3983: 		$rlinks[$#rlinks+1]=$token->[2]->{'src'};
 3984: 	    } elsif ($token->[1] eq 'base') {
 3985: 		$thisdir=$token->[2]->{'href'};
 3986: 	    }
 3987: 	}
 3988:     }
 3989:     $thisdir=~s-/[^/]*$--;
 3990:     foreach my $link (@rlinks) {
 3991: 	unless (($link=~/^https?\:\/\//i) ||
 3992: 		($link=~/^\//) ||
 3993: 		($link=~/^javascript:/i) ||
 3994: 		($link=~/^mailto:/i) ||
 3995: 		($link=~/^\#/)) {
 3996: 	    my $newlocation=&Apache::lonnet::hreflocation($thisdir,$link);
 3997: 	    $output=~s/(\"|\'|\=\s*)\Q$link\E(\"|\'|\s|\>)/$1$newlocation$2/;
 3998: 	}
 3999:     }
 4000: # -------------------------------------------------- Deal with Applet codebases
 4001:     $output=~s/(\<applet[^\>]+)(codebase\=[^\S\>]+)*([^\>]*)\>/$1.($2?$2:' codebase="'.$thisdir.'"').$3.'>'/gei;
 4002:     return $output;
 4003: }
 4004: 
 4005: =pod
 4006: 
 4007: =item * &get_student_view()
 4008: 
 4009: show a snapshot of what student was looking at
 4010: 
 4011: =cut
 4012: 
 4013: sub get_student_view {
 4014:   my ($symb,$username,$domain,$courseid,$target,$moreenv) = @_;
 4015:   my ($map,$id,$feedurl) = &Apache::lonnet::decode_symb($symb);
 4016:   my (%form);
 4017:   my @elements=('symb','courseid','domain','username');
 4018:   foreach my $element (@elements) {
 4019:       $form{'grade_'.$element}=eval '$'.$element #'
 4020:   }
 4021:   if (defined($moreenv)) {
 4022:       %form=(%form,%{$moreenv});
 4023:   }
 4024:   if (defined($target)) { $form{'grade_target'} = $target; }
 4025:   $feedurl=&Apache::lonnet::clutter($feedurl);
 4026:   my ($userview,$response)=&Apache::lonnet::ssi_body($feedurl,%form);
 4027:   $userview=~s/\<body[^\>]*\>//gi;
 4028:   $userview=~s/\<\/body\>//gi;
 4029:   $userview=~s/\<html\>//gi;
 4030:   $userview=~s/\<\/html\>//gi;
 4031:   $userview=~s/\<head\>//gi;
 4032:   $userview=~s/\<\/head\>//gi;
 4033:   $userview=~s/action\s*\=/would_be_action\=/gi;
 4034:   $userview=&relative_to_absolute($feedurl,$userview);
 4035:   if (wantarray) {
 4036:      return ($userview,$response);
 4037:   } else {
 4038:      return $userview;
 4039:   }
 4040: }
 4041: 
 4042: sub get_student_view_with_retries {
 4043:   my ($symb,$retries,$username,$domain,$courseid,$target,$moreenv) = @_;
 4044: 
 4045:     my $ok = 0;                 # True if we got a good response.
 4046:     my $content;
 4047:     my $response;
 4048: 
 4049:     # Try to get the student_view done. within the retries count:
 4050:     
 4051:     do {
 4052:          ($content, $response) = &get_student_view($symb,$username,$domain,$courseid,$target,$moreenv);
 4053:          $ok      = $response->is_success;
 4054:          if (!$ok) {
 4055:             &Apache::lonnet::logthis("Failed get_student_view_with_retries on $symb: ".$response->is_success.', '.$response->code.', '.$response->message);
 4056:          }
 4057:          $retries--;
 4058:     } while (!$ok && ($retries > 0));
 4059:     
 4060:     if (!$ok) {
 4061:        $content = '';          # On error return an empty content.
 4062:     }
 4063:     if (wantarray) {
 4064:        return ($content, $response);
 4065:     } else {
 4066:        return $content;
 4067:     }
 4068: }
 4069: 
 4070: =pod
 4071: 
 4072: =item * &get_student_answers() 
 4073: 
 4074: show a snapshot of how student was answering problem
 4075: 
 4076: =cut
 4077: 
 4078: sub get_student_answers {
 4079:   my ($symb,$username,$domain,$courseid,%form) = @_;
 4080:   my ($map,$id,$feedurl) = &Apache::lonnet::decode_symb($symb);
 4081:   my (%moreenv);
 4082:   my @elements=('symb','courseid','domain','username');
 4083:   foreach my $element (@elements) {
 4084:     $moreenv{'grade_'.$element}=eval '$'.$element #'
 4085:   }
 4086:   $moreenv{'grade_target'}='answer';
 4087:   %moreenv=(%form,%moreenv);
 4088:   $feedurl = &Apache::lonnet::clutter($feedurl);
 4089:   my $userview=&Apache::lonnet::ssi($feedurl,%moreenv);
 4090:   return $userview;
 4091: }
 4092: 
 4093: =pod
 4094: 
 4095: =item * &submlink()
 4096: 
 4097: Inputs: $text $uname $udom $symb $target
 4098: 
 4099: Returns: A link to grades.pm such as to see the SUBM view of a student
 4100: 
 4101: =cut
 4102: 
 4103: ###############################################
 4104: sub submlink {
 4105:     my ($text,$uname,$udom,$symb,$target)=@_;
 4106:     if (!($uname && $udom)) {
 4107: 	(my $cursymb, my $courseid,$udom,$uname)=
 4108: 	    &Apache::lonnet::whichuser($symb);
 4109: 	if (!$symb) { $symb=$cursymb; }
 4110:     }
 4111:     if (!$symb) { $symb=&Apache::lonnet::symbread(); }
 4112:     $symb=&escape($symb);
 4113:     if ($target) { $target=" target=\"$target\""; }
 4114:     return
 4115:         '<a href="/adm/grades?command=submission'.
 4116:         '&amp;symb='.$symb.
 4117:         '&amp;student='.$uname.
 4118:         '&amp;userdom='.$udom.'"'.
 4119:         $target.'>'.$text.'</a>';
 4120: }
 4121: ##############################################
 4122: 
 4123: =pod
 4124: 
 4125: =item * &pgrdlink()
 4126: 
 4127: Inputs: $text $uname $udom $symb $target
 4128: 
 4129: Returns: A link to grades.pm such as to see the PGRD view of a student
 4130: 
 4131: =cut
 4132: 
 4133: ###############################################
 4134: sub pgrdlink {
 4135:     my $link=&submlink(@_);
 4136:     $link=~s/(&command=submission)/$1&showgrading=yes/;
 4137:     return $link;
 4138: }
 4139: ##############################################
 4140: 
 4141: =pod
 4142: 
 4143: =item * &pprmlink()
 4144: 
 4145: Inputs: $text $uname $udom $symb $target
 4146: 
 4147: Returns: A link to parmset.pm such as to see the PPRM view of a
 4148: student and a specific resource
 4149: 
 4150: =cut
 4151: 
 4152: ###############################################
 4153: sub pprmlink {
 4154:     my ($text,$uname,$udom,$symb,$target)=@_;
 4155:     if (!($uname && $udom)) {
 4156: 	(my $cursymb, my $courseid,$udom,$uname)=
 4157: 	    &Apache::lonnet::whichuser($symb);
 4158: 	if (!$symb) { $symb=$cursymb; }
 4159:     }
 4160:     if (!$symb) { $symb=&Apache::lonnet::symbread(); }
 4161:     $symb=&escape($symb);
 4162:     if ($target) { $target="target=\"$target\""; }
 4163:     return '<a href="/adm/parmset?command=set&amp;'.
 4164: 	'symb='.$symb.'&amp;uname='.$uname.
 4165: 	'&amp;udom='.$udom.'" '.$target.'>'.$text.'</a>';
 4166: }
 4167: ##############################################
 4168: 
 4169: =pod
 4170: 
 4171: =back
 4172: 
 4173: =cut
 4174: 
 4175: ###############################################
 4176: 
 4177: 
 4178: sub timehash {
 4179:     my ($thistime) = @_;
 4180:     my $timezone = &Apache::lonlocal::gettimezone();
 4181:     my $dt = DateTime->from_epoch(epoch => $thistime)
 4182:                      ->set_time_zone($timezone);
 4183:     my $wday = $dt->day_of_week();
 4184:     if ($wday == 7) { $wday = 0; }
 4185:     return ( 'second' => $dt->second(),
 4186:              'minute' => $dt->minute(),
 4187:              'hour'   => $dt->hour(),
 4188:              'day'     => $dt->day_of_month(),
 4189:              'month'   => $dt->month(),
 4190:              'year'    => $dt->year(),
 4191:              'weekday' => $wday,
 4192:              'dayyear' => $dt->day_of_year(),
 4193:              'dlsav'   => $dt->is_dst() );
 4194: }
 4195: 
 4196: sub utc_string {
 4197:     my ($date)=@_;
 4198:     return strftime("%Y%m%dT%H%M%SZ",gmtime($date));
 4199: }
 4200: 
 4201: sub maketime {
 4202:     my %th=@_;
 4203:     my ($epoch_time,$timezone,$dt);
 4204:     $timezone = &Apache::lonlocal::gettimezone();
 4205:     eval {
 4206:         $dt = DateTime->new( year   => $th{'year'},
 4207:                              month  => $th{'month'},
 4208:                              day    => $th{'day'},
 4209:                              hour   => $th{'hour'},
 4210:                              minute => $th{'minute'},
 4211:                              second => $th{'second'},
 4212:                              time_zone => $timezone,
 4213:                          );
 4214:     };
 4215:     if (!$@) {
 4216:         $epoch_time = $dt->epoch;
 4217:         if ($epoch_time) {
 4218:             return $epoch_time;
 4219:         }
 4220:     }
 4221:     return POSIX::mktime(
 4222:         ($th{'seconds'},$th{'minutes'},$th{'hours'},
 4223:          $th{'day'},$th{'month'}-1,$th{'year'}-1900,0,0,-1));
 4224: }
 4225: 
 4226: #########################################
 4227: 
 4228: sub findallcourses {
 4229:     my ($roles,$uname,$udom) = @_;
 4230:     my %roles;
 4231:     if (ref($roles)) { %roles = map { $_ => 1 } @{$roles}; }
 4232:     my %courses;
 4233:     my $now=time;
 4234:     if (!defined($uname)) {
 4235:         $uname = $env{'user.name'};
 4236:     }
 4237:     if (!defined($udom)) {
 4238:         $udom = $env{'user.domain'};
 4239:     }
 4240:     if (($uname ne $env{'user.name'}) || ($udom ne $env{'user.domain'})) {
 4241:         my %roleshash = &Apache::lonnet::dump('roles',$udom,$uname);
 4242:         if (!%roles) {
 4243:             %roles = (
 4244:                        cc => 1,
 4245:                        co => 1,
 4246:                        in => 1,
 4247:                        ep => 1,
 4248:                        ta => 1,
 4249:                        cr => 1,
 4250:                        st => 1,
 4251:              );
 4252:         }
 4253:         foreach my $entry (keys(%roleshash)) {
 4254:             my ($trole,$tend,$tstart) = split(/_/,$roleshash{$entry});
 4255:             if ($trole =~ /^cr/) { 
 4256:                 next if (!exists($roles{$trole}) && !exists($roles{'cr'}));
 4257:             } else {
 4258:                 next if (!exists($roles{$trole}));
 4259:             }
 4260:             if ($tend) {
 4261:                 next if ($tend < $now);
 4262:             }
 4263:             if ($tstart) {
 4264:                 next if ($tstart > $now);
 4265:             }
 4266:             my ($cdom,$cnum,$sec,$cnumpart,$secpart,$role);
 4267:             (undef,$cdom,$cnumpart,$secpart) = split(/\//,$entry);
 4268:             my $value = $trole.'/'.$cdom.'/';
 4269:             if ($secpart eq '') {
 4270:                 ($cnum,$role) = split(/_/,$cnumpart); 
 4271:                 $sec = 'none';
 4272:                 $value .= $cnum.'/';
 4273:             } else {
 4274:                 $cnum = $cnumpart;
 4275:                 ($sec,$role) = split(/_/,$secpart);
 4276:                 $value .= $cnum.'/'.$sec;
 4277:             }
 4278:             if (ref($courses{$cdom.'_'.$cnum}{$sec}) eq 'ARRAY') {
 4279:                 unless (grep(/^\Q$value\E$/,@{$courses{$cdom.'_'.$cnum}{$sec}})) {
 4280:                     push(@{$courses{$cdom.'_'.$cnum}{$sec}},$value);
 4281:                 }
 4282:             } else {
 4283:                 @{$courses{$cdom.'_'.$cnum}{$sec}} = ($value);
 4284:             }
 4285:         }
 4286:     } else {
 4287:         foreach my $key (keys(%env)) {
 4288: 	    if ( $key=~m{^user\.role\.(\w+)\./($match_domain)/($match_courseid)/?(\w*)$} ||
 4289:                  $key=~m{^user\.role\.(cr/$match_domain/$match_username/\w+)\./($match_domain)/($match_courseid)/?(\w*)$}) {
 4290: 	        my ($role,$cdom,$cnum,$sec) = ($1,$2,$3,$4);
 4291: 	        next if ($role eq 'ca' || $role eq 'aa');
 4292: 	        next if (%roles && !exists($roles{$role}));
 4293: 	        my ($starttime,$endtime)=split(/\./,$env{$key});
 4294:                 my $active=1;
 4295:                 if ($starttime) {
 4296: 		    if ($now<$starttime) { $active=0; }
 4297:                 }
 4298:                 if ($endtime) {
 4299:                     if ($now>$endtime) { $active=0; }
 4300:                 }
 4301:                 if ($active) {
 4302:                     my $value = $role.'/'.$cdom.'/'.$cnum.'/';
 4303:                     if ($sec eq '') {
 4304:                         $sec = 'none';
 4305:                     } else {
 4306:                         $value .= $sec;
 4307:                     }
 4308:                     if (ref($courses{$cdom.'_'.$cnum}{$sec}) eq 'ARRAY') {
 4309:                         unless (grep(/^\Q$value\E$/,@{$courses{$cdom.'_'.$cnum}{$sec}})) {
 4310:                             push(@{$courses{$cdom.'_'.$cnum}{$sec}},$value);
 4311:                         }
 4312:                     } else {
 4313:                         @{$courses{$cdom.'_'.$cnum}{$sec}} = ($value);
 4314:                     }
 4315:                 }
 4316:             }
 4317:         }
 4318:     }
 4319:     return %courses;
 4320: }
 4321: 
 4322: ###############################################
 4323: 
 4324: sub blockcheck {
 4325:     my ($setters,$activity,$uname,$udom,$url,$is_course) = @_;
 4326: 
 4327:     if (defined($udom) && defined($uname)) {
 4328:         # If uname and udom are for a course, check for blocks in the course.
 4329:         if (($is_course) || (&Apache::lonnet::is_course($udom,$uname))) {
 4330:             my ($startblock,$endblock,$triggerblock) =
 4331:                 &get_blocks($setters,$activity,$udom,$uname,$url);
 4332:             return ($startblock,$endblock,$triggerblock);
 4333:         }
 4334:     } else {
 4335:         $udom = $env{'user.domain'};
 4336:         $uname = $env{'user.name'};
 4337:     }
 4338: 
 4339:     my $startblock = 0;
 4340:     my $endblock = 0;
 4341:     my $triggerblock = '';
 4342:     my %live_courses = &findallcourses(undef,$uname,$udom);
 4343: 
 4344:     # If uname is for a user, and activity is course-specific, i.e.,
 4345:     # boards, chat or groups, check for blocking in current course only.
 4346: 
 4347:     if (($activity eq 'boards' || $activity eq 'chat' ||
 4348:          $activity eq 'groups' || $activity eq 'printout') &&
 4349:         ($env{'request.course.id'})) {
 4350:         foreach my $key (keys(%live_courses)) {
 4351:             if ($key ne $env{'request.course.id'}) {
 4352:                 delete($live_courses{$key});
 4353:             }
 4354:         }
 4355:     }
 4356: 
 4357:     my $otheruser = 0;
 4358:     my %own_courses;
 4359:     if ((($uname ne $env{'user.name'})) || ($udom ne $env{'user.domain'})) {
 4360:         # Resource belongs to user other than current user.
 4361:         $otheruser = 1;
 4362:         # Gather courses for current user
 4363:         %own_courses = 
 4364:             &findallcourses(undef,$env{'user.name'},$env{'user.domain'});
 4365:     }
 4366: 
 4367:     # Gather active course roles - course coordinator, instructor, 
 4368:     # exam proctor, ta, student, or custom role.
 4369: 
 4370:     foreach my $course (keys(%live_courses)) {
 4371:         my ($cdom,$cnum);
 4372:         if ((defined($env{'course.'.$course.'.domain'})) && (defined($env{'course.'.$course.'.num'}))) {
 4373:             $cdom = $env{'course.'.$course.'.domain'};
 4374:             $cnum = $env{'course.'.$course.'.num'};
 4375:         } else {
 4376:             ($cdom,$cnum) = split(/_/,$course); 
 4377:         }
 4378:         my $no_ownblock = 0;
 4379:         my $no_userblock = 0;
 4380:         if ($otheruser && $activity ne 'com') {
 4381:             # Check if current user has 'evb' priv for this
 4382:             if (defined($own_courses{$course})) {
 4383:                 foreach my $sec (keys(%{$own_courses{$course}})) {
 4384:                     my $checkrole = 'cm./'.$cdom.'/'.$cnum;
 4385:                     if ($sec ne 'none') {
 4386:                         $checkrole .= '/'.$sec;
 4387:                     }
 4388:                     if (&Apache::lonnet::allowed('evb',undef,undef,$checkrole)) {
 4389:                         $no_ownblock = 1;
 4390:                         last;
 4391:                     }
 4392:                 }
 4393:             }
 4394:             # if they have 'evb' priv and are currently not playing student
 4395:             next if (($no_ownblock) &&
 4396:                  ($env{'request.role'} !~ m{^st\./$cdom/$cnum}));
 4397:         }
 4398:         foreach my $sec (keys(%{$live_courses{$course}})) {
 4399:             my $checkrole = 'cm./'.$cdom.'/'.$cnum;
 4400:             if ($sec ne 'none') {
 4401:                 $checkrole .= '/'.$sec;
 4402:             }
 4403:             if ($otheruser) {
 4404:                 # Resource belongs to user other than current user.
 4405:                 # Assemble privs for that user, and check for 'evb' priv.
 4406:                 my (%allroles,%userroles);
 4407:                 if (ref($live_courses{$course}{$sec}) eq 'ARRAY') {
 4408:                     foreach my $entry (@{$live_courses{$course}{$sec}}) { 
 4409:                         my ($trole,$tdom,$tnum,$tsec);
 4410:                         if ($entry =~ /^cr/) {
 4411:                             ($trole,$tdom,$tnum,$tsec) = 
 4412:                                 ($entry =~ m|^(cr/$match_domain/$match_username/\w+)\./($match_domain)/($match_username)/?(\w*)$|);
 4413:                         } else {
 4414:                            ($trole,$tdom,$tnum,$tsec) = split(/\//,$entry);
 4415:                         }
 4416:                         my ($spec,$area,$trest);
 4417:                         $area = '/'.$tdom.'/'.$tnum;
 4418:                         $trest = $tnum;
 4419:                         if ($tsec ne '') {
 4420:                             $area .= '/'.$tsec;
 4421:                             $trest .= '/'.$tsec;
 4422:                         }
 4423:                         $spec = $trole.'.'.$area;
 4424:                         if ($trole =~ /^cr/) {
 4425:                             &Apache::lonnet::custom_roleprivs(\%allroles,$trole,
 4426:                                                               $tdom,$spec,$trest,$area);
 4427:                         } else {
 4428:                             &Apache::lonnet::standard_roleprivs(\%allroles,$trole,
 4429:                                                                 $tdom,$spec,$trest,$area);
 4430:                         }
 4431:                     }
 4432:                     my ($author,$adv) = &Apache::lonnet::set_userprivs(\%userroles,\%allroles);
 4433:                     if ($userroles{'user.priv.'.$checkrole} =~ /evb\&([^\:]*)/) {
 4434:                         if ($1) {
 4435:                             $no_userblock = 1;
 4436:                             last;
 4437:                         }
 4438:                     }
 4439:                 }
 4440:             } else {
 4441:                 # Resource belongs to current user
 4442:                 # Check for 'evb' priv via lonnet::allowed().
 4443:                 if (&Apache::lonnet::allowed('evb',undef,undef,$checkrole)) {
 4444:                     $no_ownblock = 1;
 4445:                     last;
 4446:                 }
 4447:             }
 4448:         }
 4449:         # if they have the evb priv and are currently not playing student
 4450:         next if (($no_ownblock) &&
 4451:                  ($env{'request.role'} !~ m{^st\./\Q$cdom\E/\Q$cnum\E}));
 4452:         next if ($no_userblock);
 4453: 
 4454:         # Retrieve blocking times and identity of locker for course
 4455:         # of specified user, unless user has 'evb' privilege.
 4456:         
 4457:         my ($start,$end,$trigger) = 
 4458:             &get_blocks($setters,$activity,$cdom,$cnum,$url);
 4459:         if (($start != 0) && 
 4460:             (($startblock == 0) || ($startblock > $start))) {
 4461:             $startblock = $start;
 4462:             if ($trigger ne '') {
 4463:                 $triggerblock = $trigger;
 4464:             }
 4465:         }
 4466:         if (($end != 0)  &&
 4467:             (($endblock == 0) || ($endblock < $end))) {
 4468:             $endblock = $end;
 4469:             if ($trigger ne '') {
 4470:                 $triggerblock = $trigger;
 4471:             }
 4472:         }
 4473:     }
 4474:     return ($startblock,$endblock,$triggerblock);
 4475: }
 4476: 
 4477: sub get_blocks {
 4478:     my ($setters,$activity,$cdom,$cnum,$url) = @_;
 4479:     my $startblock = 0;
 4480:     my $endblock = 0;
 4481:     my $triggerblock = '';
 4482:     my $course = $cdom.'_'.$cnum;
 4483:     $setters->{$course} = {};
 4484:     $setters->{$course}{'staff'} = [];
 4485:     $setters->{$course}{'times'} = [];
 4486:     $setters->{$course}{'triggers'} = [];
 4487:     my (@blockers,%triggered);
 4488:     my $now = time;
 4489:     my %commblocks = &Apache::lonnet::get_comm_blocks($cdom,$cnum);
 4490:     if ($activity eq 'docs') {
 4491:         @blockers = &Apache::lonnet::has_comm_blocking('bre',undef,$url,\%commblocks);
 4492:         foreach my $block (@blockers) {
 4493:             if ($block =~ /^firstaccess____(.+)$/) {
 4494:                 my $item = $1;
 4495:                 my $type = 'map';
 4496:                 my $timersymb = $item;
 4497:                 if ($item eq 'course') {
 4498:                     $type = 'course';
 4499:                 } elsif ($item =~ /___\d+___/) {
 4500:                     $type = 'resource';
 4501:                 } else {
 4502:                     $timersymb = &Apache::lonnet::symbread($item);
 4503:                 }
 4504:                 my $start = $env{'course.'.$cdom.'_'.$cnum.'.firstaccess.'.$timersymb};
 4505:                 my $end = $start + $env{'course.'.$cdom.'_'.$cnum.'.timerinterval.'.$timersymb};
 4506:                 $triggered{$block} = {
 4507:                                        start => $start,
 4508:                                        end   => $end,
 4509:                                        type  => $type,
 4510:                                      };
 4511:             }
 4512:         }
 4513:     } else {
 4514:         foreach my $block (keys(%commblocks)) {
 4515:             if ($block =~ m/^(\d+)____(\d+)$/) { 
 4516:                 my ($start,$end) = ($1,$2);
 4517:                 if ($start <= time && $end >= time) {
 4518:                     if (ref($commblocks{$block}) eq 'HASH') {
 4519:                         if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
 4520:                             if ($commblocks{$block}{'blocks'}{$activity} eq 'on') {
 4521:                                 unless(grep(/^\Q$block\E$/,@blockers)) {
 4522:                                     push(@blockers,$block);
 4523:                                 }
 4524:                             }
 4525:                         }
 4526:                     }
 4527:                 }
 4528:             } elsif ($block =~ /^firstaccess____(.+)$/) {
 4529:                 my $item = $1;
 4530:                 my $timersymb = $item; 
 4531:                 my $type = 'map';
 4532:                 if ($item eq 'course') {
 4533:                     $type = 'course';
 4534:                 } elsif ($item =~ /___\d+___/) {
 4535:                     $type = 'resource';
 4536:                 } else {
 4537:                     $timersymb = &Apache::lonnet::symbread($item);
 4538:                 }
 4539:                 my $start = $env{'course.'.$cdom.'_'.$cnum.'.firstaccess.'.$timersymb};
 4540:                 my $end = $start + $env{'course.'.$cdom.'_'.$cnum.'.timerinterval.'.$timersymb}; 
 4541:                 if ($start && $end) {
 4542:                     if (($start <= time) && ($end >= time)) {
 4543:                         unless (grep(/^\Q$block\E$/,@blockers)) {
 4544:                             push(@blockers,$block);
 4545:                             $triggered{$block} = {
 4546:                                                    start => $start,
 4547:                                                    end   => $end,
 4548:                                                    type  => $type,
 4549:                                                  };
 4550:                         }
 4551:                     }
 4552:                 }
 4553:             }
 4554:         }
 4555:     }
 4556:     foreach my $blocker (@blockers) {
 4557:         my ($staff_name,$staff_dom,$title,$blocks) =
 4558:             &parse_block_record($commblocks{$blocker});
 4559:         push(@{$$setters{$course}{'staff'}},[$staff_name,$staff_dom]);
 4560:         my ($start,$end,$triggertype);
 4561:         if ($blocker =~ m/^(\d+)____(\d+)$/) {
 4562:             ($start,$end) = ($1,$2);
 4563:         } elsif (ref($triggered{$blocker}) eq 'HASH') {
 4564:             $start = $triggered{$blocker}{'start'};
 4565:             $end = $triggered{$blocker}{'end'};
 4566:             $triggertype = $triggered{$blocker}{'type'};
 4567:         }
 4568:         if ($start) {
 4569:             push(@{$$setters{$course}{'times'}}, [$start,$end]);
 4570:             if ($triggertype) {
 4571:                 push(@{$$setters{$course}{'triggers'}},$triggertype);
 4572:             } else {
 4573:                 push(@{$$setters{$course}{'triggers'}},0);
 4574:             }
 4575:             if ( ($startblock == 0) || ($startblock > $start) ) {
 4576:                 $startblock = $start;
 4577:                 if ($triggertype) {
 4578:                     $triggerblock = $blocker;
 4579:                 }
 4580:             }
 4581:             if ( ($endblock == 0) || ($endblock < $end) ) {
 4582:                $endblock = $end;
 4583:                if ($triggertype) {
 4584:                    $triggerblock = $blocker;
 4585:                }
 4586:             }
 4587:         }
 4588:     }
 4589:     return ($startblock,$endblock,$triggerblock);
 4590: }
 4591: 
 4592: sub parse_block_record {
 4593:     my ($record) = @_;
 4594:     my ($setuname,$setudom,$title,$blocks);
 4595:     if (ref($record) eq 'HASH') {
 4596:         ($setuname,$setudom) = split(/:/,$record->{'setter'});
 4597:         $title = &unescape($record->{'event'});
 4598:         $blocks = $record->{'blocks'};
 4599:     } else {
 4600:         my @data = split(/:/,$record,3);
 4601:         if (scalar(@data) eq 2) {
 4602:             $title = $data[1];
 4603:             ($setuname,$setudom) = split(/@/,$data[0]);
 4604:         } else {
 4605:             ($setuname,$setudom,$title) = @data;
 4606:         }
 4607:         $blocks = { 'com' => 'on' };
 4608:     }
 4609:     return ($setuname,$setudom,$title,$blocks);
 4610: }
 4611: 
 4612: sub blocking_status {
 4613:     my ($activity,$uname,$udom,$url,$is_course) = @_;
 4614:     my %setters;
 4615: 
 4616: # check for active blocking
 4617:     my ($startblock,$endblock,$triggerblock) = 
 4618:         &blockcheck(\%setters,$activity,$uname,$udom,$url,$is_course);
 4619:     my $blocked = 0;
 4620:     if ($startblock && $endblock) {
 4621:         $blocked = 1;
 4622:     }
 4623: 
 4624: # caller just wants to know whether a block is active
 4625:     if (!wantarray) { return $blocked; }
 4626: 
 4627: # build a link to a popup window containing the details
 4628:     my $querystring  = "?activity=$activity";
 4629: # $uname and $udom decide whose portfolio the user is trying to look at
 4630:     if ($activity eq 'port') {
 4631:         $querystring .= "&amp;udom=$udom"      if $udom;
 4632:         $querystring .= "&amp;uname=$uname"    if $uname;
 4633:     } elsif ($activity eq 'docs') {
 4634:         $querystring .= '&amp;url='.&HTML::Entities::encode($url,'&"');
 4635:     }
 4636: 
 4637:     my $output .= <<'END_MYBLOCK';
 4638: function openWindow(url, wdwName, w, h, toolbar,scrollbar) {
 4639:     var options = "width=" + w + ",height=" + h + ",";
 4640:     options += "resizable=yes,scrollbars="+scrollbar+",status=no,";
 4641:     options += "menubar=no,toolbar="+toolbar+",location=no,directories=no";
 4642:     var newWin = window.open(url, wdwName, options);
 4643:     newWin.focus();
 4644: }
 4645: END_MYBLOCK
 4646: 
 4647:     $output = Apache::lonhtmlcommon::scripttag($output);
 4648:   
 4649:     my $popupUrl = "/adm/blockingstatus/$querystring";
 4650:     my $text = &mt('Communication Blocked');
 4651:     if ($activity eq 'docs') {
 4652:         $text = &mt('Content Access Blocked');
 4653:     } elsif ($activity eq 'printout') {
 4654:         $text = &mt('Printing Blocked');
 4655:     }
 4656:     $output .= <<"END_BLOCK";
 4657: <div class='LC_comblock'>
 4658:   <a onclick='openWindow("$popupUrl","Blocking Table",600,300,"no","no");return false;' href='/adm/blockingstatus/$querystring'
 4659:   title='$text'>
 4660:   <img class='LC_noBorder LC_middle' title='$text' src='/res/adm/pages/comblock.png' alt='$text'/></a>
 4661:   <a onclick='openWindow("$popupUrl","Blocking Table",600,300,"no","no");return false;' href='/adm/blockingstatus/$querystring' 
 4662:   title='$text'>$text</a>
 4663: </div>
 4664: 
 4665: END_BLOCK
 4666: 
 4667:     return ($blocked, $output);
 4668: }
 4669: 
 4670: ###############################################
 4671: 
 4672: sub check_ip_acc {
 4673:     my ($acc)=@_;
 4674:     &Apache::lonxml::debug("acc is $acc");
 4675:     if (!defined($acc) || $acc =~ /^\s*$/ || $acc =~/^\s*no\s*$/i) {
 4676:         return 1;
 4677:     }
 4678:     my $allowed=0;
 4679:     my $ip=$env{'request.host'} || $ENV{'REMOTE_ADDR'};
 4680: 
 4681:     my $name;
 4682:     foreach my $pattern (split(',',$acc)) {
 4683:         $pattern =~ s/^\s*//;
 4684:         $pattern =~ s/\s*$//;
 4685:         if ($pattern =~ /\*$/) {
 4686:             #35.8.*
 4687:             $pattern=~s/\*//;
 4688:             if ($ip =~ /^\Q$pattern\E/) { $allowed=1; }
 4689:         } elsif ($pattern =~ /(\d+\.\d+\.\d+)\.\[(\d+)-(\d+)\]$/) {
 4690:             #35.8.3.[34-56]
 4691:             my $low=$2;
 4692:             my $high=$3;
 4693:             $pattern=$1;
 4694:             if ($ip =~ /^\Q$pattern\E/) {
 4695:                 my $last=(split(/\./,$ip))[3];
 4696:                 if ($last <=$high && $last >=$low) { $allowed=1; }
 4697:             }
 4698:         } elsif ($pattern =~ /^\*/) {
 4699:             #*.msu.edu
 4700:             $pattern=~s/\*//;
 4701:             if (!defined($name)) {
 4702:                 use Socket;
 4703:                 my $netaddr=inet_aton($ip);
 4704:                 ($name)=gethostbyaddr($netaddr,AF_INET);
 4705:             }
 4706:             if ($name =~ /\Q$pattern\E$/i) { $allowed=1; }
 4707:         } elsif ($pattern =~ /\d+\.\d+\.\d+\.\d+/) {
 4708:             #127.0.0.1
 4709:             if ($ip =~ /^\Q$pattern\E/) { $allowed=1; }
 4710:         } else {
 4711:             #some.name.com
 4712:             if (!defined($name)) {
 4713:                 use Socket;
 4714:                 my $netaddr=inet_aton($ip);
 4715:                 ($name)=gethostbyaddr($netaddr,AF_INET);
 4716:             }
 4717:             if ($name =~ /\Q$pattern\E$/i) { $allowed=1; }
 4718:         }
 4719:         if ($allowed) { last; }
 4720:     }
 4721:     return $allowed;
 4722: }
 4723: 
 4724: ###############################################
 4725: 
 4726: =pod
 4727: 
 4728: =head1 Domain Template Functions
 4729: 
 4730: =over 4
 4731: 
 4732: =item * &determinedomain()
 4733: 
 4734: Inputs: $domain (usually will be undef)
 4735: 
 4736: Returns: Determines which domain should be used for designs
 4737: 
 4738: =cut
 4739: 
 4740: ###############################################
 4741: sub determinedomain {
 4742:     my $domain=shift;
 4743:     if (! $domain) {
 4744:         # Determine domain if we have not been given one
 4745:         $domain = &Apache::lonnet::default_login_domain();
 4746:         if ($env{'user.domain'}) { $domain=$env{'user.domain'}; }
 4747:         if ($env{'request.role.domain'}) { 
 4748:             $domain=$env{'request.role.domain'}; 
 4749:         }
 4750:     }
 4751:     return $domain;
 4752: }
 4753: ###############################################
 4754: 
 4755: sub devalidate_domconfig_cache {
 4756:     my ($udom)=@_;
 4757:     &Apache::lonnet::devalidate_cache_new('domainconfig',$udom);
 4758: }
 4759: 
 4760: # ---------------------- Get domain configuration for a domain
 4761: sub get_domainconf {
 4762:     my ($udom) = @_;
 4763:     my $cachetime=1800;
 4764:     my ($result,$cached)=&Apache::lonnet::is_cached_new('domainconfig',$udom);
 4765:     if (defined($cached)) { return %{$result}; }
 4766: 
 4767:     my %domconfig = &Apache::lonnet::get_dom('configuration',
 4768: 					     ['login','rolecolors','autoenroll'],$udom);
 4769:     my (%designhash,%legacy);
 4770:     if (keys(%domconfig) > 0) {
 4771:         if (ref($domconfig{'login'}) eq 'HASH') {
 4772:             if (keys(%{$domconfig{'login'}})) {
 4773:                 foreach my $key (keys(%{$domconfig{'login'}})) {
 4774:                     if (ref($domconfig{'login'}{$key}) eq 'HASH') {
 4775:                         if ($key eq 'loginvia') {
 4776:                             if (ref($domconfig{'login'}{'loginvia'}) eq 'HASH') {
 4777:                                 foreach my $hostname (keys(%{$domconfig{'login'}{'loginvia'}})) {
 4778:                                     if (ref($domconfig{'login'}{'loginvia'}{$hostname}) eq 'HASH') {
 4779:                                         if ($domconfig{'login'}{'loginvia'}{$hostname}{'server'}) {
 4780:                                             my $server = $domconfig{'login'}{'loginvia'}{$hostname}{'server'};
 4781:                                             $designhash{$udom.'.login.loginvia'} = $server;
 4782:                                             if ($domconfig{'login'}{'loginvia'}{$hostname}{'serverpath'} eq 'custom') {
 4783: 
 4784:                                                 $designhash{$udom.'.login.loginvia_'.$hostname} = $server.':'.$domconfig{'login'}{'loginvia'}{$hostname}{'custompath'};
 4785:                                             } else {
 4786:                                                 $designhash{$udom.'.login.loginvia_'.$hostname} = $server.':'.$domconfig{'login'}{'loginvia'}{$hostname}{'serverpath'};
 4787:                                             }
 4788:                                             if ($domconfig{'login'}{'loginvia'}{$hostname}{'exempt'}) {
 4789:                                                 $designhash{$udom.'.login.loginvia_exempt_'.$hostname} = $domconfig{'login'}{'loginvia'}{$hostname}{'exempt'};
 4790:                                             }
 4791:                                         }
 4792:                                     }
 4793:                                 }
 4794:                             }
 4795:                         } else {
 4796:                             foreach my $img (keys(%{$domconfig{'login'}{$key}})) {
 4797:                                 $designhash{$udom.'.login.'.$key.'_'.$img} = 
 4798:                                     $domconfig{'login'}{$key}{$img};
 4799:                             }
 4800:                         }
 4801:                     } else {
 4802:                         $designhash{$udom.'.login.'.$key}=$domconfig{'login'}{$key};
 4803:                     }
 4804:                 }
 4805:             } else {
 4806:                 $legacy{'login'} = 1;
 4807:             }
 4808:         } else {
 4809:             $legacy{'login'} = 1;
 4810:         }
 4811:         if (ref($domconfig{'rolecolors'}) eq 'HASH') {
 4812:             if (keys(%{$domconfig{'rolecolors'}})) {
 4813:                 foreach my $role (keys(%{$domconfig{'rolecolors'}})) {
 4814:                     if (ref($domconfig{'rolecolors'}{$role}) eq 'HASH') {
 4815:                         foreach my $item (keys(%{$domconfig{'rolecolors'}{$role}})) {
 4816:                             $designhash{$udom.'.'.$role.'.'.$item}=$domconfig{'rolecolors'}{$role}{$item};
 4817:                         }
 4818:                     }
 4819:                 }
 4820:             } else {
 4821:                 $legacy{'rolecolors'} = 1;
 4822:             }
 4823:         } else {
 4824:             $legacy{'rolecolors'} = 1;
 4825:         }
 4826:         if (ref($domconfig{'autoenroll'}) eq 'HASH') {
 4827:             if ($domconfig{'autoenroll'}{'co-owners'}) {
 4828:                 $designhash{$udom.'.autoassign.co-owners'}=$domconfig{'autoenroll'}{'co-owners'};
 4829:             }
 4830:         }
 4831:         if (keys(%legacy) > 0) {
 4832:             my %legacyhash = &get_legacy_domconf($udom);
 4833:             foreach my $item (keys(%legacyhash)) {
 4834:                 if ($item =~ /^\Q$udom\E\.login/) {
 4835:                     if ($legacy{'login'}) { 
 4836:                         $designhash{$item} = $legacyhash{$item};
 4837:                     }
 4838:                 } else {
 4839:                     if ($legacy{'rolecolors'}) {
 4840:                         $designhash{$item} = $legacyhash{$item};
 4841:                     }
 4842:                 }
 4843:             }
 4844:         }
 4845:     } else {
 4846:         %designhash = &get_legacy_domconf($udom); 
 4847:     }
 4848:     &Apache::lonnet::do_cache_new('domainconfig',$udom,\%designhash,
 4849: 				  $cachetime);
 4850:     return %designhash;
 4851: }
 4852: 
 4853: sub get_legacy_domconf {
 4854:     my ($udom) = @_;
 4855:     my %legacyhash;
 4856:     my $designdir=$Apache::lonnet::perlvar{'lonTabDir'}.'/lonDomColors';
 4857:     my $designfile =  $designdir.'/'.$udom.'.tab';
 4858:     if (-e $designfile) {
 4859:         if ( open (my $fh,"<$designfile") ) {
 4860:             while (my $line = <$fh>) {
 4861:                 next if ($line =~ /^\#/);
 4862:                 chomp($line);
 4863:                 my ($key,$val)=(split(/\=/,$line));
 4864:                 if ($val) { $legacyhash{$udom.'.'.$key}=$val; }
 4865:             }
 4866:             close($fh);
 4867:         }
 4868:     }
 4869:     if (-e $Apache::lonnet::perlvar{'lonDocRoot'}.'/adm/lonDomLogos/'.$udom.'.gif') {
 4870:         $legacyhash{$udom.'.login.domlogo'} = "/adm/lonDomLogos/$udom.gif";
 4871:     }
 4872:     return %legacyhash;
 4873: }
 4874: 
 4875: =pod
 4876: 
 4877: =item * &domainlogo()
 4878: 
 4879: Inputs: $domain (usually will be undef)
 4880: 
 4881: Returns: A link to a domain logo, if the domain logo exists.
 4882: If the domain logo does not exist, a description of the domain.
 4883: 
 4884: =cut
 4885: 
 4886: ###############################################
 4887: sub domainlogo {
 4888:     my $domain = &determinedomain(shift);
 4889:     my %designhash = &get_domainconf($domain);    
 4890:     # See if there is a logo
 4891:     if ($designhash{$domain.'.login.domlogo'} ne '') {
 4892:         my $imgsrc = $designhash{$domain.'.login.domlogo'};
 4893:         if ($imgsrc =~ m{^/(adm|res)/}) {
 4894: 	    if ($imgsrc =~ m{^/res/}) {
 4895: 		my $local_name = &Apache::lonnet::filelocation('',$imgsrc);
 4896: 		&Apache::lonnet::repcopy($local_name);
 4897: 	    }
 4898: 	   $imgsrc = &lonhttpdurl($imgsrc);
 4899:         } 
 4900:         return '<img src="'.$imgsrc.'" alt="'.$domain.'" />';
 4901:     } elsif (defined(&Apache::lonnet::domain($domain,'description'))) {
 4902:         return &Apache::lonnet::domain($domain,'description');
 4903:     } else {
 4904:         return '';
 4905:     }
 4906: }
 4907: ##############################################
 4908: 
 4909: =pod
 4910: 
 4911: =item * &designparm()
 4912: 
 4913: Inputs: $which parameter; $domain (usually will be undef)
 4914: 
 4915: Returns: value of designparamter $which
 4916: 
 4917: =cut
 4918: 
 4919: 
 4920: ##############################################
 4921: sub designparm {
 4922:     my ($which,$domain)=@_;
 4923:     if (exists($env{'environment.color.'.$which})) {
 4924:         return $env{'environment.color.'.$which};
 4925:     }
 4926:     $domain=&determinedomain($domain);
 4927:     my %domdesign;
 4928:     unless ($domain eq 'public') {
 4929:         %domdesign = &get_domainconf($domain);
 4930:     }
 4931:     my $output;
 4932:     if ($domdesign{$domain.'.'.$which} ne '') {
 4933:         $output = $domdesign{$domain.'.'.$which};
 4934:     } else {
 4935:         $output = $defaultdesign{$which};
 4936:     }
 4937:     if (($which =~ /^(student|coordinator|author|admin)\.img$/) ||
 4938:         ($which =~ /login\.(img|logo|domlogo|login)/)) {
 4939:         if ($output =~ m{^/(adm|res)/}) {
 4940:             if ($output =~ m{^/res/}) {
 4941:                 my $local_name = &Apache::lonnet::filelocation('',$output);
 4942:                 &Apache::lonnet::repcopy($local_name);
 4943:             }
 4944:             $output = &lonhttpdurl($output);
 4945:         }
 4946:     }
 4947:     return $output;
 4948: }
 4949: 
 4950: ##############################################
 4951: =pod
 4952: 
 4953: =item * &authorspace()
 4954: 
 4955: Inputs: $url (usually will be undef).
 4956: 
 4957: Returns: Path to Authoring Space containing the resource or 
 4958:          directory being viewed (or for which action is being taken). 
 4959:          If $url is provided, and begins /priv/<domain>/<uname>
 4960:          the path will be that portion of the $context argument.
 4961:          Otherwise the path will be for the author space of the current
 4962:          user when the current role is author, or for that of the 
 4963:          co-author/assistant co-author space when the current role 
 4964:          is co-author or assistant co-author.
 4965: 
 4966: =cut
 4967: 
 4968: sub authorspace {
 4969:     my ($url) = @_;
 4970:     if ($url ne '') {
 4971:         if ($url =~ m{^(/priv/$match_domain/$match_username/)}) {
 4972:            return $1;
 4973:         }
 4974:     }
 4975:     my $caname = '';
 4976:     my $cadom = '';
 4977:     if ($env{'request.role'} =~ /^(?:ca|aa)/) {
 4978:         ($cadom,$caname) =
 4979:             ($env{'request.role'}=~/($match_domain)\/($match_username)$/);
 4980:     } elsif ($env{'request.role'} =~ m{^au\./($match_domain)/}) {
 4981:         $caname = $env{'user.name'};
 4982:         $cadom = $env{'user.domain'};
 4983:     }
 4984:     if (($caname ne '') && ($cadom ne '')) {
 4985:         return "/priv/$cadom/$caname/";
 4986:     }
 4987:     return;
 4988: }
 4989: 
 4990: ##############################################
 4991: =pod
 4992: 
 4993: =item * &head_subbox()
 4994: 
 4995: Inputs: $content (contains HTML code with page functions, etc.)
 4996: 
 4997: Returns: HTML div with $content
 4998:          To be included in page header
 4999: 
 5000: =cut
 5001: 
 5002: sub head_subbox {
 5003:     my ($content)=@_;
 5004:     my $output =
 5005:         '<div class="LC_head_subbox">'
 5006:        .$content
 5007:        .'</div>'
 5008: }
 5009: 
 5010: ##############################################
 5011: =pod
 5012: 
 5013: =item * &CSTR_pageheader()
 5014: 
 5015: Input: (optional) filename from which breadcrumb trail is built.
 5016:        In most cases no input as needed, as $env{'request.filename'}
 5017:        is appropriate for use in building the breadcrumb trail.
 5018: 
 5019: Returns: HTML div with CSTR path and recent box
 5020:          To be included on Authoring Space pages
 5021: 
 5022: =cut
 5023: 
 5024: sub CSTR_pageheader {
 5025:     my ($trailfile) = @_;
 5026:     if ($trailfile eq '') {
 5027:         $trailfile = $env{'request.filename'};
 5028:     }
 5029: 
 5030: # this is for resources; directories have customtitle, and crumbs
 5031: # and select recent are created in lonpubdir.pm
 5032: 
 5033:     my $londocroot = $Apache::lonnet::perlvar{'lonDocRoot'};
 5034:     my ($udom,$uname,$thisdisfn)=
 5035:         ($trailfile =~ m{^\Q$londocroot\E/priv/([^/]+)/([^/]+)(?:|/(.*))$});
 5036:     my $formaction = "/priv/$udom/$uname/$thisdisfn";
 5037:     $formaction =~ s{/+}{/}g;
 5038: 
 5039:     my $parentpath = '';
 5040:     my $lastitem = '';
 5041:     if ($thisdisfn =~ m-(.+/)([^/]*)$-) {
 5042:         $parentpath = $1;
 5043:         $lastitem = $2;
 5044:     } else {
 5045:         $lastitem = $thisdisfn;
 5046:     }
 5047: 
 5048:     my $output =
 5049:          '<div>'
 5050:         .&Apache::loncommon::help_open_menu('','',3,'Authoring') #FIXME: Broken? Where is it?
 5051:         .'<b>'.&mt('Authoring Space:').'</b> '
 5052:         .'<form name="dirs" method="post" action="'.$formaction
 5053:         .'" target="_top">' #FIXME lonpubdir: target="_parent"
 5054:         .&Apache::lonhtmlcommon::crumbs($uname.'/'.$parentpath,'_top','/priv/'.$udom,undef,undef);
 5055: 
 5056:     if ($lastitem) {
 5057:         $output .=
 5058:              '<span class="LC_filename">'
 5059:             .$lastitem
 5060:             .'</span>';
 5061:     }
 5062:     $output .=
 5063:          '<br />'
 5064:         #FIXME lonpubdir: &Apache::lonhtmlcommon::crumbs($uname.$thisdisfn.'/','_top','/priv','','+1',1)."</b></tt><br />"
 5065:         .&Apache::lonhtmlcommon::select_recent('construct','recent','this.form.action=this.form.recent.value;this.form.submit()')
 5066:         .'</form>'
 5067:         .&Apache::lonmenu::constspaceform()
 5068:         .'</div>';
 5069: 
 5070:     return $output;
 5071: }
 5072: 
 5073: ###############################################
 5074: ###############################################
 5075: 
 5076: =pod
 5077: 
 5078: =back
 5079: 
 5080: =head1 HTML Helpers
 5081: 
 5082: =over 4
 5083: 
 5084: =item * &bodytag()
 5085: 
 5086: Returns a uniform header for LON-CAPA web pages.
 5087: 
 5088: Inputs: 
 5089: 
 5090: =over 4
 5091: 
 5092: =item * $title, A title to be displayed on the page.
 5093: 
 5094: =item * $function, the current role (can be undef).
 5095: 
 5096: =item * $addentries, extra parameters for the <body> tag.
 5097: 
 5098: =item * $bodyonly, if defined, only return the <body> tag.
 5099: 
 5100: =item * $domain, if defined, force a given domain.
 5101: 
 5102: =item * $forcereg, if page should register as content page (relevant for 
 5103:             text interface only)
 5104: 
 5105: =item * $no_nav_bar, if true, keep the 'what is this' info but remove the
 5106:                      navigational links
 5107: 
 5108: =item * $bgcolor, used to override the bgcolor on a webpage to a specific value
 5109: 
 5110: =item * $args, optional argument valid values are
 5111:             no_auto_mt_title -> prevents &mt()ing the title arg
 5112:             inherit_jsmath -> when creating popup window in a page,
 5113:                               should it have jsmath forced on by the
 5114:                               current page
 5115: 
 5116: =item * $advtoolsref, optional argument, ref to an array containing
 5117:             inlineremote items to be added in "Functions" menu below
 5118:             breadcrumbs.
 5119: 
 5120: =back
 5121: 
 5122: Returns: A uniform header for LON-CAPA web pages.  
 5123: If $bodyonly is nonzero, a string containing a <body> tag will be returned.
 5124: If $bodyonly is undef or zero, an html string containing a <body> tag and 
 5125: other decorations will be returned.
 5126: 
 5127: =cut
 5128: 
 5129: sub bodytag {
 5130:     my ($title,$function,$addentries,$bodyonly,$domain,$forcereg,
 5131:         $no_nav_bar,$bgcolor,$args,$advtoolsref)=@_;
 5132: 
 5133:     my $public;
 5134:     if ((($env{'user.name'} eq 'public') && ($env{'user.domain'} eq 'public'))
 5135:         || ($env{'user.name'} eq '') && ($env{'user.domain'} eq '')) {
 5136:         $public = 1;
 5137:     }
 5138:     if (!$args->{'no_auto_mt_title'}) { $title = &mt($title); }
 5139:     my $httphost = $args->{'use_absolute'};
 5140: 
 5141:     $function = &get_users_function() if (!$function);
 5142:     my $img =    &designparm($function.'.img',$domain);
 5143:     my $font =   &designparm($function.'.font',$domain);
 5144:     my $pgbg   = $bgcolor || &designparm($function.'.pgbg',$domain);
 5145: 
 5146:     my %design = ( 'style'   => 'margin-top: 0',
 5147: 		   'bgcolor' => $pgbg,
 5148: 		   'text'    => $font,
 5149:                    'alink'   => &designparm($function.'.alink',$domain),
 5150: 		   'vlink'   => &designparm($function.'.vlink',$domain),
 5151: 		   'link'    => &designparm($function.'.link',$domain),);
 5152:     @design{keys(%$addentries)} = @$addentries{keys(%$addentries)}; 
 5153: 
 5154:  # role and realm
 5155:     my ($role,$realm) = split(m{\./},$env{'request.role'},2);
 5156:     if ($realm) {
 5157:         $realm = '/'.$realm;
 5158:     }
 5159:     if ($role  eq 'ca') {
 5160:         my ($rdom,$rname) = ($realm =~ m{^/($match_domain)/($match_username)$});
 5161:         $realm = &plainname($rname,$rdom);
 5162:     } 
 5163: # realm
 5164:     if ($env{'request.course.id'}) {
 5165:         if ($env{'request.role'} !~ /^cr/) {
 5166:             $role = &Apache::lonnet::plaintext($role,&course_type());
 5167:         }
 5168:         if ($env{'request.course.sec'}) {
 5169:             $role .= ('&nbsp;'x2).'-&nbsp;'.&mt('section:').'&nbsp;'.$env{'request.course.sec'};
 5170:         }   
 5171: 	$realm = $env{'course.'.$env{'request.course.id'}.'.description'};
 5172:     } else {
 5173:         $role = &Apache::lonnet::plaintext($role);
 5174:     }
 5175: 
 5176:     if (!$realm) { $realm='&nbsp;'; }
 5177: 
 5178:     my $extra_body_attr = &make_attr_string($forcereg,\%design);
 5179: 
 5180: # construct main body tag
 5181:     my $bodytag = "<body $extra_body_attr>".
 5182: 	&Apache::lontexconvert::init_math_support($args->{'inherit_jsmath'});
 5183: 
 5184:     &get_unprocessed_cgi($ENV{'QUERY_STRING'}, ['inhibitmenu']);
 5185: 
 5186:     if (($bodyonly) || ($no_nav_bar) || ($env{'form.inhibitmenu'} eq 'yes')) {
 5187:         return $bodytag;
 5188:     }
 5189: 
 5190:     if ($public) {
 5191: 	undef($role);
 5192:     }
 5193:     
 5194:     my $titleinfo = '<h1>'.$title.'</h1>';
 5195:     #
 5196:     # Extra info if you are the DC
 5197:     my $dc_info = '';
 5198:     if ($env{'user.adv'} && exists($env{'user.role.dc./'.
 5199:                         $env{'course.'.$env{'request.course.id'}.
 5200:                                  '.domain'}.'/'})) {
 5201:         my $cid = $env{'request.course.id'};
 5202:         $dc_info = $cid.' '.$env{'course.'.$cid.'.internal.coursecode'};
 5203:         $dc_info =~ s/\s+$//;
 5204:     }
 5205: 
 5206:     $role = '<span class="LC_nobreak">('.$role.')</span>' if $role;
 5207: 
 5208:         if ($env{'request.state'} eq 'construct') { $forcereg=1; }
 5209: 
 5210:         #    if ($env{'request.state'} eq 'construct') {
 5211:         #        $titleinfo = &CSTR_pageheader(); #FIXME: Will be removed once all scripts have their own calls
 5212:         #    }
 5213: 
 5214:         $bodytag .= Apache::lonhtmlcommon::scripttag(
 5215:             Apache::lonmenu::utilityfunctions($httphost), 'start');
 5216: 
 5217:         my ($left,$right) = Apache::lonmenu::primary_menu();
 5218: 
 5219:         if ($env{'request.noversionuri'} =~ m{^/res/adm/pages/}) {
 5220:              if ($dc_info) {
 5221:                  $dc_info = qq|<span class="LC_cusr_subheading">$dc_info</span>|;
 5222:              }
 5223:              $bodytag .= qq|<div id="LC_nav_bar">$left $role<br />
 5224:                 <em>$realm</em> $dc_info</div>|;
 5225:             return $bodytag;
 5226:         }
 5227: 
 5228:         unless ($env{'request.symb'} =~ m/\.page___\d+___/) {
 5229:             $bodytag .= qq|<div id="LC_nav_bar">$left $role</div>|;
 5230:         }
 5231: 
 5232:         $bodytag .= $right;
 5233: 
 5234:         if ($dc_info) {
 5235:             $dc_info = &dc_courseid_toggle($dc_info);
 5236:         }
 5237:         $bodytag .= qq|<div id="LC_realm">$realm $dc_info</div>|;
 5238: 
 5239:         #if directed to not display the secondary menu, don't.  
 5240:         if ($args->{'no_secondary_menu'}) {
 5241:             return $bodytag;
 5242:         }
 5243:         #don't show menus for public users
 5244:         if (!$public){
 5245:             $bodytag .= Apache::lonmenu::secondary_menu($httphost);
 5246:             $bodytag .= Apache::lonmenu::serverform();
 5247:             $bodytag .= Apache::lonhtmlcommon::scripttag('', 'end');
 5248:             if ($env{'request.state'} eq 'construct') {
 5249:                 $bodytag .= &Apache::lonmenu::innerregister($forcereg,
 5250:                                 $args->{'bread_crumbs'});
 5251:             } elsif ($forcereg) {
 5252:                 $bodytag .= &Apache::lonmenu::innerregister($forcereg,undef,
 5253:                                                             $args->{'group'});
 5254:             } else {
 5255:                 $bodytag .= 
 5256:                     &Apache::lonmenu::prepare_functions($env{'request.noversionuri'},
 5257:                                                         $forcereg,$args->{'group'},
 5258:                                                         $args->{'bread_crumbs'},
 5259:                                                         $advtoolsref);
 5260:             }
 5261:         }else{
 5262:             # this is to seperate menu from content when there's no secondary
 5263:             # menu. Especially needed for public accessible ressources.
 5264:             $bodytag .= '<hr style="clear:both" />';
 5265:             $bodytag .= Apache::lonhtmlcommon::scripttag('', 'end'); 
 5266:         }
 5267: 
 5268:         return $bodytag;
 5269: }
 5270: 
 5271: sub dc_courseid_toggle {
 5272:     my ($dc_info) = @_;
 5273:     return ' <span id="dccidtext" class="LC_cusr_subheading LC_nobreak">'.
 5274:            '<a href="javascript:showCourseID();" class="LC_menubuttons_link">'.
 5275:            &mt('(More ...)').'</a></span>'.
 5276:            '<div id="dccid" class="LC_dccid">'.$dc_info.'</div>';
 5277: }
 5278: 
 5279: sub make_attr_string {
 5280:     my ($register,$attr_ref) = @_;
 5281: 
 5282:     if ($attr_ref && !ref($attr_ref)) {
 5283: 	die("addentries Must be a hash ref ".
 5284: 	    join(':',caller(1))." ".
 5285: 	    join(':',caller(0))." ");
 5286:     }
 5287: 
 5288:     if ($register) {
 5289: 	my ($on_load,$on_unload);
 5290: 	foreach my $key (keys(%{$attr_ref})) {
 5291: 	    if      (lc($key) eq 'onload') {
 5292: 		$on_load.=$attr_ref->{$key}.';';
 5293: 		delete($attr_ref->{$key});
 5294: 
 5295: 	    } elsif (lc($key) eq 'onunload') {
 5296: 		$on_unload.=$attr_ref->{$key}.';';
 5297: 		delete($attr_ref->{$key});
 5298: 	    }
 5299: 	}
 5300: 	$attr_ref->{'onload'}  = $on_load;
 5301: 	$attr_ref->{'onunload'}= $on_unload;
 5302:     }
 5303: 
 5304:     my $attr_string;
 5305:     foreach my $attr (sort(keys(%$attr_ref))) {
 5306: 	$attr_string .= " $attr=\"".$attr_ref->{$attr}.'" ';
 5307:     }
 5308:     return $attr_string;
 5309: }
 5310: 
 5311: 
 5312: ###############################################
 5313: ###############################################
 5314: 
 5315: =pod
 5316: 
 5317: =item * &endbodytag()
 5318: 
 5319: Returns a uniform footer for LON-CAPA web pages.
 5320: 
 5321: Inputs: 1 - optional reference to an args hash
 5322: If in the hash, key for noredirectlink has a value which evaluates to true,
 5323: a 'Continue' link is not displayed if the page contains an
 5324: internal redirect in the <head></head> section,
 5325: i.e., $env{'internal.head.redirect'} exists   
 5326: 
 5327: =cut
 5328: 
 5329: sub endbodytag {
 5330:     my ($args) = @_;
 5331:     my $endbodytag;
 5332:     unless ((ref($args) eq 'HASH') && ($args->{'notbody'})) {
 5333:         $endbodytag='</body>';
 5334:     }
 5335:     $endbodytag=&Apache::lontexconvert::jsMath_process()."\n".$endbodytag;
 5336:     if ( exists( $env{'internal.head.redirect'} ) ) {
 5337:         if (!(ref($args) eq 'HASH' && $args->{'noredirectlink'})) {
 5338: 	    $endbodytag=
 5339: 	        "<br /><a href=\"$env{'internal.head.redirect'}\">".
 5340: 	        &mt('Continue').'</a>'.
 5341: 	        $endbodytag;
 5342:         }
 5343:     }
 5344:     return $endbodytag;
 5345: }
 5346: 
 5347: =pod
 5348: 
 5349: =item * &standard_css()
 5350: 
 5351: Returns a style sheet
 5352: 
 5353: Inputs: (all optional)
 5354:             domain         -> force to color decorate a page for a specific
 5355:                                domain
 5356:             function       -> force usage of a specific rolish color scheme
 5357:             bgcolor        -> override the default page bgcolor
 5358: 
 5359: =cut
 5360: 
 5361: sub standard_css {
 5362:     my ($function,$domain,$bgcolor) = @_;
 5363:     $function  = &get_users_function() if (!$function);
 5364:     my $img    = &designparm($function.'.img',   $domain);
 5365:     my $tabbg  = &designparm($function.'.tabbg', $domain);
 5366:     my $font   = &designparm($function.'.font',  $domain);
 5367:     my $fontmenu = &designparm($function.'.fontmenu', $domain);
 5368: #second colour for later usage
 5369:     my $sidebg = &designparm($function.'.sidebg',$domain);
 5370:     my $pgbg_or_bgcolor =
 5371: 	         $bgcolor ||
 5372: 	         &designparm($function.'.pgbg',  $domain);
 5373:     my $pgbg   = &designparm($function.'.pgbg',  $domain);
 5374:     my $alink  = &designparm($function.'.alink', $domain);
 5375:     my $vlink  = &designparm($function.'.vlink', $domain);
 5376:     my $link   = &designparm($function.'.link',  $domain);
 5377: 
 5378:     my $sans                 = 'Verdana,Arial,Helvetica,sans-serif';
 5379:     my $mono                 = 'monospace';
 5380:     my $data_table_head      = $sidebg;
 5381:     my $data_table_light     = '#FAFAFA';
 5382:     my $data_table_dark      = '#E0E0E0';
 5383:     my $data_table_darker    = '#CCCCCC';
 5384:     my $data_table_highlight = '#FFFF00';
 5385:     my $mail_new             = '#FFBB77';
 5386:     my $mail_new_hover       = '#DD9955';
 5387:     my $mail_read            = '#BBBB77';
 5388:     my $mail_read_hover      = '#999944';
 5389:     my $mail_replied         = '#AAAA88';
 5390:     my $mail_replied_hover   = '#888855';
 5391:     my $mail_other           = '#99BBBB';
 5392:     my $mail_other_hover     = '#669999';
 5393:     my $table_header         = '#DDDDDD';
 5394:     my $feedback_link_bg     = '#BBBBBB';
 5395:     my $lg_border_color      = '#C8C8C8';
 5396:     my $button_hover         = '#BF2317';
 5397: 
 5398:     my $border = ($env{'browser.type'} eq 'explorer' ||
 5399:       $env{'browser.type'} eq 'safari'     ) ? '0 2px 0 2px'
 5400:                                              : '0 3px 0 4px';
 5401: 
 5402: 
 5403:     return <<END;
 5404: 
 5405: /* needed for iframe to allow 100% height in FF */
 5406: body, html { 
 5407:     margin: 0;
 5408:     padding: 0 0.5%;
 5409:     height: 99%; /* to avoid scrollbars */
 5410: }
 5411: 
 5412: body {
 5413:   font-family: $sans;
 5414:   line-height:130%;
 5415:   font-size:0.83em;
 5416:   color:$font;
 5417: }
 5418: 
 5419: a:focus,
 5420: a:focus img {
 5421:   color: red;
 5422: }
 5423: 
 5424: form, .inline {
 5425:   display: inline;
 5426: }
 5427: 
 5428: .LC_right {
 5429:   text-align:right;
 5430: }
 5431: 
 5432: .LC_middle {
 5433:   vertical-align:middle;
 5434: }
 5435: 
 5436: .LC_floatleft {
 5437:   float: left;
 5438: }
 5439: 
 5440: .LC_floatright {
 5441:   float: right;
 5442: }
 5443: 
 5444: .LC_400Box {
 5445:   width:400px;
 5446: }
 5447: 
 5448: .LC_iframecontainer {
 5449:     width: 98%;
 5450:     margin: 0;
 5451:     position: fixed;
 5452:     top: 8.5em;
 5453:     bottom: 0;
 5454: }
 5455: 
 5456: .LC_iframecontainer iframe{
 5457:     border: none;
 5458:     width: 100%;
 5459:     height: 100%;
 5460: }
 5461: 
 5462: .LC_filename {
 5463:   font-family: $mono;
 5464:   white-space:pre;
 5465:   font-size: 120%;
 5466: }
 5467: 
 5468: .LC_fileicon {
 5469:   border: none;
 5470:   height: 1.3em;
 5471:   vertical-align: text-bottom;
 5472:   margin-right: 0.3em;
 5473:   text-decoration:none;
 5474: }
 5475: 
 5476: .LC_setting {
 5477:   text-decoration:underline;
 5478: }
 5479: 
 5480: .LC_error {
 5481:   color: red;
 5482: }
 5483: 
 5484: .LC_warning {
 5485:   color: darkorange;
 5486: }
 5487: 
 5488: .LC_diff_removed {
 5489:   color: red;
 5490: }
 5491: 
 5492: .LC_info,
 5493: .LC_success,
 5494: .LC_diff_added {
 5495:   color: green;
 5496: }
 5497: 
 5498: div.LC_confirm_box {
 5499:   background-color: #FAFAFA;
 5500:   border: 1px solid $lg_border_color;
 5501:   margin-right: 0;
 5502:   padding: 5px;
 5503: }
 5504: 
 5505: div.LC_confirm_box .LC_error img,
 5506: div.LC_confirm_box .LC_success img {
 5507:   vertical-align: middle;
 5508: }
 5509: 
 5510: .LC_icon {
 5511:   border: none;
 5512:   vertical-align: middle;
 5513: }
 5514: 
 5515: .LC_docs_spacer {
 5516:   width: 25px;
 5517:   height: 1px;
 5518:   border: none;
 5519: }
 5520: 
 5521: .LC_internal_info {
 5522:   color: #999999;
 5523: }
 5524: 
 5525: .LC_discussion {
 5526:   background: $data_table_dark;
 5527:   border: 1px solid black;
 5528:   margin: 2px;
 5529: }
 5530: 
 5531: .LC_disc_action_left {
 5532:   background: $sidebg;
 5533:   text-align: left;
 5534:   padding: 4px;
 5535:   margin: 2px;
 5536: }
 5537: 
 5538: .LC_disc_action_right {
 5539:   background: $sidebg;
 5540:   text-align: right;
 5541:   padding: 4px;
 5542:   margin: 2px;
 5543: }
 5544: 
 5545: .LC_disc_new_item {
 5546:   background: white;
 5547:   border: 2px solid red;
 5548:   margin: 4px;
 5549:   padding: 4px;
 5550: }
 5551: 
 5552: .LC_disc_old_item {
 5553:   background: white;
 5554:   margin: 4px;
 5555:   padding: 4px;
 5556: }
 5557: 
 5558: table.LC_pastsubmission {
 5559:   border: 1px solid black;
 5560:   margin: 2px;
 5561: }
 5562: 
 5563: table#LC_menubuttons {
 5564:   width: 100%;
 5565:   background: $pgbg;
 5566:   border: 2px;
 5567:   border-collapse: separate;
 5568:   padding: 0;
 5569: }
 5570: 
 5571: table#LC_title_bar a {
 5572:   color: $fontmenu;
 5573: }
 5574: 
 5575: table#LC_title_bar {
 5576:   clear: both;
 5577:   display: none;
 5578: }
 5579: 
 5580: table#LC_title_bar,
 5581: table.LC_breadcrumbs, /* obsolete? */
 5582: table#LC_title_bar.LC_with_remote {
 5583:   width: 100%;
 5584:   border-color: $pgbg;
 5585:   border-style: solid;
 5586:   border-width: $border;
 5587:   background: $pgbg;
 5588:   color: $fontmenu;
 5589:   border-collapse: collapse;
 5590:   padding: 0;
 5591:   margin: 0;
 5592: }
 5593: 
 5594: ul.LC_breadcrumb_tools_outerlist {
 5595:     margin: 0;
 5596:     padding: 0;
 5597:     position: relative;
 5598:     list-style: none;
 5599: }
 5600: ul.LC_breadcrumb_tools_outerlist li {
 5601:     display: inline;
 5602: }
 5603: 
 5604: .LC_breadcrumb_tools_navigation {
 5605:     padding: 0;
 5606:     margin: 0;
 5607:     float: left;
 5608: }
 5609: .LC_breadcrumb_tools_tools {
 5610:     padding: 0;
 5611:     margin: 0;
 5612:     float: right;
 5613: }
 5614: 
 5615: table#LC_title_bar td {
 5616:   background: $tabbg;
 5617: }
 5618: 
 5619: table#LC_menubuttons img {
 5620:   border: none;
 5621: }
 5622: 
 5623: .LC_breadcrumbs_component {
 5624:   float: right;
 5625:   margin: 0 1em;
 5626: }
 5627: .LC_breadcrumbs_component img {
 5628:   vertical-align: middle;
 5629: }
 5630: 
 5631: td.LC_table_cell_checkbox {
 5632:   text-align: center;
 5633: }
 5634: 
 5635: .LC_fontsize_small {
 5636:   font-size: 70%;
 5637: }
 5638: 
 5639: #LC_breadcrumbs {
 5640:   clear:both;
 5641:   background: $sidebg;
 5642:   border-bottom: 1px solid $lg_border_color;
 5643:   line-height: 2.5em;
 5644:   overflow: hidden;
 5645:   margin: 0;
 5646:   padding: 0;
 5647:   text-align: left;
 5648: }
 5649: 
 5650: .LC_head_subbox, .LC_actionbox {
 5651:   clear:both;
 5652:   background: #F8F8F8; /* $sidebg; */
 5653:   border: 1px solid $sidebg;
 5654:   margin: 0 0 10px 0;
 5655:   padding: 3px;
 5656:   text-align: left;
 5657: }
 5658: 
 5659: .LC_fontsize_medium {
 5660:   font-size: 85%;
 5661: }
 5662: 
 5663: .LC_fontsize_large {
 5664:   font-size: 120%;
 5665: }
 5666: 
 5667: .LC_menubuttons_inline_text {
 5668:   color: $font;
 5669:   font-size: 90%;
 5670:   padding-left:3px;
 5671: }
 5672: 
 5673: .LC_menubuttons_inline_text img{
 5674:   vertical-align: middle;
 5675: }
 5676: 
 5677: li.LC_menubuttons_inline_text img {
 5678:   cursor:pointer;
 5679:   text-decoration: none;
 5680: }
 5681: 
 5682: .LC_menubuttons_link {
 5683:   text-decoration: none;
 5684: }
 5685: 
 5686: .LC_menubuttons_category {
 5687:   color: $font;
 5688:   background: $pgbg;
 5689:   font-size: larger;
 5690:   font-weight: bold;
 5691: }
 5692: 
 5693: td.LC_menubuttons_text {
 5694:   color: $font;
 5695: }
 5696: 
 5697: .LC_current_location {
 5698:   background: $tabbg;
 5699: }
 5700: 
 5701: table.LC_data_table {
 5702:   border: 1px solid #000000;
 5703:   border-collapse: separate;
 5704:   border-spacing: 1px;
 5705:   background: $pgbg;
 5706: }
 5707: 
 5708: .LC_data_table_dense {
 5709:   font-size: small;
 5710: }
 5711: 
 5712: table.LC_nested_outer {
 5713:   border: 1px solid #000000;
 5714:   border-collapse: collapse;
 5715:   border-spacing: 0;
 5716:   width: 100%;
 5717: }
 5718: 
 5719: table.LC_innerpickbox,
 5720: table.LC_nested {
 5721:   border: none;
 5722:   border-collapse: collapse;
 5723:   border-spacing: 0;
 5724:   width: 100%;
 5725: }
 5726: 
 5727: table.LC_data_table tr th,
 5728: table.LC_calendar tr th,
 5729: table.LC_prior_tries tr th,
 5730: table.LC_innerpickbox tr th {
 5731:   font-weight: bold;
 5732:   background-color: $data_table_head;
 5733:   color:$fontmenu;
 5734:   font-size:90%;
 5735: }
 5736: 
 5737: table.LC_innerpickbox tr th,
 5738: table.LC_innerpickbox tr td {
 5739:   vertical-align: top;
 5740: }
 5741: 
 5742: table.LC_data_table tr.LC_info_row > td {
 5743:   background-color: #CCCCCC;
 5744:   font-weight: bold;
 5745:   text-align: left;
 5746: }
 5747: 
 5748: table.LC_data_table tr.LC_odd_row > td {
 5749:   background-color: $data_table_light;
 5750:   padding: 2px;
 5751:   vertical-align: top;
 5752: }
 5753: 
 5754: table.LC_pick_box tr > td.LC_odd_row {
 5755:   background-color: $data_table_light;
 5756:   vertical-align: top;
 5757: }
 5758: 
 5759: table.LC_data_table tr.LC_even_row > td {
 5760:   background-color: $data_table_dark;
 5761:   padding: 2px;
 5762:   vertical-align: top;
 5763: }
 5764: 
 5765: table.LC_pick_box tr > td.LC_even_row {
 5766:   background-color: $data_table_dark;
 5767:   vertical-align: top;
 5768: }
 5769: 
 5770: table.LC_data_table tr.LC_data_table_highlight td {
 5771:   background-color: $data_table_darker;
 5772: }
 5773: 
 5774: table.LC_data_table tr td.LC_leftcol_header {
 5775:   background-color: $data_table_head;
 5776:   font-weight: bold;
 5777: }
 5778: 
 5779: table.LC_data_table tr.LC_empty_row td,
 5780: table.LC_nested tr.LC_empty_row td {
 5781:   font-weight: bold;
 5782:   font-style: italic;
 5783:   text-align: center;
 5784:   padding: 8px;
 5785: }
 5786: 
 5787: table.LC_data_table tr.LC_empty_row td,
 5788: table.LC_data_table tr.LC_footer_row td {
 5789:   background-color: $sidebg;
 5790: }
 5791: 
 5792: table.LC_nested tr.LC_empty_row td {
 5793:   background-color: #FFFFFF;
 5794: }
 5795: 
 5796: table.LC_caption {
 5797: }
 5798: 
 5799: table.LC_nested tr.LC_empty_row td {
 5800:   padding: 4ex
 5801: }
 5802: 
 5803: table.LC_nested_outer tr th {
 5804:   font-weight: bold;
 5805:   color:$fontmenu;
 5806:   background-color: $data_table_head;
 5807:   font-size: small;
 5808:   border-bottom: 1px solid #000000;
 5809: }
 5810: 
 5811: table.LC_nested_outer tr td.LC_subheader {
 5812:   background-color: $data_table_head;
 5813:   font-weight: bold;
 5814:   font-size: small;
 5815:   border-bottom: 1px solid #000000;
 5816:   text-align: right;
 5817: }
 5818: 
 5819: table.LC_nested tr.LC_info_row td {
 5820:   background-color: #CCCCCC;
 5821:   font-weight: bold;
 5822:   font-size: small;
 5823:   text-align: center;
 5824: }
 5825: 
 5826: table.LC_nested tr.LC_info_row td.LC_left_item,
 5827: table.LC_nested_outer tr th.LC_left_item {
 5828:   text-align: left;
 5829: }
 5830: 
 5831: table.LC_nested td {
 5832:   background-color: #FFFFFF;
 5833:   font-size: small;
 5834: }
 5835: 
 5836: table.LC_nested_outer tr th.LC_right_item,
 5837: table.LC_nested tr.LC_info_row td.LC_right_item,
 5838: table.LC_nested tr.LC_odd_row td.LC_right_item,
 5839: table.LC_nested tr td.LC_right_item {
 5840:   text-align: right;
 5841: }
 5842: 
 5843: table.LC_nested tr.LC_odd_row td {
 5844:   background-color: #EEEEEE;
 5845: }
 5846: 
 5847: table.LC_createuser {
 5848: }
 5849: 
 5850: table.LC_createuser tr.LC_section_row td {
 5851:   font-size: small;
 5852: }
 5853: 
 5854: table.LC_createuser tr.LC_info_row td  {
 5855:   background-color: #CCCCCC;
 5856:   font-weight: bold;
 5857:   text-align: center;
 5858: }
 5859: 
 5860: table.LC_calendar {
 5861:   border: 1px solid #000000;
 5862:   border-collapse: collapse;
 5863:   width: 98%;
 5864: }
 5865: 
 5866: table.LC_calendar_pickdate {
 5867:   font-size: xx-small;
 5868: }
 5869: 
 5870: table.LC_calendar tr td {
 5871:   border: 1px solid #000000;
 5872:   vertical-align: top;
 5873:   width: 14%;
 5874: }
 5875: 
 5876: table.LC_calendar tr td.LC_calendar_day_empty {
 5877:   background-color: $data_table_dark;
 5878: }
 5879: 
 5880: table.LC_calendar tr td.LC_calendar_day_current {
 5881:   background-color: $data_table_highlight;
 5882: }
 5883: 
 5884: table.LC_data_table tr td.LC_mail_new {
 5885:   background-color: $mail_new;
 5886: }
 5887: 
 5888: table.LC_data_table tr.LC_mail_new:hover {
 5889:   background-color: $mail_new_hover;
 5890: }
 5891: 
 5892: table.LC_data_table tr td.LC_mail_read {
 5893:   background-color: $mail_read;
 5894: }
 5895: 
 5896: /*
 5897: table.LC_data_table tr.LC_mail_read:hover {
 5898:   background-color: $mail_read_hover;
 5899: }
 5900: */
 5901: 
 5902: table.LC_data_table tr td.LC_mail_replied {
 5903:   background-color: $mail_replied;
 5904: }
 5905: 
 5906: /*
 5907: table.LC_data_table tr.LC_mail_replied:hover {
 5908:   background-color: $mail_replied_hover;
 5909: }
 5910: */
 5911: 
 5912: table.LC_data_table tr td.LC_mail_other {
 5913:   background-color: $mail_other;
 5914: }
 5915: 
 5916: /*
 5917: table.LC_data_table tr.LC_mail_other:hover {
 5918:   background-color: $mail_other_hover;
 5919: }
 5920: */
 5921: 
 5922: table.LC_data_table tr > td.LC_browser_file,
 5923: table.LC_data_table tr > td.LC_browser_file_published {
 5924:   background: #AAEE77;
 5925: }
 5926: 
 5927: table.LC_data_table tr > td.LC_browser_file_locked,
 5928: table.LC_data_table tr > td.LC_browser_file_unpublished {
 5929:   background: #FFAA99;
 5930: }
 5931: 
 5932: table.LC_data_table tr > td.LC_browser_file_obsolete {
 5933:   background: #888888;
 5934: }
 5935: 
 5936: table.LC_data_table tr > td.LC_browser_file_modified,
 5937: table.LC_data_table tr > td.LC_browser_file_metamodified {
 5938:   background: #F8F866;
 5939: }
 5940: 
 5941: table.LC_data_table tr.LC_browser_folder > td {
 5942:   background: #E0E8FF;
 5943: }
 5944: 
 5945: table.LC_data_table tr > td.LC_roles_is {
 5946:   /* background: #77FF77; */
 5947: }
 5948: 
 5949: table.LC_data_table tr > td.LC_roles_future {
 5950:   border-right: 8px solid #FFFF77;
 5951: }
 5952: 
 5953: table.LC_data_table tr > td.LC_roles_will {
 5954:   border-right: 8px solid #FFAA77;
 5955: }
 5956: 
 5957: table.LC_data_table tr > td.LC_roles_expired {
 5958:   border-right: 8px solid #FF7777;
 5959: }
 5960: 
 5961: table.LC_data_table tr > td.LC_roles_will_not {
 5962:   border-right: 8px solid #AAFF77;
 5963: }
 5964: 
 5965: table.LC_data_table tr > td.LC_roles_selected {
 5966:   border-right: 8px solid #11CC55;
 5967: }
 5968: 
 5969: span.LC_current_location {
 5970:   font-size:larger;
 5971:   background: $pgbg;
 5972: }
 5973: 
 5974: span.LC_current_nav_location {
 5975:   font-weight:bold;
 5976:   background: $sidebg;
 5977: }
 5978: 
 5979: span.LC_parm_menu_item {
 5980:   font-size: larger;
 5981: }
 5982: 
 5983: span.LC_parm_scope_all {
 5984:   color: red;
 5985: }
 5986: 
 5987: span.LC_parm_scope_folder {
 5988:   color: green;
 5989: }
 5990: 
 5991: span.LC_parm_scope_resource {
 5992:   color: orange;
 5993: }
 5994: 
 5995: span.LC_parm_part {
 5996:   color: blue;
 5997: }
 5998: 
 5999: span.LC_parm_folder,
 6000: span.LC_parm_symb {
 6001:   font-size: x-small;
 6002:   font-family: $mono;
 6003:   color: #AAAAAA;
 6004: }
 6005: 
 6006: ul.LC_parm_parmlist li {
 6007:   display: inline-block;
 6008:   padding: 0.3em 0.8em;
 6009:   vertical-align: top;
 6010:   width: 150px;
 6011:   border-top:1px solid $lg_border_color;
 6012: }
 6013: 
 6014: td.LC_parm_overview_level_menu,
 6015: td.LC_parm_overview_map_menu,
 6016: td.LC_parm_overview_parm_selectors,
 6017: td.LC_parm_overview_restrictions  {
 6018:   border: 1px solid black;
 6019:   border-collapse: collapse;
 6020: }
 6021: 
 6022: table.LC_parm_overview_restrictions td {
 6023:   border-width: 1px 4px 1px 4px;
 6024:   border-style: solid;
 6025:   border-color: $pgbg;
 6026:   text-align: center;
 6027: }
 6028: 
 6029: table.LC_parm_overview_restrictions th {
 6030:   background: $tabbg;
 6031:   border-width: 1px 4px 1px 4px;
 6032:   border-style: solid;
 6033:   border-color: $pgbg;
 6034: }
 6035: 
 6036: table#LC_helpmenu {
 6037:   border: none;
 6038:   height: 55px;
 6039:   border-spacing: 0;
 6040: }
 6041: 
 6042: table#LC_helpmenu fieldset legend {
 6043:   font-size: larger;
 6044: }
 6045: 
 6046: table#LC_helpmenu_links {
 6047:   width: 100%;
 6048:   border: 1px solid black;
 6049:   background: $pgbg;
 6050:   padding: 0;
 6051:   border-spacing: 1px;
 6052: }
 6053: 
 6054: table#LC_helpmenu_links tr td {
 6055:   padding: 1px;
 6056:   background: $tabbg;
 6057:   text-align: center;
 6058:   font-weight: bold;
 6059: }
 6060: 
 6061: table#LC_helpmenu_links a:link,
 6062: table#LC_helpmenu_links a:visited,
 6063: table#LC_helpmenu_links a:active {
 6064:   text-decoration: none;
 6065:   color: $font;
 6066: }
 6067: 
 6068: table#LC_helpmenu_links a:hover {
 6069:   text-decoration: underline;
 6070:   color: $vlink;
 6071: }
 6072: 
 6073: .LC_chrt_popup_exists {
 6074:   border: 1px solid #339933;
 6075:   margin: -1px;
 6076: }
 6077: 
 6078: .LC_chrt_popup_up {
 6079:   border: 1px solid yellow;
 6080:   margin: -1px;
 6081: }
 6082: 
 6083: .LC_chrt_popup {
 6084:   border: 1px solid #8888FF;
 6085:   background: #CCCCFF;
 6086: }
 6087: 
 6088: table.LC_pick_box {
 6089:   border-collapse: separate;
 6090:   background: white;
 6091:   border: 1px solid black;
 6092:   border-spacing: 1px;
 6093: }
 6094: 
 6095: table.LC_pick_box td.LC_pick_box_title {
 6096:   background: $sidebg;
 6097:   font-weight: bold;
 6098:   text-align: left;
 6099:   vertical-align: top;
 6100:   width: 184px;
 6101:   padding: 8px;
 6102: }
 6103: 
 6104: table.LC_pick_box td.LC_pick_box_value {
 6105:   text-align: left;
 6106:   padding: 8px;
 6107: }
 6108: 
 6109: table.LC_pick_box td.LC_pick_box_select {
 6110:   text-align: left;
 6111:   padding: 8px;
 6112: }
 6113: 
 6114: table.LC_pick_box td.LC_pick_box_separator {
 6115:   padding: 0;
 6116:   height: 1px;
 6117:   background: black;
 6118: }
 6119: 
 6120: table.LC_pick_box td.LC_pick_box_submit {
 6121:   text-align: right;
 6122: }
 6123: 
 6124: table.LC_pick_box td.LC_evenrow_value {
 6125:   text-align: left;
 6126:   padding: 8px;
 6127:   background-color: $data_table_light;
 6128: }
 6129: 
 6130: table.LC_pick_box td.LC_oddrow_value {
 6131:   text-align: left;
 6132:   padding: 8px;
 6133:   background-color: $data_table_light;
 6134: }
 6135: 
 6136: span.LC_helpform_receipt_cat {
 6137:   font-weight: bold;
 6138: }
 6139: 
 6140: table.LC_group_priv_box {
 6141:   background: white;
 6142:   border: 1px solid black;
 6143:   border-spacing: 1px;
 6144: }
 6145: 
 6146: table.LC_group_priv_box td.LC_pick_box_title {
 6147:   background: $tabbg;
 6148:   font-weight: bold;
 6149:   text-align: right;
 6150:   width: 184px;
 6151: }
 6152: 
 6153: table.LC_group_priv_box td.LC_groups_fixed {
 6154:   background: $data_table_light;
 6155:   text-align: center;
 6156: }
 6157: 
 6158: table.LC_group_priv_box td.LC_groups_optional {
 6159:   background: $data_table_dark;
 6160:   text-align: center;
 6161: }
 6162: 
 6163: table.LC_group_priv_box td.LC_groups_functionality {
 6164:   background: $data_table_darker;
 6165:   text-align: center;
 6166:   font-weight: bold;
 6167: }
 6168: 
 6169: table.LC_group_priv td {
 6170:   text-align: left;
 6171:   padding: 0;
 6172: }
 6173: 
 6174: .LC_navbuttons {
 6175:   margin: 2ex 0ex 2ex 0ex;
 6176: }
 6177: 
 6178: .LC_topic_bar {
 6179:   font-weight: bold;
 6180:   background: $tabbg;
 6181:   margin: 1em 0em 1em 2em;
 6182:   padding: 3px;
 6183:   font-size: 1.2em;
 6184: }
 6185: 
 6186: .LC_topic_bar span {
 6187:   left: 0.5em;
 6188:   position: absolute;
 6189:   vertical-align: middle;
 6190:   font-size: 1.2em;
 6191: }
 6192: 
 6193: table.LC_course_group_status {
 6194:   margin: 20px;
 6195: }
 6196: 
 6197: table.LC_status_selector td {
 6198:   vertical-align: top;
 6199:   text-align: center;
 6200:   padding: 4px;
 6201: }
 6202: 
 6203: div.LC_feedback_link {
 6204:   clear: both;
 6205:   background: $sidebg;
 6206:   width: 100%;
 6207:   padding-bottom: 10px;
 6208:   border: 1px $tabbg solid;
 6209:   height: 22px;
 6210:   line-height: 22px;
 6211:   padding-top: 5px;
 6212: }
 6213: 
 6214: div.LC_feedback_link img {
 6215:   height: 22px;
 6216:   vertical-align:middle;
 6217: }
 6218: 
 6219: div.LC_feedback_link a {
 6220:   text-decoration: none;
 6221: }
 6222: 
 6223: div.LC_comblock {
 6224:   display:inline;
 6225:   color:$font;
 6226:   font-size:90%;
 6227: }
 6228: 
 6229: div.LC_feedback_link div.LC_comblock {
 6230:   padding-left:5px;
 6231: }
 6232: 
 6233: div.LC_feedback_link div.LC_comblock a {
 6234:   color:$font;
 6235: }
 6236: 
 6237: span.LC_feedback_link {
 6238:   /* background: $feedback_link_bg; */
 6239:   font-size: larger;
 6240: }
 6241: 
 6242: span.LC_message_link {
 6243:   /* background: $feedback_link_bg; */
 6244:   font-size: larger;
 6245:   position: absolute;
 6246:   right: 1em;
 6247: }
 6248: 
 6249: table.LC_prior_tries {
 6250:   border: 1px solid #000000;
 6251:   border-collapse: separate;
 6252:   border-spacing: 1px;
 6253: }
 6254: 
 6255: table.LC_prior_tries td {
 6256:   padding: 2px;
 6257: }
 6258: 
 6259: .LC_answer_correct {
 6260:   background: lightgreen;
 6261:   color: darkgreen;
 6262:   padding: 6px;
 6263: }
 6264: 
 6265: .LC_answer_charged_try {
 6266:   background: #FFAAAA;
 6267:   color: darkred;
 6268:   padding: 6px;
 6269: }
 6270: 
 6271: .LC_answer_not_charged_try,
 6272: .LC_answer_no_grade,
 6273: .LC_answer_late {
 6274:   background: lightyellow;
 6275:   color: black;
 6276:   padding: 6px;
 6277: }
 6278: 
 6279: .LC_answer_previous {
 6280:   background: lightblue;
 6281:   color: darkblue;
 6282:   padding: 6px;
 6283: }
 6284: 
 6285: .LC_answer_no_message {
 6286:   background: #FFFFFF;
 6287:   color: black;
 6288:   padding: 6px;
 6289: }
 6290: 
 6291: .LC_answer_unknown {
 6292:   background: orange;
 6293:   color: black;
 6294:   padding: 6px;
 6295: }
 6296: 
 6297: span.LC_prior_numerical,
 6298: span.LC_prior_string,
 6299: span.LC_prior_custom,
 6300: span.LC_prior_reaction,
 6301: span.LC_prior_math {
 6302:   font-family: $mono;
 6303:   white-space: pre;
 6304: }
 6305: 
 6306: span.LC_prior_string {
 6307:   font-family: $mono;
 6308:   white-space: pre;
 6309: }
 6310: 
 6311: table.LC_prior_option {
 6312:   width: 100%;
 6313:   border-collapse: collapse;
 6314: }
 6315: 
 6316: table.LC_prior_rank,
 6317: table.LC_prior_match {
 6318:   border-collapse: collapse;
 6319: }
 6320: 
 6321: table.LC_prior_option tr td,
 6322: table.LC_prior_rank tr td,
 6323: table.LC_prior_match tr td {
 6324:   border: 1px solid #000000;
 6325: }
 6326: 
 6327: .LC_nobreak {
 6328:   white-space: nowrap;
 6329: }
 6330: 
 6331: span.LC_cusr_emph {
 6332:   font-style: italic;
 6333: }
 6334: 
 6335: span.LC_cusr_subheading {
 6336:   font-weight: normal;
 6337:   font-size: 85%;
 6338: }
 6339: 
 6340: div.LC_docs_entry_move {
 6341:   border: 1px solid #BBBBBB;
 6342:   background: #DDDDDD;
 6343:   width: 22px;
 6344:   padding: 1px;
 6345:   margin: 0;
 6346: }
 6347: 
 6348: table.LC_data_table tr > td.LC_docs_entry_commands,
 6349: table.LC_data_table tr > td.LC_docs_entry_parameter {
 6350:   font-size: x-small;
 6351: }
 6352: 
 6353: .LC_docs_entry_parameter {
 6354:   white-space: nowrap;
 6355: }
 6356: 
 6357: .LC_docs_copy {
 6358:   color: #000099;
 6359: }
 6360: 
 6361: .LC_docs_cut {
 6362:   color: #550044;
 6363: }
 6364: 
 6365: .LC_docs_rename {
 6366:   color: #009900;
 6367: }
 6368: 
 6369: .LC_docs_remove {
 6370:   color: #990000;
 6371: }
 6372: 
 6373: .LC_docs_reinit_warn,
 6374: .LC_docs_ext_edit {
 6375:   font-size: x-small;
 6376: }
 6377: 
 6378: table.LC_docs_adddocs td,
 6379: table.LC_docs_adddocs th {
 6380:   border: 1px solid #BBBBBB;
 6381:   padding: 4px;
 6382:   background: #DDDDDD;
 6383: }
 6384: 
 6385: table.LC_sty_begin {
 6386:   background: #BBFFBB;
 6387: }
 6388: 
 6389: table.LC_sty_end {
 6390:   background: #FFBBBB;
 6391: }
 6392: 
 6393: table.LC_double_column {
 6394:   border-width: 0;
 6395:   border-collapse: collapse;
 6396:   width: 100%;
 6397:   padding: 2px;
 6398: }
 6399: 
 6400: table.LC_double_column tr td.LC_left_col {
 6401:   top: 2px;
 6402:   left: 2px;
 6403:   width: 47%;
 6404:   vertical-align: top;
 6405: }
 6406: 
 6407: table.LC_double_column tr td.LC_right_col {
 6408:   top: 2px;
 6409:   right: 2px;
 6410:   width: 47%;
 6411:   vertical-align: top;
 6412: }
 6413: 
 6414: div.LC_left_float {
 6415:   float: left;
 6416:   padding-right: 5%;
 6417:   padding-bottom: 4px;
 6418: }
 6419: 
 6420: div.LC_clear_float_header {
 6421:   padding-bottom: 2px;
 6422: }
 6423: 
 6424: div.LC_clear_float_footer {
 6425:   padding-top: 10px;
 6426:   clear: both;
 6427: }
 6428: 
 6429: div.LC_grade_show_user {
 6430: /*  border-left: 5px solid $sidebg; */
 6431:   border-top: 5px solid #000000;
 6432:   margin: 50px 0 0 0;
 6433:   padding: 15px 0 5px 10px;
 6434: }
 6435: 
 6436: div.LC_grade_show_user_odd_row {
 6437: /*  border-left: 5px solid #000000; */
 6438: }
 6439: 
 6440: div.LC_grade_show_user div.LC_Box {
 6441:   margin-right: 50px;
 6442: }
 6443: 
 6444: div.LC_grade_submissions,
 6445: div.LC_grade_message_center,
 6446: div.LC_grade_info_links {
 6447:   margin: 5px;
 6448:   width: 99%;
 6449:   background: #FFFFFF;
 6450: }
 6451: 
 6452: div.LC_grade_submissions_header,
 6453: div.LC_grade_message_center_header {
 6454:   font-weight: bold;
 6455:   font-size: large;
 6456: }
 6457: 
 6458: div.LC_grade_submissions_body,
 6459: div.LC_grade_message_center_body {
 6460:   border: 1px solid black;
 6461:   width: 99%;
 6462:   background: #FFFFFF;
 6463: }
 6464: 
 6465: table.LC_scantron_action {
 6466:   width: 100%;
 6467: }
 6468: 
 6469: table.LC_scantron_action tr th {
 6470:   font-weight:bold;
 6471:   font-style:normal;
 6472: }
 6473: 
 6474: .LC_edit_problem_header,
 6475: div.LC_edit_problem_footer {
 6476:   font-weight: normal;
 6477:   font-size:  medium;
 6478:   margin: 2px;
 6479:   background-color: $sidebg;
 6480: }
 6481: 
 6482: div.LC_edit_problem_header,
 6483: div.LC_edit_problem_header div,
 6484: div.LC_edit_problem_footer,
 6485: div.LC_edit_problem_footer div,
 6486: div.LC_edit_problem_editxml_header,
 6487: div.LC_edit_problem_editxml_header div {
 6488:   margin-top: 5px;
 6489: }
 6490: 
 6491: div.LC_edit_problem_header_title {
 6492:   font-weight: bold;
 6493:   font-size: larger;
 6494:   background: $tabbg;
 6495:   padding: 3px;
 6496:   margin: 0 0 5px 0;
 6497: }
 6498: 
 6499: table.LC_edit_problem_header_title {
 6500:   width: 100%;
 6501:   background: $tabbg;
 6502: }
 6503: 
 6504: div.LC_edit_problem_discards {
 6505:   float: left;
 6506:   padding-bottom: 5px;
 6507: }
 6508: 
 6509: div.LC_edit_problem_saves {
 6510:   float: right;
 6511:   padding-bottom: 5px;
 6512: }
 6513: 
 6514: .LC_edit_opt {
 6515:   padding-left: 1em;
 6516:   white-space: nowrap;
 6517: }
 6518: 
 6519: .LC_edit_problem_latexhelper{
 6520:     text-align: right;
 6521: }
 6522: 
 6523: #LC_edit_problem_colorful div{
 6524:     margin-left: 40px;
 6525: }
 6526: 
 6527: img.stift {
 6528:   border-width: 0;
 6529:   vertical-align: middle;
 6530: }
 6531: 
 6532: table td.LC_mainmenu_col_fieldset {
 6533:   vertical-align: top;
 6534: }
 6535: 
 6536: div.LC_createcourse {
 6537:   margin: 10px 10px 10px 10px;
 6538: }
 6539: 
 6540: .LC_dccid {
 6541:   float: right;
 6542:   margin: 0.2em 0 0 0;
 6543:   padding: 0;
 6544:   font-size: 90%;
 6545:   display:none;
 6546: }
 6547: 
 6548: ol.LC_primary_menu a:hover,
 6549: ol#LC_MenuBreadcrumbs a:hover,
 6550: ol#LC_PathBreadcrumbs a:hover,
 6551: ul#LC_secondary_menu a:hover,
 6552: .LC_FormSectionClearButton input:hover
 6553: ul.LC_TabContent   li:hover a {
 6554:   color:$button_hover;
 6555:   text-decoration:none;
 6556: }
 6557: 
 6558: h1 {
 6559:   padding: 0;
 6560:   line-height:130%;
 6561: }
 6562: 
 6563: h2,
 6564: h3,
 6565: h4,
 6566: h5,
 6567: h6 {
 6568:   margin: 5px 0 5px 0;
 6569:   padding: 0;
 6570:   line-height:130%;
 6571: }
 6572: 
 6573: .LC_hcell {
 6574:   padding:3px 15px 3px 15px;
 6575:   margin: 0;
 6576:   background-color:$tabbg;
 6577:   color:$fontmenu;
 6578:   border-bottom:solid 1px $lg_border_color;
 6579: }
 6580: 
 6581: .LC_Box > .LC_hcell {
 6582:   margin: 0 -10px 10px -10px;
 6583: }
 6584: 
 6585: .LC_noBorder {
 6586:   border: 0;
 6587: }
 6588: 
 6589: .LC_FormSectionClearButton input {
 6590:   background-color:transparent;
 6591:   border: none;
 6592:   cursor:pointer;
 6593:   text-decoration:underline;
 6594: }
 6595: 
 6596: .LC_help_open_topic {
 6597:   color: #FFFFFF;
 6598:   background-color: #EEEEFF;
 6599:   margin: 1px;
 6600:   padding: 4px;
 6601:   border: 1px solid #000033;
 6602:   white-space: nowrap;
 6603:   /* vertical-align: middle; */
 6604: }
 6605: 
 6606: dl,
 6607: ul,
 6608: div,
 6609: fieldset {
 6610:   margin: 10px 10px 10px 0;
 6611:   /* overflow: hidden; */
 6612: }
 6613: 
 6614: fieldset > legend {
 6615:   font-weight: bold;
 6616:   padding: 0 5px 0 5px;
 6617: }
 6618: 
 6619: #LC_nav_bar {
 6620:   float: left;
 6621:   background-color: $pgbg_or_bgcolor;
 6622:   margin: 0 0 2px 0;
 6623: }
 6624: 
 6625: #LC_realm {
 6626:   margin: 0.2em 0 0 0;
 6627:   padding: 0;
 6628:   font-weight: bold;
 6629:   text-align: center;
 6630:   background-color: $pgbg_or_bgcolor;
 6631: }
 6632: 
 6633: #LC_nav_bar em {
 6634:   font-weight: bold;
 6635:   font-style: normal;
 6636: }
 6637: 
 6638: ol.LC_primary_menu {
 6639:   margin: 0;
 6640:   padding: 0;
 6641:   background-color: $pgbg_or_bgcolor;
 6642: }
 6643: 
 6644: ol#LC_PathBreadcrumbs {
 6645:   margin: 0;
 6646: }
 6647: 
 6648: ol.LC_primary_menu li {
 6649:   color: RGB(80, 80, 80);
 6650:   vertical-align: middle;
 6651:   text-align: left;
 6652:   list-style: none;
 6653:   float: left;
 6654: }
 6655: 
 6656: ol.LC_primary_menu li a {
 6657:   display: block;
 6658:   margin: 0;
 6659:   padding: 0 5px 0 10px;
 6660:   text-decoration: none;
 6661: }
 6662: 
 6663: ol.LC_primary_menu li ul {
 6664:   display: none;
 6665:   width: 10em;
 6666:   background-color: $data_table_light;
 6667: }
 6668: 
 6669: ol.LC_primary_menu li:hover ul, ol.LC_primary_menu li.hover ul {
 6670:   display: block;
 6671:   position: absolute;
 6672:   margin: 0;
 6673:   padding: 0;
 6674:   z-index: 2;
 6675: }
 6676: 
 6677: ol.LC_primary_menu li:hover li, ol.LC_primary_menu li.hover li {
 6678:   font-size: 90%;
 6679:   vertical-align: top;
 6680:   float: none;
 6681:   border-left: 1px solid black;
 6682:   border-right: 1px solid black;
 6683: }
 6684: 
 6685: ol.LC_primary_menu li:hover li a, ol.LC_primary_menu li.hover li a {
 6686:   background-color:$data_table_light;
 6687: }
 6688: 
 6689: ol.LC_primary_menu li li a:hover {
 6690:    color:$button_hover;
 6691:    background-color:$data_table_dark;
 6692: }
 6693: 
 6694: ol.LC_primary_menu li img {
 6695:   vertical-align: bottom;
 6696:   height: 1.1em;
 6697:   margin: 0.2em 0 0 0;
 6698: }
 6699: 
 6700: ol.LC_primary_menu a {
 6701:   color: RGB(80, 80, 80);
 6702:   text-decoration: none;
 6703: }
 6704: 
 6705: ol.LC_primary_menu a.LC_new_message {
 6706:   font-weight:bold;
 6707:   color: darkred;
 6708: }
 6709: 
 6710: ol.LC_docs_parameters {
 6711:   margin-left: 0;
 6712:   padding: 0;
 6713:   list-style: none;
 6714: }
 6715: 
 6716: ol.LC_docs_parameters li {
 6717:   margin: 0;
 6718:   padding-right: 20px;
 6719:   display: inline;
 6720: }
 6721: 
 6722: ol.LC_docs_parameters li:before {
 6723:   content: "\\002022 \\0020";
 6724: }
 6725: 
 6726: li.LC_docs_parameters_title {
 6727:   font-weight: bold;
 6728: }
 6729: 
 6730: ol.LC_docs_parameters li.LC_docs_parameters_title:before {
 6731:   content: "";
 6732: }
 6733: 
 6734: ul#LC_secondary_menu {
 6735:   clear: right;
 6736:   color: $fontmenu;
 6737:   background: $tabbg;
 6738:   list-style: none;
 6739:   padding: 0;
 6740:   margin: 0;
 6741:   width: 100%;
 6742:   text-align: left;
 6743:   float: left;
 6744: }
 6745: 
 6746: ul#LC_secondary_menu li {
 6747:   font-weight: bold;
 6748:   line-height: 1.8em;
 6749:   border-right: 1px solid black;
 6750:   float: left;
 6751: }
 6752: 
 6753: ul#LC_secondary_menu li.LC_hoverable:hover, ul#LC_secondary_menu li.hover {
 6754:   background-color: $data_table_light;
 6755: }
 6756: 
 6757: ul#LC_secondary_menu li a {
 6758:   padding: 0 0.8em;
 6759: }
 6760: 
 6761: ul#LC_secondary_menu li ul {
 6762:   display: none;
 6763: }
 6764: 
 6765: ul#LC_secondary_menu li:hover ul, ul#LC_secondary_menu li.hover ul {
 6766:   display: block;
 6767:   position: absolute;
 6768:   margin: 0;
 6769:   padding: 0;
 6770:   list-style:none;
 6771:   float: none;
 6772:   background-color: $data_table_light;
 6773:   z-index: 2;
 6774:   margin-left: -1px;
 6775: }
 6776: 
 6777: ul#LC_secondary_menu li ul li {
 6778:   font-size: 90%;
 6779:   vertical-align: top;
 6780:   border-left: 1px solid black;
 6781:   border-right: 1px solid black;
 6782:   background-color: $data_table_light;
 6783:   list-style:none;
 6784:   float: none;
 6785: }
 6786: 
 6787: ul#LC_secondary_menu li ul li:hover, ul#LC_secondary_menu li ul li.hover {
 6788:   background-color: $data_table_dark;
 6789: }
 6790: 
 6791: ul.LC_TabContent {
 6792:   display:block;
 6793:   background: $sidebg;
 6794:   border-bottom: solid 1px $lg_border_color;
 6795:   list-style:none;
 6796:   margin: -1px -10px 0 -10px;
 6797:   padding: 0;
 6798: }
 6799: 
 6800: ul.LC_TabContent li,
 6801: ul.LC_TabContentBigger li {
 6802:   float:left;
 6803: }
 6804: 
 6805: ul#LC_secondary_menu li a {
 6806:   color: $fontmenu;
 6807:   text-decoration: none;
 6808: }
 6809: 
 6810: ul.LC_TabContent {
 6811:   min-height:20px;
 6812: }
 6813: 
 6814: ul.LC_TabContent li {
 6815:   vertical-align:middle;
 6816:   padding: 0 16px 0 10px;
 6817:   background-color:$tabbg;
 6818:   border-bottom:solid 1px $lg_border_color;
 6819:   border-left: solid 1px $font;
 6820: }
 6821: 
 6822: ul.LC_TabContent .right {
 6823:   float:right;
 6824: }
 6825: 
 6826: ul.LC_TabContent li a,
 6827: ul.LC_TabContent li {
 6828:   color:rgb(47,47,47);
 6829:   text-decoration:none;
 6830:   font-size:95%;
 6831:   font-weight:bold;
 6832:   min-height:20px;
 6833: }
 6834: 
 6835: ul.LC_TabContent li a:hover,
 6836: ul.LC_TabContent li a:focus {
 6837:   color: $button_hover;
 6838:   background:none;
 6839:   outline:none;
 6840: }
 6841: 
 6842: ul.LC_TabContent li:hover {
 6843:   color: $button_hover;
 6844:   cursor:pointer;
 6845: }
 6846: 
 6847: ul.LC_TabContent li.active {
 6848:   color: $font;
 6849:   background:#FFFFFF url(/adm/lonIcons/open.gif) no-repeat scroll right center;
 6850:   border-bottom:solid 1px #FFFFFF;
 6851:   cursor: default;
 6852: }
 6853: 
 6854: ul.LC_TabContent li.active a {
 6855:   color:$font;
 6856:   background:#FFFFFF;
 6857:   outline: none;
 6858: }
 6859: 
 6860: ul.LC_TabContent li.goback {
 6861:   float: left;
 6862:   border-left: none;
 6863: }
 6864: 
 6865: #maincoursedoc {
 6866:   clear:both;
 6867: }
 6868: 
 6869: ul.LC_TabContentBigger {
 6870:   display:block;
 6871:   list-style:none;
 6872:   padding: 0;
 6873: }
 6874: 
 6875: ul.LC_TabContentBigger li {
 6876:   vertical-align:bottom;
 6877:   height: 30px;
 6878:   font-size:110%;
 6879:   font-weight:bold;
 6880:   color: #737373;
 6881: }
 6882: 
 6883: ul.LC_TabContentBigger li.active {
 6884:   position: relative;
 6885:   top: 1px;
 6886: }
 6887: 
 6888: ul.LC_TabContentBigger li a {
 6889:   background:url('/adm/lonIcons/tabbgleft.gif') left bottom no-repeat;
 6890:   height: 30px;
 6891:   line-height: 30px;
 6892:   text-align: center;
 6893:   display: block;
 6894:   text-decoration: none;
 6895:   outline: none;  
 6896: }
 6897: 
 6898: ul.LC_TabContentBigger li.active a {
 6899:   background:url('/adm/lonIcons/tabbgleft.gif') left top no-repeat;
 6900:   color:$font;
 6901: }
 6902: 
 6903: ul.LC_TabContentBigger li b {
 6904:   background: url('/adm/lonIcons/tabbgright.gif') no-repeat right bottom;
 6905:   display: block;
 6906:   float: left;
 6907:   padding: 0 30px;
 6908:   border-bottom: 1px solid $lg_border_color;
 6909: }
 6910: 
 6911: ul.LC_TabContentBigger li:hover b {
 6912:   color:$button_hover;
 6913: }
 6914: 
 6915: ul.LC_TabContentBigger li.active b {
 6916:   background:url('/adm/lonIcons/tabbgright.gif') right top no-repeat;
 6917:   color:$font;
 6918:   border: 0;
 6919: }
 6920: 
 6921: 
 6922: ul.LC_CourseBreadcrumbs {
 6923:   background: $sidebg;
 6924:   height: 2em;
 6925:   padding-left: 10px;
 6926:   margin: 0;
 6927:   list-style-position: inside;
 6928: }
 6929: 
 6930: ol#LC_MenuBreadcrumbs,
 6931: ol#LC_PathBreadcrumbs {
 6932:   padding-left: 10px;
 6933:   margin: 0;
 6934:   height: 2.5em;  /* equal to #LC_breadcrumbs line-height */
 6935: }
 6936: 
 6937: ol#LC_MenuBreadcrumbs li,
 6938: ol#LC_PathBreadcrumbs li,
 6939: ul.LC_CourseBreadcrumbs li {
 6940:   display: inline;
 6941:   white-space: normal;  
 6942: }
 6943: 
 6944: ol#LC_MenuBreadcrumbs li a,
 6945: ul.LC_CourseBreadcrumbs li a {
 6946:   text-decoration: none;
 6947:   font-size:90%;
 6948: }
 6949: 
 6950: ol#LC_MenuBreadcrumbs h1 {
 6951:   display: inline;
 6952:   font-size: 90%;
 6953:   line-height: 2.5em;
 6954:   margin: 0;
 6955:   padding: 0;
 6956: }
 6957: 
 6958: ol#LC_PathBreadcrumbs li a {
 6959:   text-decoration:none;
 6960:   font-size:100%;
 6961:   font-weight:bold;
 6962: }
 6963: 
 6964: .LC_Box {
 6965:   border: solid 1px $lg_border_color;
 6966:   padding: 0 10px 10px 10px;
 6967: }
 6968: 
 6969: .LC_DocsBox {
 6970:   border: solid 1px $lg_border_color;
 6971:   padding: 0 0 10px 10px;
 6972: }
 6973: 
 6974: .LC_AboutMe_Image {
 6975:   float:left;
 6976:   margin-right:10px;
 6977: }
 6978: 
 6979: .LC_Clear_AboutMe_Image {
 6980:   clear:left;
 6981: }
 6982: 
 6983: dl.LC_ListStyleClean dt {
 6984:   padding-right: 5px;
 6985:   display: table-header-group;
 6986: }
 6987: 
 6988: dl.LC_ListStyleClean dd {
 6989:   display: table-row;
 6990: }
 6991: 
 6992: .LC_ListStyleClean,
 6993: .LC_ListStyleSimple,
 6994: .LC_ListStyleNormal,
 6995: .LC_ListStyleSpecial {
 6996:   /* display:block; */
 6997:   list-style-position: inside;
 6998:   list-style-type: none;
 6999:   overflow: hidden;
 7000:   padding: 0;
 7001: }
 7002: 
 7003: .LC_ListStyleSimple li,
 7004: .LC_ListStyleSimple dd,
 7005: .LC_ListStyleNormal li,
 7006: .LC_ListStyleNormal dd,
 7007: .LC_ListStyleSpecial li,
 7008: .LC_ListStyleSpecial dd {
 7009:   margin: 0;
 7010:   padding: 5px 5px 5px 10px;
 7011:   clear: both;
 7012: }
 7013: 
 7014: .LC_ListStyleClean li,
 7015: .LC_ListStyleClean dd {
 7016:   padding-top: 0;
 7017:   padding-bottom: 0;
 7018: }
 7019: 
 7020: .LC_ListStyleSimple dd,
 7021: .LC_ListStyleSimple li {
 7022:   border-bottom: solid 1px $lg_border_color;
 7023: }
 7024: 
 7025: .LC_ListStyleSpecial li,
 7026: .LC_ListStyleSpecial dd {
 7027:   list-style-type: none;
 7028:   background-color: RGB(220, 220, 220);
 7029:   margin-bottom: 4px;
 7030: }
 7031: 
 7032: table.LC_SimpleTable {
 7033:   margin:5px;
 7034:   border:solid 1px $lg_border_color;
 7035: }
 7036: 
 7037: table.LC_SimpleTable tr {
 7038:   padding: 0;
 7039:   border:solid 1px $lg_border_color;
 7040: }
 7041: 
 7042: table.LC_SimpleTable thead {
 7043:   background:rgb(220,220,220);
 7044: }
 7045: 
 7046: div.LC_columnSection {
 7047:   display: block;
 7048:   clear: both;
 7049:   overflow: hidden;
 7050:   margin: 0;
 7051: }
 7052: 
 7053: div.LC_columnSection>* {
 7054:   float: left;
 7055:   margin: 10px 20px 10px 0;
 7056:   overflow:hidden;
 7057: }
 7058: 
 7059: table em {
 7060:   font-weight: bold;
 7061:   font-style: normal;
 7062: }
 7063: 
 7064: table.LC_tableBrowseRes,
 7065: table.LC_tableOfContent {
 7066:   border:none;
 7067:   border-spacing: 1px;
 7068:   padding: 3px;
 7069:   background-color: #FFFFFF;
 7070:   font-size: 90%;
 7071: }
 7072: 
 7073: table.LC_tableOfContent {
 7074:   border-collapse: collapse;
 7075: }
 7076: 
 7077: table.LC_tableBrowseRes a,
 7078: table.LC_tableOfContent a {
 7079:   background-color: transparent;
 7080:   text-decoration: none;
 7081: }
 7082: 
 7083: table.LC_tableOfContent img {
 7084:   border: none;
 7085:   height: 1.3em;
 7086:   vertical-align: text-bottom;
 7087:   margin-right: 0.3em;
 7088: }
 7089: 
 7090: a#LC_content_toolbar_firsthomework {
 7091:   background-image:url(/res/adm/pages/open-first-problem.gif);
 7092: }
 7093: 
 7094: a#LC_content_toolbar_everything {
 7095:   background-image:url(/res/adm/pages/show-all.gif);
 7096: }
 7097: 
 7098: a#LC_content_toolbar_uncompleted {
 7099:   background-image:url(/res/adm/pages/show-incomplete-problems.gif);
 7100: }
 7101: 
 7102: #LC_content_toolbar_clearbubbles {
 7103:   background-image:url(/res/adm/pages/mark-discussionentries-read.gif);
 7104: }
 7105: 
 7106: a#LC_content_toolbar_changefolder {
 7107:   background : url(/res/adm/pages/close-all-folders.gif) top center ;
 7108: }
 7109: 
 7110: a#LC_content_toolbar_changefolder_toggled {
 7111:   background-image:url(/res/adm/pages/open-all-folders.gif);
 7112: }
 7113: 
 7114: a#LC_content_toolbar_edittoplevel {
 7115:   background-image:url(/res/adm/pages/edittoplevel.gif);
 7116: }
 7117: 
 7118: ul#LC_toolbar li a:hover {
 7119:   background-position: bottom center;
 7120: }
 7121: 
 7122: ul#LC_toolbar {
 7123:   padding: 0;
 7124:   margin: 2px;
 7125:   list-style:none;
 7126:   position:relative;
 7127:   background-color:white;
 7128:   overflow: auto;
 7129: }
 7130: 
 7131: ul#LC_toolbar li {
 7132:   border:1px solid white;
 7133:   padding: 0;
 7134:   margin: 0;
 7135:   float: left;
 7136:   display:inline;
 7137:   vertical-align:middle;
 7138:   white-space: nowrap;
 7139: }
 7140: 
 7141: 
 7142: a.LC_toolbarItem {
 7143:   display:block;
 7144:   padding: 0;
 7145:   margin: 0;
 7146:   height: 32px;
 7147:   width: 32px;
 7148:   color:white;
 7149:   border: none;
 7150:   background-repeat:no-repeat;
 7151:   background-color:transparent;
 7152: }
 7153: 
 7154: ul.LC_funclist {
 7155:     margin: 0;
 7156:     padding: 0.5em 1em 0.5em 0;
 7157: }
 7158: 
 7159: ul.LC_funclist > li:first-child {
 7160:     font-weight:bold; 
 7161:     margin-left:0.8em;
 7162: }
 7163: 
 7164: ul.LC_funclist + ul.LC_funclist {
 7165:     /* 
 7166:        left border as a seperator if we have more than
 7167:        one list 
 7168:     */
 7169:     border-left: 1px solid $sidebg;
 7170:     /* 
 7171:        this hides the left border behind the border of the 
 7172:        outer box if element is wrapped to the next 'line' 
 7173:     */
 7174:     margin-left: -1px;
 7175: }
 7176: 
 7177: ul.LC_funclist li {
 7178:   display: inline;
 7179:   white-space: nowrap;
 7180:   margin: 0 0 0 25px;
 7181:   line-height: 150%;
 7182: }
 7183: 
 7184: .LC_hidden {
 7185:   display: none;
 7186: }
 7187: 
 7188: .LCmodal-overlay {
 7189: 		position:fixed;
 7190: 		top:0;
 7191: 		right:0;
 7192: 		bottom:0;
 7193: 		left:0;
 7194: 		height:100%;
 7195: 		width:100%;
 7196: 		margin:0;
 7197: 		padding:0;
 7198: 		background:#999;
 7199: 		opacity:.75;
 7200: 		filter: alpha(opacity=75);
 7201: 		-moz-opacity: 0.75;
 7202: 		z-index:101;
 7203: }
 7204: 
 7205: * html .LCmodal-overlay {   
 7206: 		position: absolute;
 7207: 		height: expression(document.body.scrollHeight > document.body.offsetHeight ? document.body.scrollHeight : document.body.offsetHeight + 'px');
 7208: }
 7209: 
 7210: .LCmodal-window {
 7211: 		position:fixed;
 7212: 		top:50%;
 7213: 		left:50%;
 7214: 		margin:0;
 7215: 		padding:0;
 7216: 		z-index:102;
 7217: 	}
 7218: 
 7219: * html .LCmodal-window {
 7220: 		position:absolute;
 7221: }
 7222: 
 7223: .LCclose-window {
 7224: 		position:absolute;
 7225: 		width:32px;
 7226: 		height:32px;
 7227: 		right:8px;
 7228: 		top:8px;
 7229: 		background:transparent url('/res/adm/pages/process-stop.png') no-repeat scroll right top;
 7230: 		text-indent:-99999px;
 7231: 		overflow:hidden;
 7232: 		cursor:pointer;
 7233: }
 7234: 
 7235: /*
 7236:   styles used by TTH when "Default set of options to pass to tth/m
 7237:   when converting TeX" in course settings has been set
 7238: 
 7239:   option passed: -t
 7240: 
 7241: */
 7242: 
 7243: td div.comp { margin-top: -0.6ex; margin-bottom: -1ex;}
 7244: td div.comb { margin-top: -0.6ex; margin-bottom: -.6ex;}
 7245: td div.hrcomp { line-height: 0.9; margin-top: -0.8ex; margin-bottom: -1ex;}
 7246: td div.norm {line-height:normal;}
 7247: 
 7248: /*
 7249:   option passed -y3
 7250: */
 7251: 
 7252: span.roman {font-family: serif; font-style: normal; font-weight: normal;}
 7253: span.overacc2 {position: relative;  left: .8em; top: -1.2ex;}
 7254: span.overacc1 {position: relative;  left: .6em; top: -1.2ex;}
 7255: 
 7256: END
 7257: }
 7258: 
 7259: =pod
 7260: 
 7261: =item * &headtag()
 7262: 
 7263: Returns a uniform footer for LON-CAPA web pages.
 7264: 
 7265: Inputs: $title - optional title for the head
 7266:         $head_extra - optional extra HTML to put inside the <head>
 7267:         $args - optional arguments
 7268:             force_register - if is true call registerurl so the remote is 
 7269:                              informed
 7270:             redirect       -> array ref of
 7271:                                    1- seconds before redirect occurs
 7272:                                    2- url to redirect to
 7273:                                    3- whether the side effect should occur
 7274:                            (side effect of setting 
 7275:                                $env{'internal.head.redirect'} to the url 
 7276:                                redirected too)
 7277:             domain         -> force to color decorate a page for a specific
 7278:                                domain
 7279:             function       -> force usage of a specific rolish color scheme
 7280:             bgcolor        -> override the default page bgcolor
 7281:             no_auto_mt_title
 7282:                            -> prevent &mt()ing the title arg
 7283: 
 7284: =cut
 7285: 
 7286: sub headtag {
 7287:     my ($title,$head_extra,$args) = @_;
 7288:     
 7289:     my $function = $args->{'function'} || &get_users_function();
 7290:     my $domain   = $args->{'domain'}   || &determinedomain();
 7291:     my $bgcolor  = $args->{'bgcolor'}  || &designparm($function.'.pgbg',$domain);
 7292:     my $httphost = $args->{'use_absolute'};
 7293:     my $url = join(':',$env{'user.name'},$env{'user.domain'},
 7294: 		   $Apache::lonnet::perlvar{'lonVersion'},
 7295: 		   #time(),
 7296: 		   $env{'environment.color.timestamp'},
 7297: 		   $function,$domain,$bgcolor);
 7298: 
 7299:     $url = '/adm/css/'.&escape($url).'.css';
 7300: 
 7301:     my $result =
 7302: 	'<head>'.
 7303: 	&font_settings($args);
 7304: 
 7305:     my $inhibitprint;
 7306:     if ($args->{'print_suppress'}) {
 7307:         $inhibitprint = &print_suppression();
 7308:     }
 7309: 
 7310:     if (!$args->{'frameset'}) {
 7311: 	$result .= &Apache::lonhtmlcommon::htmlareaheaders();
 7312:     }
 7313:     if ($args->{'force_register'} && $env{'request.noversionuri'} !~ m{^/res/adm/pages/}) {
 7314:         $result .= Apache::lonxml::display_title();
 7315:     }
 7316:     if (!$args->{'no_nav_bar'} 
 7317: 	&& !$args->{'only_body'}
 7318: 	&& !$args->{'frameset'}) {
 7319: 	$result .= &help_menu_js($httphost);
 7320:         $result.=&modal_window();
 7321:         $result.=&togglebox_script();
 7322:         $result.=&wishlist_window();
 7323:         $result.=&LCprogressbarUpdate_script();
 7324:     } else {
 7325:         if ($args->{'add_modal'}) {
 7326:            $result.=&modal_window();
 7327:         }
 7328:         if ($args->{'add_wishlist'}) {
 7329:            $result.=&wishlist_window();
 7330:         }
 7331:         if ($args->{'add_togglebox'}) {
 7332:            $result.=&togglebox_script();
 7333:         }
 7334:         if ($args->{'add_progressbar'}) {
 7335:            $result.=&LCprogressbarUpdate_script();
 7336:         }
 7337:     }
 7338:     if (ref($args->{'redirect'})) {
 7339: 	my ($time,$url,$inhibit_continue) = @{$args->{'redirect'}};
 7340: 	$url = &Apache::lonenc::check_encrypt($url);
 7341: 	if (!$inhibit_continue) {
 7342: 	    $env{'internal.head.redirect'} = $url;
 7343: 	}
 7344: 	$result.=<<ADDMETA
 7345: <meta http-equiv="pragma" content="no-cache" />
 7346: <meta http-equiv="Refresh" content="$time; url=$url" />
 7347: ADDMETA
 7348:     }
 7349:     if (!defined($title)) {
 7350: 	$title = 'The LearningOnline Network with CAPA';
 7351:     }
 7352:     if (!$args->{'no_auto_mt_title'}) { $title = &mt($title); }
 7353:     $result .= '<title> LON-CAPA '.$title.'</title>'
 7354: 	.'<link rel="stylesheet" type="text/css" href="'.$url.'"';
 7355:     if (!$args->{'frameset'}) {
 7356:         $result .= ' /';
 7357:     }
 7358:     $result .= '>' 
 7359:         .$inhibitprint
 7360: 	.$head_extra;
 7361:     if ($env{'browser.mobile'}) {
 7362:         $result .= '
 7363: <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=0, minimum-scale=1.0, maximum-scale=1.0">
 7364: <meta name="apple-mobile-web-app-capable" content="yes" />';
 7365:     }
 7366:     return $result.'</head>';
 7367: }
 7368: 
 7369: =pod
 7370: 
 7371: =item * &font_settings()
 7372: 
 7373: Returns neccessary <meta> to set the proper encoding
 7374: 
 7375: Inputs: optional reference to HASH -- $args passed to &headtag()
 7376: 
 7377: =cut
 7378: 
 7379: sub font_settings {
 7380:     my ($args) = @_;
 7381:     my $headerstring='';
 7382:     if ((!$env{'browser.mathml'} && $env{'browser.unicode'}) ||
 7383:         ((ref($args) eq 'HASH') && ($args->{'browser.unicode'}))) {
 7384:         $headerstring.=
 7385:             '<meta http-equiv="Content-Type" content="text/html; charset=utf-8"';
 7386:         if (!$args->{'frameset'}) {
 7387: 	    $headerstring.= ' /';
 7388:         }
 7389: 	$headerstring .= '>'."\n";
 7390:     }
 7391:     return $headerstring;
 7392: }
 7393: 
 7394: =pod
 7395: 
 7396: =item * &print_suppression()
 7397: 
 7398: In course context returns css which causes the body to be blank when media="print",
 7399: if printout generation is unavailable for the current resource.
 7400: 
 7401: This could be because:
 7402: 
 7403: (a) printstartdate is in the future
 7404: 
 7405: (b) printenddate is in the past
 7406: 
 7407: (c) there is an active exam block with "printout"
 7408: functionality blocked
 7409: 
 7410: Users with pav, pfo or evb privileges are exempt.
 7411: 
 7412: Inputs: none
 7413: 
 7414: =cut
 7415: 
 7416: 
 7417: sub print_suppression {
 7418:     my $noprint;
 7419:     if ($env{'request.course.id'}) {
 7420:         my $scope = $env{'request.course.id'};
 7421:         if ((&Apache::lonnet::allowed('pav',$scope)) ||
 7422:             (&Apache::lonnet::allowed('pfo',$scope))) {
 7423:             return;
 7424:         }
 7425:         if ($env{'request.course.sec'} ne '') {
 7426:             $scope .= "/$env{'request.course.sec'}";
 7427:             if ((&Apache::lonnet::allowed('pav',$scope)) ||
 7428:                 (&Apache::lonnet::allowed('pfo',$scope))) {
 7429:                 return;
 7430:             }
 7431:         }
 7432:         my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 7433:         my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 7434:         my $blocked = &blocking_status('printout',$cnum,$cdom,undef,1);
 7435:         if ($blocked) {
 7436:             my $checkrole = "cm./$cdom/$cnum";
 7437:             if ($env{'request.course.sec'} ne '') {
 7438:                 $checkrole .= "/$env{'request.course.sec'}";
 7439:             }
 7440:             unless ((&Apache::lonnet::allowed('evb',undef,undef,$checkrole)) &&
 7441:                     ($env{'request.role'} !~ m{^st\./$cdom/$cnum})) {
 7442:                 $noprint = 1;
 7443:             }
 7444:         }
 7445:         unless ($noprint) {
 7446:             my $symb = &Apache::lonnet::symbread();
 7447:             if ($symb ne '') {
 7448:                 my $navmap = Apache::lonnavmaps::navmap->new();
 7449:                 if (ref($navmap)) {
 7450:                     my $res = $navmap->getBySymb($symb);
 7451:                     if (ref($res)) {
 7452:                         if (!$res->resprintable()) {
 7453:                             $noprint = 1;
 7454:                         }
 7455:                     }
 7456:                 }
 7457:             }
 7458:         }
 7459:         if ($noprint) {
 7460:             return <<"ENDSTYLE";
 7461: <style type="text/css" media="print">
 7462:     body { display:none }
 7463: </style>
 7464: ENDSTYLE
 7465:         }
 7466:     }
 7467:     return;
 7468: }
 7469: 
 7470: =pod
 7471: 
 7472: =item * &xml_begin()
 7473: 
 7474: Returns the needed doctype and <html>
 7475: 
 7476: Inputs: none
 7477: 
 7478: =cut
 7479: 
 7480: sub xml_begin {
 7481:     my ($is_frameset) = @_;
 7482:     my $output='';
 7483: 
 7484:     if ($env{'browser.mathml'}) {
 7485: 	$output='<?xml version="1.0"?>'
 7486:             #.'<?xml-stylesheet type="text/css" href="/adm/MathML/mathml.css"?>'."\n"
 7487: #            .'<!DOCTYPE html SYSTEM "/adm/MathML/mathml.dtd" '
 7488:             
 7489: #	    .'<!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">] >'
 7490: 	    .'<!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">'
 7491:             .'<html xmlns:math="http://www.w3.org/1998/Math/MathML" ' 
 7492: 	    .'xmlns="http://www.w3.org/1999/xhtml">';
 7493:     } elsif ($is_frameset) {
 7494:         $output='<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Frameset//EN" "http://www.w3.org/TR/html4/frameset.dtd">'."\n".
 7495:                 '<html>'."\n";
 7496:     } else {
 7497: 	$output='<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">'."\n".
 7498:                 '<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">'."\n";
 7499:     }
 7500:     return $output;
 7501: }
 7502: 
 7503: =pod
 7504: 
 7505: =item * &start_page()
 7506: 
 7507: Returns a complete <html> .. <body> section for LON-CAPA web pages.
 7508: 
 7509: Inputs:
 7510: 
 7511: =over 4
 7512: 
 7513: $title - optional title for the page
 7514: 
 7515: $head_extra - optional extra HTML to incude inside the <head>
 7516: 
 7517: $args - additional optional args supported are:
 7518: 
 7519: =over 8
 7520: 
 7521:              only_body      -> is true will set &bodytag() onlybodytag
 7522:                                     arg on
 7523:              no_nav_bar     -> is true will set &bodytag() no_nav_bar arg on
 7524:              add_entries    -> additional attributes to add to the  <body>
 7525:              domain         -> force to color decorate a page for a 
 7526:                                     specific domain
 7527:              function       -> force usage of a specific rolish color
 7528:                                     scheme
 7529:              redirect       -> see &headtag()
 7530:              bgcolor        -> override the default page bg color
 7531:              js_ready       -> return a string ready for being used in 
 7532:                                     a javascript writeln
 7533:              html_encode    -> return a string ready for being used in 
 7534:                                     a html attribute
 7535:              force_register -> if is true will turn on the &bodytag()
 7536:                                     $forcereg arg
 7537:              frameset       -> if true will start with a <frameset>
 7538:                                     rather than <body>
 7539:              skip_phases    -> hash ref of 
 7540:                                     head -> skip the <html><head> generation
 7541:                                     body -> skip all <body> generation
 7542:              no_auto_mt_title -> prevent &mt()ing the title arg
 7543:              inherit_jsmath -> when creating popup window in a page,
 7544:                                     should it have jsmath forced on by the
 7545:                                     current page
 7546:              bread_crumbs ->             Array containing breadcrumbs
 7547:              bread_crumbs_component ->  if exists show it as headline else show only the breadcrumbs
 7548:              group          -> includes the current group, if page is for a 
 7549:                                specific group  
 7550: 
 7551: =back
 7552: 
 7553: =back
 7554: 
 7555: =cut
 7556: 
 7557: sub start_page {
 7558:     my ($title,$head_extra,$args) = @_;
 7559:     #&Apache::lonnet::logthis("start_page ".join(':',caller(0)));
 7560: 
 7561:     $env{'internal.start_page'}++;
 7562:     my ($result,@advtools);
 7563: 
 7564:     if (! exists($args->{'skip_phases'}{'head'}) ) {
 7565:         $result .= &xml_begin($args->{'frameset'}) . &headtag($title, $head_extra, $args);
 7566:     }
 7567:     
 7568:     if (! exists($args->{'skip_phases'}{'body'}) ) {
 7569: 	if ($args->{'frameset'}) {
 7570: 	    my $attr_string = &make_attr_string($args->{'force_register'},
 7571: 						$args->{'add_entries'});
 7572: 	    $result .= "\n<frameset $attr_string>\n";
 7573:         } else {
 7574:             $result .=
 7575:                 &bodytag($title, 
 7576:                          $args->{'function'},       $args->{'add_entries'},
 7577:                          $args->{'only_body'},      $args->{'domain'},
 7578:                          $args->{'force_register'}, $args->{'no_nav_bar'},
 7579:                          $args->{'bgcolor'},        $args,
 7580:                          \@advtools);
 7581:         }
 7582:     }
 7583: 
 7584:     if ($args->{'js_ready'}) {
 7585: 		$result = &js_ready($result);
 7586:     }
 7587:     if ($args->{'html_encode'}) {
 7588: 		$result = &html_encode($result);
 7589:     }
 7590: 
 7591:     # Preparation for new and consistent functionlist at top of screen
 7592:     # if ($args->{'functionlist'}) {
 7593:     #            $result .= &build_functionlist();
 7594:     #}
 7595: 
 7596:     # Don't add anything more if only_body wanted or in const space
 7597:     return $result if    $args->{'only_body'} 
 7598:                       || $env{'request.state'} eq 'construct';
 7599: 
 7600:     #Breadcrumbs
 7601:     if (exists($args->{'bread_crumbs'}) or exists($args->{'bread_crumbs_component'})) {
 7602: 		&Apache::lonhtmlcommon::clear_breadcrumbs();
 7603: 		#if any br links exists, add them to the breadcrumbs
 7604: 		if (exists($args->{'bread_crumbs'}) and ref($args->{'bread_crumbs'}) eq 'ARRAY') {         
 7605: 			foreach my $crumb (@{$args->{'bread_crumbs'}}){
 7606: 				&Apache::lonhtmlcommon::add_breadcrumb($crumb);
 7607: 			}
 7608: 		}
 7609:                 # if @advtools array contains items add then to the breadcrumbs
 7610:                 if (@advtools > 0) {
 7611:                     &Apache::lonmenu::advtools_crumbs(@advtools);
 7612:                 }
 7613: 
 7614: 		#if bread_crumbs_component exists show it as headline else show only the breadcrumbs
 7615: 		if(exists($args->{'bread_crumbs_component'})){
 7616: 			$result .= &Apache::lonhtmlcommon::breadcrumbs($args->{'bread_crumbs_component'});
 7617: 		}else{
 7618: 			$result .= &Apache::lonhtmlcommon::breadcrumbs();
 7619: 		}
 7620:     }
 7621:     return $result;
 7622: }
 7623: 
 7624: sub end_page {
 7625:     my ($args) = @_;
 7626:     $env{'internal.end_page'}++;
 7627:     my $result;
 7628:     if ($args->{'discussion'}) {
 7629: 	my ($target,$parser);
 7630: 	if (ref($args->{'discussion'})) {
 7631: 	    ($target,$parser) =($args->{'discussion'}{'target'},
 7632: 				$args->{'discussion'}{'parser'});
 7633: 	}
 7634: 	$result .= &Apache::lonxml::xmlend($target,$parser);
 7635:     }
 7636:     if ($args->{'frameset'}) {
 7637: 	$result .= '</frameset>';
 7638:     } else {
 7639: 	$result .= &endbodytag($args);
 7640:     }
 7641:     unless ($args->{'notbody'}) {
 7642:         $result .= "\n</html>";
 7643:     }
 7644: 
 7645:     if ($args->{'js_ready'}) {
 7646: 	$result = &js_ready($result);
 7647:     }
 7648: 
 7649:     if ($args->{'html_encode'}) {
 7650: 	$result = &html_encode($result);
 7651:     }
 7652: 
 7653:     return $result;
 7654: }
 7655: 
 7656: sub wishlist_window {
 7657:     return(<<'ENDWISHLIST');
 7658: <script type="text/javascript">
 7659: // <![CDATA[
 7660: // <!-- BEGIN LON-CAPA Internal
 7661: function set_wishlistlink(title, path) {
 7662:     if (!title) {
 7663:         title = document.title;
 7664:         title = title.replace(/^LON-CAPA /,'');
 7665:     }
 7666:     title = encodeURIComponent(title);
 7667:     if (!path) {
 7668:         path = location.pathname;
 7669:     }
 7670:     path = encodeURIComponent(path);
 7671:     Win = window.open('/adm/wishlist?mode=newLink&setTitle='+title+'&setPath='+path,
 7672:                       'wishlistNewLink','width=560,height=350,scrollbars=0');
 7673: }
 7674: // END LON-CAPA Internal -->
 7675: // ]]>
 7676: </script>
 7677: ENDWISHLIST
 7678: }
 7679: 
 7680: sub modal_window {
 7681:     return(<<'ENDMODAL');
 7682: <script type="text/javascript">
 7683: // <![CDATA[
 7684: // <!-- BEGIN LON-CAPA Internal
 7685: var modalWindow = {
 7686: 	parent:"body",
 7687: 	windowId:null,
 7688: 	content:null,
 7689: 	width:null,
 7690: 	height:null,
 7691: 	close:function()
 7692: 	{
 7693: 	        $(".LCmodal-window").remove();
 7694: 	        $(".LCmodal-overlay").remove();
 7695: 	},
 7696: 	open:function()
 7697: 	{
 7698: 		var modal = "";
 7699: 		modal += "<div class=\"LCmodal-overlay\"></div>";
 7700: 		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;\">";
 7701: 		modal += this.content;
 7702: 		modal += "</div>";	
 7703: 
 7704: 		$(this.parent).append(modal);
 7705: 
 7706: 		$(".LCmodal-window").append("<a class=\"LCclose-window\"></a>");
 7707: 		$(".LCclose-window").click(function(){modalWindow.close();});
 7708: 		$(".LCmodal-overlay").click(function(){modalWindow.close();});
 7709: 	}
 7710: };
 7711: 	var openMyModal = function(source,width,height,scrolling,transparency,style)
 7712: 	{
 7713: 		modalWindow.windowId = "myModal";
 7714: 		modalWindow.width = width;
 7715: 		modalWindow.height = height;
 7716: 		modalWindow.content = "<iframe width='"+width+"' height='"+height+"' frameborder='0' scrolling='"+scrolling+"' allowtransparency='"+transparency+"' src='" + source + "' style='"+style+"'>&lt/iframe>";
 7717: 		modalWindow.open();
 7718: 	};	
 7719: // END LON-CAPA Internal -->
 7720: // ]]>
 7721: </script>
 7722: ENDMODAL
 7723: }
 7724: 
 7725: sub modal_link {
 7726:     my ($link,$linktext,$width,$height,$target,$scrolling,$title,$transparency,$style)=@_;
 7727:     unless ($width) { $width=480; }
 7728:     unless ($height) { $height=400; }
 7729:     unless ($scrolling) { $scrolling='yes'; }
 7730:     unless ($transparency) { $transparency='true'; }
 7731: 
 7732:     my $target_attr;
 7733:     if (defined($target)) {
 7734:         $target_attr = 'target="'.$target.'"';
 7735:     }
 7736:     return <<"ENDLINK";
 7737: <a href="$link" $target_attr title="$title" onclick="javascript:openMyModal('$link',$width,$height,'$scrolling','$transparency','$style'); return false;">
 7738:            $linktext</a>
 7739: ENDLINK
 7740: }
 7741: 
 7742: sub modal_adhoc_script {
 7743:     my ($funcname,$width,$height,$content)=@_;
 7744:     return (<<ENDADHOC);
 7745: <script type="text/javascript">
 7746: // <![CDATA[
 7747:         var $funcname = function()
 7748:         {
 7749:                 modalWindow.windowId = "myModal";
 7750:                 modalWindow.width = $width;
 7751:                 modalWindow.height = $height;
 7752:                 modalWindow.content = '$content';
 7753:                 modalWindow.open();
 7754:         };  
 7755: // ]]>
 7756: </script>
 7757: ENDADHOC
 7758: }
 7759: 
 7760: sub modal_adhoc_inner {
 7761:     my ($funcname,$width,$height,$content)=@_;
 7762:     my $innerwidth=$width-20;
 7763:     $content=&js_ready(
 7764:                  &start_page('Dialog',undef,{'only_body'=>1,'bgcolor'=>'#FFFFFF'}).
 7765:                  &start_scrollbox($width.'px',$innerwidth.'px',$height.'px','myModal','#FFFFFF',undef,1).
 7766:                  $content.
 7767:                  &end_scrollbox().
 7768:                  &end_page()
 7769:              );
 7770:     return &modal_adhoc_script($funcname,$width,$height,$content);
 7771: }
 7772: 
 7773: sub modal_adhoc_window {
 7774:     my ($funcname,$width,$height,$content,$linktext)=@_;
 7775:     return &modal_adhoc_inner($funcname,$width,$height,$content).
 7776:            "<a href=\"javascript:$funcname();void(0);\">".$linktext."</a>";
 7777: }
 7778: 
 7779: sub modal_adhoc_launch {
 7780:     my ($funcname,$width,$height,$content)=@_;
 7781:     return &modal_adhoc_inner($funcname,$width,$height,$content).(<<ENDLAUNCH);
 7782: <script type="text/javascript">
 7783: // <![CDATA[
 7784: $funcname();
 7785: // ]]>
 7786: </script>
 7787: ENDLAUNCH
 7788: }
 7789: 
 7790: sub modal_adhoc_close {
 7791:     return (<<ENDCLOSE);
 7792: <script type="text/javascript">
 7793: // <![CDATA[
 7794: modalWindow.close();
 7795: // ]]>
 7796: </script>
 7797: ENDCLOSE
 7798: }
 7799: 
 7800: sub togglebox_script {
 7801:    return(<<ENDTOGGLE);
 7802: <script type="text/javascript"> 
 7803: // <![CDATA[
 7804: function LCtoggleDisplay(id,hidetext,showtext) {
 7805:    link = document.getElementById(id + "link").childNodes[0];
 7806:    with (document.getElementById(id).style) {
 7807:       if (display == "none" ) {
 7808:           display = "inline";
 7809:           link.nodeValue = hidetext;
 7810:         } else {
 7811:           display = "none";
 7812:           link.nodeValue = showtext;
 7813:        }
 7814:    }
 7815: }
 7816: // ]]>
 7817: </script>
 7818: ENDTOGGLE
 7819: }
 7820: 
 7821: sub start_togglebox {
 7822:     my ($id,$heading,$headerbg,$hidetext,$showtext)=@_;
 7823:     unless ($heading) { $heading=''; } else { $heading.=' '; }
 7824:     unless ($showtext) { $showtext=&mt('show'); }
 7825:     unless ($hidetext) { $hidetext=&mt('hide'); }
 7826:     unless ($headerbg) { $headerbg='#FFFFFF'; }
 7827:     return &start_data_table().
 7828:            &start_data_table_header_row().
 7829:            '<td bgcolor="'.$headerbg.'">'.$heading.
 7830:            '[<a id="'.$id.'link" href="javascript:LCtoggleDisplay(\''.$id.'\',\''.$hidetext.'\',\''.
 7831:            $showtext.'\')">'.$showtext.'</a>]</td>'.
 7832:            &end_data_table_header_row().
 7833:            '<tr id="'.$id.'" style="display:none""><td>';
 7834: }
 7835: 
 7836: sub end_togglebox {
 7837:     return '</td></tr>'.&end_data_table();
 7838: }
 7839: 
 7840: sub LCprogressbar_script {
 7841:    my ($id)=@_;
 7842:    return(<<ENDPROGRESS);
 7843: <script type="text/javascript">
 7844: // <![CDATA[
 7845: \$('#progressbar$id').progressbar({
 7846:   value: 0,
 7847:   change: function(event, ui) {
 7848:     var newVal = \$(this).progressbar('option', 'value');
 7849:     \$('.pblabel', this).text(LCprogressTxt);
 7850:   }
 7851: });
 7852: // ]]>
 7853: </script>
 7854: ENDPROGRESS
 7855: }
 7856: 
 7857: sub LCprogressbarUpdate_script {
 7858:    return(<<ENDPROGRESSUPDATE);
 7859: <style type="text/css">
 7860: .ui-progressbar { position:relative; }
 7861: .pblabel { position: absolute; width: 100%; text-align: center; line-height: 1.9em; }
 7862: </style>
 7863: <script type="text/javascript">
 7864: // <![CDATA[
 7865: var LCprogressTxt='---';
 7866: 
 7867: function LCupdateProgress(percent,progresstext,id) {
 7868:    LCprogressTxt=progresstext;
 7869:    \$('#progressbar'+id).progressbar('value',percent);
 7870: }
 7871: // ]]>
 7872: </script>
 7873: ENDPROGRESSUPDATE
 7874: }
 7875: 
 7876: my $LClastpercent;
 7877: my $LCidcnt;
 7878: my $LCcurrentid;
 7879: 
 7880: sub LCprogressbar {
 7881:     my ($r)=(@_);
 7882:     $LClastpercent=0;
 7883:     $LCidcnt++;
 7884:     $LCcurrentid=$$.'_'.$LCidcnt;
 7885:     my $starting=&mt('Starting');
 7886:     my $content=(<<ENDPROGBAR);
 7887:   <div id="progressbar$LCcurrentid">
 7888:     <span class="pblabel">$starting</span>
 7889:   </div>
 7890: ENDPROGBAR
 7891:     &r_print($r,$content.&LCprogressbar_script($LCcurrentid));
 7892: }
 7893: 
 7894: sub LCprogressbarUpdate {
 7895:     my ($r,$val,$text)=@_;
 7896:     unless ($val) { 
 7897:        if ($LClastpercent) {
 7898:            $val=$LClastpercent;
 7899:        } else {
 7900:            $val=0;
 7901:        }
 7902:     }
 7903:     if ($val<0) { $val=0; }
 7904:     if ($val>100) { $val=0; }
 7905:     $LClastpercent=$val;
 7906:     unless ($text) { $text=$val.'%'; }
 7907:     $text=&js_ready($text);
 7908:     &r_print($r,<<ENDUPDATE);
 7909: <script type="text/javascript">
 7910: // <![CDATA[
 7911: LCupdateProgress($val,'$text','$LCcurrentid');
 7912: // ]]>
 7913: </script>
 7914: ENDUPDATE
 7915: }
 7916: 
 7917: sub LCprogressbarClose {
 7918:     my ($r)=@_;
 7919:     $LClastpercent=0;
 7920:     &r_print($r,<<ENDCLOSE);
 7921: <script type="text/javascript">
 7922: // <![CDATA[
 7923: \$("#progressbar$LCcurrentid").hide('slow'); 
 7924: // ]]>
 7925: </script>
 7926: ENDCLOSE
 7927: }
 7928: 
 7929: sub r_print {
 7930:     my ($r,$to_print)=@_;
 7931:     if ($r) {
 7932:       $r->print($to_print);
 7933:       $r->rflush();
 7934:     } else {
 7935:       print($to_print);
 7936:     }
 7937: }
 7938: 
 7939: sub html_encode {
 7940:     my ($result) = @_;
 7941: 
 7942:     $result = &HTML::Entities::encode($result,'<>&"');
 7943:     
 7944:     return $result;
 7945: }
 7946: 
 7947: sub js_ready {
 7948:     my ($result) = @_;
 7949: 
 7950:     $result =~ s/[\n\r]/ /xmsg;
 7951:     $result =~ s/\\/\\\\/xmsg;
 7952:     $result =~ s/'/\\'/xmsg;
 7953:     $result =~ s{</}{<\\/}xmsg;
 7954:     
 7955:     return $result;
 7956: }
 7957: 
 7958: sub validate_page {
 7959:     if (  exists($env{'internal.start_page'})
 7960: 	  &&     $env{'internal.start_page'} > 1) {
 7961: 	&Apache::lonnet::logthis('start_page called multiple times '.
 7962: 				 $env{'internal.start_page'}.' '.
 7963: 				 $ENV{'request.filename'});
 7964:     }
 7965:     if (  exists($env{'internal.end_page'})
 7966: 	  &&     $env{'internal.end_page'} > 1) {
 7967: 	&Apache::lonnet::logthis('end_page called multiple times '.
 7968: 				 $env{'internal.end_page'}.' '.
 7969: 				 $env{'request.filename'});
 7970:     }
 7971:     if (     exists($env{'internal.start_page'})
 7972: 	&& ! exists($env{'internal.end_page'})) {
 7973: 	&Apache::lonnet::logthis('start_page called without end_page '.
 7974: 				 $env{'request.filename'});
 7975:     }
 7976:     if (   ! exists($env{'internal.start_page'})
 7977: 	&&   exists($env{'internal.end_page'})) {
 7978: 	&Apache::lonnet::logthis('end_page called without start_page'.
 7979: 				 $env{'request.filename'});
 7980:     }
 7981: }
 7982: 
 7983: 
 7984: sub start_scrollbox {
 7985:     my ($outerwidth,$width,$height,$id,$bgcolor,$cursor,$needjsready) = @_;
 7986:     unless ($outerwidth) { $outerwidth='520px'; }
 7987:     unless ($width) { $width='500px'; }
 7988:     unless ($height) { $height='200px'; }
 7989:     my ($table_id,$div_id,$tdcol);
 7990:     if ($id ne '') {
 7991:         $table_id = ' id="table_'.$id.'"';
 7992:         $div_id = ' id="div_'.$id.'"';
 7993:     }
 7994:     if ($bgcolor ne '') {
 7995:         $tdcol = "background-color: $bgcolor;";
 7996:     }
 7997:     my $nicescroll_js;
 7998:     if ($env{'browser.mobile'}) {
 7999:         $nicescroll_js = &nicescroll_javascript('div_'.$id,$cursor,$needjsready);
 8000:     }
 8001:     return <<"END";
 8002: $nicescroll_js
 8003: 
 8004: <table style="width: $outerwidth; border: 1px solid none;"$table_id><tr><td style="width: $width;$tdcol">
 8005: <div style="overflow:auto; width:$width; height:$height;"$div_id>
 8006: END
 8007: }
 8008: 
 8009: sub end_scrollbox {
 8010:     return '</div></td></tr></table>';
 8011: }
 8012: 
 8013: sub nicescroll_javascript {
 8014:     my ($id,$cursor,$needjsready,$framecheck,$location) = @_;
 8015:     my %options;
 8016:     if (ref($cursor) eq 'HASH') {
 8017:         %options = %{$cursor};
 8018:     }
 8019:     unless ($options{'railalign'} =~ /^left|right$/) {
 8020:         $options{'railalign'} = 'left';
 8021:     }
 8022:     unless ($options{'cursorcolor'} =~ /^\#\w+$/) {
 8023:         my $function  = &get_users_function();
 8024:         $options{'cursorcolor'} = &designparm($function.'.sidebg',$env{'request.role.domain'});
 8025:         unless ($options{'cursorcolor'} =~ /^\#\w+$/) {
 8026:             $options{'cursorcolor'} = '#00F';
 8027:         }
 8028:     }
 8029:     if ($options{'cursoropacity'} =~ /^[\d.]+$/) {
 8030:         unless ($options{'cursoropacity'} >= 0.0 && $options{'cursoropacity'} <=1.0) {
 8031:             $options{'cursoropacity'}='1.0';
 8032:         }
 8033:     } else {
 8034:         $options{'cursoropacity'}='1.0';
 8035:     }
 8036:     if ($options{'cursorfixedheight'} eq 'none') {
 8037:         delete($options{'cursorfixedheight'});
 8038:     } else {
 8039:         unless ($options{'cursorfixedheight'} =~ /^\d+$/) { $options{'cursorfixedheight'}='50'; }
 8040:     }
 8041:     unless ($options{'railoffset'} =~ /^{[\w\:\d\-,]+}$/) {
 8042:         delete($options{'railoffset'});
 8043:     }
 8044:     my @niceoptions;
 8045:     while (my($key,$value) = each(%options)) {
 8046:         if ($value =~ /^\{.+\}$/) {
 8047:             push(@niceoptions,$key.':'.$value);
 8048:         } else {
 8049:             push(@niceoptions,$key.':"'.$value.'"');
 8050:         }
 8051:     }
 8052:     my $nicescroll_js = '
 8053: $(document).ready(
 8054:       function() {
 8055:           $("#'.$id.'").niceScroll({'.join(',',@niceoptions).'});
 8056:       }
 8057: );
 8058: ';
 8059:     if ($framecheck) {
 8060:         $nicescroll_js .= '
 8061: function expand_div(caller) {
 8062:     if (top === self) {
 8063:         document.getElementById("'.$id.'").style.width = "auto";
 8064:         document.getElementById("'.$id.'").style.height = "auto";
 8065:     } else {
 8066:         try {
 8067:             if (parent.frames) {
 8068:                 if (parent.frames.length > 1) {
 8069:                     var framesrc = parent.frames[1].location.href;
 8070:                     var currsrc = framesrc.replace(/\#.*$/,"");
 8071:                     if ((caller == "search") || (currsrc == "'.$location.'")) {
 8072:                         document.getElementById("'.$id.'").style.width = "auto";
 8073:                         document.getElementById("'.$id.'").style.height = "auto";
 8074:                     }
 8075:                 }
 8076:             }
 8077:         } catch (e) {
 8078:             return;
 8079:         }
 8080:     }
 8081:     return;
 8082: }
 8083: ';
 8084:     }
 8085:     if ($needjsready) {
 8086:         $nicescroll_js = '
 8087: <script type="text/javascript">'."\n".$nicescroll_js."\n</script>\n";
 8088:     } else {
 8089:         $nicescroll_js = &Apache::lonhtmlcommon::scripttag($nicescroll_js);
 8090:     }
 8091:     return $nicescroll_js;
 8092: }
 8093: 
 8094: sub simple_error_page {
 8095:     my ($r,$title,$msg,$args) = @_;
 8096:     if (ref($args) eq 'HASH') {
 8097:         if (!$args->{'no_auto_mt_msg'}) { $msg = &mt($msg); }
 8098:     } else {
 8099:         $msg = &mt($msg);
 8100:     }
 8101: 
 8102:     my $page =
 8103: 	&Apache::loncommon::start_page($title).
 8104: 	'<p class="LC_error">'.$msg.'</p>'.
 8105: 	&Apache::loncommon::end_page();
 8106:     if (ref($r)) {
 8107: 	$r->print($page);
 8108: 	return;
 8109:     }
 8110:     return $page;
 8111: }
 8112: 
 8113: {
 8114:     my @row_count;
 8115: 
 8116:     sub start_data_table_count {
 8117:         unshift(@row_count, 0);
 8118:         return;
 8119:     }
 8120: 
 8121:     sub end_data_table_count {
 8122:         shift(@row_count);
 8123:         return;
 8124:     }
 8125: 
 8126:     sub start_data_table {
 8127: 	my ($add_class,$id) = @_;
 8128: 	my $css_class = (join(' ','LC_data_table',$add_class));
 8129:         my $table_id;
 8130:         if (defined($id)) {
 8131:             $table_id = ' id="'.$id.'"';
 8132:         }
 8133: 	&start_data_table_count();
 8134: 	return '<table class="'.$css_class.'"'.$table_id.'>'."\n";
 8135:     }
 8136: 
 8137:     sub end_data_table {
 8138: 	&end_data_table_count();
 8139: 	return '</table>'."\n";;
 8140:     }
 8141: 
 8142:     sub start_data_table_row {
 8143: 	my ($add_class, $id) = @_;
 8144: 	$row_count[0]++;
 8145: 	my $css_class = ($row_count[0] % 2)?'LC_odd_row':'LC_even_row';
 8146: 	$css_class = (join(' ',$css_class,$add_class)) unless ($add_class eq '');
 8147:         $id = (' id="'.$id.'"') unless ($id eq '');
 8148:         return  '<tr class="'.$css_class.'"'.$id.'>'."\n";
 8149:     }
 8150:     
 8151:     sub continue_data_table_row {
 8152: 	my ($add_class, $id) = @_;
 8153: 	my $css_class = ($row_count[0] % 2)?'LC_odd_row':'LC_even_row';
 8154: 	$css_class = (join(' ',$css_class,$add_class)) unless ($add_class eq '');
 8155:         $id = (' id="'.$id.'"') unless ($id eq '');
 8156:         return  '<tr class="'.$css_class.'"'.$id.'>'."\n";
 8157:     }
 8158: 
 8159:     sub end_data_table_row {
 8160: 	return '</tr>'."\n";;
 8161:     }
 8162: 
 8163:     sub start_data_table_empty_row {
 8164: #	$row_count[0]++;
 8165: 	return  '<tr class="LC_empty_row" >'."\n";;
 8166:     }
 8167: 
 8168:     sub end_data_table_empty_row {
 8169: 	return '</tr>'."\n";;
 8170:     }
 8171: 
 8172:     sub start_data_table_header_row {
 8173: 	return  '<tr class="LC_header_row">'."\n";;
 8174:     }
 8175: 
 8176:     sub end_data_table_header_row {
 8177: 	return '</tr>'."\n";;
 8178:     }
 8179: 
 8180:     sub data_table_caption {
 8181:         my $caption = shift;
 8182:         return "<caption class=\"LC_caption\">$caption</caption>";
 8183:     }
 8184: }
 8185: 
 8186: =pod
 8187: 
 8188: =item * &inhibit_menu_check($arg)
 8189: 
 8190: Checks for a inhibitmenu state and generates output to preserve it
 8191: 
 8192: Inputs:         $arg - can be any of
 8193:                      - undef - in which case the return value is a string 
 8194:                                to add  into arguments list of a uri
 8195:                      - 'input' - in which case the return value is a HTML
 8196:                                  <form> <input> field of type hidden to
 8197:                                  preserve the value
 8198:                      - a url - in which case the return value is the url with
 8199:                                the neccesary cgi args added to preserve the
 8200:                                inhibitmenu state
 8201:                      - a ref to a url - no return value, but the string is
 8202:                                         updated to include the neccessary cgi
 8203:                                         args to preserve the inhibitmenu state
 8204: 
 8205: =cut
 8206: 
 8207: sub inhibit_menu_check {
 8208:     my ($arg) = @_;
 8209:     &get_unprocessed_cgi($ENV{'QUERY_STRING'}, ['inhibitmenu']);
 8210:     if ($arg eq 'input') {
 8211: 	if ($env{'form.inhibitmenu'}) {
 8212: 	    return '<input type="hidden" name="inhibitmenu" value="'.$env{'form.inhibitmenu'}.'" />';
 8213: 	} else {
 8214: 	    return
 8215: 	}
 8216:     }
 8217:     if ($env{'form.inhibitmenu'}) {
 8218: 	if (ref($arg)) {
 8219: 	    $$arg .= '?inhibitmenu='.$env{'form.inhibitmenu'};
 8220: 	} elsif ($arg eq '') {
 8221: 	    $arg .= 'inhibitmenu='.$env{'form.inhibitmenu'};
 8222: 	} else {
 8223: 	    $arg .= '?inhibitmenu='.$env{'form.inhibitmenu'};
 8224: 	}
 8225:     }
 8226:     if (!ref($arg)) {
 8227: 	return $arg;
 8228:     }
 8229: }
 8230: 
 8231: ###############################################
 8232: 
 8233: =pod
 8234: 
 8235: =back
 8236: 
 8237: =head1 User Information Routines
 8238: 
 8239: =over 4
 8240: 
 8241: =item * &get_users_function()
 8242: 
 8243: Used by &bodytag to determine the current users primary role.
 8244: Returns either 'student','coordinator','admin', or 'author'.
 8245: 
 8246: =cut
 8247: 
 8248: ###############################################
 8249: sub get_users_function {
 8250:     my $function = 'norole';
 8251:     if ($env{'request.role'}=~/^(st)/) {
 8252:         $function='student';
 8253:     }
 8254:     if ($env{'request.role'}=~/^(cc|co|in|ta|ep)/) {
 8255:         $function='coordinator';
 8256:     }
 8257:     if ($env{'request.role'}=~/^(su|dc|ad|li)/) {
 8258:         $function='admin';
 8259:     }
 8260:     if (($env{'request.role'}=~/^(au|ca|aa)/) ||
 8261:         ($ENV{'REQUEST_URI'}=~ m{/^(/priv)})) {
 8262:         $function='author';
 8263:     }
 8264:     return $function;
 8265: }
 8266: 
 8267: ###############################################
 8268: 
 8269: =pod
 8270: 
 8271: =item * &show_course()
 8272: 
 8273: Used by lonmenu.pm and lonroles.pm to determine whether to use the word
 8274: 'Courses' or 'Roles' in inline navigation and on screen displaying user's roles.
 8275: 
 8276: Inputs:
 8277: None
 8278: 
 8279: Outputs:
 8280: Scalar: 1 if 'Course' to be used, 0 otherwise.
 8281: 
 8282: =cut
 8283: 
 8284: ###############################################
 8285: sub show_course {
 8286:     my $course = !$env{'user.adv'};
 8287:     if (!$env{'user.adv'}) {
 8288:         foreach my $env (keys(%env)) {
 8289:             next if ($env !~ m/^user\.priv\./);
 8290:             if ($env !~ m/^user\.priv\.(?:st|cm)/) {
 8291:                 $course = 0;
 8292:                 last;
 8293:             }
 8294:         }
 8295:     }
 8296:     return $course;
 8297: }
 8298: 
 8299: ###############################################
 8300: 
 8301: =pod
 8302: 
 8303: =item * &check_user_status()
 8304: 
 8305: Determines current status of supplied role for a
 8306: specific user. Roles can be active, previous or future.
 8307: 
 8308: Inputs: 
 8309: user's domain, user's username, course's domain,
 8310: course's number, optional section ID.
 8311: 
 8312: Outputs:
 8313: role status: active, previous or future. 
 8314: 
 8315: =cut
 8316: 
 8317: sub check_user_status {
 8318:     my ($udom,$uname,$cdom,$crs,$role,$sec) = @_;
 8319:     my %userinfo = &Apache::lonnet::dump('roles',$udom,$uname);
 8320:     my @uroles = keys %userinfo;
 8321:     my $srchstr;
 8322:     my $active_chk = 'none';
 8323:     my $now = time;
 8324:     if (@uroles > 0) {
 8325:         if (($role eq 'cc') || ($role eq 'co') || ($sec eq '') || (!defined($sec))) {
 8326:             $srchstr = '/'.$cdom.'/'.$crs.'_'.$role;
 8327:         } else {
 8328:             $srchstr = '/'.$cdom.'/'.$crs.'/'.$sec.'_'.$role;
 8329:         }
 8330:         if (grep/^\Q$srchstr\E$/,@uroles) {
 8331:             my $role_end = 0;
 8332:             my $role_start = 0;
 8333:             $active_chk = 'active';
 8334:             if ($userinfo{$srchstr} =~ m/^\Q$role\E_(\d+)/) {
 8335:                 $role_end = $1;
 8336:                 if ($userinfo{$srchstr} =~ m/^\Q$role\E_\Q$role_end\E_(\d+)$/) {
 8337:                     $role_start = $1;
 8338:                 }
 8339:             }
 8340:             if ($role_start > 0) {
 8341:                 if ($now < $role_start) {
 8342:                     $active_chk = 'future';
 8343:                 }
 8344:             }
 8345:             if ($role_end > 0) {
 8346:                 if ($now > $role_end) {
 8347:                     $active_chk = 'previous';
 8348:                 }
 8349:             }
 8350:         }
 8351:     }
 8352:     return $active_chk;
 8353: }
 8354: 
 8355: ###############################################
 8356: 
 8357: =pod
 8358: 
 8359: =item * &get_sections()
 8360: 
 8361: Determines all the sections for a course including
 8362: sections with students and sections containing other roles.
 8363: Incoming parameters: 
 8364: 
 8365: 1. domain
 8366: 2. course number 
 8367: 3. reference to array containing roles for which sections should 
 8368: be gathered (optional).
 8369: 4. reference to array containing status types for which sections 
 8370: should be gathered (optional).
 8371: 
 8372: If the third argument is undefined, sections are gathered for any role. 
 8373: If the fourth argument is undefined, sections are gathered for any status.
 8374: Permissible values are 'active' or 'future' or 'previous'.
 8375:  
 8376: Returns section hash (keys are section IDs, values are
 8377: number of users in each section), subject to the
 8378: optional roles filter, optional status filter 
 8379: 
 8380: =cut
 8381: 
 8382: ###############################################
 8383: sub get_sections {
 8384:     my ($cdom,$cnum,$possible_roles,$possible_status) = @_;
 8385:     if (!defined($cdom) || !defined($cnum)) {
 8386:         my $cid =  $env{'request.course.id'};
 8387: 
 8388: 	return if (!defined($cid));
 8389: 
 8390:         $cdom = $env{'course.'.$cid.'.domain'};
 8391:         $cnum = $env{'course.'.$cid.'.num'};
 8392:     }
 8393: 
 8394:     my %sectioncount;
 8395:     my $now = time;
 8396: 
 8397:     my $check_students = 1;
 8398:     my $only_students = 0;
 8399:     if (ref($possible_roles) eq 'ARRAY') {
 8400:         if (grep(/^st$/,@{$possible_roles})) {
 8401:             if (@{$possible_roles} == 1) {
 8402:                 $only_students = 1;
 8403:             }
 8404:         } else {
 8405:             $check_students = 0;
 8406:         }
 8407:     }
 8408: 
 8409:     if ($check_students) { 
 8410: 	my ($classlist) = &Apache::loncoursedata::get_classlist($cdom,$cnum);
 8411: 	my $sec_index = &Apache::loncoursedata::CL_SECTION();
 8412: 	my $status_index = &Apache::loncoursedata::CL_STATUS();
 8413:         my $start_index = &Apache::loncoursedata::CL_START();
 8414:         my $end_index = &Apache::loncoursedata::CL_END();
 8415:         my $status;
 8416: 	while (my ($student,$data) = each(%$classlist)) {
 8417: 	    my ($section,$stu_status,$start,$end) = ($data->[$sec_index],
 8418: 				                     $data->[$status_index],
 8419:                                                      $data->[$start_index],
 8420:                                                      $data->[$end_index]);
 8421:             if ($stu_status eq 'Active') {
 8422:                 $status = 'active';
 8423:             } elsif ($end < $now) {
 8424:                 $status = 'previous';
 8425:             } elsif ($start > $now) {
 8426:                 $status = 'future';
 8427:             } 
 8428: 	    if ($section ne '-1' && $section !~ /^\s*$/) {
 8429:                 if ((!defined($possible_status)) || (($status ne '') && 
 8430:                     (grep/^\Q$status\E$/,@{$possible_status}))) { 
 8431: 		    $sectioncount{$section}++;
 8432:                 }
 8433: 	    }
 8434: 	}
 8435:     }
 8436:     if ($only_students) {
 8437:         return %sectioncount;
 8438:     }
 8439:     my %courseroles = &Apache::lonnet::dump('nohist_userroles',$cdom,$cnum);
 8440:     foreach my $user (sort(keys(%courseroles))) {
 8441: 	if ($user !~ /^(\w{2})/) { next; }
 8442: 	my ($role) = ($user =~ /^(\w{2})/);
 8443: 	if ($possible_roles && !(grep(/^$role$/,@$possible_roles))) { next; }
 8444: 	my ($section,$status);
 8445: 	if ($role eq 'cr' &&
 8446: 	    $user =~ m-^$role/[^/]*/[^/]*/[^/]*:[^:]*:[^:]*:(\w+)-) {
 8447: 	    $section=$1;
 8448: 	}
 8449: 	if ($user =~ /^$role:[^:]*:[^:]*:(\w+)/) { $section=$1; }
 8450: 	if (!defined($section) || $section eq '-1') { next; }
 8451:         my ($end,$start) = ($courseroles{$user} =~ /^([^:]*):([^:]*)$/);
 8452:         if ($end == -1 && $start == -1) {
 8453:             next; #deleted role
 8454:         }
 8455:         if (!defined($possible_status)) { 
 8456:             $sectioncount{$section}++;
 8457:         } else {
 8458:             if ((!$end || $end >= $now) && (!$start || $start <= $now)) {
 8459:                 $status = 'active';
 8460:             } elsif ($end < $now) {
 8461:                 $status = 'future';
 8462:             } elsif ($start > $now) {
 8463:                 $status = 'previous';
 8464:             }
 8465:             if (($status ne '') && (grep/^\Q$status\E$/,@{$possible_status})) {
 8466:                 $sectioncount{$section}++;
 8467:             }
 8468:         }
 8469:     }
 8470:     return %sectioncount;
 8471: }
 8472: 
 8473: ###############################################
 8474: 
 8475: =pod
 8476: 
 8477: =item * &get_course_users()
 8478: 
 8479: Retrieves usernames:domains for users in the specified course
 8480: with specific role(s), and access status. 
 8481: 
 8482: Incoming parameters:
 8483: 1. course domain
 8484: 2. course number
 8485: 3. access status: users must have - either active, 
 8486: previous, future, or all.
 8487: 4. reference to array of permissible roles
 8488: 5. reference to array of section restrictions (optional)
 8489: 6. reference to results object (hash of hashes).
 8490: 7. reference to optional userdata hash
 8491: 8. reference to optional statushash
 8492: 9. flag if privileged users (except those set to unhide in
 8493:    course settings) should be excluded    
 8494: Keys of top level results hash are roles.
 8495: Keys of inner hashes are username:domain, with 
 8496: values set to access type.
 8497: Optional userdata hash returns an array with arguments in the 
 8498: same order as loncoursedata::get_classlist() for student data.
 8499: 
 8500: Optional statushash returns
 8501: 
 8502: Entries for end, start, section and status are blank because
 8503: of the possibility of multiple values for non-student roles.
 8504: 
 8505: =cut
 8506: 
 8507: ###############################################
 8508: 
 8509: sub get_course_users {
 8510:     my ($cdom,$cnum,$types,$roles,$sections,$users,$userdata,$statushash,$hidepriv) = @_;
 8511:     my %idx = ();
 8512:     my %seclists;
 8513: 
 8514:     $idx{udom} = &Apache::loncoursedata::CL_SDOM();
 8515:     $idx{uname} =  &Apache::loncoursedata::CL_SNAME();
 8516:     $idx{end} = &Apache::loncoursedata::CL_END();
 8517:     $idx{start} = &Apache::loncoursedata::CL_START();
 8518:     $idx{id} = &Apache::loncoursedata::CL_ID();
 8519:     $idx{section} = &Apache::loncoursedata::CL_SECTION();
 8520:     $idx{fullname} = &Apache::loncoursedata::CL_FULLNAME();
 8521:     $idx{status} = &Apache::loncoursedata::CL_STATUS();
 8522: 
 8523:     if (grep(/^st$/,@{$roles})) {
 8524:         my ($classlist,$keylist)=&Apache::loncoursedata::get_classlist($cdom,$cnum);
 8525:         my $now = time;
 8526:         foreach my $student (keys(%{$classlist})) {
 8527:             my $match = 0;
 8528:             my $secmatch = 0;
 8529:             my $section = $$classlist{$student}[$idx{section}];
 8530:             my $status = $$classlist{$student}[$idx{status}];
 8531:             if ($section eq '') {
 8532:                 $section = 'none';
 8533:             }
 8534:             if ((ref($sections) eq 'ARRAY') && (@{$sections} > 0)) {
 8535:                 if (grep(/^all$/,@{$sections})) {
 8536:                     $secmatch = 1;
 8537:                 } elsif ($$classlist{$student}[$idx{section}] eq '') {
 8538:                     if (grep(/^none$/,@{$sections})) {
 8539:                         $secmatch = 1;
 8540:                     }
 8541:                 } else {  
 8542: 		    if (grep(/^\Q$section\E$/,@{$sections})) {
 8543: 		        $secmatch = 1;
 8544:                     }
 8545: 		}
 8546:                 if (!$secmatch) {
 8547:                     next;
 8548:                 }
 8549:             }
 8550:             if (defined($$types{'active'})) {
 8551:                 if ($$classlist{$student}[$idx{status}] eq 'Active') {
 8552:                     push(@{$$users{st}{$student}},'active');
 8553:                     $match = 1;
 8554:                 }
 8555:             }
 8556:             if (defined($$types{'previous'})) {
 8557:                 if ($$classlist{$student}[$idx{status}] eq 'Expired') {
 8558:                     push(@{$$users{st}{$student}},'previous');
 8559:                     $match = 1;
 8560:                 }
 8561:             }
 8562:             if (defined($$types{'future'})) {
 8563:                 if ($$classlist{$student}[$idx{status}] eq 'Future') {
 8564:                     push(@{$$users{st}{$student}},'future');
 8565:                     $match = 1;
 8566:                 }
 8567:             }
 8568:             if ($match) {
 8569:                 push(@{$seclists{$student}},$section);
 8570:                 if (ref($userdata) eq 'HASH') {
 8571:                     $$userdata{$student} = $$classlist{$student};
 8572:                 }
 8573:                 if (ref($statushash) eq 'HASH') {
 8574:                     $statushash->{$student}{'st'}{$section} = $status;
 8575:                 }
 8576:             }
 8577:         }
 8578:     }
 8579:     if ((@{$roles} > 1) || ((@{$roles} == 1) && ($$roles[0] ne "st"))) {
 8580:         my %coursepersonnel = &Apache::lonnet::dump('nohist_userroles',$cdom,$cnum);
 8581:         my $now = time;
 8582:         my %displaystatus = ( previous => 'Expired',
 8583:                               active   => 'Active',
 8584:                               future   => 'Future',
 8585:                             );
 8586:         my (%nothide,@possdoms);
 8587:         if ($hidepriv) {
 8588:             my %coursehash=&Apache::lonnet::coursedescription($cdom.'_'.$cnum);
 8589:             foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
 8590:                 if ($user !~ /:/) {
 8591:                     $nothide{join(':',split(/[\@]/,$user))}=1;
 8592:                 } else {
 8593:                     $nothide{$user} = 1;
 8594:                 }
 8595:             }
 8596:             my @possdoms = ($cdom);
 8597:             if ($coursehash{'checkforpriv'}) {
 8598:                 push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
 8599:             }
 8600:         }
 8601:         foreach my $person (sort(keys(%coursepersonnel))) {
 8602:             my $match = 0;
 8603:             my $secmatch = 0;
 8604:             my $status;
 8605:             my ($role,$user,$usec) = ($person =~ /^([^:]*):([^:]+:[^:]+):([^:]*)/);
 8606:             $user =~ s/:$//;
 8607:             my ($end,$start) = split(/:/,$coursepersonnel{$person});
 8608:             if ($end == -1 || $start == -1) {
 8609:                 next;
 8610:             }
 8611:             if (($role) && ((grep(/^\Q$role\E$/,@{$roles})) ||
 8612:                 (grep(/^cr$/,@{$roles}) && $role =~ /^cr\//))) {
 8613:                 my ($uname,$udom) = split(/:/,$user);
 8614:                 if ((ref($sections) eq 'ARRAY') && (@{$sections} > 0)) {
 8615:                     if (grep(/^all$/,@{$sections})) {
 8616:                         $secmatch = 1;
 8617:                     } elsif ($usec eq '') {
 8618:                         if (grep(/^none$/,@{$sections})) {
 8619:                             $secmatch = 1;
 8620:                         }
 8621:                     } else {
 8622:                         if (grep(/^\Q$usec\E$/,@{$sections})) {
 8623:                             $secmatch = 1;
 8624:                         }
 8625:                     }
 8626:                     if (!$secmatch) {
 8627:                         next;
 8628:                     }
 8629:                 }
 8630:                 if ($usec eq '') {
 8631:                     $usec = 'none';
 8632:                 }
 8633:                 if ($uname ne '' && $udom ne '') {
 8634:                     if ($hidepriv) {
 8635:                         if ((&Apache::lonnet::privileged($uname,$udom,\@possdoms)) &&
 8636:                             (!$nothide{$uname.':'.$udom})) {
 8637:                             next;
 8638:                         }
 8639:                     }
 8640:                     if ($end > 0 && $end < $now) {
 8641:                         $status = 'previous';
 8642:                     } elsif ($start > $now) {
 8643:                         $status = 'future';
 8644:                     } else {
 8645:                         $status = 'active';
 8646:                     }
 8647:                     foreach my $type (keys(%{$types})) { 
 8648:                         if ($status eq $type) {
 8649:                             if (!grep(/^\Q$type\E$/,@{$$users{$role}{$user}})) {
 8650:                                 push(@{$$users{$role}{$user}},$type);
 8651:                             }
 8652:                             $match = 1;
 8653:                         }
 8654:                     }
 8655:                     if (($match) && (ref($userdata) eq 'HASH')) {
 8656:                         if (!exists($$userdata{$uname.':'.$udom})) {
 8657: 			    &get_user_info($udom,$uname,\%idx,$userdata);
 8658:                         }
 8659:                         if (!grep(/^\Q$usec\E$/,@{$seclists{$uname.':'.$udom}})) {
 8660:                             push(@{$seclists{$uname.':'.$udom}},$usec);
 8661:                         }
 8662:                         if (ref($statushash) eq 'HASH') {
 8663:                             $statushash->{$uname.':'.$udom}{$role}{$usec} = $displaystatus{$status};
 8664:                         }
 8665:                     }
 8666:                 }
 8667:             }
 8668:         }
 8669:         if (grep(/^ow$/,@{$roles})) {
 8670:             if ((defined($cdom)) && (defined($cnum))) {
 8671:                 my %csettings = &Apache::lonnet::get('environment',['internal.courseowner'],$cdom,$cnum);
 8672:                 if ( defined($csettings{'internal.courseowner'}) ) {
 8673:                     my $owner = $csettings{'internal.courseowner'};
 8674:                     next if ($owner eq '');
 8675:                     my ($ownername,$ownerdom);
 8676:                     if ($owner =~ /^([^:]+):([^:]+)$/) {
 8677:                         $ownername = $1;
 8678:                         $ownerdom = $2;
 8679:                     } else {
 8680:                         $ownername = $owner;
 8681:                         $ownerdom = $cdom;
 8682:                         $owner = $ownername.':'.$ownerdom;
 8683:                     }
 8684:                     @{$$users{'ow'}{$owner}} = 'any';
 8685:                     if (defined($userdata) && 
 8686: 			!exists($$userdata{$owner})) {
 8687: 			&get_user_info($ownerdom,$ownername,\%idx,$userdata);
 8688:                         if (!grep(/^none$/,@{$seclists{$owner}})) {
 8689:                             push(@{$seclists{$owner}},'none');
 8690:                         }
 8691:                         if (ref($statushash) eq 'HASH') {
 8692:                             $statushash->{$owner}{'ow'}{'none'} = 'Any';
 8693:                         }
 8694: 		    }
 8695:                 }
 8696:             }
 8697:         }
 8698:         foreach my $user (keys(%seclists)) {
 8699:             @{$seclists{$user}} = (sort {$a <=> $b} @{$seclists{$user}});
 8700:             $$userdata{$user}[$idx{section}] = join(',',@{$seclists{$user}});
 8701:         }
 8702:     }
 8703:     return;
 8704: }
 8705: 
 8706: sub get_user_info {
 8707:     my ($udom,$uname,$idx,$userdata) = @_;
 8708:     $$userdata{$uname.':'.$udom}[$$idx{fullname}] = 
 8709: 	&plainname($uname,$udom,'lastname');
 8710:     $$userdata{$uname.':'.$udom}[$$idx{uname}] = $uname;
 8711:     $$userdata{$uname.':'.$udom}[$$idx{udom}] = $udom;
 8712:     my %idhash =  &Apache::lonnet::idrget($udom,($uname));
 8713:     $$userdata{$uname.':'.$udom}[$$idx{id}] = $idhash{$uname}; 
 8714:     return;
 8715: }
 8716: 
 8717: ###############################################
 8718: 
 8719: =pod
 8720: 
 8721: =item * &get_user_quota()
 8722: 
 8723: Retrieves quota assigned for storage of user files.
 8724: Default is to report quota for portfolio files.
 8725: 
 8726: Incoming parameters:
 8727: 1. user's username
 8728: 2. user's domain
 8729: 3. quota name - portfolio, author, or course
 8730:    (if no quota name provided, defaults to portfolio).
 8731: 4. crstype - official, unofficial, textbook or community, if quota name is
 8732:    course
 8733: 
 8734: Returns:
 8735: 1. Disk quota (in MB) assigned to student.
 8736: 2. (Optional) Type of setting: custom or default
 8737:    (individually assigned or default for user's 
 8738:    institutional status).
 8739: 3. (Optional) - User's institutional status (e.g., faculty, staff
 8740:    or student - types as defined in localenroll::inst_usertypes 
 8741:    for user's domain, which determines default quota for user.
 8742: 4. (Optional) - Default quota which would apply to the user.
 8743: 
 8744: If a value has been stored in the user's environment, 
 8745: it will return that, otherwise it returns the maximal default
 8746: defined for the user's institutional status(es) in the domain.
 8747: 
 8748: =cut
 8749: 
 8750: ###############################################
 8751: 
 8752: 
 8753: sub get_user_quota {
 8754:     my ($uname,$udom,$quotaname,$crstype) = @_;
 8755:     my ($quota,$quotatype,$settingstatus,$defquota);
 8756:     if (!defined($udom)) {
 8757:         $udom = $env{'user.domain'};
 8758:     }
 8759:     if (!defined($uname)) {
 8760:         $uname = $env{'user.name'};
 8761:     }
 8762:     if (($udom eq '' || $uname eq '') ||
 8763:         ($udom eq 'public') && ($uname eq 'public')) {
 8764:         $quota = 0;
 8765:         $quotatype = 'default';
 8766:         $defquota = 0; 
 8767:     } else {
 8768:         my $inststatus;
 8769:         if ($quotaname eq 'course') {
 8770:             if (($env{'course.'.$udom.'_'.$uname.'.num'} eq $uname) &&
 8771:                 ($env{'course.'.$udom.'_'.$uname.'.domain'} eq $udom)) {
 8772:                 $quota = $env{'course.'.$udom.'_'.$uname.'.internal.uploadquota'};
 8773:             } else {
 8774:                 my %cenv = &Apache::lonnet::coursedescription("$udom/$uname");
 8775:                 $quota = $cenv{'internal.uploadquota'};
 8776:             }
 8777:         } else {
 8778:             if ($udom eq $env{'user.domain'} && $uname eq $env{'user.name'}) {
 8779:                 if ($quotaname eq 'author') {
 8780:                     $quota = $env{'environment.authorquota'};
 8781:                 } else {
 8782:                     $quota = $env{'environment.portfolioquota'};
 8783:                 }
 8784:                 $inststatus = $env{'environment.inststatus'};
 8785:             } else {
 8786:                 my %userenv = 
 8787:                     &Apache::lonnet::get('environment',['portfolioquota',
 8788:                                          'authorquota','inststatus'],$udom,$uname);
 8789:                 my ($tmp) = keys(%userenv);
 8790:                 if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
 8791:                     if ($quotaname eq 'author') {
 8792:                         $quota = $userenv{'authorquota'};
 8793:                     } else {
 8794:                         $quota = $userenv{'portfolioquota'};
 8795:                     }
 8796:                     $inststatus = $userenv{'inststatus'};
 8797:                 } else {
 8798:                     undef(%userenv);
 8799:                 }
 8800:             }
 8801:         }
 8802:         if ($quota eq '' || wantarray) {
 8803:             if ($quotaname eq 'course') {
 8804:                 my %domdefs = &Apache::lonnet::get_domain_defaults($udom);
 8805:                 if (($crstype eq 'official') || ($crstype eq 'unofficial') || 
 8806:                     ($crstype eq 'community') || ($crstype eq 'textbook')) { 
 8807:                     $defquota = $domdefs{$crstype.'quota'};
 8808:                 }
 8809:                 if ($defquota eq '') {
 8810:                     $defquota = 500;
 8811:                 }
 8812:             } else {
 8813:                 ($defquota,$settingstatus) = &default_quota($udom,$inststatus,$quotaname);
 8814:             }
 8815:             if ($quota eq '') {
 8816:                 $quota = $defquota;
 8817:                 $quotatype = 'default';
 8818:             } else {
 8819:                 $quotatype = 'custom';
 8820:             }
 8821:         }
 8822:     }
 8823:     if (wantarray) {
 8824:         return ($quota,$quotatype,$settingstatus,$defquota);
 8825:     } else {
 8826:         return $quota;
 8827:     }
 8828: }
 8829: 
 8830: ###############################################
 8831: 
 8832: =pod
 8833: 
 8834: =item * &default_quota()
 8835: 
 8836: Retrieves default quota assigned for storage of user portfolio files,
 8837: given an (optional) user's institutional status.
 8838: 
 8839: Incoming parameters:
 8840: 
 8841: 1. domain
 8842: 2. (Optional) institutional status(es).  This is a : separated list of 
 8843:    status types (e.g., faculty, staff, student etc.)
 8844:    which apply to the user for whom the default is being retrieved.
 8845:    If the institutional status string in undefined, the domain
 8846:    default quota will be returned.
 8847: 3.  quota name - portfolio, author, or course
 8848:    (if no quota name provided, defaults to portfolio).
 8849: 
 8850: Returns:
 8851: 
 8852: 1. Default disk quota (in MB) for user portfolios in the domain.
 8853: 2. (Optional) institutional type which determined the value of the
 8854:    default quota.
 8855: 
 8856: If a value has been stored in the domain's configuration db,
 8857: it will return that, otherwise it returns 20 (for backwards 
 8858: compatibility with domains which have not set up a configuration
 8859: db file; the original statically defined portfolio quota was 20 MB). 
 8860: 
 8861: If the user's status includes multiple types (e.g., staff and student),
 8862: the largest default quota which applies to the user determines the
 8863: default quota returned.
 8864: 
 8865: =cut
 8866: 
 8867: ###############################################
 8868: 
 8869: 
 8870: sub default_quota {
 8871:     my ($udom,$inststatus,$quotaname) = @_;
 8872:     my ($defquota,$settingstatus);
 8873:     my %quotahash = &Apache::lonnet::get_dom('configuration',
 8874:                                             ['quotas'],$udom);
 8875:     my $key = 'defaultquota';
 8876:     if ($quotaname eq 'author') {
 8877:         $key = 'authorquota';
 8878:     }
 8879:     if (ref($quotahash{'quotas'}) eq 'HASH') {
 8880:         if ($inststatus ne '') {
 8881:             my @statuses = map { &unescape($_); } split(/:/,$inststatus);
 8882:             foreach my $item (@statuses) {
 8883:                 if (ref($quotahash{'quotas'}{$key}) eq 'HASH') {
 8884:                     if ($quotahash{'quotas'}{$key}{$item} ne '') {
 8885:                         if ($defquota eq '') {
 8886:                             $defquota = $quotahash{'quotas'}{$key}{$item};
 8887:                             $settingstatus = $item;
 8888:                         } elsif ($quotahash{'quotas'}{$key}{$item} > $defquota) {
 8889:                             $defquota = $quotahash{'quotas'}{$key}{$item};
 8890:                             $settingstatus = $item;
 8891:                         }
 8892:                     }
 8893:                 } elsif ($key eq 'defaultquota') {
 8894:                     if ($quotahash{'quotas'}{$item} ne '') {
 8895:                         if ($defquota eq '') {
 8896:                             $defquota = $quotahash{'quotas'}{$item};
 8897:                             $settingstatus = $item;
 8898:                         } elsif ($quotahash{'quotas'}{$item} > $defquota) {
 8899:                             $defquota = $quotahash{'quotas'}{$item};
 8900:                             $settingstatus = $item;
 8901:                         }
 8902:                     }
 8903:                 }
 8904:             }
 8905:         }
 8906:         if ($defquota eq '') {
 8907:             if (ref($quotahash{'quotas'}{$key}) eq 'HASH') {
 8908:                 $defquota = $quotahash{'quotas'}{$key}{'default'};
 8909:             } elsif ($key eq 'defaultquota') {
 8910:                 $defquota = $quotahash{'quotas'}{'default'};
 8911:             }
 8912:             $settingstatus = 'default';
 8913:             if ($defquota eq '') {
 8914:                 if ($quotaname eq 'author') {
 8915:                     $defquota = 500;
 8916:                 }
 8917:             }
 8918:         }
 8919:     } else {
 8920:         $settingstatus = 'default';
 8921:         if ($quotaname eq 'author') {
 8922:             $defquota = 500;
 8923:         } else {
 8924:             $defquota = 20;
 8925:         }
 8926:     }
 8927:     if (wantarray) {
 8928:         return ($defquota,$settingstatus);
 8929:     } else {
 8930:         return $defquota;
 8931:     }
 8932: }
 8933: 
 8934: ###############################################
 8935: 
 8936: =pod
 8937: 
 8938: =item * &excess_filesize_warning()
 8939: 
 8940: Returns warning message if upload of file to authoring space, or copying
 8941: of existing file within authoring space will cause quota for the authoring
 8942: space to be exceeded.
 8943: 
 8944: Same, if upload of a file directly to a course/community via Course Editor
 8945: will cause quota for uploaded content for the course to be exceeded.
 8946: 
 8947: Inputs: 7 
 8948: 1. username or coursenum
 8949: 2. domain
 8950: 3. context ('author' or 'course')
 8951: 4. filename of file for which action is being requested
 8952: 5. filesize (kB) of file
 8953: 6. action being taken: copy or upload.
 8954: 7. quotatype (in course context -- official, unofficial, community or textbook).
 8955: 
 8956: Returns: 1 scalar: HTML to display containing warning if quota would be exceeded,
 8957:          otherwise return null.
 8958: 
 8959: =back
 8960: 
 8961: =cut
 8962: 
 8963: sub excess_filesize_warning {
 8964:     my ($uname,$udom,$context,$filename,$filesize,$action,$quotatype) = @_;
 8965:     my $current_disk_usage = 0;
 8966:     my $disk_quota = &get_user_quota($uname,$udom,$context,$quotatype); #expressed in MB
 8967:     if ($context eq 'author') {
 8968:         my $authorspace = $Apache::lonnet::perlvar{'lonDocRoot'}."/priv/$udom/$uname";
 8969:         $current_disk_usage = &Apache::lonnet::diskusage($udom,$uname,$authorspace);
 8970:     } else {
 8971:         foreach my $subdir ('docs','supplemental') {
 8972:             $current_disk_usage += &Apache::lonnet::diskusage($udom,$uname,"userfiles/$subdir",1);
 8973:         }
 8974:     }
 8975:     $disk_quota = int($disk_quota * 1000);
 8976:     if (($current_disk_usage + $filesize) > $disk_quota) {
 8977:         return '<p class="LC_warning">'.
 8978:                 &mt("Unable to $action [_1]. (size = [_2] kilobytes). Disk quota will be exceeded.",
 8979:                     '<span class="LC_filename">'.$filename.'</span>',$filesize).'</p>'.
 8980:                '<p>'.&mt('Disk quota is [_1] kilobytes. Your current disk usage is [_2] kilobytes.',
 8981:                             $disk_quota,$current_disk_usage).
 8982:                '</p>';
 8983:     }
 8984:     return;
 8985: }
 8986: 
 8987: ###############################################
 8988: 
 8989: 
 8990: 
 8991: 
 8992: sub get_secgrprole_info {
 8993:     my ($cdom,$cnum,$needroles,$type)  = @_;
 8994:     my %sections_count = &get_sections($cdom,$cnum);
 8995:     my @sections =  (sort {$a <=> $b} keys(%sections_count));
 8996:     my %curr_groups = &Apache::longroup::coursegroups($cdom,$cnum);
 8997:     my @groups = sort(keys(%curr_groups));
 8998:     my $allroles = [];
 8999:     my $rolehash;
 9000:     my $accesshash = {
 9001:                      active => 'Currently has access',
 9002:                      future => 'Will have future access',
 9003:                      previous => 'Previously had access',
 9004:                   };
 9005:     if ($needroles) {
 9006:         $rolehash = {'all' => 'all'};
 9007:         my %user_roles = &Apache::lonnet::dump('nohist_userroles',$cdom,$cnum);
 9008: 	if (&Apache::lonnet::error(%user_roles)) {
 9009: 	    undef(%user_roles);
 9010: 	}
 9011:         foreach my $item (keys(%user_roles)) {
 9012:             my ($role)=split(/\:/,$item,2);
 9013:             if ($role eq 'cr') { next; }
 9014:             if ($role =~ /^cr/) {
 9015:                 $$rolehash{$role} = (split('/',$role))[3];
 9016:             } else {
 9017:                 $$rolehash{$role} = &Apache::lonnet::plaintext($role,$type);
 9018:             }
 9019:         }
 9020:         foreach my $key (sort(keys(%{$rolehash}))) {
 9021:             push(@{$allroles},$key);
 9022:         }
 9023:         push (@{$allroles},'st');
 9024:         $$rolehash{'st'} = &Apache::lonnet::plaintext('st',$type);
 9025:     }
 9026:     return (\@sections,\@groups,$allroles,$rolehash,$accesshash);
 9027: }
 9028: 
 9029: sub user_picker {
 9030:     my ($dom,$srch,$forcenewuser,$caller,$cancreate,$usertype,$context) = @_;
 9031:     my $currdom = $dom;
 9032:     my %curr_selected = (
 9033:                         srchin => 'dom',
 9034:                         srchby => 'lastname',
 9035:                       );
 9036:     my $srchterm;
 9037:     if ((ref($srch) eq 'HASH') && ($env{'form.origform'} ne 'crtusername')) {
 9038:         if ($srch->{'srchby'} ne '') {
 9039:             $curr_selected{'srchby'} = $srch->{'srchby'};
 9040:         }
 9041:         if ($srch->{'srchin'} ne '') {
 9042:             $curr_selected{'srchin'} = $srch->{'srchin'};
 9043:         }
 9044:         if ($srch->{'srchtype'} ne '') {
 9045:             $curr_selected{'srchtype'} = $srch->{'srchtype'};
 9046:         }
 9047:         if ($srch->{'srchdomain'} ne '') {
 9048:             $currdom = $srch->{'srchdomain'};
 9049:         }
 9050:         $srchterm = $srch->{'srchterm'};
 9051:     }
 9052:     my %lt=&Apache::lonlocal::texthash(
 9053:                     'usr'       => 'Search criteria',
 9054:                     'doma'      => 'Domain/institution to search',
 9055:                     'uname'     => 'username',
 9056:                     'lastname'  => 'last name',
 9057:                     'lastfirst' => 'last name, first name',
 9058:                     'crs'       => 'in this course',
 9059:                     'dom'       => 'in selected LON-CAPA domain', 
 9060:                     'alc'       => 'all LON-CAPA',
 9061:                     'instd'     => 'in institutional directory for selected domain',
 9062:                     'exact'     => 'is',
 9063:                     'contains'  => 'contains',
 9064:                     'begins'    => 'begins with',
 9065:                     'youm'      => "You must include some text to search for.",
 9066:                     'thte'      => "The text you are searching for must contain at least two characters when using a 'begins' type search.",
 9067:                     'thet'      => "The text you are searching for must contain at least three characters when using a 'contains' type search.",
 9068:                     'yomc'      => "You must choose a domain when using an institutional directory search.",
 9069:                     'ymcd'      => "You must choose a domain when using a domain search.",
 9070:                     'whus'      => "When using searching by last,first you must include a comma as separator between last name and first name.",
 9071:                     'whse'      => "When searching by last,first you must include at least one character in the first name.",
 9072:                      'thfo'     => "The following need to be corrected before the search can be run:",
 9073:                                        );
 9074:     my $domform = &select_dom_form($currdom,'srchdomain',1,1);
 9075:     my $srchinsel = ' <select name="srchin">';
 9076: 
 9077:     my @srchins = ('crs','dom','alc','instd');
 9078: 
 9079:     foreach my $option (@srchins) {
 9080:         # FIXME 'alc' option unavailable until 
 9081:         #       loncreateuser::print_user_query_page()
 9082:         #       has been completed.
 9083:         next if ($option eq 'alc');
 9084:         next if (($option eq 'crs') && ($env{'form.form'} eq 'requestcrs'));  
 9085:         next if ($option eq 'crs' && !$env{'request.course.id'});
 9086:         if ($curr_selected{'srchin'} eq $option) {
 9087:             $srchinsel .= ' 
 9088:    <option value="'.$option.'" selected="selected">'.$lt{$option}.'</option>';
 9089:         } else {
 9090:             $srchinsel .= '
 9091:    <option value="'.$option.'">'.$lt{$option}.'</option>';
 9092:         }
 9093:     }
 9094:     $srchinsel .= "\n  </select>\n";
 9095: 
 9096:     my $srchbysel =  ' <select name="srchby">';
 9097:     foreach my $option ('lastname','lastfirst','uname') {
 9098:         if ($curr_selected{'srchby'} eq $option) {
 9099:             $srchbysel .= '
 9100:    <option value="'.$option.'" selected="selected">'.$lt{$option}.'</option>';
 9101:         } else {
 9102:             $srchbysel .= '
 9103:    <option value="'.$option.'">'.$lt{$option}.'</option>';
 9104:          }
 9105:     }
 9106:     $srchbysel .= "\n  </select>\n";
 9107: 
 9108:     my $srchtypesel = ' <select name="srchtype">';
 9109:     foreach my $option ('begins','contains','exact') {
 9110:         if ($curr_selected{'srchtype'} eq $option) {
 9111:             $srchtypesel .= '
 9112:    <option value="'.$option.'" selected="selected">'.$lt{$option}.'</option>';
 9113:         } else {
 9114:             $srchtypesel .= '
 9115:    <option value="'.$option.'">'.$lt{$option}.'</option>';
 9116:         }
 9117:     }
 9118:     $srchtypesel .= "\n  </select>\n";
 9119: 
 9120:     my ($newuserscript,$new_user_create);
 9121:     my $context_dom = $env{'request.role.domain'};
 9122:     if ($context eq 'requestcrs') {
 9123:         if ($env{'form.coursedom'} ne '') { 
 9124:             $context_dom = $env{'form.coursedom'};
 9125:         }
 9126:     }
 9127:     if ($forcenewuser) {
 9128:         if (ref($srch) eq 'HASH') {
 9129:             if ($srch->{'srchby'} eq 'uname' && $srch->{'srchtype'} eq 'exact' && $srch->{'srchin'} eq 'dom' && $srch->{'srchdomain'} eq $context_dom) {
 9130:                 if ($cancreate) {
 9131:                     $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>';
 9132:                 } else {
 9133:                     my $helplink = 'javascript:helpMenu('."'display'".')';
 9134:                     my %usertypetext = (
 9135:                         official   => 'institutional',
 9136:                         unofficial => 'non-institutional',
 9137:                     );
 9138:                     $new_user_create = '<p class="LC_warning">'
 9139:                                       .&mt("You are not authorized to create new $usertypetext{$usertype} users in this domain.")
 9140:                                       .' '
 9141:                                       .&mt('Please contact the [_1]helpdesk[_2] for assistance.'
 9142:                                           ,'<a href="'.$helplink.'">','</a>')
 9143:                                       .'</p><br />';
 9144:                 }
 9145:             }
 9146:         }
 9147: 
 9148:         $newuserscript = <<"ENDSCRIPT";
 9149: 
 9150: function setSearch(createnew,callingForm) {
 9151:     if (createnew == 1) {
 9152:         for (var i=0; i<callingForm.srchby.length; i++) {
 9153:             if (callingForm.srchby.options[i].value == 'uname') {
 9154:                 callingForm.srchby.selectedIndex = i;
 9155:             }
 9156:         }
 9157:         for (var i=0; i<callingForm.srchin.length; i++) {
 9158:             if ( callingForm.srchin.options[i].value == 'dom') {
 9159: 		callingForm.srchin.selectedIndex = i;
 9160:             }
 9161:         }
 9162:         for (var i=0; i<callingForm.srchtype.length; i++) {
 9163:             if (callingForm.srchtype.options[i].value == 'exact') {
 9164:                 callingForm.srchtype.selectedIndex = i;
 9165:             }
 9166:         }
 9167:         for (var i=0; i<callingForm.srchdomain.length; i++) {
 9168:             if (callingForm.srchdomain.options[i].value == '$context_dom') {
 9169:                 callingForm.srchdomain.selectedIndex = i;
 9170:             }
 9171:         }
 9172:     }
 9173: }
 9174: ENDSCRIPT
 9175: 
 9176:     }
 9177: 
 9178:     my $output = <<"END_BLOCK";
 9179: <script type="text/javascript">
 9180: // <![CDATA[
 9181: function validateEntry(callingForm) {
 9182: 
 9183:     var checkok = 1;
 9184:     var srchin;
 9185:     for (var i=0; i<callingForm.srchin.length; i++) {
 9186: 	if ( callingForm.srchin[i].checked ) {
 9187: 	    srchin = callingForm.srchin[i].value;
 9188: 	}
 9189:     }
 9190: 
 9191:     var srchtype = callingForm.srchtype.options[callingForm.srchtype.selectedIndex].value;
 9192:     var srchby = callingForm.srchby.options[callingForm.srchby.selectedIndex].value;
 9193:     var srchdomain = callingForm.srchdomain.options[callingForm.srchdomain.selectedIndex].value;
 9194:     var srchterm =  callingForm.srchterm.value;
 9195:     var srchin = callingForm.srchin.options[callingForm.srchin.selectedIndex].value;
 9196:     var msg = "";
 9197: 
 9198:     if (srchterm == "") {
 9199:         checkok = 0;
 9200:         msg += "$lt{'youm'}\\n";
 9201:     }
 9202: 
 9203:     if (srchtype== 'begins') {
 9204:         if (srchterm.length < 2) {
 9205:             checkok = 0;
 9206:             msg += "$lt{'thte'}\\n";
 9207:         }
 9208:     }
 9209: 
 9210:     if (srchtype== 'contains') {
 9211:         if (srchterm.length < 3) {
 9212:             checkok = 0;
 9213:             msg += "$lt{'thet'}\\n";
 9214:         }
 9215:     }
 9216:     if (srchin == 'instd') {
 9217:         if (srchdomain == '') {
 9218:             checkok = 0;
 9219:             msg += "$lt{'yomc'}\\n";
 9220:         }
 9221:     }
 9222:     if (srchin == 'dom') {
 9223:         if (srchdomain == '') {
 9224:             checkok = 0;
 9225:             msg += "$lt{'ymcd'}\\n";
 9226:         }
 9227:     }
 9228:     if (srchby == 'lastfirst') {
 9229:         if (srchterm.indexOf(",") == -1) {
 9230:             checkok = 0;
 9231:             msg += "$lt{'whus'}\\n";
 9232:         }
 9233:         if (srchterm.indexOf(",") == srchterm.length -1) {
 9234:             checkok = 0;
 9235:             msg += "$lt{'whse'}\\n";
 9236:         }
 9237:     }
 9238:     if (checkok == 0) {
 9239:         alert("$lt{'thfo'}\\n"+msg);
 9240:         return;
 9241:     }
 9242:     if (checkok == 1) {
 9243:         callingForm.submit();
 9244:     }
 9245: }
 9246: 
 9247: $newuserscript
 9248: 
 9249: // ]]>
 9250: </script>
 9251: 
 9252: $new_user_create
 9253: 
 9254: END_BLOCK
 9255: 
 9256:     $output .= &Apache::lonhtmlcommon::start_pick_box().
 9257:                &Apache::lonhtmlcommon::row_title($lt{'doma'}).
 9258:                $domform.
 9259:                &Apache::lonhtmlcommon::row_closure().
 9260:                &Apache::lonhtmlcommon::row_title($lt{'usr'}).
 9261:                $srchbysel.
 9262:                $srchtypesel. 
 9263:                '<input type="text" size="15" name="srchterm" value="'.$srchterm.'" />'.
 9264:                $srchinsel.
 9265:                &Apache::lonhtmlcommon::row_closure(1). 
 9266:                &Apache::lonhtmlcommon::end_pick_box().
 9267:                '<br />';
 9268:     return $output;
 9269: }
 9270: 
 9271: sub user_rule_check {
 9272:     my ($usershash,$checks,$alerts,$rulematch,$inst_results,$curr_rules,$got_rules) = @_;
 9273:     my $response;
 9274:     if (ref($usershash) eq 'HASH') {
 9275:         foreach my $user (keys(%{$usershash})) {
 9276:             my ($uname,$udom) = split(/:/,$user);
 9277:             next if ($udom eq '' || $uname eq '');
 9278:             my ($id,$newuser);
 9279:             if (ref($usershash->{$user}) eq 'HASH') {
 9280:                 $newuser = $usershash->{$user}->{'newuser'};
 9281:                 $id = $usershash->{$user}->{'id'};
 9282:             }
 9283:             my $inst_response;
 9284:             if (ref($checks) eq 'HASH') {
 9285:                 if (defined($checks->{'username'})) {
 9286:                     ($inst_response,%{$inst_results->{$user}}) = 
 9287:                         &Apache::lonnet::get_instuser($udom,$uname);
 9288:                 } elsif (defined($checks->{'id'})) {
 9289:                     ($inst_response,%{$inst_results->{$user}}) =
 9290:                         &Apache::lonnet::get_instuser($udom,undef,$id);
 9291:                 }
 9292:             } else {
 9293:                 ($inst_response,%{$inst_results->{$user}}) =
 9294:                     &Apache::lonnet::get_instuser($udom,$uname);
 9295:                 return;
 9296:             }
 9297:             if (!$got_rules->{$udom}) {
 9298:                 my %domconfig = &Apache::lonnet::get_dom('configuration',
 9299:                                                   ['usercreation'],$udom);
 9300:                 if (ref($domconfig{'usercreation'}) eq 'HASH') {
 9301:                     foreach my $item ('username','id') {
 9302:                         if (ref($domconfig{'usercreation'}{$item.'_rule'}) eq 'ARRAY') {
 9303:                             $$curr_rules{$udom}{$item} = 
 9304:                                 $domconfig{'usercreation'}{$item.'_rule'};
 9305:                         }
 9306:                     }
 9307:                 }
 9308:                 $got_rules->{$udom} = 1;  
 9309:             }
 9310:             foreach my $item (keys(%{$checks})) {
 9311:                 if (ref($$curr_rules{$udom}) eq 'HASH') {
 9312:                     if (ref($$curr_rules{$udom}{$item}) eq 'ARRAY') {
 9313:                         if (@{$$curr_rules{$udom}{$item}} > 0) {
 9314:                             my %rule_check = &Apache::lonnet::inst_rulecheck($udom,$uname,$id,$item,$$curr_rules{$udom}{$item});
 9315:                             foreach my $rule (@{$$curr_rules{$udom}{$item}}) {
 9316:                                 if ($rule_check{$rule}) {
 9317:                                     $$rulematch{$user}{$item} = $rule;
 9318:                                     if ($inst_response eq 'ok') {
 9319:                                         if (ref($inst_results) eq 'HASH') {
 9320:                                             if (ref($inst_results->{$user}) eq 'HASH') {
 9321:                                                 if (keys(%{$inst_results->{$user}}) == 0) {
 9322:                                                     $$alerts{$item}{$udom}{$uname} = 1;
 9323:                                                 }
 9324:                                             }
 9325:                                         }
 9326:                                     }
 9327:                                     last;
 9328:                                 }
 9329:                             }
 9330:                         }
 9331:                     }
 9332:                 }
 9333:             }
 9334:         }
 9335:     }
 9336:     return;
 9337: }
 9338: 
 9339: sub user_rule_formats {
 9340:     my ($domain,$domdesc,$curr_rules,$check) = @_;
 9341:     my %text = ( 
 9342:                  'username' => 'Usernames',
 9343:                  'id'       => 'IDs',
 9344:                );
 9345:     my $output;
 9346:     my ($rules,$ruleorder) = &Apache::lonnet::inst_userrules($domain,$check);
 9347:     if ((ref($rules) eq 'HASH') && (ref($ruleorder) eq 'ARRAY')) {
 9348:         if (@{$ruleorder} > 0) {
 9349:             $output = '<br />'.
 9350:                       &mt($text{$check}.' with the following format(s) may [_1]only[_2] be used for verified users at [_3]:',
 9351:                           '<span class="LC_cusr_emph">','</span>',$domdesc).
 9352:                       ' <ul>';
 9353:             foreach my $rule (@{$ruleorder}) {
 9354:                 if (ref($curr_rules) eq 'ARRAY') {
 9355:                     if (grep(/^\Q$rule\E$/,@{$curr_rules})) {
 9356:                         if (ref($rules->{$rule}) eq 'HASH') {
 9357:                             $output .= '<li>'.$rules->{$rule}{'name'}.': '.
 9358:                                         $rules->{$rule}{'desc'}.'</li>';
 9359:                         }
 9360:                     }
 9361:                 }
 9362:             }
 9363:             $output .= '</ul>';
 9364:         }
 9365:     }
 9366:     return $output;
 9367: }
 9368: 
 9369: sub instrule_disallow_msg {
 9370:     my ($checkitem,$domdesc,$count,$mode) = @_;
 9371:     my $response;
 9372:     my %text = (
 9373:                   item   => 'username',
 9374:                   items  => 'usernames',
 9375:                   match  => 'matches',
 9376:                   do     => 'does',
 9377:                   action => 'a username',
 9378:                   one    => 'one',
 9379:                );
 9380:     if ($count > 1) {
 9381:         $text{'item'} = 'usernames';
 9382:         $text{'match'} ='match';
 9383:         $text{'do'} = 'do';
 9384:         $text{'action'} = 'usernames',
 9385:         $text{'one'} = 'ones';
 9386:     }
 9387:     if ($checkitem eq 'id') {
 9388:         $text{'items'} = 'IDs';
 9389:         $text{'item'} = 'ID';
 9390:         $text{'action'} = 'an ID';
 9391:         if ($count > 1) {
 9392:             $text{'item'} = 'IDs';
 9393:             $text{'action'} = 'IDs';
 9394:         }
 9395:     }
 9396:     $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 />';
 9397:     if ($mode eq 'upload') {
 9398:         if ($checkitem eq 'username') {
 9399:             $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'}.");
 9400:         } elsif ($checkitem eq 'id') {
 9401:             $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.");
 9402:         }
 9403:     } elsif ($mode eq 'selfcreate') {
 9404:         if ($checkitem eq 'id') {
 9405:             $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.");
 9406:         }
 9407:     } else {
 9408:         if ($checkitem eq 'username') {
 9409:             $response .= &mt("You must choose $text{'action'} with a different format --  $text{'one'} that will not conflict with 'official' institutional $text{'items'}.");
 9410:         } elsif ($checkitem eq 'id') {
 9411:             $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.");
 9412:         }
 9413:     }
 9414:     return $response;
 9415: }
 9416: 
 9417: sub personal_data_fieldtitles {
 9418:     my %fieldtitles = &Apache::lonlocal::texthash (
 9419:                         id => 'Student/Employee ID',
 9420:                         permanentemail => 'E-mail address',
 9421:                         lastname => 'Last Name',
 9422:                         firstname => 'First Name',
 9423:                         middlename => 'Middle Name',
 9424:                         generation => 'Generation',
 9425:                         gen => 'Generation',
 9426:                         inststatus => 'Affiliation',
 9427:                    );
 9428:     return %fieldtitles;
 9429: }
 9430: 
 9431: sub sorted_inst_types {
 9432:     my ($dom) = @_;
 9433:     my ($usertypes,$order);
 9434:     my %domdefaults = &Apache::lonnet::get_domain_defaults($dom);
 9435:     if (ref($domdefaults{'inststatus'}) eq 'HASH') {
 9436:         $usertypes = $domdefaults{'inststatus'}{'inststatustypes'};
 9437:         $order = $domdefaults{'inststatus'}{'inststatusorder'};
 9438:     } else {
 9439:         ($usertypes,$order) = &Apache::lonnet::retrieve_inst_usertypes($dom);
 9440:     }
 9441:     my $othertitle = &mt('All users');
 9442:     if ($env{'request.course.id'}) {
 9443:         $othertitle  = &mt('Any users');
 9444:     }
 9445:     my @types;
 9446:     if (ref($order) eq 'ARRAY') {
 9447:         @types = @{$order};
 9448:     }
 9449:     if (@types == 0) {
 9450:         if (ref($usertypes) eq 'HASH') {
 9451:             @types = sort(keys(%{$usertypes}));
 9452:         }
 9453:     }
 9454:     if (keys(%{$usertypes}) > 0) {
 9455:         $othertitle = &mt('Other users');
 9456:     }
 9457:     return ($othertitle,$usertypes,\@types);
 9458: }
 9459: 
 9460: sub get_institutional_codes {
 9461:     my ($settings,$allcourses,$LC_code) = @_;
 9462: # Get complete list of course sections to update
 9463:     my @currsections = ();
 9464:     my @currxlists = ();
 9465:     my $coursecode = $$settings{'internal.coursecode'};
 9466: 
 9467:     if ($$settings{'internal.sectionnums'} ne '') {
 9468:         @currsections = split(/,/,$$settings{'internal.sectionnums'});
 9469:     }
 9470: 
 9471:     if ($$settings{'internal.crosslistings'} ne '') {
 9472:         @currxlists = split(/,/,$$settings{'internal.crosslistings'});
 9473:     }
 9474: 
 9475:     if (@currxlists > 0) {
 9476:         foreach (@currxlists) {
 9477:             if (m/^([^:]+):(\w*)$/) {
 9478:                 unless (grep/^$1$/,@{$allcourses}) {
 9479:                     push @{$allcourses},$1;
 9480:                     $$LC_code{$1} = $2;
 9481:                 }
 9482:             }
 9483:         }
 9484:     }
 9485:  
 9486:     if (@currsections > 0) {
 9487:         foreach (@currsections) {
 9488:             if (m/^(\w+):(\w*)$/) {
 9489:                 my $sec = $coursecode.$1;
 9490:                 my $lc_sec = $2;
 9491:                 unless (grep/^$sec$/,@{$allcourses}) {
 9492:                     push @{$allcourses},$sec;
 9493:                     $$LC_code{$sec} = $lc_sec;
 9494:                 }
 9495:             }
 9496:         }
 9497:     }
 9498:     return;
 9499: }
 9500: 
 9501: sub get_standard_codeitems {
 9502:     return ('Year','Semester','Department','Number','Section');
 9503: }
 9504: 
 9505: =pod
 9506: 
 9507: =head1 Slot Helpers
 9508: 
 9509: =over 4
 9510: 
 9511: =item * sorted_slots()
 9512: 
 9513: Sorts an array of slot names in order of an optional sort key,
 9514: default sort is by slot start time (earliest first). 
 9515: 
 9516: Inputs:
 9517: 
 9518: =over 4
 9519: 
 9520: slotsarr  - Reference to array of unsorted slot names.
 9521: 
 9522: slots     - Reference to hash of hash, where outer hash keys are slot names.
 9523: 
 9524: sortkey   - Name of key in inner hash to be sorted on (e.g., starttime).
 9525: 
 9526: =back
 9527: 
 9528: Returns:
 9529: 
 9530: =over 4
 9531: 
 9532: sorted   - An array of slot names sorted by a specified sort key 
 9533:            (default sort key is start time of the slot).
 9534: 
 9535: =back
 9536: 
 9537: =cut
 9538: 
 9539: 
 9540: sub sorted_slots {
 9541:     my ($slotsarr,$slots,$sortkey) = @_;
 9542:     if ($sortkey eq '') {
 9543:         $sortkey = 'starttime';
 9544:     }
 9545:     my @sorted;
 9546:     if ((ref($slotsarr) eq 'ARRAY') && (ref($slots) eq 'HASH')) {
 9547:         @sorted =
 9548:             sort {
 9549:                      if (ref($slots->{$a}) && ref($slots->{$b})) {
 9550:                          return $slots->{$a}{$sortkey} <=> $slots->{$b}{$sortkey}
 9551:                      }
 9552:                      if (ref($slots->{$a})) { return -1;}
 9553:                      if (ref($slots->{$b})) { return 1;}
 9554:                      return 0;
 9555:                  } @{$slotsarr};
 9556:     }
 9557:     return @sorted;
 9558: }
 9559: 
 9560: =pod
 9561: 
 9562: =item * get_future_slots()
 9563: 
 9564: Inputs:
 9565: 
 9566: =over 4
 9567: 
 9568: cnum - course number
 9569: 
 9570: cdom - course domain
 9571: 
 9572: now - current UNIX time
 9573: 
 9574: symb - optional symb
 9575: 
 9576: =back
 9577: 
 9578: Returns:
 9579: 
 9580: =over 4
 9581: 
 9582: sorted_reservable - ref to array of student_schedulable slots currently 
 9583:                     reservable, ordered by end date of reservation period.
 9584: 
 9585: reservable_now - ref to hash of student_schedulable slots currently
 9586:                  reservable.
 9587: 
 9588:     Keys in inner hash are:
 9589:     (a) symb: either blank or symb to which slot use is restricted.
 9590:     (b) endreserve: end date of reservation period. 
 9591: 
 9592: sorted_future - ref to array of student_schedulable slots reservable in
 9593:                 the future, ordered by start date of reservation period.
 9594: 
 9595: future_reservable - ref to hash of student_schedulable slots reservable
 9596:                     in the future.
 9597: 
 9598:     Keys in inner hash are:
 9599:     (a) symb: either blank or symb to which slot use is restricted.
 9600:     (b) startreserve:  start date of reservation period.
 9601: 
 9602: =back
 9603: 
 9604: =cut
 9605: 
 9606: sub get_future_slots {
 9607:     my ($cnum,$cdom,$now,$symb) = @_;
 9608:     my (%reservable_now,%future_reservable,@sorted_reservable,@sorted_future);
 9609:     my %slots = &Apache::lonnet::get_course_slots($cnum,$cdom);
 9610:     foreach my $slot (keys(%slots)) {
 9611:         next unless($slots{$slot}->{'type'} eq 'schedulable_student');
 9612:         if ($symb) {
 9613:             next if (($slots{$slot}->{'symb'} ne '') && 
 9614:                      ($slots{$slot}->{'symb'} ne $symb));
 9615:         }
 9616:         if (($slots{$slot}->{'starttime'} > $now) &&
 9617:             ($slots{$slot}->{'endtime'} > $now)) {
 9618:             if (($slots{$slot}->{'allowedsections'}) || ($slots{$slot}->{'allowedusers'})) {
 9619:                 my $userallowed = 0;
 9620:                 if ($slots{$slot}->{'allowedsections'}) {
 9621:                     my @allowed_sec = split(',',$slots{$slot}->{'allowedsections'});
 9622:                     if (!defined($env{'request.role.sec'})
 9623:                         && grep(/^No section assigned$/,@allowed_sec)) {
 9624:                         $userallowed=1;
 9625:                     } else {
 9626:                         if (grep(/^\Q$env{'request.role.sec'}\E$/,@allowed_sec)) {
 9627:                             $userallowed=1;
 9628:                         }
 9629:                     }
 9630:                     unless ($userallowed) {
 9631:                         if (defined($env{'request.course.groups'})) {
 9632:                             my @groups = split(/:/,$env{'request.course.groups'});
 9633:                             foreach my $group (@groups) {
 9634:                                 if (grep(/^\Q$group\E$/,@allowed_sec)) {
 9635:                                     $userallowed=1;
 9636:                                     last;
 9637:                                 }
 9638:                             }
 9639:                         }
 9640:                     }
 9641:                 }
 9642:                 if ($slots{$slot}->{'allowedusers'}) {
 9643:                     my @allowed_users = split(',',$slots{$slot}->{'allowedusers'});
 9644:                     my $user = $env{'user.name'}.':'.$env{'user.domain'};
 9645:                     if (grep(/^\Q$user\E$/,@allowed_users)) {
 9646:                         $userallowed = 1;
 9647:                     }
 9648:                 }
 9649:                 next unless($userallowed);
 9650:             }
 9651:             my $startreserve = $slots{$slot}->{'startreserve'};
 9652:             my $endreserve = $slots{$slot}->{'endreserve'};
 9653:             my $symb = $slots{$slot}->{'symb'};
 9654:             if (($startreserve < $now) &&
 9655:                 (!$endreserve || $endreserve > $now)) {
 9656:                 my $lastres = $endreserve;
 9657:                 if (!$lastres) {
 9658:                     $lastres = $slots{$slot}->{'starttime'};
 9659:                 }
 9660:                 $reservable_now{$slot} = {
 9661:                                            symb       => $symb,
 9662:                                            endreserve => $lastres
 9663:                                          };
 9664:             } elsif (($startreserve > $now) &&
 9665:                      (!$endreserve || $endreserve > $startreserve)) {
 9666:                 $future_reservable{$slot} = {
 9667:                                               symb         => $symb,
 9668:                                               startreserve => $startreserve
 9669:                                             };
 9670:             }
 9671:         }
 9672:     }
 9673:     my @unsorted_reservable = keys(%reservable_now);
 9674:     if (@unsorted_reservable > 0) {
 9675:         @sorted_reservable = 
 9676:             &sorted_slots(\@unsorted_reservable,\%reservable_now,'endreserve');
 9677:     }
 9678:     my @unsorted_future = keys(%future_reservable);
 9679:     if (@unsorted_future > 0) {
 9680:         @sorted_future =
 9681:             &sorted_slots(\@unsorted_future,\%future_reservable,'startreserve');
 9682:     }
 9683:     return (\@sorted_reservable,\%reservable_now,\@sorted_future,\%future_reservable);
 9684: }
 9685: 
 9686: =pod
 9687: 
 9688: =back
 9689: 
 9690: =head1 HTTP Helpers
 9691: 
 9692: =over 4
 9693: 
 9694: =item * &get_unprocessed_cgi($query,$possible_names)
 9695: 
 9696: Modify the %env hash to contain unprocessed CGI form parameters held in
 9697: $query.  The parameters listed in $possible_names (an array reference),
 9698: will be set in $env{'form.name'} if they do not already exist.
 9699: 
 9700: Typically called with $ENV{'QUERY_STRING'} as the first parameter.  
 9701: $possible_names is an ref to an array of form element names.  As an example:
 9702: get_unprocessed_cgi($ENV{'QUERY_STRING'},['uname','udom']);
 9703: will result in $env{'form.uname'} and $env{'form.udom'} being set.
 9704: 
 9705: =cut
 9706: 
 9707: sub get_unprocessed_cgi {
 9708:   my ($query,$possible_names)= @_;
 9709:   # $Apache::lonxml::debug=1;
 9710:   foreach my $pair (split(/&/,$query)) {
 9711:     my ($name, $value) = split(/=/,$pair);
 9712:     $name = &unescape($name);
 9713:     if (!defined($possible_names) || (grep {$_ eq $name} @$possible_names)) {
 9714:       $value =~ tr/+/ /;
 9715:       $value =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack("C",hex($1))/eg;
 9716:       unless (defined($env{'form.'.$name})) { &add_to_env('form.'.$name,$value) };
 9717:     }
 9718:   }
 9719: }
 9720: 
 9721: =pod
 9722: 
 9723: =item * &cacheheader() 
 9724: 
 9725: returns cache-controlling header code
 9726: 
 9727: =cut
 9728: 
 9729: sub cacheheader {
 9730:     unless ($env{'request.method'} eq 'GET') { return ''; }
 9731:     my $date=strftime("%a, %d %b %Y %H:%M:%S GMT",gmtime);
 9732:     my $output .='<meta HTTP-EQUIV="Expires" CONTENT="'.$date.'" />
 9733:                 <meta HTTP-EQUIV="Cache-control" CONTENT="no-cache" />
 9734:                 <meta HTTP-EQUIV="Pragma" CONTENT="no-cache" />';
 9735:     return $output;
 9736: }
 9737: 
 9738: =pod
 9739: 
 9740: =item * &no_cache($r) 
 9741: 
 9742: specifies header code to not have cache
 9743: 
 9744: =cut
 9745: 
 9746: sub no_cache {
 9747:     my ($r) = @_;
 9748:     if ($ENV{'REQUEST_METHOD'} ne 'GET' &&
 9749: 	$env{'request.method'} ne 'GET') { return ''; }
 9750:     my $date=strftime("%a, %d %b %Y %H:%M:%S GMT",gmtime(time));
 9751:     $r->no_cache(1);
 9752:     $r->header_out("Expires" => $date);
 9753:     $r->header_out("Pragma" => "no-cache");
 9754: }
 9755: 
 9756: sub content_type {
 9757:     my ($r,$type,$charset) = @_;
 9758:     if ($r) {
 9759: 	#  Note that printout.pl calls this with undef for $r.
 9760: 	&no_cache($r);
 9761:     }
 9762:     if ($env{'browser.mathml'} && $type eq 'text/html') { $type='text/xml'; }
 9763:     unless ($charset) {
 9764: 	$charset=&Apache::lonlocal::current_encoding;
 9765:     }
 9766:     if ($charset) { $type.='; charset='.$charset; }
 9767:     if ($r) {
 9768: 	$r->content_type($type);
 9769:     } else {
 9770: 	print("Content-type: $type\n\n");
 9771:     }
 9772: }
 9773: 
 9774: =pod
 9775: 
 9776: =item * &add_to_env($name,$value) 
 9777: 
 9778: adds $name to the %env hash with value
 9779: $value, if $name already exists, the entry is converted to an array
 9780: reference and $value is added to the array.
 9781: 
 9782: =cut
 9783: 
 9784: sub add_to_env {
 9785:   my ($name,$value)=@_;
 9786:   if (defined($env{$name})) {
 9787:     if (ref($env{$name})) {
 9788:       #already have multiple values
 9789:       push(@{ $env{$name} },$value);
 9790:     } else {
 9791:       #first time seeing multiple values, convert hash entry to an arrayref
 9792:       my $first=$env{$name};
 9793:       undef($env{$name});
 9794:       push(@{ $env{$name} },$first,$value);
 9795:     }
 9796:   } else {
 9797:     $env{$name}=$value;
 9798:   }
 9799: }
 9800: 
 9801: =pod
 9802: 
 9803: =item * &get_env_multiple($name) 
 9804: 
 9805: gets $name from the %env hash, it seemlessly handles the cases where multiple
 9806: values may be defined and end up as an array ref.
 9807: 
 9808: returns an array of values
 9809: 
 9810: =cut
 9811: 
 9812: sub get_env_multiple {
 9813:     my ($name) = @_;
 9814:     my @values;
 9815:     if (defined($env{$name})) {
 9816:         # exists is it an array
 9817:         if (ref($env{$name})) {
 9818:             @values=@{ $env{$name} };
 9819:         } else {
 9820:             $values[0]=$env{$name};
 9821:         }
 9822:     }
 9823:     return(@values);
 9824: }
 9825: 
 9826: sub ask_for_embedded_content {
 9827:     my ($actionurl,$state,$allfiles,$codebase,$args)=@_;
 9828:     my (%subdependencies,%dependencies,%mapping,%existing,%newfiles,%pathchanges,
 9829:         %currsubfile,%unused,$rem);
 9830:     my $counter = 0;
 9831:     my $numnew = 0;
 9832:     my $numremref = 0;
 9833:     my $numinvalid = 0;
 9834:     my $numpathchg = 0;
 9835:     my $numexisting = 0;
 9836:     my $numunused = 0;
 9837:     my ($output,$upload_output,$toplevel,$url,$udom,$uname,$getpropath,$cdom,$cnum,
 9838:         $fileloc,$filename,$delete_output,$modify_output,$title,$symb,$path,$navmap);
 9839:     my $heading = &mt('Upload embedded files');
 9840:     my $buttontext = &mt('Upload');
 9841: 
 9842:     if ($env{'request.course.id'}) {
 9843:         if ($actionurl eq '/adm/dependencies') {
 9844:             $navmap = Apache::lonnavmaps::navmap->new();
 9845:         }
 9846:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 9847:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 9848:     }
 9849:     if (($actionurl eq '/adm/portfolio') || 
 9850:         ($actionurl eq '/adm/coursegrp_portfolio')) {
 9851:         my $current_path='/';
 9852:         if ($env{'form.currentpath'}) {
 9853:             $current_path = $env{'form.currentpath'};
 9854:         }
 9855:         if ($actionurl eq '/adm/coursegrp_portfolio') {
 9856:             $udom = $cdom;
 9857:             $uname = $cnum;
 9858:             $url = '/userfiles/groups/'.$env{'form.group'}.'/portfolio';
 9859:         } else {
 9860:             $udom = $env{'user.domain'};
 9861:             $uname = $env{'user.name'};
 9862:             $url = '/userfiles/portfolio';
 9863:         }
 9864:         $toplevel = $url.'/';
 9865:         $url .= $current_path;
 9866:         $getpropath = 1;
 9867:     } elsif (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank') ||
 9868:              ($actionurl eq '/adm/imsimport')) { 
 9869:         my ($udom,$uname,$rest) = ($args->{'current_path'} =~ m{/priv/($match_domain)/($match_username)/?(.*)$});
 9870:         $url = $Apache::lonnet::perlvar{'lonDocRoot'}."/priv/$udom/$uname/";
 9871:         $toplevel = $url;
 9872:         if ($rest ne '') {
 9873:             $url .= $rest;
 9874:         }
 9875:     } elsif ($actionurl eq '/adm/coursedocs') {
 9876:         if (ref($args) eq 'HASH') {
 9877:             $url = $args->{'docs_url'};
 9878:             $toplevel = $url;
 9879:             if ($args->{'context'} eq 'paste') {
 9880:                 ($cdom,$cnum) = ($url =~ m{^\Q/uploaded/\E($match_domain)/($match_courseid)/});
 9881:                 ($path) = 
 9882:                     ($toplevel =~ m{^(\Q/uploaded/$cdom/$cnum/\E(?:docs|supplemental)/(?:default|\d+)/\d+)/});
 9883:                 $fileloc = &Apache::lonnet::filelocation('',$toplevel);
 9884:                 $fileloc =~ s{^/}{};
 9885:             }
 9886:         }
 9887:     } elsif ($actionurl eq '/adm/dependencies')  {
 9888:         if ($env{'request.course.id'} ne '') {
 9889:             if (ref($args) eq 'HASH') {
 9890:                 $url = $args->{'docs_url'};
 9891:                 $title = $args->{'docs_title'};
 9892:                 $toplevel = $url; 
 9893:                 unless ($toplevel =~ m{^/}) {
 9894:                     $toplevel = "/$url";
 9895:                 }
 9896:                 ($rem) = ($toplevel =~ m{^(.+/)[^/]+$});
 9897:                 if ($toplevel =~ m{^(\Q/uploaded/$cdom/$cnum/portfolio/syllabus\E)}) {
 9898:                     $path = $1;
 9899:                 } else {
 9900:                     ($path) =
 9901:                         ($toplevel =~ m{^(\Q/uploaded/$cdom/$cnum/\E(?:docs|supplemental)/(?:default|\d+)/\d+)/});
 9902:                 }
 9903:                 $fileloc = &Apache::lonnet::filelocation('',$toplevel);
 9904:                 $fileloc =~ s{^/}{};
 9905:                 ($filename) = ($fileloc =~ m{.+/([^/]+)$});
 9906:                 $heading = &mt('Status of dependencies in [_1]',"$title ($filename)");
 9907:             }
 9908:         }
 9909:     } elsif ($actionurl eq "/public/$cdom/$cnum/syllabus") {
 9910:         $udom = $cdom;
 9911:         $uname = $cnum;
 9912:         $url = "/uploaded/$cdom/$cnum/portfolio/syllabus";
 9913:         $toplevel = $url;
 9914:         $path = $url;
 9915:         $fileloc = &Apache::lonnet::filelocation('',$toplevel).'/';
 9916:         $fileloc =~ s{^/}{};
 9917:     }
 9918:     foreach my $file (keys(%{$allfiles})) {
 9919:         my $embed_file;
 9920:         if (($path eq "/uploaded/$cdom/$cnum/portfolio/syllabus") && ($file =~ m{^\Q$path/\E(.+)$})) {
 9921:             $embed_file = $1;
 9922:         } else {
 9923:             $embed_file = $file;
 9924:         }
 9925:         my ($absolutepath,$cleaned_file);
 9926:         if ($embed_file =~ m{^\w+://}) {
 9927:             $cleaned_file = $embed_file;
 9928:             $newfiles{$cleaned_file} = 1;
 9929:             $mapping{$cleaned_file} = $embed_file;
 9930:         } else {
 9931:             $cleaned_file = &clean_path($embed_file);
 9932:             if ($embed_file =~ m{^/}) {
 9933:                 $absolutepath = $embed_file;
 9934:             }
 9935:             if ($cleaned_file =~ m{/}) {
 9936:                 my ($path,$fname) = ($cleaned_file =~ m{^(.+)/([^/]*)$});
 9937:                 $path = &check_for_traversal($path,$url,$toplevel);
 9938:                 my $item = $fname;
 9939:                 if ($path ne '') {
 9940:                     $item = $path.'/'.$fname;
 9941:                     $subdependencies{$path}{$fname} = 1;
 9942:                 } else {
 9943:                     $dependencies{$item} = 1;
 9944:                 }
 9945:                 if ($absolutepath) {
 9946:                     $mapping{$item} = $absolutepath;
 9947:                 } else {
 9948:                     $mapping{$item} = $embed_file;
 9949:                 }
 9950:             } else {
 9951:                 $dependencies{$embed_file} = 1;
 9952:                 if ($absolutepath) {
 9953:                     $mapping{$cleaned_file} = $absolutepath;
 9954:                 } else {
 9955:                     $mapping{$cleaned_file} = $embed_file;
 9956:                 }
 9957:             }
 9958:         }
 9959:     }
 9960:     my $dirptr = 16384;
 9961:     foreach my $path (keys(%subdependencies)) {
 9962:         $currsubfile{$path} = {};
 9963:         if (($actionurl eq '/adm/portfolio') || 
 9964:             ($actionurl eq '/adm/coursegrp_portfolio')) {
 9965:             my ($sublistref,$listerror) =
 9966:                 &Apache::lonnet::dirlist($url.$path,$udom,$uname,$getpropath);
 9967:             if (ref($sublistref) eq 'ARRAY') {
 9968:                 foreach my $line (@{$sublistref}) {
 9969:                     my ($file_name,$rest) = split(/\&/,$line,2);
 9970:                     $currsubfile{$path}{$file_name} = 1;
 9971:                 }
 9972:             }
 9973:         } elsif (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank')) {
 9974:             if (opendir(my $dir,$url.'/'.$path)) {
 9975:                 my @subdir_list = grep(!/^\./,readdir($dir));
 9976:                 map {$currsubfile{$path}{$_} = 1;} @subdir_list;
 9977:             }
 9978:         } elsif (($actionurl eq '/adm/dependencies') ||
 9979:                  (($actionurl eq '/adm/coursedocs') && (ref($args) eq 'HASH') &&
 9980:                   ($args->{'context'} eq 'paste')) ||
 9981:                  ($actionurl eq "/public/$cdom/$cnum/syllabus")) {
 9982:             if ($env{'request.course.id'} ne '') {
 9983:                 my $dir;
 9984:                 if ($actionurl eq "/public/$cdom/$cnum/syllabus") {
 9985:                     $dir = $fileloc;
 9986:                 } else {
 9987:                     ($dir) = ($fileloc =~ m{^(.+/)[^/]+$});
 9988:                 }
 9989:                 if ($dir ne '') {
 9990:                     my ($sublistref,$listerror) =
 9991:                         &Apache::lonnet::dirlist($dir.$path,$cdom,$cnum,$getpropath,undef,'/');
 9992:                     if (ref($sublistref) eq 'ARRAY') {
 9993:                         foreach my $line (@{$sublistref}) {
 9994:                             my ($file_name,$dom,undef,$testdir,undef,undef,undef,undef,$size,
 9995:                                 undef,$mtime)=split(/\&/,$line,12);
 9996:                             unless (($testdir&$dirptr) ||
 9997:                                     ($file_name =~ /^\.\.?$/)) {
 9998:                                 $currsubfile{$path}{$file_name} = [$size,$mtime];
 9999:                             }
10000:                         }
10001:                     }
10002:                 }
10003:             }
10004:         }
10005:         foreach my $file (keys(%{$subdependencies{$path}})) {
10006:             if (exists($currsubfile{$path}{$file})) {
10007:                 my $item = $path.'/'.$file;
10008:                 unless ($mapping{$item} eq $item) {
10009:                     $pathchanges{$item} = 1;
10010:                 }
10011:                 $existing{$item} = 1;
10012:                 $numexisting ++;
10013:             } else {
10014:                 $newfiles{$path.'/'.$file} = 1;
10015:             }
10016:         }
10017:         if ($actionurl eq '/adm/dependencies') {
10018:             foreach my $path (keys(%currsubfile)) {
10019:                 if (ref($currsubfile{$path}) eq 'HASH') {
10020:                     foreach my $file (keys(%{$currsubfile{$path}})) {
10021:                          unless ($subdependencies{$path}{$file}) {
10022:                              next if (($rem ne '') &&
10023:                                       (($env{"httpref.$rem"."$path/$file"} ne '') ||
10024:                                        (ref($navmap) &&
10025:                                        (($navmap->getResourceByUrl($rem."$path/$file") ne '') ||
10026:                                         (($file =~ /^(.*\.s?html?)\.bak$/i) &&
10027:                                          ($navmap->getResourceByUrl($rem."$path/$1")))))));
10028:                              $unused{$path.'/'.$file} = 1; 
10029:                          }
10030:                     }
10031:                 }
10032:             }
10033:         }
10034:     }
10035:     my %currfile;
10036:     if (($actionurl eq '/adm/portfolio') ||
10037:         ($actionurl eq '/adm/coursegrp_portfolio')) {
10038:         my ($dirlistref,$listerror) =
10039:             &Apache::lonnet::dirlist($url,$udom,$uname,$getpropath);
10040:         if (ref($dirlistref) eq 'ARRAY') {
10041:             foreach my $line (@{$dirlistref}) {
10042:                 my ($file_name,$rest) = split(/\&/,$line,2);
10043:                 $currfile{$file_name} = 1;
10044:             }
10045:         }
10046:     } elsif (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank')) {
10047:         if (opendir(my $dir,$url)) {
10048:             my @dir_list = grep(!/^\./,readdir($dir));
10049:             map {$currfile{$_} = 1;} @dir_list;
10050:         }
10051:     } elsif (($actionurl eq '/adm/dependencies') ||
10052:              (($actionurl eq '/adm/coursedocs') && (ref($args) eq 'HASH') &&
10053:               ($args->{'context'} eq 'paste')) ||
10054:              ($actionurl eq "/public/$cdom/$cnum/syllabus")) {
10055:         if ($env{'request.course.id'} ne '') {
10056:             my ($dir) = ($fileloc =~ m{^(.+/)[^/]+$});
10057:             if ($dir ne '') {
10058:                 my ($dirlistref,$listerror) =
10059:                     &Apache::lonnet::dirlist($dir,$cdom,$cnum,$getpropath,undef,'/');
10060:                 if (ref($dirlistref) eq 'ARRAY') {
10061:                     foreach my $line (@{$dirlistref}) {
10062:                         my ($file_name,$dom,undef,$testdir,undef,undef,undef,undef,
10063:                             $size,undef,$mtime)=split(/\&/,$line,12);
10064:                         unless (($testdir&$dirptr) ||
10065:                                 ($file_name =~ /^\.\.?$/)) {
10066:                             $currfile{$file_name} = [$size,$mtime];
10067:                         }
10068:                     }
10069:                 }
10070:             }
10071:         }
10072:     }
10073:     foreach my $file (keys(%dependencies)) {
10074:         if (exists($currfile{$file})) {
10075:             unless ($mapping{$file} eq $file) {
10076:                 $pathchanges{$file} = 1;
10077:             }
10078:             $existing{$file} = 1;
10079:             $numexisting ++;
10080:         } else {
10081:             $newfiles{$file} = 1;
10082:         }
10083:     }
10084:     foreach my $file (keys(%currfile)) {
10085:         unless (($file eq $filename) ||
10086:                 ($file eq $filename.'.bak') ||
10087:                 ($dependencies{$file})) {
10088:             if ($actionurl eq '/adm/dependencies') {
10089:                 unless ($toplevel =~ m{^\Q/uploaded/$cdom/$cnum/portfolio/syllabus\E}) {
10090:                     next if (($rem ne '') &&
10091:                              (($env{"httpref.$rem".$file} ne '') ||
10092:                               (ref($navmap) &&
10093:                               (($navmap->getResourceByUrl($rem.$file) ne '') ||
10094:                                (($file =~ /^(.*\.s?html?)\.bak$/i) &&
10095:                                 ($navmap->getResourceByUrl($rem.$1)))))));
10096:                 }
10097:             }
10098:             $unused{$file} = 1;
10099:         }
10100:     }
10101:     if (($actionurl eq '/adm/coursedocs') && (ref($args) eq 'HASH') &&
10102:         ($args->{'context'} eq 'paste')) {
10103:         $counter = scalar(keys(%existing));
10104:         $numpathchg = scalar(keys(%pathchanges));
10105:         return ($output,$counter,$numpathchg,\%existing);
10106:     } elsif (($actionurl eq "/public/$cdom/$cnum/syllabus") && 
10107:              (ref($args) eq 'HASH') && ($args->{'context'} eq 'rewrites')) {
10108:         $counter = scalar(keys(%existing));
10109:         $numpathchg = scalar(keys(%pathchanges));
10110:         return ($output,$counter,$numpathchg,\%existing,\%mapping);
10111:     }
10112:     foreach my $embed_file (sort {lc($a) cmp lc($b)} keys(%newfiles)) {
10113:         if ($actionurl eq '/adm/dependencies') {
10114:             next if ($embed_file =~ m{^\w+://});
10115:         }
10116:         $upload_output .= &start_data_table_row().
10117:                           '<td valign="top"><img src="'.&icon($embed_file).'" />&nbsp;'.
10118:                           '<span class="LC_filename">'.$embed_file.'</span>';
10119:         unless ($mapping{$embed_file} eq $embed_file) {
10120:             $upload_output .= '<br /><span class="LC_info" style="font-size:smaller;">'.
10121:                               &mt('changed from: [_1]',$mapping{$embed_file}).'</span>';
10122:         }
10123:         $upload_output .= '</td>';
10124:         if ($args->{'ignore_remote_references'} && $embed_file =~ m{^\w+://}) { 
10125:             $upload_output.='<td align="right">'.
10126:                             '<span class="LC_info LC_fontsize_medium">'.
10127:                             &mt("URL points to web address").'</span>';
10128:             $numremref++;
10129:         } elsif ($args->{'error_on_invalid_names'}
10130:             && $embed_file ne &Apache::lonnet::clean_filename($embed_file,{'keep_path' => 1,})) {
10131:             $upload_output.='<td align="right"><span class="LC_warning">'.
10132:                             &mt('Invalid characters').'</span>';
10133:             $numinvalid++;
10134:         } else {
10135:             $upload_output .= '<td>'.
10136:                               &embedded_file_element('upload_embedded',$counter,
10137:                                                      $embed_file,\%mapping,
10138:                                                      $allfiles,$codebase,'upload');
10139:             $counter ++;
10140:             $numnew ++;
10141:         }
10142:         $upload_output .= '</td>'.&Apache::loncommon::end_data_table_row()."\n";
10143:     }
10144:     foreach my $embed_file (sort {lc($a) cmp lc($b)} keys(%existing)) {
10145:         if ($actionurl eq '/adm/dependencies') {
10146:             my ($size,$mtime) = &get_dependency_details(\%currfile,\%currsubfile,$embed_file);
10147:             $modify_output .= &start_data_table_row().
10148:                               '<td><a href="'.$path.'/'.$embed_file.'" style="text-decoration:none;">'.
10149:                               '<img src="'.&icon($embed_file).'" border="0" />'.
10150:                               '&nbsp;<span class="LC_filename">'.$embed_file.'</span></a></td>'.
10151:                               '<td>'.$size.'</td>'.
10152:                               '<td>'.$mtime.'</td>'.
10153:                               '<td><label><input type="checkbox" name="mod_upload_dep" '.
10154:                               'onclick="toggleBrowse('."'$counter'".')" id="mod_upload_dep_'.
10155:                               $counter.'" value="'.$counter.'" />'.&mt('Yes').'</label>'.
10156:                               '<div id="moduploaddep_'.$counter.'" style="display:none;">'.
10157:                               &embedded_file_element('upload_embedded',$counter,
10158:                                                      $embed_file,\%mapping,
10159:                                                      $allfiles,$codebase,'modify').
10160:                               '</div></td>'.
10161:                               &end_data_table_row()."\n";
10162:             $counter ++;
10163:         } else {
10164:             $upload_output .= &start_data_table_row().
10165:                               '<td valign="top"><img src="'.&icon($embed_file).'" />&nbsp;'.
10166:                               '<span class="LC_filename">'.$embed_file.'</span></td>'.
10167:                               '<td align="right"><span class="LC_info LC_fontsize_medium">'.&mt('Already exists').'</span></td>'.
10168:                               &Apache::loncommon::end_data_table_row()."\n";
10169:         }
10170:     }
10171:     my $delidx = $counter;
10172:     foreach my $oldfile (sort {lc($a) cmp lc($b)} keys(%unused)) {
10173:         my ($size,$mtime) = &get_dependency_details(\%currfile,\%currsubfile,$oldfile);
10174:         $delete_output .= &start_data_table_row().
10175:                           '<td><img src="'.&icon($oldfile).'" />'.
10176:                           '&nbsp;<span class="LC_filename">'.$oldfile.'</span></td>'.
10177:                           '<td>'.$size.'</td>'.
10178:                           '<td>'.$mtime.'</td>'.
10179:                           '<td><label><input type="checkbox" name="del_upload_dep" '.
10180:                           ' value="'.$delidx.'" />'.&mt('Yes').'</label>'.
10181:                           &embedded_file_element('upload_embedded',$delidx,
10182:                                                  $oldfile,\%mapping,$allfiles,
10183:                                                  $codebase,'delete').'</td>'.
10184:                           &end_data_table_row()."\n"; 
10185:         $numunused ++;
10186:         $delidx ++;
10187:     }
10188:     if ($upload_output) {
10189:         $upload_output = &start_data_table().
10190:                          $upload_output.
10191:                          &end_data_table()."\n";
10192:     }
10193:     if ($modify_output) {
10194:         $modify_output = &start_data_table().
10195:                          &start_data_table_header_row().
10196:                          '<th>'.&mt('File').'</th>'.
10197:                          '<th>'.&mt('Size (KB)').'</th>'.
10198:                          '<th>'.&mt('Modified').'</th>'.
10199:                          '<th>'.&mt('Upload replacement?').'</th>'.
10200:                          &end_data_table_header_row().
10201:                          $modify_output.
10202:                          &end_data_table()."\n";
10203:     }
10204:     if ($delete_output) {
10205:         $delete_output = &start_data_table().
10206:                          &start_data_table_header_row().
10207:                          '<th>'.&mt('File').'</th>'.
10208:                          '<th>'.&mt('Size (KB)').'</th>'.
10209:                          '<th>'.&mt('Modified').'</th>'.
10210:                          '<th>'.&mt('Delete?').'</th>'.
10211:                          &end_data_table_header_row().
10212:                          $delete_output.
10213:                          &end_data_table()."\n";
10214:     }
10215:     my $applies = 0;
10216:     if ($numremref) {
10217:         $applies ++;
10218:     }
10219:     if ($numinvalid) {
10220:         $applies ++;
10221:     }
10222:     if ($numexisting) {
10223:         $applies ++;
10224:     }
10225:     if ($counter || $numunused) {
10226:         $output = '<form name="upload_embedded" action="'.$actionurl.'"'.
10227:                   ' method="post" enctype="multipart/form-data">'."\n".
10228:                   $state.'<h3>'.$heading.'</h3>'; 
10229:         if ($actionurl eq '/adm/dependencies') {
10230:             if ($numnew) {
10231:                 $output .= '<h4>'.&mt('Missing dependencies').'</h4>'.
10232:                            '<p>'.&mt('The following files need to be uploaded.').'</p>'."\n".
10233:                            $upload_output.'<br />'."\n";
10234:             }
10235:             if ($numexisting) {
10236:                 $output .= '<h4>'.&mt('Uploaded dependencies (in use)').'</h4>'.
10237:                            '<p>'.&mt('Upload a new file to replace the one currently in use.').'</p>'."\n".
10238:                            $modify_output.'<br />'."\n";
10239:                            $buttontext = &mt('Save changes');
10240:             }
10241:             if ($numunused) {
10242:                 $output .= '<h4>'.&mt('Unused files').'</h4>'.
10243:                            '<p>'.&mt('The following uploaded files are no longer used.').'</p>'."\n".
10244:                            $delete_output.'<br />'."\n";
10245:                            $buttontext = &mt('Save changes');
10246:             }
10247:         } else {
10248:             $output .= $upload_output.'<br />'."\n";
10249:         }
10250:         $output .= '<input type ="hidden" name="number_embedded_items" value="'.
10251:                    $counter.'" />'."\n";
10252:         if ($actionurl eq '/adm/dependencies') { 
10253:             $output .= '<input type ="hidden" name="number_newemb_items" value="'.
10254:                        $numnew.'" />'."\n";
10255:         } elsif ($actionurl eq '') {
10256:             $output .=  '<input type="hidden" name="phase" value="three" />';
10257:         }
10258:     } elsif ($applies) {
10259:         $output = '<b>'.&mt('Referenced files').'</b>:<br />';
10260:         if ($applies > 1) {
10261:             $output .=  
10262:                 &mt('No dependencies need to be uploaded, as one of the following applies to each reference:').'<ul>';
10263:             if ($numremref) {
10264:                 $output .= '<li>'.&mt('reference is to a URL which points to another server').'</li>'."\n";
10265:             }
10266:             if ($numinvalid) {
10267:                 $output .= '<li>'.&mt('reference is to file with a name containing invalid characters').'</li>'."\n";
10268:             }
10269:             if ($numexisting) {
10270:                 $output .= '<li>'.&mt('reference is to an existing file at the specified location').'</li>'."\n";
10271:             }
10272:             $output .= '</ul><br />';
10273:         } elsif ($numremref) {
10274:             $output .= '<p>'.&mt('None to upload, as all references are to URLs pointing to another server.').'</p>';
10275:         } elsif ($numinvalid) {
10276:             $output .= '<p>'.&mt('None to upload, as all references are to files with names containing invalid characters.').'</p>';
10277:         } elsif ($numexisting) {
10278:             $output .= '<p>'.&mt('None to upload, as all references are to existing files.').'</p>';
10279:         }
10280:         $output .= $upload_output.'<br />';
10281:     }
10282:     my ($pathchange_output,$chgcount);
10283:     $chgcount = $counter;
10284:     if (keys(%pathchanges) > 0) {
10285:         foreach my $embed_file (sort {lc($a) cmp lc($b)} keys(%pathchanges)) {
10286:             if ($counter) {
10287:                 $output .= &embedded_file_element('pathchange',$chgcount,
10288:                                                   $embed_file,\%mapping,
10289:                                                   $allfiles,$codebase,'change');
10290:             } else {
10291:                 $pathchange_output .= 
10292:                     &start_data_table_row().
10293:                     '<td><input type ="checkbox" name="namechange" value="'.
10294:                     $chgcount.'" checked="checked" /></td>'.
10295:                     '<td>'.$mapping{$embed_file}.'</td>'.
10296:                     '<td>'.$embed_file.
10297:                     &embedded_file_element('pathchange',$numpathchg,$embed_file,
10298:                                            \%mapping,$allfiles,$codebase,'change').
10299:                     '</td>'.&end_data_table_row();
10300:             }
10301:             $numpathchg ++;
10302:             $chgcount ++;
10303:         }
10304:     }
10305:     if (($counter) || ($numunused)) {
10306:         if ($numpathchg) {
10307:             $output .= '<input type ="hidden" name="number_pathchange_items" value="'.
10308:                        $numpathchg.'" />'."\n";
10309:         }
10310:         if (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank') || 
10311:             ($actionurl eq '/adm/imsimport')) {
10312:             $output .= '<input type="hidden" name="phase" value="three" />'."\n";
10313:         } elsif ($actionurl eq '/adm/portfolio' || $actionurl eq '/adm/coursegrp_portfolio') {
10314:             $output .= '<input type="hidden" name="action" value="upload_embedded" />';
10315:         } elsif ($actionurl eq '/adm/dependencies') {
10316:             $output .= '<input type="hidden" name="action" value="process_changes" />';
10317:         }
10318:         $output .= '<input type ="submit" value="'.$buttontext.'" />'."\n".'</form>'."\n";
10319:     } elsif ($numpathchg) {
10320:         my %pathchange = ();
10321:         $output .= &modify_html_form('pathchange',$actionurl,$state,\%pathchange,$pathchange_output);
10322:         if (($actionurl eq '/adm/portfolio') || ($actionurl eq '/adm/coursegrp_portfolio')) {
10323:             $output .= '<p>'.&mt('or').'</p>'; 
10324:         }
10325:     }
10326:     return ($output,$counter,$numpathchg);
10327: }
10328: 
10329: =pod
10330: 
10331: =item * clean_path($name)
10332: 
10333: Performs clean-up of directories, subdirectories and filename in an
10334: embedded object, referenced in an HTML file which is being uploaded
10335: to a course or portfolio, where 
10336: "Upload embedded images/multimedia files if HTML file" checkbox was
10337: checked.
10338: 
10339: Clean-up is similar to replacements in lonnet::clean_filename()
10340: except each / between sub-directory and next level is preserved.
10341: 
10342: =cut
10343: 
10344: sub clean_path {
10345:     my ($embed_file) = @_;
10346:     $embed_file =~s{^/+}{};
10347:     my @contents;
10348:     if ($embed_file =~ m{/}) {
10349:         @contents = split(/\//,$embed_file);
10350:     } else {
10351:         @contents = ($embed_file);
10352:     }
10353:     my $lastidx = scalar(@contents)-1;
10354:     for (my $i=0; $i<=$lastidx; $i++) { 
10355:         $contents[$i]=~s{\\}{/}g;
10356:         $contents[$i]=~s/\s+/\_/g;
10357:         $contents[$i]=~s{[^/\w\.\-]}{}g;
10358:         if ($i == $lastidx) {
10359:             $contents[$i]=~s/\.(\d+)(?=\.)/_$1/g;
10360:         }
10361:     }
10362:     if ($lastidx > 0) {
10363:         return join('/',@contents);
10364:     } else {
10365:         return $contents[0];
10366:     }
10367: }
10368: 
10369: sub embedded_file_element {
10370:     my ($context,$num,$embed_file,$mapping,$allfiles,$codebase,$type) = @_;
10371:     return unless ((ref($mapping) eq 'HASH') && (ref($allfiles) eq 'HASH') &&
10372:                    (ref($codebase) eq 'HASH'));
10373:     my $output;
10374:     if (($context eq 'upload_embedded') && ($type ne 'delete')) {
10375:        $output = '<input name="embedded_item_'.$num.'" type="file" value="" />'."\n";
10376:     }
10377:     $output .= '<input name="embedded_orig_'.$num.'" type="hidden" value="'.
10378:                &escape($embed_file).'" />';
10379:     unless (($context eq 'upload_embedded') && 
10380:             ($mapping->{$embed_file} eq $embed_file)) {
10381:         $output .='
10382:         <input name="embedded_ref_'.$num.'" type="hidden" value="'.&escape($mapping->{$embed_file}).'" />';
10383:     }
10384:     my $attrib;
10385:     if (ref($allfiles->{$mapping->{$embed_file}}) eq 'ARRAY') {
10386:         $attrib = &escape(join(':',@{$allfiles->{$mapping->{$embed_file}}}));
10387:     }
10388:     $output .=
10389:         "\n\t\t".
10390:         '<input name="embedded_attrib_'.$num.'" type="hidden" value="'.
10391:         $attrib.'" />';
10392:     if (exists($codebase->{$mapping->{$embed_file}})) {
10393:         $output .=
10394:             "\n\t\t".
10395:             '<input name="codebase_'.$num.'" type="hidden" value="'.
10396:             &escape($codebase->{$mapping->{$embed_file}}).'" />';
10397:     }
10398:     return $output;
10399: }
10400: 
10401: sub get_dependency_details {
10402:     my ($currfile,$currsubfile,$embed_file) = @_;
10403:     my ($size,$mtime,$showsize,$showmtime);
10404:     if ((ref($currfile) eq 'HASH') && (ref($currsubfile))) {
10405:         if ($embed_file =~ m{/}) {
10406:             my ($path,$fname) = split(/\//,$embed_file);
10407:             if (ref($currsubfile->{$path}{$fname}) eq 'ARRAY') {
10408:                 ($size,$mtime) = @{$currsubfile->{$path}{$fname}};
10409:             }
10410:         } else {
10411:             if (ref($currfile->{$embed_file}) eq 'ARRAY') {
10412:                 ($size,$mtime) = @{$currfile->{$embed_file}};
10413:             }
10414:         }
10415:         $showsize = $size/1024.0;
10416:         $showsize = sprintf("%.1f",$showsize);
10417:         if ($mtime > 0) {
10418:             $showmtime = &Apache::lonlocal::locallocaltime($mtime);
10419:         }
10420:     }
10421:     return ($showsize,$showmtime);
10422: }
10423: 
10424: sub ask_embedded_js {
10425:     return <<"END";
10426: <script type="text/javascript"">
10427: // <![CDATA[
10428: function toggleBrowse(counter) {
10429:     var chkboxid = document.getElementById('mod_upload_dep_'+counter);
10430:     var fileid = document.getElementById('embedded_item_'+counter);
10431:     var uploaddivid = document.getElementById('moduploaddep_'+counter);
10432:     if (chkboxid.checked == true) {
10433:         uploaddivid.style.display='block';
10434:     } else {
10435:         uploaddivid.style.display='none';
10436:         fileid.value = '';
10437:     }
10438: }
10439: // ]]>
10440: </script>
10441: 
10442: END
10443: }
10444: 
10445: sub upload_embedded {
10446:     my ($context,$dirpath,$uname,$udom,$dir_root,$url_root,$group,$disk_quota,
10447:         $current_disk_usage,$hiddenstate,$actionurl) = @_;
10448:     my (%pathchange,$output,$modifyform,$footer,$returnflag);
10449:     for (my $i=0; $i<$env{'form.number_embedded_items'}; $i++) {
10450:         next if (!exists($env{'form.embedded_item_'.$i.'.filename'}));
10451:         my $orig_uploaded_filename =
10452:             $env{'form.embedded_item_'.$i.'.filename'};
10453:         foreach my $type ('orig','ref','attrib','codebase') {
10454:             if ($env{'form.embedded_'.$type.'_'.$i} ne '') {
10455:                 $env{'form.embedded_'.$type.'_'.$i} =
10456:                     &unescape($env{'form.embedded_'.$type.'_'.$i});
10457:             }
10458:         }
10459:         my ($path,$fname) =
10460:             ($env{'form.embedded_orig_'.$i} =~ m{(.*/)([^/]*)});
10461:         # no path, whole string is fname
10462:         if (!$fname) { $fname = $env{'form.embedded_orig_'.$i} };
10463:         $fname = &Apache::lonnet::clean_filename($fname);
10464:         # See if there is anything left
10465:         next if ($fname eq '');
10466: 
10467:         # Check if file already exists as a file or directory.
10468:         my ($state,$msg);
10469:         if ($context eq 'portfolio') {
10470:             my $port_path = $dirpath;
10471:             if ($group ne '') {
10472:                 $port_path = "groups/$group/$port_path";
10473:             }
10474:             ($state,$msg) = &check_for_upload($env{'form.currentpath'}.$path,
10475:                                               $fname,$group,'embedded_item_'.$i,
10476:                                               $dir_root,$port_path,$disk_quota,
10477:                                               $current_disk_usage,$uname,$udom);
10478:             if ($state eq 'will_exceed_quota'
10479:                 || $state eq 'file_locked') {
10480:                 $output .= $msg;
10481:                 next;
10482:             }
10483:         } elsif (($context eq 'author') || ($context eq 'testbank')) {
10484:             ($state,$msg) = &check_for_existing($path,$fname,'embedded_item_'.$i);
10485:             if ($state eq 'exists') {
10486:                 $output .= $msg;
10487:                 next;
10488:             }
10489:         }
10490:         # Check if extension is valid
10491:         if (($fname =~ /\.(\w+)$/) &&
10492:             (&Apache::loncommon::fileembstyle($1) eq 'hdn')) {
10493:             $output .= &mt('Invalid file extension ([_1]) - reserved for internal use.',$1)
10494:                       .' '.&mt('Rename the file with a different extension and re-upload.').'<br />';
10495:             next;
10496:         } elsif (($fname =~ /\.(\w+)$/) &&
10497:                  (!defined(&Apache::loncommon::fileembstyle($1)))) {
10498:             $output .= &mt('Unrecognized file extension ([_1]) - rename the file with a proper extension and re-upload.',$1).'<br />';
10499:             next;
10500:         } elsif ($fname=~/\.(\d+)\.(\w+)$/) {
10501:             $output .= &mt('Filename not allowed - rename the file to remove the number immediately before the file extension([_1]) and re-upload.',$2).'<br />';
10502:             next;
10503:         }
10504:         $env{'form.embedded_item_'.$i.'.filename'}=$fname;
10505:         my $subdir = $path;
10506:         $subdir =~ s{/+$}{};
10507:         if ($context eq 'portfolio') {
10508:             my $result;
10509:             if ($state eq 'existingfile') {
10510:                 $result=
10511:                     &Apache::lonnet::userfileupload('embedded_item_'.$i,'existingfile',
10512:                                                     $dirpath.$env{'form.currentpath'}.$subdir);
10513:             } else {
10514:                 $result=
10515:                     &Apache::lonnet::userfileupload('embedded_item_'.$i,'',
10516:                                                     $dirpath.
10517:                                                     $env{'form.currentpath'}.$subdir);
10518:                 if ($result !~ m|^/uploaded/|) {
10519:                     $output .= '<span class="LC_error">'
10520:                                .&mt('An error occurred ([_1]) while trying to upload [_2] for embedded element [_3].'
10521:                                ,$result,$orig_uploaded_filename,$env{'form.embedded_orig_'.$i})
10522:                                .'</span><br />';
10523:                     next;
10524:                 } else {
10525:                     $output .= &mt('Uploaded [_1]','<span class="LC_filename">'.
10526:                                $path.$fname.'</span>').'<br />';     
10527:                 }
10528:             }
10529:         } elsif (($context eq 'coursedoc') || ($context eq 'syllabus')) {
10530:             my $extendedsubdir = $dirpath.'/'.$subdir;
10531:             $extendedsubdir =~ s{/+$}{};
10532:             my $result =
10533:                 &Apache::lonnet::userfileupload('embedded_item_'.$i,$context,$extendedsubdir);
10534:             if ($result !~ m|^/uploaded/|) {
10535:                 $output .= '<span class="LC_error">'
10536:                            .&mt('An error occurred ([_1]) while trying to upload [_2] for embedded element [_3].'
10537:                            ,$result,$orig_uploaded_filename,$env{'form.embedded_orig_'.$i})
10538:                            .'</span><br />';
10539:                     next;
10540:             } else {
10541:                 $output .= &mt('Uploaded [_1]','<span class="LC_filename">'.
10542:                            $path.$fname.'</span>').'<br />';
10543:                 if ($context eq 'syllabus') {
10544:                     &Apache::lonnet::make_public_indefinitely($result);
10545:                 }
10546:             }
10547:         } else {
10548: # Save the file
10549:             my $target = $env{'form.embedded_item_'.$i};
10550:             my $fullpath = $dir_root.$dirpath.'/'.$path;
10551:             my $dest = $fullpath.$fname;
10552:             my $url = $url_root.$dirpath.'/'.$path.$fname;
10553:             my @parts=split(/\//,"$dirpath/$path");
10554:             my $count;
10555:             my $filepath = $dir_root;
10556:             foreach my $subdir (@parts) {
10557:                 $filepath .= "/$subdir";
10558:                 if (!-e $filepath) {
10559:                     mkdir($filepath,0770);
10560:                 }
10561:             }
10562:             my $fh;
10563:             if (!open($fh,'>'.$dest)) {
10564:                 &Apache::lonnet::logthis('Failed to create '.$dest);
10565:                 $output .= '<span class="LC_error">'.
10566:                            &mt('An error occurred while trying to upload [_1] for embedded element [_2].',
10567:                                $orig_uploaded_filename,$env{'form.embedded_orig_'.$i}).
10568:                            '</span><br />';
10569:             } else {
10570:                 if (!print $fh $env{'form.embedded_item_'.$i}) {
10571:                     &Apache::lonnet::logthis('Failed to write to '.$dest);
10572:                     $output .= '<span class="LC_error">'.
10573:                               &mt('An error occurred while writing the file [_1] for embedded element [_2].',
10574:                                   $orig_uploaded_filename,$env{'form.embedded_orig_'.$i}).
10575:                               '</span><br />';
10576:                 } else {
10577:                     $output .= &mt('Uploaded [_1]','<span class="LC_filename">'.
10578:                                $url.'</span>').'<br />';
10579:                     unless ($context eq 'testbank') {
10580:                         $footer .= &mt('View embedded file: [_1]',
10581:                                        '<a href="'.$url.'">'.$fname.'</a>').'<br />';
10582:                     }
10583:                 }
10584:                 close($fh);
10585:             }
10586:         }
10587:         if ($env{'form.embedded_ref_'.$i}) {
10588:             $pathchange{$i} = 1;
10589:         }
10590:     }
10591:     if ($output) {
10592:         $output = '<p>'.$output.'</p>';
10593:     }
10594:     $output .= &modify_html_form('upload_embedded',$actionurl,$hiddenstate,\%pathchange);
10595:     $returnflag = 'ok';
10596:     my $numpathchgs = scalar(keys(%pathchange));
10597:     if ($numpathchgs > 0) {
10598:         if ($context eq 'portfolio') {
10599:             $output .= '<p>'.&mt('or').'</p>';
10600:         } elsif ($context eq 'testbank') {
10601:             $output .=  '<p>'.&mt('Or [_1]continue[_2] the testbank import without modifying the reference(s).',
10602:                                   '<a href="javascript:document.testbankForm.submit();">','</a>').'</p>';
10603:             $returnflag = 'modify_orightml';
10604:         }
10605:     }
10606:     return ($output.$footer,$returnflag,$numpathchgs);
10607: }
10608: 
10609: sub modify_html_form {
10610:     my ($context,$actionurl,$hiddenstate,$pathchange,$pathchgtable) = @_;
10611:     my $end = 0;
10612:     my $modifyform;
10613:     if ($context eq 'upload_embedded') {
10614:         return unless (ref($pathchange) eq 'HASH');
10615:         if ($env{'form.number_embedded_items'}) {
10616:             $end += $env{'form.number_embedded_items'};
10617:         }
10618:         if ($env{'form.number_pathchange_items'}) {
10619:             $end += $env{'form.number_pathchange_items'};
10620:         }
10621:         if ($end) {
10622:             for (my $i=0; $i<$end; $i++) {
10623:                 if ($i < $env{'form.number_embedded_items'}) {
10624:                     next unless($pathchange->{$i});
10625:                 }
10626:                 $modifyform .=
10627:                     &start_data_table_row().
10628:                     '<td><input type ="checkbox" name="namechange" value="'.$i.'" '.
10629:                     'checked="checked" /></td>'.
10630:                     '<td>'.$env{'form.embedded_ref_'.$i}.
10631:                     '<input type="hidden" name="embedded_ref_'.$i.'" value="'.
10632:                     &escape($env{'form.embedded_ref_'.$i}).'" />'.
10633:                     '<input type="hidden" name="embedded_codebase_'.$i.'" value="'.
10634:                     &escape($env{'form.embedded_codebase_'.$i}).'" />'.
10635:                     '<input type="hidden" name="embedded_attrib_'.$i.'" value="'.
10636:                     &escape($env{'form.embedded_attrib_'.$i}).'" /></td>'.
10637:                     '<td>'.$env{'form.embedded_orig_'.$i}.
10638:                     '<input type="hidden" name="embedded_orig_'.$i.'" value="'.
10639:                     &escape($env{'form.embedded_orig_'.$i}).'" /></td>'.
10640:                     &end_data_table_row();
10641:             }
10642:         }
10643:     } else {
10644:         $modifyform = $pathchgtable;
10645:         if (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank')) {
10646:             $hiddenstate .= '<input type="hidden" name="phase" value="four" />';
10647:         } elsif (($actionurl eq '/adm/portfolio') || ($actionurl eq '/adm/coursegrp_portfolio')) {
10648:             $hiddenstate .= '<input type="hidden" name="action" value="modify_orightml" />';
10649:         }
10650:     }
10651:     if ($modifyform) {
10652:         if ($actionurl eq '/adm/dependencies') {
10653:             $hiddenstate .= '<input type="hidden" name="action" value="modifyhrefs" />';
10654:         }
10655:         return '<h3>'.&mt('Changes in content of HTML file required').'</h3>'."\n".
10656:                '<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".
10657:                '<li>'.&mt('For consistency between the reference(s) and the location of the corresponding stored file within LON-CAPA.').'</li>'."\n".
10658:                '<li>'.&mt('To change absolute paths to relative paths, or replace directory traversal via "../" within the original reference.').'</li>'."\n".
10659:                '</ol></p>'."\n".'<p>'.
10660:                &mt('LON-CAPA can make the required changes to your HTML file.').'</p>'."\n".
10661:                '<form method="post" name="refchanger" action="'.$actionurl.'">'.
10662:                &start_data_table()."\n".
10663:                &start_data_table_header_row().
10664:                '<th>'.&mt('Change?').'</th>'.
10665:                '<th>'.&mt('Current reference').'</th>'.
10666:                '<th>'.&mt('Required reference').'</th>'.
10667:                &end_data_table_header_row()."\n".
10668:                $modifyform.
10669:                &end_data_table().'<br />'."\n".$hiddenstate.
10670:                '<input type="submit" name="pathchanges" value="'.&mt('Modify HTML file').'" />'.
10671:                '</form>'."\n";
10672:     }
10673:     return;
10674: }
10675: 
10676: sub modify_html_refs {
10677:     my ($context,$dirpath,$uname,$udom,$dir_root,$url) = @_;
10678:     my $container;
10679:     if ($context eq 'portfolio') {
10680:         $container = $env{'form.container'};
10681:     } elsif ($context eq 'coursedoc') {
10682:         $container = $env{'form.primaryurl'};
10683:     } elsif ($context eq 'manage_dependencies') {
10684:         (undef,undef,$container) = &Apache::lonnet::decode_symb($env{'form.symb'});
10685:         $container = "/$container";
10686:     } elsif ($context eq 'syllabus') {
10687:         $container = $url;
10688:     } else {
10689:         $container = $Apache::lonnet::perlvar{'lonDocRoot'}.$env{'form.filename'};
10690:     }
10691:     my (%allfiles,%codebase,$output,$content);
10692:     my @changes = &get_env_multiple('form.namechange');
10693:     unless ((@changes > 0) || ($context eq 'syllabus')) {
10694:         if (wantarray) {
10695:             return ('',0,0); 
10696:         } else {
10697:             return;
10698:         }
10699:     }
10700:     if (($context eq 'portfolio') || ($context eq 'coursedoc') || 
10701:         ($context eq 'manage_dependencies') || ($context eq 'syllabus')) {
10702:         unless ($container =~ m{^/uploaded/\Q$udom\E/\Q$uname\E/}) {
10703:             if (wantarray) {
10704:                 return ('',0,0);
10705:             } else {
10706:                 return;
10707:             }
10708:         } 
10709:         $content = &Apache::lonnet::getfile($container);
10710:         if ($content eq '-1') {
10711:             if (wantarray) {
10712:                 return ('',0,0);
10713:             } else {
10714:                 return;
10715:             }
10716:         }
10717:     } else {
10718:         unless ($container =~ /^\Q$dir_root\E/) {
10719:             if (wantarray) {
10720:                 return ('',0,0);
10721:             } else {
10722:                 return;
10723:             }
10724:         } 
10725:         if (open(my $fh,"<$container")) {
10726:             $content = join('', <$fh>);
10727:             close($fh);
10728:         } else {
10729:             if (wantarray) {
10730:                 return ('',0,0);
10731:             } else {
10732:                 return;
10733:             }
10734:         }
10735:     }
10736:     my ($count,$codebasecount) = (0,0);
10737:     my $mm = new File::MMagic;
10738:     my $mime_type = $mm->checktype_contents($content);
10739:     if ($mime_type eq 'text/html') {
10740:         my $parse_result = 
10741:             &Apache::lonnet::extract_embedded_items($container,\%allfiles,
10742:                                                     \%codebase,\$content);
10743:         if ($parse_result eq 'ok') {
10744:             foreach my $i (@changes) {
10745:                 my $orig = &unescape($env{'form.embedded_orig_'.$i});
10746:                 my $ref = &unescape($env{'form.embedded_ref_'.$i});
10747:                 if ($allfiles{$ref}) {
10748:                     my $newname =  $orig;
10749:                     my ($attrib_regexp,$codebase);
10750:                     $attrib_regexp = &unescape($env{'form.embedded_attrib_'.$i});
10751:                     if ($attrib_regexp =~ /:/) {
10752:                         $attrib_regexp =~ s/\:/|/g;
10753:                     }
10754:                     if ($content =~ m{($attrib_regexp\s*=\s*['"]?)\Q$ref\E(['"]?)}) {
10755:                         my $numchg = ($content =~ s{($attrib_regexp\s*=\s*['"]?)\Q$ref\E(['"]?)}{$1$newname$2}gi);
10756:                         $count += $numchg;
10757:                         $allfiles{$newname} = $allfiles{$ref};
10758:                         delete($allfiles{$ref});
10759:                     }
10760:                     if ($env{'form.embedded_codebase_'.$i} ne '') {
10761:                         $codebase = &unescape($env{'form.embedded_codebase_'.$i});
10762:                         my $numchg = ($content =~ s/(codebase\s*=\s*["']?)\Q$codebase\E(["']?)/$1.$2/i); #' stupid emacs
10763:                         $codebasecount ++;
10764:                     }
10765:                 }
10766:             }
10767:             my $skiprewrites;
10768:             if ($count || $codebasecount) {
10769:                 my $saveresult;
10770:                 if (($context eq 'portfolio') || ($context eq 'coursedoc') || 
10771:                     ($context eq 'manage_dependencies') || ($context eq 'syllabus')) {
10772:                     my $url = &Apache::lonnet::store_edited_file($container,$content,$udom,$uname,\$saveresult);
10773:                     if ($url eq $container) {
10774:                         my ($fname) = ($container =~ m{/([^/]+)$});
10775:                         $output = '<p>'.&mt('Updated [quant,_1,reference] in [_2].',
10776:                                             $count,'<span class="LC_filename">'.
10777:                                             $fname.'</span>').'</p>';
10778:                     } else {
10779:                          $output = '<p class="LC_error">'.
10780:                                    &mt('Error: update failed for: [_1].',
10781:                                    '<span class="LC_filename">'.
10782:                                    $container.'</span>').'</p>';
10783:                     }
10784:                     if ($context eq 'syllabus') {
10785:                         unless ($saveresult eq 'ok') {
10786:                             $skiprewrites = 1;
10787:                         }
10788:                     }
10789:                 } else {
10790:                     if (open(my $fh,">$container")) {
10791:                         print $fh $content;
10792:                         close($fh);
10793:                         $output = '<p>'.&mt('Updated [quant,_1,reference] in [_2].',
10794:                                   $count,'<span class="LC_filename">'.
10795:                                   $container.'</span>').'</p>';
10796:                     } else {
10797:                          $output = '<p class="LC_error">'.
10798:                                    &mt('Error: could not update [_1].',
10799:                                    '<span class="LC_filename">'.
10800:                                    $container.'</span>').'</p>';
10801:                     }
10802:                 }
10803:             }
10804:             if (($context eq 'syllabus') && (!$skiprewrites)) {
10805:                 my ($actionurl,$state);
10806:                 $actionurl = "/public/$udom/$uname/syllabus";
10807:                 my ($ignore,$num,$numpathchanges,$existing,$mapping) =
10808:                     &ask_for_embedded_content($actionurl,$state,\%allfiles,
10809:                                               \%codebase,
10810:                                               {'context' => 'rewrites',
10811:                                                'ignore_remote_references' => 1,});
10812:                 if (ref($mapping) eq 'HASH') {
10813:                     my $rewrites = 0;
10814:                     foreach my $key (keys(%{$mapping})) {
10815:                         next if ($key =~ m{^https?://});
10816:                         my $ref = $mapping->{$key};
10817:                         my $newname = "/uploaded/$udom/$uname/portfolio/syllabus/$key";
10818:                         my $attrib;
10819:                         if (ref($allfiles{$mapping->{$key}}) eq 'ARRAY') {
10820:                             $attrib = join('|',@{$allfiles{$mapping->{$key}}});
10821:                         }
10822:                         if ($content =~ m{($attrib\s*=\s*['"]?)\Q$ref\E(['"]?)}) {
10823:                             my $numchg = ($content =~ s{($attrib\s*=\s*['"]?)\Q$ref\E(['"]?)}{$1$newname$2}gi);
10824:                             $rewrites += $numchg;
10825:                         }
10826:                     }
10827:                     if ($rewrites) {
10828:                         my $saveresult; 
10829:                         my $url = &Apache::lonnet::store_edited_file($container,$content,$udom,$uname,\$saveresult);
10830:                         if ($url eq $container) {
10831:                             my ($fname) = ($container =~ m{/([^/]+)$});
10832:                             $output .= '<p>'.&mt('Rewrote [quant,_1,link] as [quant,_1,absolute link] in [_2].',
10833:                                             $count,'<span class="LC_filename">'.
10834:                                             $fname.'</span>').'</p>';
10835:                         } else {
10836:                             $output .= '<p class="LC_error">'.
10837:                                        &mt('Error: could not update links in [_1].',
10838:                                        '<span class="LC_filename">'.
10839:                                        $container.'</span>').'</p>';
10840: 
10841:                         }
10842:                     }
10843:                 }
10844:             }
10845:         } else {
10846:             &logthis('Failed to parse '.$container.
10847:                      ' to modify references: '.$parse_result);
10848:         }
10849:     }
10850:     if (wantarray) {
10851:         return ($output,$count,$codebasecount);
10852:     } else {
10853:         return $output;
10854:     }
10855: }
10856: 
10857: sub check_for_existing {
10858:     my ($path,$fname,$element) = @_;
10859:     my ($state,$msg);
10860:     if (-d $path.'/'.$fname) {
10861:         $state = 'exists';
10862:         $msg = &mt('Unable to upload [_1]. A directory by that name was found in [_2].','<span class="LC_filename">'.$fname.'</span>',$path);
10863:     } elsif (-e $path.'/'.$fname) {
10864:         $state = 'exists';
10865:         $msg = &mt('Unable to upload [_1]. A file by that name was found in [_2].','<span class="LC_filename">'.$fname.'</span>',$path);
10866:     }
10867:     if ($state eq 'exists') {
10868:         $msg = '<span class="LC_error">'.$msg.'</span><br />';
10869:     }
10870:     return ($state,$msg);
10871: }
10872: 
10873: sub check_for_upload {
10874:     my ($path,$fname,$group,$element,$portfolio_root,$port_path,
10875:         $disk_quota,$current_disk_usage,$uname,$udom) = @_;
10876:     my $filesize = length($env{'form.'.$element});
10877:     if (!$filesize) {
10878:         my $msg = '<span class="LC_error">'.
10879:                   &mt('Unable to upload [_1]. (size = [_2] bytes)', 
10880:                       '<span class="LC_filename">'.$fname.'</span>',
10881:                       $filesize).'<br />'.
10882:                   &mt('Either the file you attempted to upload was empty, or your web browser was unable to read its contents.').'<br />'.
10883:                   '</span>';
10884:         return ('zero_bytes',$msg);
10885:     }
10886:     $filesize =  $filesize/1000; #express in k (1024?)
10887:     my $getpropath = 1;
10888:     my ($dirlistref,$listerror) =
10889:          &Apache::lonnet::dirlist($portfolio_root.$path,$udom,$uname,$getpropath);
10890:     my $found_file = 0;
10891:     my $locked_file = 0;
10892:     my @lockers;
10893:     my $navmap;
10894:     if ($env{'request.course.id'}) {
10895:         $navmap = Apache::lonnavmaps::navmap->new();
10896:     }
10897:     if (ref($dirlistref) eq 'ARRAY') {
10898:         foreach my $line (@{$dirlistref}) {
10899:             my ($file_name,$rest)=split(/\&/,$line,2);
10900:             if ($file_name eq $fname){
10901:                 $file_name = $path.$file_name;
10902:                 if ($group ne '') {
10903:                     $file_name = $group.$file_name;
10904:                 }
10905:                 $found_file = 1;
10906:                 if (&Apache::lonnet::is_locked($file_name,$udom,$uname,\@lockers) eq 'true') {
10907:                     foreach my $lock (@lockers) {
10908:                         if (ref($lock) eq 'ARRAY') {
10909:                             my ($symb,$crsid) = @{$lock};
10910:                             if ($crsid eq $env{'request.course.id'}) {
10911:                                 if (ref($navmap)) {
10912:                                     my $res = $navmap->getBySymb($symb);
10913:                                     foreach my $part (@{$res->parts()}) { 
10914:                                         my ($slot_status,$slot_time,$slot_name)=$res->check_for_slot($part);
10915:                                         unless (($slot_status == $res->RESERVED) ||
10916:                                                 ($slot_status == $res->RESERVED_LOCATION)) {
10917:                                             $locked_file = 1;
10918:                                         }
10919:                                     }
10920:                                 } else {
10921:                                     $locked_file = 1;
10922:                                 }
10923:                             } else {
10924:                                 $locked_file = 1;
10925:                             }
10926:                         }
10927:                    }
10928:                 } else {
10929:                     my @info = split(/\&/,$rest);
10930:                     my $currsize = $info[6]/1000;
10931:                     if ($currsize < $filesize) {
10932:                         my $extra = $filesize - $currsize;
10933:                         if (($current_disk_usage + $extra) > $disk_quota) {
10934:                             my $msg = '<p class="LC_warning">'.
10935:                                       &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.',
10936:                                           '<span class="LC_filename">'.$fname.'</span>',$filesize,$currsize).'</p>'.
10937:                                       '<p>'.&mt('Disk quota is [_1] kilobytes. Your current disk usage is [_2] kilobytes.',
10938:                                                    $disk_quota,$current_disk_usage).'</p>';
10939:                             return ('will_exceed_quota',$msg);
10940:                         }
10941:                     }
10942:                 }
10943:             }
10944:         }
10945:     }
10946:     if (($current_disk_usage + $filesize) > $disk_quota){
10947:         my $msg = '<p class="LC_warning">'.
10948:                 &mt('Unable to upload [_1]. (size = [_2] kilobytes). Disk quota will be exceeded.','<span class="LC_filename">'.$fname.'</span>',$filesize).'</p>'.
10949:                   '<p>'.&mt('Disk quota is [_1] kilobytes. Your current disk usage is [_2] kilobytes.',$disk_quota,$current_disk_usage).'</p>';
10950:         return ('will_exceed_quota',$msg);
10951:     } elsif ($found_file) {
10952:         if ($locked_file) {
10953:             my $msg = '<p class="LC_warning">';
10954:             $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>');
10955:             $msg .= '</p>';
10956:             $msg .= &mt('You will be able to rename or delete existing [_1] after a grade has been assigned.','<span class="LC_filename">'.$fname.'</span>');
10957:             return ('file_locked',$msg);
10958:         } else {
10959:             my $msg = '<p class="LC_error">';
10960:             $msg .= &mt(' A file by that name: [_1] was found in [_2].','<span class="LC_filename">'.$fname.'</span>',$port_path.$env{'form.currentpath'});
10961:             $msg .= '</p>';
10962:             return ('existingfile',$msg);
10963:         }
10964:     }
10965: }
10966: 
10967: sub check_for_traversal {
10968:     my ($path,$url,$toplevel) = @_;
10969:     my @parts=split(/\//,$path);
10970:     my $cleanpath;
10971:     my $fullpath = $url;
10972:     for (my $i=0;$i<@parts;$i++) {
10973:         next if ($parts[$i] eq '.');
10974:         if ($parts[$i] eq '..') {
10975:             $fullpath =~ s{([^/]+/)$}{};
10976:         } else {
10977:             $fullpath .= $parts[$i].'/';
10978:         }
10979:     }
10980:     if ($fullpath =~ /^\Q$url\E(.*)$/) {
10981:         $cleanpath = $1;
10982:     } elsif ($fullpath =~ /^\Q$toplevel\E(.*)$/) {
10983:         my $curr_toprel = $1;
10984:         my @parts = split(/\//,$curr_toprel);
10985:         my ($url_toprel) = ($url =~ /^\Q$toplevel\E(.*)$/);
10986:         my @urlparts = split(/\//,$url_toprel);
10987:         my $doubledots;
10988:         my $startdiff = -1;
10989:         for (my $i=0; $i<@urlparts; $i++) {
10990:             if ($startdiff == -1) {
10991:                 unless ($urlparts[$i] eq $parts[$i]) {
10992:                     $startdiff = $i;
10993:                     $doubledots .= '../';
10994:                 }
10995:             } else {
10996:                 $doubledots .= '../';
10997:             }
10998:         }
10999:         if ($startdiff > -1) {
11000:             $cleanpath = $doubledots;
11001:             for (my $i=$startdiff; $i<@parts; $i++) {
11002:                 $cleanpath .= $parts[$i].'/';
11003:             }
11004:         }
11005:     }
11006:     $cleanpath =~ s{(/)$}{};
11007:     return $cleanpath;
11008: }
11009: 
11010: sub is_archive_file {
11011:     my ($mimetype) = @_;
11012:     if (($mimetype eq 'application/octet-stream') ||
11013:         ($mimetype eq 'application/x-stuffit') ||
11014:         ($mimetype =~ m{^application/(x\-)?(compressed|tar|zip|tgz|gz|gtar|gzip|gunzip|bz|bz2|bzip2)})) {
11015:         return 1;
11016:     }
11017:     return;
11018: }
11019: 
11020: sub decompress_form {
11021:     my ($mimetype,$archiveurl,$action,$noextract,$hiddenelements,$dirlist) = @_;
11022:     my %lt = &Apache::lonlocal::texthash (
11023:         this => 'This file is an archive file.',
11024:         camt => 'This file is a Camtasia archive file.',
11025:         itsc => 'Its contents are as follows:',
11026:         youm => 'You may wish to extract its contents.',
11027:         extr => 'Extract contents',
11028:         auto => 'LON-CAPA can process the files automatically, or you can decide how each should be handled.',
11029:         proa => 'Process automatically?',
11030:         yes  => 'Yes',
11031:         no   => 'No',
11032:         fold => 'Title for folder containing movie',
11033:         movi => 'Title for page containing embedded movie', 
11034:     );
11035:     my $fileloc = &Apache::lonnet::filelocation(undef,$archiveurl);
11036:     my ($is_camtasia,$topdir,%toplevel,@paths);
11037:     my $info = &list_archive_contents($fileloc,\@paths);
11038:     if (@paths) {
11039:         foreach my $path (@paths) {
11040:             $path =~ s{^/}{};
11041:             if ($path =~ m{^([^/]+)/$}) {
11042:                 $topdir = $1;
11043:             }
11044:             if ($path =~ m{^([^/]+)/}) {
11045:                 $toplevel{$1} = $path;
11046:             } else {
11047:                 $toplevel{$path} = $path;
11048:             }
11049:         }
11050:     }
11051:     if ($mimetype =~ m{^application/(x\-)?(compressed|zip)}) {
11052:         my @camtasia6 = ("$topdir/","$topdir/index.html",
11053:                         "$topdir/media/",
11054:                         "$topdir/media/$topdir.mp4",
11055:                         "$topdir/media/FirstFrame.png",
11056:                         "$topdir/media/player.swf",
11057:                         "$topdir/media/swfobject.js",
11058:                         "$topdir/media/expressInstall.swf");
11059:         my @camtasia8 = ("$topdir/","$topdir/$topdir.html",
11060:                          "$topdir/$topdir.mp4",
11061:                          "$topdir/$topdir\_config.xml",
11062:                          "$topdir/$topdir\_controller.swf",
11063:                          "$topdir/$topdir\_embed.css",
11064:                          "$topdir/$topdir\_First_Frame.png",
11065:                          "$topdir/$topdir\_player.html",
11066:                          "$topdir/$topdir\_Thumbnails.png",
11067:                          "$topdir/playerProductInstall.swf",
11068:                          "$topdir/scripts/",
11069:                          "$topdir/scripts/config_xml.js",
11070:                          "$topdir/scripts/handlebars.js",
11071:                          "$topdir/scripts/jquery-1.7.1.min.js",
11072:                          "$topdir/scripts/jquery-ui-1.8.15.custom.min.js",
11073:                          "$topdir/scripts/modernizr.js",
11074:                          "$topdir/scripts/player-min.js",
11075:                          "$topdir/scripts/swfobject.js",
11076:                          "$topdir/skins/",
11077:                          "$topdir/skins/configuration_express.xml",
11078:                          "$topdir/skins/express_show/",
11079:                          "$topdir/skins/express_show/player-min.css",
11080:                          "$topdir/skins/express_show/spritesheet.png");
11081:         my @diffs = &compare_arrays(\@paths,\@camtasia6);
11082:         if (@diffs == 0) {
11083:             $is_camtasia = 6;
11084:         } else {
11085:             @diffs = &compare_arrays(\@paths,\@camtasia8);
11086:             if (@diffs == 0) {
11087:                 $is_camtasia = 8;
11088:             }
11089:         }
11090:     }
11091:     my $output;
11092:     if ($is_camtasia) {
11093:         $output = <<"ENDCAM";
11094: <script type="text/javascript" language="Javascript">
11095: // <![CDATA[
11096: 
11097: function camtasiaToggle() {
11098:     for (var i=0; i<document.uploaded_decompress.autoextract_camtasia.length; i++) {
11099:         if (document.uploaded_decompress.autoextract_camtasia[i].checked) {
11100:             if (document.uploaded_decompress.autoextract_camtasia[i].value == $is_camtasia) {
11101: 
11102:                 document.getElementById('camtasia_titles').style.display='block';
11103:             } else {
11104:                 document.getElementById('camtasia_titles').style.display='none';
11105:             }
11106:         }
11107:     }
11108:     return;
11109: }
11110: 
11111: // ]]>
11112: </script>
11113: <p>$lt{'camt'}</p>
11114: ENDCAM
11115:     } else {
11116:         $output = '<p>'.$lt{'this'};
11117:         if ($info eq '') {
11118:             $output .= ' '.$lt{'youm'}.'</p>'."\n";
11119:         } else {
11120:             $output .= ' '.$lt{'itsc'}.'</p>'."\n".
11121:                        '<div><pre>'.$info.'</pre></div>';
11122:         }
11123:     }
11124:     $output .= '<form name="uploaded_decompress" action="'.$action.'" method="post">'."\n";
11125:     my $duplicates;
11126:     my $num = 0;
11127:     if (ref($dirlist) eq 'ARRAY') {
11128:         foreach my $item (@{$dirlist}) {
11129:             if (ref($item) eq 'ARRAY') {
11130:                 if (exists($toplevel{$item->[0]})) {
11131:                     $duplicates .= 
11132:                         &start_data_table_row().
11133:                         '<td><label><input type="radio" name="archive_overwrite_'.$num.'" '.
11134:                         'value="0" checked="checked" />'.&mt('No').'</label>'.
11135:                         '&nbsp;<label><input type="radio" name="archive_overwrite_'.$num.'" '.
11136:                         'value="1" />'.&mt('Yes').'</label>'.
11137:                         '<input type="hidden" name="archive_overwrite_name_'.$num.'" value="'.$item->[0].'" /></td>'."\n".
11138:                         '<td>'.$item->[0].'</td>';
11139:                     if ($item->[2]) {
11140:                         $duplicates .= '<td>'.&mt('Directory').'</td>';
11141:                     } else {
11142:                         $duplicates .= '<td>'.&mt('File').'</td>';
11143:                     }
11144:                     $duplicates .= '<td>'.$item->[3].'</td>'.
11145:                                    '<td>'.
11146:                                    &Apache::lonlocal::locallocaltime($item->[4]).
11147:                                    '</td>'.
11148:                                    &end_data_table_row();
11149:                     $num ++;
11150:                 }
11151:             }
11152:         }
11153:     }
11154:     my $itemcount;
11155:     if (@paths > 0) {
11156:         $itemcount = scalar(@paths);
11157:     } else {
11158:         $itemcount = 1;
11159:     }
11160:     if ($is_camtasia) {
11161:         $output .= $lt{'auto'}.'<br />'.
11162:                    '<span class="LC_nobreak">'.$lt{'proa'}.'<label>'.
11163:                    '<input type="radio" name="autoextract_camtasia" value="'.$is_camtasia.'" onclick="javascript:camtasiaToggle();" checked="checked" />'.
11164:                    $lt{'yes'}.'</label>&nbsp;<label>'.
11165:                    '<input type="radio" name="autoextract_camtasia" value="0" onclick="javascript:camtasiaToggle();" />'.
11166:                    $lt{'no'}.'</label></span><br />'.
11167:                    '<div id="camtasia_titles" style="display:block">'.
11168:                    &Apache::lonhtmlcommon::start_pick_box().
11169:                    &Apache::lonhtmlcommon::row_title($lt{'fold'}).
11170:                    '<input type="textbox" name="camtasia_foldername" value="'.$env{'form.comment'}.'" />'."\n".
11171:                    &Apache::lonhtmlcommon::row_closure().
11172:                    &Apache::lonhtmlcommon::row_title($lt{'movi'}).
11173:                    '<input type="textbox" name="camtasia_moviename" value="" />'."\n".
11174:                    &Apache::lonhtmlcommon::row_closure(1).
11175:                    &Apache::lonhtmlcommon::end_pick_box().
11176:                    '</div>';
11177:     }
11178:     $output .= 
11179:         '<input type="hidden" name="archive_overwrite_total" value="'.$num.'" />'.
11180:         '<input type="hidden" name="archive_itemcount" value="'.$itemcount.'" />'.
11181:         "\n";
11182:     if ($duplicates ne '') {
11183:         $output .= '<p><span class="LC_warning">'.
11184:                    &mt('Warning: decompression of the archive will overwrite the following items which already exist:').'</span><br />'.  
11185:                    &start_data_table().
11186:                    &start_data_table_header_row().
11187:                    '<th>'.&mt('Overwrite?').'</th>'.
11188:                    '<th>'.&mt('Name').'</th>'.
11189:                    '<th>'.&mt('Type').'</th>'.
11190:                    '<th>'.&mt('Size').'</th>'.
11191:                    '<th>'.&mt('Last modified').'</th>'.
11192:                    &end_data_table_header_row().
11193:                    $duplicates.
11194:                    &end_data_table().
11195:                    '</p>';
11196:     }
11197:     $output .= '<input type="hidden" name="archiveurl" value="'.$archiveurl.'" />'."\n";
11198:     if (ref($hiddenelements) eq 'HASH') {
11199:         foreach my $hidden (sort(keys(%{$hiddenelements}))) {
11200:             $output .= '<input type="hidden" name="'.$hidden.'" value="'.$hiddenelements->{$hidden}.'" />'."\n";
11201:         }
11202:     }
11203:     $output .= <<"END";
11204: <br />
11205: <input type="submit" name="decompress" value="$lt{'extr'}" />
11206: </form>
11207: $noextract
11208: END
11209:     return $output;
11210: }
11211: 
11212: sub decompression_utility {
11213:     my ($program) = @_;
11214:     my @utilities = ('tar','gunzip','bunzip2','unzip'); 
11215:     my $location;
11216:     if (grep(/^\Q$program\E$/,@utilities)) { 
11217:         foreach my $dir ('/bin/','/usr/bin/','/usr/local/bin/','/sbin/',
11218:                          '/usr/sbin/') {
11219:             if (-x $dir.$program) {
11220:                 $location = $dir.$program;
11221:                 last;
11222:             }
11223:         }
11224:     }
11225:     return $location;
11226: }
11227: 
11228: sub list_archive_contents {
11229:     my ($file,$pathsref) = @_;
11230:     my (@cmd,$output);
11231:     my $needsregexp;
11232:     if ($file =~ /\.zip$/) {
11233:         @cmd = (&decompression_utility('unzip'),"-l");
11234:         $needsregexp = 1;
11235:     } elsif (($file =~ m/\.tar\.gz$/) ||
11236:              ($file =~ /\.tgz$/)) {
11237:         @cmd = (&decompression_utility('tar'),"-ztf");
11238:     } elsif ($file =~ /\.tar\.bz2$/) {
11239:         @cmd = (&decompression_utility('tar'),"-jtf");
11240:     } elsif ($file =~ m|\.tar$|) {
11241:         @cmd = (&decompression_utility('tar'),"-tf");
11242:     }
11243:     if (@cmd) {
11244:         undef($!);
11245:         undef($@);
11246:         if (open(my $fh,"-|", @cmd, $file)) {
11247:             while (my $line = <$fh>) {
11248:                 $output .= $line;
11249:                 chomp($line);
11250:                 my $item;
11251:                 if ($needsregexp) {
11252:                     ($item) = ($line =~ /^\s*\d+\s+[\d\-]+\s+[\d:]+\s*(.+)$/); 
11253:                 } else {
11254:                     $item = $line;
11255:                 }
11256:                 if ($item ne '') {
11257:                     unless (grep(/^\Q$item\E$/,@{$pathsref})) {
11258:                         push(@{$pathsref},$item);
11259:                     } 
11260:                 }
11261:             }
11262:             close($fh);
11263:         }
11264:     }
11265:     return $output;
11266: }
11267: 
11268: sub decompress_uploaded_file {
11269:     my ($file,$dir) = @_;
11270:     &Apache::lonnet::appenv({'cgi.file' => $file});
11271:     &Apache::lonnet::appenv({'cgi.dir' => $dir});
11272:     my $result = &Apache::lonnet::ssi_body('/cgi-bin/decompress.pl');
11273:     my ($handle) = ($env{'user.environment'} =~m{/([^/]+)\.id$});
11274:     my $lonidsdir = $Apache::lonnet::perlvar{'lonIDsDir'};
11275:     &Apache::lonnet::transfer_profile_to_env($lonidsdir,$handle,1);
11276:     my $decompressed = $env{'cgi.decompressed'};
11277:     &Apache::lonnet::delenv('cgi.file');
11278:     &Apache::lonnet::delenv('cgi.dir');
11279:     &Apache::lonnet::delenv('cgi.decompressed');
11280:     return ($decompressed,$result);
11281: }
11282: 
11283: sub process_decompression {
11284:     my ($docudom,$docuname,$file,$destination,$dir_root,$hiddenelem) = @_;
11285:     my ($dir,$error,$warning,$output);
11286:     if ($file !~ /\.(zip|tar|bz2|gz|tar.gz|tar.bz2|tgz)$/i) {
11287:         $error = &mt('Filename not a supported archive file type.').
11288:                  '<br />'.&mt('Filename should end with one of: [_1].',
11289:                               '.zip, .tar, .bz2, .gz, .tar.gz, .tar.bz2, .tgz');
11290:     } else {
11291:         my $docuhome = &Apache::lonnet::homeserver($docuname,$docudom);
11292:         if ($docuhome eq 'no_host') {
11293:             $error = &mt('Could not determine home server for course.');
11294:         } else {
11295:             my @ids=&Apache::lonnet::current_machine_ids();
11296:             my $currdir = "$dir_root/$destination";
11297:             if (grep(/^\Q$docuhome\E$/,@ids)) {
11298:                 $dir = &LONCAPA::propath($docudom,$docuname).
11299:                        "$dir_root/$destination";
11300:             } else {
11301:                 $dir = $Apache::lonnet::perlvar{'lonDocRoot'}.
11302:                        "$dir_root/$docudom/$docuname/$destination";
11303:                 unless (&Apache::lonnet::repcopy_userfile("$dir/$file") eq 'ok') {
11304:                     $error = &mt('Archive file not found.');
11305:                 }
11306:             }
11307:             my (@to_overwrite,@to_skip);
11308:             if ($env{'form.archive_overwrite_total'} > 0) {
11309:                 my $total = $env{'form.archive_overwrite_total'};
11310:                 for (my $i=0; $i<$total; $i++) {
11311:                     if ($env{'form.archive_overwrite_'.$i} == 1) {
11312:                         push(@to_overwrite,$env{'form.archive_overwrite_name_'.$i});
11313:                     } elsif ($env{'form.archive_overwrite_'.$i} == 0) {
11314:                         push(@to_skip,$env{'form.archive_overwrite_name_'.$i});
11315:                     }
11316:                 }
11317:             }
11318:             my $numskip = scalar(@to_skip);
11319:             if (($numskip > 0) && 
11320:                 ($numskip == $env{'form.archive_itemcount'})) {
11321:                 $warning = &mt('All items in the archive file already exist, and no overwriting of existing files has been requested.');         
11322:             } elsif ($dir eq '') {
11323:                 $error = &mt('Directory containing archive file unavailable.');
11324:             } elsif (!$error) {
11325:                 my ($decompressed,$display);
11326:                 if ($numskip > 0) {
11327:                     my $tempdir = time.'_'.$$.int(rand(10000));
11328:                     mkdir("$dir/$tempdir",0755);
11329:                     system("mv $dir/$file $dir/$tempdir/$file");
11330:                     ($decompressed,$display) = 
11331:                         &decompress_uploaded_file($file,"$dir/$tempdir");
11332:                     foreach my $item (@to_skip) {
11333:                         if (($item ne '') && ($item !~ /\.\./)) {
11334:                             if (-f "$dir/$tempdir/$item") { 
11335:                                 unlink("$dir/$tempdir/$item");
11336:                             } elsif (-d "$dir/$tempdir/$item") {
11337:                                 system("rm -rf $dir/$tempdir/$item");
11338:                             }
11339:                         }
11340:                     }
11341:                     system("mv $dir/$tempdir/* $dir");
11342:                     rmdir("$dir/$tempdir");   
11343:                 } else {
11344:                     ($decompressed,$display) = 
11345:                         &decompress_uploaded_file($file,$dir);
11346:                 }
11347:                 if ($decompressed eq 'ok') {
11348:                     $output = '<p class="LC_info">'.
11349:                               &mt('Files extracted successfully from archive.').
11350:                               '</p>'."\n";
11351:                     my ($warning,$result,@contents);
11352:                     my ($newdirlistref,$newlisterror) =
11353:                         &Apache::lonnet::dirlist($currdir,$docudom,
11354:                                                  $docuname,1);
11355:                     my (%is_dir,%changes,@newitems);
11356:                     my $dirptr = 16384;
11357:                     if (ref($newdirlistref) eq 'ARRAY') {
11358:                         foreach my $dir_line (@{$newdirlistref}) {
11359:                             my ($item,undef,undef,$testdir)=split(/\&/,$dir_line,5);
11360:                             unless (($item =~ /^\.+$/) || ($item eq $file) || 
11361:                                     ((@to_skip > 0) && (grep(/^\Q$item\E$/,@to_skip)))) {
11362:                                 push(@newitems,$item);
11363:                                 if ($dirptr&$testdir) {
11364:                                     $is_dir{$item} = 1;
11365:                                 }
11366:                                 $changes{$item} = 1;
11367:                             }
11368:                         }
11369:                     }
11370:                     if (keys(%changes) > 0) {
11371:                         foreach my $item (sort(@newitems)) {
11372:                             if ($changes{$item}) {
11373:                                 push(@contents,$item);
11374:                             }
11375:                         }
11376:                     }
11377:                     if (@contents > 0) {
11378:                         my $wantform;
11379:                         unless ($env{'form.autoextract_camtasia'}) {
11380:                             $wantform = 1;
11381:                         }
11382:                         my (%children,%parent,%dirorder,%titles);
11383:                         my ($count,$datatable) = &get_extracted($docudom,$docuname,
11384:                                                                 $currdir,\%is_dir,
11385:                                                                 \%children,\%parent,
11386:                                                                 \@contents,\%dirorder,
11387:                                                                 \%titles,$wantform);
11388:                         if ($datatable ne '') {
11389:                             $output .= &archive_options_form('decompressed',$datatable,
11390:                                                              $count,$hiddenelem);
11391:                             my $startcount = 6;
11392:                             $output .= &archive_javascript($startcount,$count,
11393:                                                            \%titles,\%children);
11394:                         }
11395:                         if ($env{'form.autoextract_camtasia'}) {
11396:                             my $version = $env{'form.autoextract_camtasia'};
11397:                             my %displayed;
11398:                             my $total = 1;
11399:                             $env{'form.archive_directory'} = [];
11400:                             foreach my $i (sort { $a <=> $b } keys(%dirorder)) {
11401:                                 my $path = join('/',map { $titles{$_}; } @{$dirorder{$i}});
11402:                                 $path =~ s{/$}{};
11403:                                 my $item;
11404:                                 if ($path ne '') {
11405:                                     $item = "$path/$titles{$i}";
11406:                                 } else {
11407:                                     $item = $titles{$i};
11408:                                 }
11409:                                 $env{'form.archive_content_'.$i} = "$dir_root/$destination/$item";
11410:                                 if ($item eq $contents[0]) {
11411:                                     push(@{$env{'form.archive_directory'}},$i);
11412:                                     $env{'form.archive_'.$i} = 'display';
11413:                                     $env{'form.archive_title_'.$i} = $env{'form.camtasia_foldername'};
11414:                                     $displayed{'folder'} = $i;
11415:                                 } elsif ((($item eq "$contents[0]/index.html") && ($version == 6)) ||
11416:                                          (($item eq "$contents[0]/$contents[0]".'.html') && ($version == 8))) { 
11417:                                     $env{'form.archive_'.$i} = 'display';
11418:                                     $env{'form.archive_title_'.$i} = $env{'form.camtasia_moviename'};
11419:                                     $displayed{'web'} = $i;
11420:                                 } else {
11421:                                     if ((($item eq "$contents[0]/media") && ($version == 6)) ||
11422:                                         ((($item eq "$contents[0]/scripts") || ($item eq "$contents[0]/skins") ||
11423:                                              ($item eq "$contents[0]/skins/express_show")) && ($version == 8))) {
11424:                                         push(@{$env{'form.archive_directory'}},$i);
11425:                                     }
11426:                                     $env{'form.archive_'.$i} = 'dependency';
11427:                                 }
11428:                                 $total ++;
11429:                             }
11430:                             for (my $i=1; $i<$total; $i++) {
11431:                                 next if ($i == $displayed{'web'});
11432:                                 next if ($i == $displayed{'folder'});
11433:                                 $env{'form.archive_dependent_on_'.$i} = $displayed{'web'};
11434:                             }
11435:                             $env{'form.phase'} = 'decompress_cleanup';
11436:                             $env{'form.archivedelete'} = 1;
11437:                             $env{'form.archive_count'} = $total-1;
11438:                             $output .=
11439:                                 &process_extracted_files('coursedocs',$docudom,
11440:                                                          $docuname,$destination,
11441:                                                          $dir_root,$hiddenelem);
11442:                         }
11443:                     } else {
11444:                         $warning = &mt('No new items extracted from archive file.');
11445:                     }
11446:                 } else {
11447:                     $output = $display;
11448:                     $error = &mt('An error occurred during extraction from the archive file.');
11449:                 }
11450:             }
11451:         }
11452:     }
11453:     if ($error) {
11454:         $output .= '<p class="LC_error">'.&mt('Not extracted.').'<br />'.
11455:                    $error.'</p>'."\n";
11456:     }
11457:     if ($warning) {
11458:         $output .= '<p class="LC_warning">'.$warning.'</p>'."\n";
11459:     }
11460:     return $output;
11461: }
11462: 
11463: sub get_extracted {
11464:     my ($docudom,$docuname,$currdir,$is_dir,$children,$parent,$contents,$dirorder,
11465:         $titles,$wantform) = @_;
11466:     my $count = 0;
11467:     my $depth = 0;
11468:     my $datatable;
11469:     my @hierarchy;
11470:     return unless ((ref($is_dir) eq 'HASH') && (ref($children) eq 'HASH') &&
11471:                    (ref($parent) eq 'HASH') && (ref($contents) eq 'ARRAY') &&
11472:                    (ref($dirorder) eq 'HASH') && (ref($titles) eq 'HASH'));
11473:     foreach my $item (@{$contents}) {
11474:         $count ++;
11475:         @{$dirorder->{$count}} = @hierarchy;
11476:         $titles->{$count} = $item;
11477:         &archive_hierarchy($depth,$count,$parent,$children);
11478:         if ($wantform) {
11479:             $datatable .= &archive_row($is_dir->{$item},$item,
11480:                                        $currdir,$depth,$count);
11481:         }
11482:         if ($is_dir->{$item}) {
11483:             $depth ++;
11484:             push(@hierarchy,$count);
11485:             $parent->{$depth} = $count;
11486:             $datatable .=
11487:                 &recurse_extracted_archive("$currdir/$item",$docudom,$docuname,
11488:                                            \$depth,\$count,\@hierarchy,$dirorder,
11489:                                            $children,$parent,$titles,$wantform);
11490:             $depth --;
11491:             pop(@hierarchy);
11492:         }
11493:     }
11494:     return ($count,$datatable);
11495: }
11496: 
11497: sub recurse_extracted_archive {
11498:     my ($currdir,$docudom,$docuname,$depth,$count,$hierarchy,$dirorder,
11499:         $children,$parent,$titles,$wantform) = @_;
11500:     my $result='';
11501:     unless ((ref($depth)) && (ref($count)) && (ref($hierarchy) eq 'ARRAY') &&
11502:             (ref($children) eq 'HASH') && (ref($parent) eq 'HASH') &&
11503:             (ref($dirorder) eq 'HASH')) {
11504:         return $result;
11505:     }
11506:     my $dirptr = 16384;
11507:     my ($newdirlistref,$newlisterror) =
11508:         &Apache::lonnet::dirlist($currdir,$docudom,$docuname,1);
11509:     if (ref($newdirlistref) eq 'ARRAY') {
11510:         foreach my $dir_line (@{$newdirlistref}) {
11511:             my ($item,undef,undef,$testdir)=split(/\&/,$dir_line,5);
11512:             unless ($item =~ /^\.+$/) {
11513:                 $$count ++;
11514:                 @{$dirorder->{$$count}} = @{$hierarchy};
11515:                 $titles->{$$count} = $item;
11516:                 &archive_hierarchy($$depth,$$count,$parent,$children);
11517: 
11518:                 my $is_dir;
11519:                 if ($dirptr&$testdir) {
11520:                     $is_dir = 1;
11521:                 }
11522:                 if ($wantform) {
11523:                     $result .= &archive_row($is_dir,$item,$currdir,$$depth,$$count);
11524:                 }
11525:                 if ($is_dir) {
11526:                     $$depth ++;
11527:                     push(@{$hierarchy},$$count);
11528:                     $parent->{$$depth} = $$count;
11529:                     $result .=
11530:                         &recurse_extracted_archive("$currdir/$item",$docudom,
11531:                                                    $docuname,$depth,$count,
11532:                                                    $hierarchy,$dirorder,$children,
11533:                                                    $parent,$titles,$wantform);
11534:                     $$depth --;
11535:                     pop(@{$hierarchy});
11536:                 }
11537:             }
11538:         }
11539:     }
11540:     return $result;
11541: }
11542: 
11543: sub archive_hierarchy {
11544:     my ($depth,$count,$parent,$children) =@_;
11545:     if ((ref($parent) eq 'HASH') && (ref($children) eq 'HASH')) {
11546:         if (exists($parent->{$depth})) {
11547:              $children->{$parent->{$depth}} .= $count.':';
11548:         }
11549:     }
11550:     return;
11551: }
11552: 
11553: sub archive_row {
11554:     my ($is_dir,$item,$currdir,$depth,$count) = @_;
11555:     my ($name) = ($item =~ m{([^/]+)$});
11556:     my %choices = &Apache::lonlocal::texthash (
11557:                                        'display'    => 'Add as file',
11558:                                        'dependency' => 'Include as dependency',
11559:                                        'discard'    => 'Discard',
11560:                                       );
11561:     if ($is_dir) {
11562:         $choices{'display'} = &mt('Add as folder'); 
11563:     }
11564:     my $output = &start_data_table_row().'<td align="right">'.$count.'</td>'."\n";
11565:     my $offset = 0;
11566:     foreach my $action ('display','dependency','discard') {
11567:         $offset ++;
11568:         if ($action ne 'display') {
11569:             $offset ++;
11570:         }  
11571:         $output .= '<td><span class="LC_nobreak">'.
11572:                    '<label><input type="radio" name="archive_'.$count.
11573:                    '" id="archive_'.$action.'_'.$count.'" value="'.$action.'"';
11574:         my $text = $choices{$action};
11575:         if ($is_dir) {
11576:             $output .= ' onclick="javascript:propagateCheck(this.form,'."'$count'".');"';
11577:             if ($action eq 'display') {
11578:                 $text = &mt('Add as folder');
11579:             }
11580:         } else {
11581:             $output .= ' onclick="javascript:dependencyCheck(this.form,'."$count,$offset".');"';
11582: 
11583:         }
11584:         $output .= ' />&nbsp;'.$choices{$action}.'</label></span>';
11585:         if ($action eq 'dependency') {
11586:             $output .= '<div id="arc_depon_'.$count.'" style="display:none;">'."\n".
11587:                        &mt('Used by:').'&nbsp;<select name="archive_dependent_on_'.$count.'" '.
11588:                        'onchange="propagateSelect(this.form,'."$count,$offset".')">'."\n".
11589:                        '<option value=""></option>'."\n".
11590:                        '</select>'."\n".
11591:                        '</div>';
11592:         } elsif ($action eq 'display') {
11593:             $output .= '<div id="arc_title_'.$count.'" style="display:none;">'."\n".
11594:                        &mt('Title:').'&nbsp;<input type="text" name="archive_title_'.$count.'" id="archive_title_'.$count.'" />'."\n".
11595:                        '</div>';
11596:         }
11597:         $output .= '</td>';
11598:     }
11599:     $output .= '<td><input type="hidden" name="archive_content_'.$count.'" value="'.
11600:                &HTML::Entities::encode("$currdir/$item",'"<>&').'" />'.('&nbsp;' x 2);
11601:     for (my $i=0; $i<$depth; $i++) {
11602:         $output .= ('<img src="/adm/lonIcons/whitespace1.gif" class="LC_docs_spacer" alt="" />' x2)."\n";
11603:     }
11604:     if ($is_dir) {
11605:         $output .= '<img src="/adm/lonIcons/navmap.folder.open.gif" alt="" />&nbsp;'."\n".
11606:                    '<input type="hidden" name="archive_directory" value="'.$count.'" />'."\n";
11607:     } else {
11608:         $output .= '<input type="hidden" name="archive_file" value="'.$count.'" />'."\n";
11609:     }
11610:     $output .= '&nbsp;'.$name.'</td>'."\n".
11611:                &end_data_table_row();
11612:     return $output;
11613: }
11614: 
11615: sub archive_options_form {
11616:     my ($form,$display,$count,$hiddenelem) = @_;
11617:     my %lt = &Apache::lonlocal::texthash(
11618:                perm => 'Permanently remove archive file?',
11619:                hows => 'How should each extracted item be incorporated in the course?',
11620:                cont => 'Content actions for all',
11621:                addf => 'Add as folder/file',
11622:                incd => 'Include as dependency for a displayed file',
11623:                disc => 'Discard',
11624:                no   => 'No',
11625:                yes  => 'Yes',
11626:                save => 'Save',
11627:     );
11628:     my $output = <<"END";
11629: <form name="$form" method="post" action="">
11630: <p><span class="LC_nobreak">$lt{'perm'}&nbsp;
11631: <label>
11632:   <input type="radio" name="archivedelete" value="0" checked="checked" />$lt{'no'}
11633: </label>
11634: &nbsp;
11635: <label>
11636:   <input type="radio" name="archivedelete" value="1" />$lt{'yes'}</label>
11637: </span>
11638: </p>
11639: <input type="hidden" name="phase" value="decompress_cleanup" />
11640: <br />$lt{'hows'}
11641: <div class="LC_columnSection">
11642:   <fieldset>
11643:     <legend>$lt{'cont'}</legend>
11644:     <input type="button" value="$lt{'addf'}" onclick="javascript:checkAll(document.$form,'display');" /> 
11645:     &nbsp;&nbsp;<input type="button" value="$lt{'incd'}" onclick="javascript:checkAll(document.$form,'dependency');" />
11646:     &nbsp;&nbsp;<input type="button" value="$lt{'disc'}" onclick="javascript:checkAll(document.$form,'discard');" />
11647:   </fieldset>
11648: </div>
11649: END
11650:     return $output.
11651:            &start_data_table()."\n".
11652:            $display."\n".
11653:            &end_data_table()."\n".
11654:            '<input type="hidden" name="archive_count" value="'.$count.'" />'.
11655:            $hiddenelem.
11656:            '<br /><input type="submit" name="archive_submit" value="'.$lt{'save'}.'" />'.
11657:            '</form>';
11658: }
11659: 
11660: sub archive_javascript {
11661:     my ($startcount,$numitems,$titles,$children) = @_;
11662:     return unless ((ref($titles) eq 'HASH') && (ref($children) eq 'HASH'));
11663:     my $maintitle = $env{'form.comment'};
11664:     my $scripttag = <<START;
11665: <script type="text/javascript">
11666: // <![CDATA[
11667: 
11668: function checkAll(form,prefix) {
11669:     var idstr =  new RegExp("^archive_"+prefix+"_\\\\d+\$");
11670:     for (var i=0; i < form.elements.length; i++) {
11671:         var id = form.elements[i].id;
11672:         if ((id != '') && (id != undefined)) {
11673:             if (idstr.test(id)) {
11674:                 if (form.elements[i].type == 'radio') {
11675:                     form.elements[i].checked = true;
11676:                     var nostart = i-$startcount;
11677:                     var offset = nostart%7;
11678:                     var count = (nostart-offset)/7;    
11679:                     dependencyCheck(form,count,offset);
11680:                 }
11681:             }
11682:         }
11683:     }
11684: }
11685: 
11686: function propagateCheck(form,count) {
11687:     if (count > 0) {
11688:         var startelement = $startcount + ((count-1) * 7);
11689:         for (var j=1; j<6; j++) {
11690:             if ((j != 2) && (j != 4)) {
11691:                 var item = startelement + j; 
11692:                 if (form.elements[item].type == 'radio') {
11693:                     if (form.elements[item].checked) {
11694:                         containerCheck(form,count,j);
11695:                         break;
11696:                     }
11697:                 }
11698:             }
11699:         }
11700:     }
11701: }
11702: 
11703: numitems = $numitems
11704: var titles = new Array(numitems);
11705: var parents = new Array(numitems);
11706: for (var i=0; i<numitems; i++) {
11707:     parents[i] = new Array;
11708: }
11709: var maintitle = '$maintitle';
11710: 
11711: START
11712: 
11713:     foreach my $container (sort { $a <=> $b } (keys(%{$children}))) {
11714:         my @contents = split(/:/,$children->{$container});
11715:         for (my $i=0; $i<@contents; $i ++) {
11716:             $scripttag .= 'parents['.$container.']['.$i.'] = '.$contents[$i]."\n";
11717:         }
11718:     }
11719: 
11720:     foreach my $key (sort { $a <=> $b } (keys(%{$titles}))) {
11721:         $scripttag .= "titles[$key] = '".$titles->{$key}."';\n";
11722:     }
11723: 
11724:     $scripttag .= <<END;
11725: 
11726: function containerCheck(form,count,offset) {
11727:     if (count > 0) {
11728:         dependencyCheck(form,count,offset);
11729:         var item = (offset+$startcount)+7*(count-1);
11730:         form.elements[item].checked = true;
11731:         if(Object.prototype.toString.call(parents[count]) === '[object Array]') {
11732:             if (parents[count].length > 0) {
11733:                 for (var j=0; j<parents[count].length; j++) {
11734:                     containerCheck(form,parents[count][j],offset);
11735:                 }
11736:             }
11737:         }
11738:     }
11739: }
11740: 
11741: function dependencyCheck(form,count,offset) {
11742:     if (count > 0) {
11743:         var chosen = (offset+$startcount)+7*(count-1);
11744:         var depitem = $startcount + ((count-1) * 7) + 4;
11745:         var currtype = form.elements[depitem].type;
11746:         if (form.elements[chosen].value == 'dependency') {
11747:             document.getElementById('arc_depon_'+count).style.display='block'; 
11748:             form.elements[depitem].options.length = 0;
11749:             form.elements[depitem].options[0] = new Option('Select','',true,true);
11750:             for (var i=1; i<=numitems; i++) {
11751:                 if (i == count) {
11752:                     continue;
11753:                 }
11754:                 var startelement = $startcount + (i-1) * 7;
11755:                 for (var j=1; j<6; j++) {
11756:                     if ((j != 2) && (j!= 4)) {
11757:                         var item = startelement + j;
11758:                         if (form.elements[item].type == 'radio') {
11759:                             if (form.elements[item].checked) {
11760:                                 if (form.elements[item].value == 'display') {
11761:                                     var n = form.elements[depitem].options.length;
11762:                                     form.elements[depitem].options[n] = new Option(titles[i],i,false,false);
11763:                                 }
11764:                             }
11765:                         }
11766:                     }
11767:                 }
11768:             }
11769:         } else {
11770:             document.getElementById('arc_depon_'+count).style.display='none';
11771:             form.elements[depitem].options.length = 0;
11772:             form.elements[depitem].options[0] = new Option('Select','',true,true);
11773:         }
11774:         titleCheck(form,count,offset);
11775:     }
11776: }
11777: 
11778: function propagateSelect(form,count,offset) {
11779:     if (count > 0) {
11780:         var item = (1+offset+$startcount)+7*(count-1);
11781:         var picked = form.elements[item].options[form.elements[item].selectedIndex].value; 
11782:         if (Object.prototype.toString.call(parents[count]) === '[object Array]') {
11783:             if (parents[count].length > 0) {
11784:                 for (var j=0; j<parents[count].length; j++) {
11785:                     containerSelect(form,parents[count][j],offset,picked);
11786:                 }
11787:             }
11788:         }
11789:     }
11790: }
11791: 
11792: function containerSelect(form,count,offset,picked) {
11793:     if (count > 0) {
11794:         var item = (offset+$startcount)+7*(count-1);
11795:         if (form.elements[item].type == 'radio') {
11796:             if (form.elements[item].value == 'dependency') {
11797:                 if (form.elements[item+1].type == 'select-one') {
11798:                     for (var i=0; i<form.elements[item+1].options.length; i++) {
11799:                         if (form.elements[item+1].options[i].value == picked) {
11800:                             form.elements[item+1].selectedIndex = i;
11801:                             break;
11802:                         }
11803:                     }
11804:                 }
11805:                 if (Object.prototype.toString.call(parents[count]) === '[object Array]') {
11806:                     if (parents[count].length > 0) {
11807:                         for (var j=0; j<parents[count].length; j++) {
11808:                             containerSelect(form,parents[count][j],offset,picked);
11809:                         }
11810:                     }
11811:                 }
11812:             }
11813:         }
11814:     }
11815: }
11816: 
11817: function titleCheck(form,count,offset) {
11818:     if (count > 0) {
11819:         var chosen = (offset+$startcount)+7*(count-1);
11820:         var depitem = $startcount + ((count-1) * 7) + 2;
11821:         var currtype = form.elements[depitem].type;
11822:         if (form.elements[chosen].value == 'display') {
11823:             document.getElementById('arc_title_'+count).style.display='block';
11824:             if ((count==1) && ((parents[count].length > 0) || (numitems == 1))) {
11825:                 document.getElementById('archive_title_'+count).value=maintitle;
11826:             }
11827:         } else {
11828:             document.getElementById('arc_title_'+count).style.display='none';
11829:             if (currtype == 'text') { 
11830:                 document.getElementById('archive_title_'+count).value='';
11831:             }
11832:         }
11833:     }
11834:     return;
11835: }
11836: 
11837: // ]]>
11838: </script>
11839: END
11840:     return $scripttag;
11841: }
11842: 
11843: sub process_extracted_files {
11844:     my ($context,$docudom,$docuname,$destination,$dir_root,$hiddenelem) = @_;
11845:     my $numitems = $env{'form.archive_count'};
11846:     return unless ($numitems);
11847:     my @ids=&Apache::lonnet::current_machine_ids();
11848:     my ($prefix,$pathtocheck,$dir,$ishome,$error,$warning,%toplevelitems,%is_dir,
11849:         %folders,%containers,%mapinner,%prompttofetch);
11850:     my $docuhome = &Apache::lonnet::homeserver($docuname,$docudom);
11851:     if (grep(/^\Q$docuhome\E$/,@ids)) {
11852:         $prefix = &LONCAPA::propath($docudom,$docuname);
11853:         $pathtocheck = "$dir_root/$destination";
11854:         $dir = $dir_root;
11855:         $ishome = 1;
11856:     } else {
11857:         $prefix = $Apache::lonnet::perlvar{'lonDocRoot'};
11858:         $pathtocheck = "$dir_root/$docudom/$docuname/$destination";
11859:         $dir = "$dir_root/$docudom/$docuname";    
11860:     }
11861:     my $currdir = "$dir_root/$destination";
11862:     (my $docstype,$mapinner{'0'}) = ($destination =~ m{^(docs|supplemental)/(\w+)/});
11863:     if ($env{'form.folderpath'}) {
11864:         my @items = split('&',$env{'form.folderpath'});
11865:         $folders{'0'} = $items[-2];
11866:         if ($env{'form.folderpath'} =~ /\:1$/) {
11867:             $containers{'0'}='page';
11868:         } else {  
11869:             $containers{'0'}='sequence';
11870:         }
11871:     }
11872:     my @archdirs = &get_env_multiple('form.archive_directory');
11873:     if ($numitems) {
11874:         for (my $i=1; $i<=$numitems; $i++) {
11875:             my $path = $env{'form.archive_content_'.$i};
11876:             if ($path =~ m{^\Q$pathtocheck\E/([^/]+)$}) {
11877:                 my $item = $1;
11878:                 $toplevelitems{$item} = $i;
11879:                 if (grep(/^\Q$i\E$/,@archdirs)) {
11880:                     $is_dir{$item} = 1;
11881:                 }
11882:             }
11883:         }
11884:     }
11885:     my ($output,%children,%parent,%titles,%dirorder,$result);
11886:     if (keys(%toplevelitems) > 0) {
11887:         my @contents = sort(keys(%toplevelitems));
11888:         (my $count,undef) = &get_extracted($docudom,$docuname,$currdir,\%is_dir,\%children,
11889:                                            \%parent,\@contents,\%dirorder,\%titles);
11890:     }
11891:     my (%referrer,%orphaned,%todelete,%todeletedir,%newdest,%newseqid);
11892:     if ($numitems) {
11893:         for (my $i=1; $i<=$numitems; $i++) {
11894:             next if ($env{'form.archive_'.$i} eq 'dependency');
11895:             my $path = $env{'form.archive_content_'.$i};
11896:             if ($path =~ /^\Q$pathtocheck\E/) {
11897:                 if ($env{'form.archive_'.$i} eq 'discard') {
11898:                     if ($prefix ne '' && $path ne '') {
11899:                         if (-e $prefix.$path) {
11900:                             if ((@archdirs > 0) && 
11901:                                 (grep(/^\Q$i\E$/,@archdirs))) {
11902:                                 $todeletedir{$prefix.$path} = 1;
11903:                             } else {
11904:                                 $todelete{$prefix.$path} = 1;
11905:                             }
11906:                         }
11907:                     }
11908:                 } elsif ($env{'form.archive_'.$i} eq 'display') {
11909:                     my ($docstitle,$title,$url,$outer);
11910:                     ($title) = ($path =~ m{/([^/]+)$});
11911:                     $docstitle = $env{'form.archive_title_'.$i};
11912:                     if ($docstitle eq '') {
11913:                         $docstitle = $title;
11914:                     }
11915:                     $outer = 0;
11916:                     if (ref($dirorder{$i}) eq 'ARRAY') {
11917:                         if (@{$dirorder{$i}} > 0) {
11918:                             foreach my $item (reverse(@{$dirorder{$i}})) {
11919:                                 if ($env{'form.archive_'.$item} eq 'display') {
11920:                                     $outer = $item;
11921:                                     last;
11922:                                 }
11923:                             }
11924:                         }
11925:                     }
11926:                     my ($errtext,$fatal) = 
11927:                         &LONCAPA::map::mapread('/uploaded/'.$docudom.'/'.$docuname.
11928:                                                '/'.$folders{$outer}.'.'.
11929:                                                $containers{$outer});
11930:                     next if ($fatal);
11931:                     if ((@archdirs > 0) && (grep(/^\Q$i\E$/,@archdirs))) {
11932:                         if ($context eq 'coursedocs') {
11933:                             $mapinner{$i} = time;
11934:                             $folders{$i} = 'default_'.$mapinner{$i};
11935:                             $containers{$i} = 'sequence';
11936:                             my $url = '/uploaded/'.$docudom.'/'.$docuname.'/'.
11937:                                       $folders{$i}.'.'.$containers{$i};
11938:                             my $newidx = &LONCAPA::map::getresidx();
11939:                             $LONCAPA::map::resources[$newidx]=
11940:                                 $docstitle.':'.$url.':false:normal:res';
11941:                             push(@LONCAPA::map::order,$newidx);
11942:                             my ($outtext,$errtext) =
11943:                                 &LONCAPA::map::storemap('/uploaded/'.$docudom.'/'.
11944:                                                         $docuname.'/'.$folders{$outer}.
11945:                                                         '.'.$containers{$outer},1,1);
11946:                             $newseqid{$i} = $newidx;
11947:                             unless ($errtext) {
11948:                                 $result .=  '<li>'.&mt('Folder: [_1] added to course',$docstitle).'</li>'."\n";
11949:                             }
11950:                         }
11951:                     } else {
11952:                         if ($context eq 'coursedocs') {
11953:                             my $newidx=&LONCAPA::map::getresidx();
11954:                             my $url = '/uploaded/'.$docudom.'/'.$docuname.'/'.
11955:                                       $docstype.'/'.$mapinner{$outer}.'/'.$newidx.'/'.
11956:                                       $title;
11957:                             if (!-e "$prefix$dir/$docstype/$mapinner{$outer}") {
11958:                                 mkdir("$prefix$dir/$docstype/$mapinner{$outer}",0755);
11959:                             }
11960:                             if (!-e "$prefix$dir/$docstype/$mapinner{$outer}/$newidx") {
11961:                                 mkdir("$prefix$dir/$docstype/$mapinner{$outer}/$newidx");
11962:                             }
11963:                             if (-e "$prefix$dir/$docstype/$mapinner{$outer}/$newidx") {
11964:                                 system("mv $prefix$path $prefix$dir/$docstype/$mapinner{$outer}/$newidx/$title");
11965:                                 $newdest{$i} = "$prefix$dir/$docstype/$mapinner{$outer}/$newidx";
11966:                                 unless ($ishome) {
11967:                                     my $fetch = "$newdest{$i}/$title";
11968:                                     $fetch =~ s/^\Q$prefix$dir\E//;
11969:                                     $prompttofetch{$fetch} = 1;
11970:                                 }
11971:                             }
11972:                             $LONCAPA::map::resources[$newidx]=
11973:                                 $docstitle.':'.$url.':false:normal:res';
11974:                             push(@LONCAPA::map::order, $newidx);
11975:                             my ($outtext,$errtext)=
11976:                                 &LONCAPA::map::storemap('/uploaded/'.$docudom.'/'.
11977:                                                         $docuname.'/'.$folders{$outer}.
11978:                                                         '.'.$containers{$outer},1,1);
11979:                             unless ($errtext) {
11980:                                 if (-e "$prefix$dir/$docstype/$mapinner{$outer}/$newidx/$title") {
11981:                                     $result .= '<li>'.&mt('File: [_1] added to course',$docstitle).'</li>'."\n";
11982:                                 }
11983:                             }
11984:                         }
11985:                     }
11986:                 }
11987:             } else {
11988:                 $warning .= &mt('Item extracted from archive: [_1] has unexpected path.',$path).'<br />'; 
11989:             }
11990:         }
11991:         for (my $i=1; $i<=$numitems; $i++) {
11992:             next unless ($env{'form.archive_'.$i} eq 'dependency');
11993:             my $path = $env{'form.archive_content_'.$i};
11994:             if ($path =~ /^\Q$pathtocheck\E/) {
11995:                 my ($title) = ($path =~ m{/([^/]+)$});
11996:                 $referrer{$i} = $env{'form.archive_dependent_on_'.$i};
11997:                 if ($env{'form.archive_'.$referrer{$i}} eq 'display') {
11998:                     if (ref($dirorder{$i}) eq 'ARRAY') {
11999:                         my ($itemidx,$fullpath,$relpath);
12000:                         if (ref($dirorder{$referrer{$i}}) eq 'ARRAY') {
12001:                             my $container = $dirorder{$referrer{$i}}->[-1];
12002:                             for (my $j=0; $j<@{$dirorder{$i}}; $j++) {
12003:                                 if ($dirorder{$i}->[$j] eq $container) {
12004:                                     $itemidx = $j;
12005:                                 }
12006:                             }
12007:                         }
12008:                         if ($itemidx eq '') {
12009:                             $itemidx =  0;
12010:                         } 
12011:                         if (grep(/^\Q$referrer{$i}\E$/,@archdirs)) {
12012:                             if ($mapinner{$referrer{$i}}) {
12013:                                 $fullpath = "$prefix$dir/$docstype/$mapinner{$referrer{$i}}";
12014:                                 for (my $j=$itemidx; $j<@{$dirorder{$i}}; $j++) {
12015:                                     if (grep(/^\Q$dirorder{$i}->[$j]\E$/,@archdirs)) {
12016:                                         unless (defined($newseqid{$dirorder{$i}->[$j]})) {
12017:                                             $fullpath .= '/'.$titles{$dirorder{$i}->[$j]};
12018:                                             $relpath .= '/'.$titles{$dirorder{$i}->[$j]};
12019:                                             if (!-e $fullpath) {
12020:                                                 mkdir($fullpath,0755);
12021:                                             }
12022:                                         }
12023:                                     } else {
12024:                                         last;
12025:                                     }
12026:                                 }
12027:                             }
12028:                         } elsif ($newdest{$referrer{$i}}) {
12029:                             $fullpath = $newdest{$referrer{$i}};
12030:                             for (my $j=$itemidx; $j<@{$dirorder{$i}}; $j++) {
12031:                                 if ($env{'form.archive_'.$dirorder{$i}->[$j]} eq 'discard') {
12032:                                     $orphaned{$i} = $env{'form.archive_'.$dirorder{$i}->[$j]};
12033:                                     last;
12034:                                 } elsif (grep(/^\Q$dirorder{$i}->[$j]\E$/,@archdirs)) {
12035:                                     unless (defined($newseqid{$dirorder{$i}->[$j]})) {
12036:                                         $fullpath .= '/'.$titles{$dirorder{$i}->[$j]};
12037:                                         $relpath .= '/'.$titles{$dirorder{$i}->[$j]};
12038:                                         if (!-e $fullpath) {
12039:                                             mkdir($fullpath,0755);
12040:                                         }
12041:                                     }
12042:                                 } else {
12043:                                     last;
12044:                                 }
12045:                             }
12046:                         }
12047:                         if ($fullpath ne '') {
12048:                             if (-e "$prefix$path") {
12049:                                 system("mv $prefix$path $fullpath/$title");
12050:                             }
12051:                             if (-e "$fullpath/$title") {
12052:                                 my $showpath;
12053:                                 if ($relpath ne '') {
12054:                                     $showpath = "$relpath/$title";
12055:                                 } else {
12056:                                     $showpath = "/$title";
12057:                                 } 
12058:                                 $result .= '<li>'.&mt('[_1] included as a dependency',$showpath).'</li>'."\n";
12059:                             } 
12060:                             unless ($ishome) {
12061:                                 my $fetch = "$fullpath/$title";
12062:                                 $fetch =~ s/^\Q$prefix$dir\E//; 
12063:                                 $prompttofetch{$fetch} = 1;
12064:                             }
12065:                         }
12066:                     }
12067:                 } elsif ($env{'form.archive_'.$referrer{$i}} eq 'discard') {
12068:                     $warning .= &mt('[_1] is a dependency of [_2], which was discarded.',
12069:                                     $path,$env{'form.archive_content_'.$referrer{$i}}).'<br />';
12070:                 }
12071:             } else {
12072:                 $warning .= &mt('Item extracted from archive: [_1] has unexpected path.',$path).'<br />'; 
12073:             }
12074:         }
12075:         if (keys(%todelete)) {
12076:             foreach my $key (keys(%todelete)) {
12077:                 unlink($key);
12078:             }
12079:         }
12080:         if (keys(%todeletedir)) {
12081:             foreach my $key (keys(%todeletedir)) {
12082:                 rmdir($key);
12083:             }
12084:         }
12085:         foreach my $dir (sort(keys(%is_dir))) {
12086:             if (($pathtocheck ne '') && ($dir ne ''))  {
12087:                 &cleanup_empty_dirs($prefix."$pathtocheck/$dir");
12088:             }
12089:         }
12090:         if ($result ne '') {
12091:             $output .= '<ul>'."\n".
12092:                        $result."\n".
12093:                        '</ul>';
12094:         }
12095:         unless ($ishome) {
12096:             my $replicationfail;
12097:             foreach my $item (keys(%prompttofetch)) {
12098:                 my $fetchresult= &Apache::lonnet::reply('fetchuserfile:'.$item,$docuhome);
12099:                 unless ($fetchresult eq 'ok') {
12100:                     $replicationfail .= '<li>'.$item.'</li>'."\n";
12101:                 }
12102:             }
12103:             if ($replicationfail) {
12104:                 $output .= '<p class="LC_error">'.
12105:                            &mt('Course home server failed to retrieve:').'<ul>'.
12106:                            $replicationfail.
12107:                            '</ul></p>';
12108:             }
12109:         }
12110:     } else {
12111:         $warning = &mt('No items found in archive.');
12112:     }
12113:     if ($error) {
12114:         $output .= '<p class="LC_error">'.&mt('Not extracted.').'<br />'.
12115:                    $error.'</p>'."\n";
12116:     }
12117:     if ($warning) {
12118:         $output .= '<p class="LC_warning">'.$warning.'</p>'."\n";
12119:     }
12120:     return $output;
12121: }
12122: 
12123: sub cleanup_empty_dirs {
12124:     my ($path) = @_;
12125:     if (($path ne '') && (-d $path)) {
12126:         if (opendir(my $dirh,$path)) {
12127:             my @dircontents = grep(!/^\./,readdir($dirh));
12128:             my $numitems = 0;
12129:             foreach my $item (@dircontents) {
12130:                 if (-d "$path/$item") {
12131:                     &cleanup_empty_dirs("$path/$item");
12132:                     if (-e "$path/$item") {
12133:                         $numitems ++;
12134:                     }
12135:                 } else {
12136:                     $numitems ++;
12137:                 }
12138:             }
12139:             if ($numitems == 0) {
12140:                 rmdir($path);
12141:             }
12142:             closedir($dirh);
12143:         }
12144:     }
12145:     return;
12146: }
12147: 
12148: =pod
12149: 
12150: =item * &get_folder_hierarchy()
12151: 
12152: Provides hierarchy of names of folders/sub-folders containing the current
12153: item,
12154: 
12155: Inputs: 3
12156:      - $navmap - navmaps object
12157: 
12158:      - $map - url for map (either the trigger itself, or map containing
12159:                            the resource, which is the trigger).
12160: 
12161:      - $showitem - 1 => show title for map itself; 0 => do not show.
12162: 
12163: Outputs: 1 @pathitems - array of folder/subfolder names.
12164: 
12165: =cut
12166: 
12167: sub get_folder_hierarchy {
12168:     my ($navmap,$map,$showitem) = @_;
12169:     my @pathitems;
12170:     if (ref($navmap)) {
12171:         my $mapres = $navmap->getResourceByUrl($map);
12172:         if (ref($mapres)) {
12173:             my $pcslist = $mapres->map_hierarchy();
12174:             if ($pcslist ne '') {
12175:                 my @pcs = split(/,/,$pcslist);
12176:                 foreach my $pc (@pcs) {
12177:                     if ($pc == 1) {
12178:                         push(@pathitems,&mt('Main Content'));
12179:                     } else {
12180:                         my $res = $navmap->getByMapPc($pc);
12181:                         if (ref($res)) {
12182:                             my $title = $res->compTitle();
12183:                             $title =~ s/\W+/_/g;
12184:                             if ($title ne '') {
12185:                                 push(@pathitems,$title);
12186:                             }
12187:                         }
12188:                     }
12189:                 }
12190:             }
12191:             if ($showitem) {
12192:                 if ($mapres->{ID} eq '0.0') {
12193:                     push(@pathitems,&mt('Main Content'));
12194:                 } else {
12195:                     my $maptitle = $mapres->compTitle();
12196:                     $maptitle =~ s/\W+/_/g;
12197:                     if ($maptitle ne '') {
12198:                         push(@pathitems,$maptitle);
12199:                     }
12200:                 }
12201:             }
12202:         }
12203:     }
12204:     return @pathitems;
12205: }
12206: 
12207: =pod
12208: 
12209: =item * &get_turnedin_filepath()
12210: 
12211: Determines path in a user's portfolio file for storage of files uploaded
12212: to a specific essayresponse or dropbox item.
12213: 
12214: Inputs: 3 required + 1 optional.
12215: $symb is symb for resource, $uname and $udom are for current user (required).
12216: $caller is optional (can be "submission", if routine is called when storing
12217: an upoaded file when "Submit Answer" button was pressed).
12218: 
12219: Returns array containing $path and $multiresp. 
12220: $path is path in portfolio.  $multiresp is 1 if this resource contains more
12221: than one file upload item.  Callers of routine should append partid as a 
12222: subdirectory to $path in cases where $multiresp is 1.
12223: 
12224: Called by: homework/essayresponse.pm and homework/structuretags.pm
12225: 
12226: =cut
12227: 
12228: sub get_turnedin_filepath {
12229:     my ($symb,$uname,$udom,$caller) = @_;
12230:     my ($map,$resid,$resurl)=&Apache::lonnet::decode_symb($symb);
12231:     my $turnindir;
12232:     my %userhash = &Apache::lonnet::userenvironment($udom,$uname,'turnindir');
12233:     $turnindir = $userhash{'turnindir'};
12234:     my ($path,$multiresp);
12235:     if ($turnindir eq '') {
12236:         if ($caller eq 'submission') {
12237:             $turnindir = &mt('turned in');
12238:             $turnindir =~ s/\W+/_/g;
12239:             my %newhash = (
12240:                             'turnindir' => $turnindir,
12241:                           );
12242:             &Apache::lonnet::put('environment',\%newhash,$udom,$uname);
12243:         }
12244:     }
12245:     if ($turnindir ne '') {
12246:         $path = '/'.$turnindir.'/';
12247:         my ($multipart,$turnin,@pathitems);
12248:         my $navmap = Apache::lonnavmaps::navmap->new();
12249:         if (defined($navmap)) {
12250:             my $mapres = $navmap->getResourceByUrl($map);
12251:             if (ref($mapres)) {
12252:                 my $pcslist = $mapres->map_hierarchy();
12253:                 if ($pcslist ne '') {
12254:                     foreach my $pc (split(/,/,$pcslist)) {
12255:                         my $res = $navmap->getByMapPc($pc);
12256:                         if (ref($res)) {
12257:                             my $title = $res->compTitle();
12258:                             $title =~ s/\W+/_/g;
12259:                             if ($title ne '') {
12260:                                 if (($pc > 1) && (length($title) > 12)) {
12261:                                     $title = substr($title,0,12);
12262:                                 }
12263:                                 push(@pathitems,$title);
12264:                             }
12265:                         }
12266:                     }
12267:                 }
12268:                 my $maptitle = $mapres->compTitle();
12269:                 $maptitle =~ s/\W+/_/g;
12270:                 if ($maptitle ne '') {
12271:                     if (length($maptitle) > 12) {
12272:                         $maptitle = substr($maptitle,0,12);
12273:                     }
12274:                     push(@pathitems,$maptitle);
12275:                 }
12276:                 unless ($env{'request.state'} eq 'construct') {
12277:                     my $res = $navmap->getBySymb($symb);
12278:                     if (ref($res)) {
12279:                         my $partlist = $res->parts();
12280:                         my $totaluploads = 0;
12281:                         if (ref($partlist) eq 'ARRAY') {
12282:                             foreach my $part (@{$partlist}) {
12283:                                 my @types = $res->responseType($part);
12284:                                 my @ids = $res->responseIds($part);
12285:                                 for (my $i=0; $i < scalar(@ids); $i++) {
12286:                                     if ($types[$i] eq 'essay') {
12287:                                         my $partid = $part.'_'.$ids[$i];
12288:                                         if (&Apache::lonnet::EXT("resource.$partid.uploadedfiletypes") ne '') {
12289:                                             $totaluploads ++;
12290:                                         }
12291:                                     }
12292:                                 }
12293:                             }
12294:                             if ($totaluploads > 1) {
12295:                                 $multiresp = 1;
12296:                             }
12297:                         }
12298:                     }
12299:                 }
12300:             } else {
12301:                 return;
12302:             }
12303:         } else {
12304:             return;
12305:         }
12306:         my $restitle=&Apache::lonnet::gettitle($symb);
12307:         $restitle =~ s/\W+/_/g;
12308:         if ($restitle eq '') {
12309:             $restitle = ($resurl =~ m{/[^/]+$});
12310:             if ($restitle eq '') {
12311:                 $restitle = time;
12312:             }
12313:         }
12314:         if (length($restitle) > 12) {
12315:             $restitle = substr($restitle,0,12);
12316:         }
12317:         push(@pathitems,$restitle);
12318:         $path .= join('/',@pathitems);
12319:     }
12320:     return ($path,$multiresp);
12321: }
12322: 
12323: =pod
12324: 
12325: =back
12326: 
12327: =head1 CSV Upload/Handling functions
12328: 
12329: =over 4
12330: 
12331: =item * &upfile_store($r)
12332: 
12333: Store uploaded file, $r should be the HTTP Request object,
12334: needs $env{'form.upfile'}
12335: returns $datatoken to be put into hidden field
12336: 
12337: =cut
12338: 
12339: sub upfile_store {
12340:     my $r=shift;
12341:     $env{'form.upfile'}=~s/\r/\n/gs;
12342:     $env{'form.upfile'}=~s/\f/\n/gs;
12343:     $env{'form.upfile'}=~s/\n+/\n/gs;
12344:     $env{'form.upfile'}=~s/\n+$//gs;
12345: 
12346:     my $datatoken=$env{'user.name'}.'_'.$env{'user.domain'}.
12347: 	'_enroll_'.$env{'request.course.id'}.'_'.time.'_'.$$;
12348:     {
12349:         my $datafile = $r->dir_config('lonDaemons').
12350:                            '/tmp/'.$datatoken.'.tmp';
12351:         if ( open(my $fh,">$datafile") ) {
12352:             print $fh $env{'form.upfile'};
12353:             close($fh);
12354:         }
12355:     }
12356:     return $datatoken;
12357: }
12358: 
12359: =pod
12360: 
12361: =item * &load_tmp_file($r)
12362: 
12363: Load uploaded file from tmp, $r should be the HTTP Request object,
12364: needs $env{'form.datatoken'},
12365: sets $env{'form.upfile'} to the contents of the file
12366: 
12367: =cut
12368: 
12369: sub load_tmp_file {
12370:     my $r=shift;
12371:     my @studentdata=();
12372:     {
12373:         my $studentfile = $r->dir_config('lonDaemons').
12374:                               '/tmp/'.$env{'form.datatoken'}.'.tmp';
12375:         if ( open(my $fh,"<$studentfile") ) {
12376:             @studentdata=<$fh>;
12377:             close($fh);
12378:         }
12379:     }
12380:     $env{'form.upfile'}=join('',@studentdata);
12381: }
12382: 
12383: =pod
12384: 
12385: =item * &upfile_record_sep()
12386: 
12387: Separate uploaded file into records
12388: returns array of records,
12389: needs $env{'form.upfile'} and $env{'form.upfiletype'}
12390: 
12391: =cut
12392: 
12393: sub upfile_record_sep {
12394:     if ($env{'form.upfiletype'} eq 'xml') {
12395:     } else {
12396: 	my @records;
12397: 	foreach my $line (split(/\n/,$env{'form.upfile'})) {
12398: 	    if ($line=~/^\s*$/) { next; }
12399: 	    push(@records,$line);
12400: 	}
12401: 	return @records;
12402:     }
12403: }
12404: 
12405: =pod
12406: 
12407: =item * &record_sep($record)
12408: 
12409: Separate a record into fields $record should be an item from the upfile_record_sep(), needs $env{'form.upfiletype'}
12410: 
12411: =cut
12412: 
12413: sub takeleft {
12414:     my $index=shift;
12415:     return substr('0000'.$index,-4,4);
12416: }
12417: 
12418: sub record_sep {
12419:     my $record=shift;
12420:     my %components=();
12421:     if ($env{'form.upfiletype'} eq 'xml') {
12422:     } elsif ($env{'form.upfiletype'} eq 'space') {
12423:         my $i=0;
12424:         foreach my $field (split(/\s+/,$record)) {
12425:             $field=~s/^(\"|\')//;
12426:             $field=~s/(\"|\')$//;
12427:             $components{&takeleft($i)}=$field;
12428:             $i++;
12429:         }
12430:     } elsif ($env{'form.upfiletype'} eq 'tab') {
12431:         my $i=0;
12432:         foreach my $field (split(/\t/,$record)) {
12433:             $field=~s/^(\"|\')//;
12434:             $field=~s/(\"|\')$//;
12435:             $components{&takeleft($i)}=$field;
12436:             $i++;
12437:         }
12438:     } else {
12439:         my $separator=',';
12440:         if ($env{'form.upfiletype'} eq 'semisv') {
12441:             $separator=';';
12442:         }
12443:         my $i=0;
12444: # the character we are looking for to indicate the end of a quote or a record 
12445:         my $looking_for=$separator;
12446: # do not add the characters to the fields
12447:         my $ignore=0;
12448: # we just encountered a separator (or the beginning of the record)
12449:         my $just_found_separator=1;
12450: # store the field we are working on here
12451:         my $field='';
12452: # work our way through all characters in record
12453:         foreach my $character ($record=~/(.)/g) {
12454:             if ($character eq $looking_for) {
12455:                if ($character ne $separator) {
12456: # Found the end of a quote, again looking for separator
12457:                   $looking_for=$separator;
12458:                   $ignore=1;
12459:                } else {
12460: # Found a separator, store away what we got
12461:                   $components{&takeleft($i)}=$field;
12462: 	          $i++;
12463:                   $just_found_separator=1;
12464:                   $ignore=0;
12465:                   $field='';
12466:                }
12467:                next;
12468:             }
12469: # single or double quotation marks after a separator indicate beginning of a quote
12470: # we are now looking for the end of the quote and need to ignore separators
12471:             if ((($character eq '"') || ($character eq "'")) && ($just_found_separator))  {
12472:                $looking_for=$character;
12473:                next;
12474:             }
12475: # ignore would be true after we reached the end of a quote
12476:             if ($ignore) { next; }
12477:             if (($just_found_separator) && ($character=~/\s/)) { next; }
12478:             $field.=$character;
12479:             $just_found_separator=0; 
12480:         }
12481: # catch the very last entry, since we never encountered the separator
12482:         $components{&takeleft($i)}=$field;
12483:     }
12484:     return %components;
12485: }
12486: 
12487: ######################################################
12488: ######################################################
12489: 
12490: =pod
12491: 
12492: =item * &upfile_select_html()
12493: 
12494: Return HTML code to select a file from the users machine and specify 
12495: the file type.
12496: 
12497: =cut
12498: 
12499: ######################################################
12500: ######################################################
12501: sub upfile_select_html {
12502:     my %Types = (
12503:                  csv   => &mt('CSV (comma separated values, spreadsheet)'),
12504:                  semisv => &mt('Semicolon separated values'),
12505:                  space => &mt('Space separated'),
12506:                  tab   => &mt('Tabulator separated'),
12507: #                 xml   => &mt('HTML/XML'),
12508:                  );
12509:     my $Str = '<input type="file" name="upfile" size="50" />'.
12510:         '<br />'.&mt('Type').': <select name="upfiletype">';
12511:     foreach my $type (sort(keys(%Types))) {
12512:         $Str .= '<option value="'.$type.'" >'.$Types{$type}."</option>\n";
12513:     }
12514:     $Str .= "</select>\n";
12515:     return $Str;
12516: }
12517: 
12518: sub get_samples {
12519:     my ($records,$toget) = @_;
12520:     my @samples=({});
12521:     my $got=0;
12522:     foreach my $rec (@$records) {
12523: 	my %temp = &record_sep($rec);
12524: 	if (! grep(/\S/, values(%temp))) { next; }
12525: 	if (%temp) {
12526: 	    $samples[$got]=\%temp;
12527: 	    $got++;
12528: 	    if ($got == $toget) { last; }
12529: 	}
12530:     }
12531:     return \@samples;
12532: }
12533: 
12534: ######################################################
12535: ######################################################
12536: 
12537: =pod
12538: 
12539: =item * &csv_print_samples($r,$records)
12540: 
12541: Prints a table of sample values from each column uploaded $r is an
12542: Apache Request ref, $records is an arrayref from
12543: &Apache::loncommon::upfile_record_sep
12544: 
12545: =cut
12546: 
12547: ######################################################
12548: ######################################################
12549: sub csv_print_samples {
12550:     my ($r,$records) = @_;
12551:     my $samples = &get_samples($records,5);
12552: 
12553:     $r->print(&mt('Samples').'<br />'.&start_data_table().
12554:               &start_data_table_header_row());
12555:     foreach my $sample (sort({$a <=> $b} keys(%{ $samples->[0] }))) { 
12556:         $r->print('<th>'.&mt('Column [_1]',($sample+1)).'</th>'); }
12557:     $r->print(&end_data_table_header_row());
12558:     foreach my $hash (@$samples) {
12559: 	$r->print(&start_data_table_row());
12560: 	foreach my $sample (sort({$a <=> $b} keys(%{ $samples->[0] }))) {
12561: 	    $r->print('<td>');
12562: 	    if (defined($$hash{$sample})) { $r->print($$hash{$sample}); }
12563: 	    $r->print('</td>');
12564: 	}
12565: 	$r->print(&end_data_table_row());
12566:     }
12567:     $r->print(&end_data_table().'<br />'."\n");
12568: }
12569: 
12570: ######################################################
12571: ######################################################
12572: 
12573: =pod
12574: 
12575: =item * &csv_print_select_table($r,$records,$d)
12576: 
12577: Prints a table to create associations between values and table columns.
12578: 
12579: $r is an Apache Request ref,
12580: $records is an arrayref from &Apache::loncommon::upfile_record_sep,
12581: $d is an array of 2 element arrays (internal name, displayed name,defaultcol)
12582: 
12583: =cut
12584: 
12585: ######################################################
12586: ######################################################
12587: sub csv_print_select_table {
12588:     my ($r,$records,$d) = @_;
12589:     my $i=0;
12590:     my $samples = &get_samples($records,1);
12591:     $r->print(&mt('Associate columns with student attributes.')."\n".
12592: 	      &start_data_table().&start_data_table_header_row().
12593:               '<th>'.&mt('Attribute').'</th>'.
12594:               '<th>'.&mt('Column').'</th>'.
12595:               &end_data_table_header_row()."\n");
12596:     foreach my $array_ref (@$d) {
12597: 	my ($value,$display,$defaultcol)=@{ $array_ref };
12598: 	$r->print(&start_data_table_row().'<td>'.$display.'</td>');
12599: 
12600: 	$r->print('<td><select name="f'.$i.'"'.
12601: 		  ' onchange="javascript:flip(this.form,'.$i.');">');
12602: 	$r->print('<option value="none"></option>');
12603: 	foreach my $sample (sort({$a <=> $b} keys(%{ $samples->[0] }))) {
12604: 	    $r->print('<option value="'.$sample.'"'.
12605:                       ($sample eq $defaultcol ? ' selected="selected" ' : '').
12606:                       '>'.&mt('Column [_1]',($sample+1)).'</option>');
12607: 	}
12608: 	$r->print('</select></td>'.&end_data_table_row()."\n");
12609: 	$i++;
12610:     }
12611:     $r->print(&end_data_table());
12612:     $i--;
12613:     return $i;
12614: }
12615: 
12616: ######################################################
12617: ######################################################
12618: 
12619: =pod
12620: 
12621: =item * &csv_samples_select_table($r,$records,$d)
12622: 
12623: Prints a table of sample values from the upload and can make associate samples to internal names.
12624: 
12625: $r is an Apache Request ref,
12626: $records is an arrayref from &Apache::loncommon::upfile_record_sep,
12627: $d is an array of 2 element arrays (internal name, displayed name)
12628: 
12629: =cut
12630: 
12631: ######################################################
12632: ######################################################
12633: sub csv_samples_select_table {
12634:     my ($r,$records,$d) = @_;
12635:     my $i=0;
12636:     #
12637:     my $max_samples = 5;
12638:     my $samples = &get_samples($records,$max_samples);
12639:     $r->print(&start_data_table().
12640:               &start_data_table_header_row().'<th>'.
12641:               &mt('Field').'</th><th>'.&mt('Samples').'</th>'.
12642:               &end_data_table_header_row());
12643: 
12644:     foreach my $key (sort(keys(%{ $samples->[0] }))) {
12645: 	$r->print(&start_data_table_row().'<td><select name="f'.$i.'"'.
12646: 		  ' onchange="javascript:flip(this.form,'.$i.');">');
12647: 	foreach my $option (@$d) {
12648: 	    my ($value,$display,$defaultcol)=@{ $option };
12649: 	    $r->print('<option value="'.$value.'"'.
12650:                       ($i eq $defaultcol ? ' selected="selected" ':'').'>'.
12651:                       $display.'</option>');
12652: 	}
12653: 	$r->print('</select></td><td>');
12654: 	foreach my $line (0..($max_samples-1)) {
12655: 	    if (defined($samples->[$line]{$key})) { 
12656: 		$r->print($samples->[$line]{$key}."<br />\n"); 
12657: 	    }
12658: 	}
12659: 	$r->print('</td>'.&end_data_table_row());
12660: 	$i++;
12661:     }
12662:     $r->print(&end_data_table());
12663:     $i--;
12664:     return($i);
12665: }
12666: 
12667: ######################################################
12668: ######################################################
12669: 
12670: =pod
12671: 
12672: =item * &clean_excel_name($name)
12673: 
12674: Returns a replacement for $name which does not contain any illegal characters.
12675: 
12676: =cut
12677: 
12678: ######################################################
12679: ######################################################
12680: sub clean_excel_name {
12681:     my ($name) = @_;
12682:     $name =~ s/[:\*\?\/\\]//g;
12683:     if (length($name) > 31) {
12684:         $name = substr($name,0,31);
12685:     }
12686:     return $name;
12687: }
12688: 
12689: =pod
12690: 
12691: =item * &check_if_partid_hidden($id,$symb,$udom,$uname)
12692: 
12693: Returns either 1 or undef
12694: 
12695: 1 if the part is to be hidden, undef if it is to be shown
12696: 
12697: Arguments are:
12698: 
12699: $id the id of the part to be checked
12700: $symb, optional the symb of the resource to check
12701: $udom, optional the domain of the user to check for
12702: $uname, optional the username of the user to check for
12703: 
12704: =cut
12705: 
12706: sub check_if_partid_hidden {
12707:     my ($id,$symb,$udom,$uname) = @_;
12708:     my $hiddenparts=&Apache::lonnet::EXT('resource.0.hiddenparts',
12709: 					 $symb,$udom,$uname);
12710:     my $truth=1;
12711:     #if the string starts with !, then the list is the list to show not hide
12712:     if ($hiddenparts=~s/^\s*!//) { $truth=undef; }
12713:     my @hiddenlist=split(/,/,$hiddenparts);
12714:     foreach my $checkid (@hiddenlist) {
12715: 	if ($checkid =~ /^\s*\Q$id\E\s*$/) { return $truth; }
12716:     }
12717:     return !$truth;
12718: }
12719: 
12720: 
12721: ############################################################
12722: ############################################################
12723: 
12724: =pod
12725: 
12726: =back 
12727: 
12728: =head1 cgi-bin script and graphing routines
12729: 
12730: =over 4
12731: 
12732: =item * &get_cgi_id()
12733: 
12734: Inputs: none
12735: 
12736: Returns an id which can be used to pass environment variables
12737: to various cgi-bin scripts.  These environment variables will
12738: be removed from the users environment after a given time by
12739: the routine &Apache::lonnet::transfer_profile_to_env.
12740: 
12741: =cut
12742: 
12743: ############################################################
12744: ############################################################
12745: my $uniq=0;
12746: sub get_cgi_id {
12747:     $uniq=($uniq+1)%100000;
12748:     return (time.'_'.$$.'_'.$uniq);
12749: }
12750: 
12751: ############################################################
12752: ############################################################
12753: 
12754: =pod
12755: 
12756: =item * &DrawBarGraph()
12757: 
12758: Facilitates the plotting of data in a (stacked) bar graph.
12759: Puts plot definition data into the users environment in order for 
12760: graph.png to plot it.  Returns an <img> tag for the plot.
12761: The bars on the plot are labeled '1','2',...,'n'.
12762: 
12763: Inputs:
12764: 
12765: =over 4
12766: 
12767: =item $Title: string, the title of the plot
12768: 
12769: =item $xlabel: string, text describing the X-axis of the plot
12770: 
12771: =item $ylabel: string, text describing the Y-axis of the plot
12772: 
12773: =item $Max: scalar, the maximum Y value to use in the plot
12774: If $Max is < any data point, the graph will not be rendered.
12775: 
12776: =item $colors: array ref holding the colors to be used for the data sets when
12777: they are plotted.  If undefined, default values will be used.
12778: 
12779: =item $labels: array ref holding the labels to use on the x-axis for the bars.
12780: 
12781: =item @Values: An array of array references.  Each array reference holds data
12782: to be plotted in a stacked bar chart.
12783: 
12784: =item If the final element of @Values is a hash reference the key/value
12785: pairs will be added to the graph definition.
12786: 
12787: =back
12788: 
12789: Returns:
12790: 
12791: An <img> tag which references graph.png and the appropriate identifying
12792: information for the plot.
12793: 
12794: =cut
12795: 
12796: ############################################################
12797: ############################################################
12798: sub DrawBarGraph {
12799:     my ($Title,$xlabel,$ylabel,$Max,$colors,$labels,@Values)=@_;
12800:     #
12801:     if (! defined($colors)) {
12802:         $colors = ['#33ff00', 
12803:                   '#0033cc', '#990000', '#aaaa66', '#663399', '#ff9933',
12804:                   '#66ccff', '#ff9999', '#cccc33', '#660000', '#33cc66',
12805:                   ]; 
12806:     }
12807:     my $extra_settings = {};
12808:     if (ref($Values[-1]) eq 'HASH') {
12809:         $extra_settings = pop(@Values);
12810:     }
12811:     #
12812:     my $identifier = &get_cgi_id();
12813:     my $id = 'cgi.'.$identifier;        
12814:     if (! @Values || ref($Values[0]) ne 'ARRAY') {
12815:         return '';
12816:     }
12817:     #
12818:     my @Labels;
12819:     if (defined($labels)) {
12820:         @Labels = @$labels;
12821:     } else {
12822:         for (my $i=0;$i<@{$Values[0]};$i++) {
12823:             push (@Labels,$i+1);
12824:         }
12825:     }
12826:     #
12827:     my $NumBars = scalar(@{$Values[0]});
12828:     if ($NumBars < scalar(@Labels)) { $NumBars = scalar(@Labels); }
12829:     my %ValuesHash;
12830:     my $NumSets=1;
12831:     foreach my $array (@Values) {
12832:         next if (! ref($array));
12833:         $ValuesHash{$id.'.data.'.$NumSets++} = 
12834:             join(',',@$array);
12835:     }
12836:     #
12837:     my ($height,$width,$xskip,$bar_width) = (200,120,1,15);
12838:     if ($NumBars < 3) {
12839:         $width = 120+$NumBars*32;
12840:         $xskip = 1;
12841:         $bar_width = 30;
12842:     } elsif ($NumBars < 5) {
12843:         $width = 120+$NumBars*20;
12844:         $xskip = 1;
12845:         $bar_width = 20;
12846:     } elsif ($NumBars < 10) {
12847:         $width = 120+$NumBars*15;
12848:         $xskip = 1;
12849:         $bar_width = 15;
12850:     } elsif ($NumBars <= 25) {
12851:         $width = 120+$NumBars*11;
12852:         $xskip = 5;
12853:         $bar_width = 8;
12854:     } elsif ($NumBars <= 50) {
12855:         $width = 120+$NumBars*8;
12856:         $xskip = 5;
12857:         $bar_width = 4;
12858:     } else {
12859:         $width = 120+$NumBars*8;
12860:         $xskip = 5;
12861:         $bar_width = 4;
12862:     }
12863:     #
12864:     $Max = 1 if ($Max < 1);
12865:     if ( int($Max) < $Max ) {
12866:         $Max++;
12867:         $Max = int($Max);
12868:     }
12869:     $Title  = '' if (! defined($Title));
12870:     $xlabel = '' if (! defined($xlabel));
12871:     $ylabel = '' if (! defined($ylabel));
12872:     $ValuesHash{$id.'.title'}    = &escape($Title);
12873:     $ValuesHash{$id.'.xlabel'}   = &escape($xlabel);
12874:     $ValuesHash{$id.'.ylabel'}   = &escape($ylabel);
12875:     $ValuesHash{$id.'.y_max_value'} = $Max;
12876:     $ValuesHash{$id.'.NumBars'}  = $NumBars;
12877:     $ValuesHash{$id.'.NumSets'}  = $NumSets;
12878:     $ValuesHash{$id.'.PlotType'} = 'bar';
12879:     $ValuesHash{$id.'.Colors'}   = join(',',@{$colors});
12880:     $ValuesHash{$id.'.height'}   = $height;
12881:     $ValuesHash{$id.'.width'}    = $width;
12882:     $ValuesHash{$id.'.xskip'}    = $xskip;
12883:     $ValuesHash{$id.'.bar_width'} = $bar_width;
12884:     $ValuesHash{$id.'.labels'} = join(',',@Labels);
12885:     #
12886:     # Deal with other parameters
12887:     while (my ($key,$value) = each(%$extra_settings)) {
12888:         $ValuesHash{$id.'.'.$key} = $value;
12889:     }
12890:     #
12891:     &Apache::lonnet::appenv(\%ValuesHash);
12892:     return '<img src="/cgi-bin/graph.png?'.$identifier.'" border="1" />';
12893: }
12894: 
12895: ############################################################
12896: ############################################################
12897: 
12898: =pod
12899: 
12900: =item * &DrawXYGraph()
12901: 
12902: Facilitates the plotting of data in an XY graph.
12903: Puts plot definition data into the users environment in order for 
12904: graph.png to plot it.  Returns an <img> tag for the plot.
12905: 
12906: Inputs:
12907: 
12908: =over 4
12909: 
12910: =item $Title: string, the title of the plot
12911: 
12912: =item $xlabel: string, text describing the X-axis of the plot
12913: 
12914: =item $ylabel: string, text describing the Y-axis of the plot
12915: 
12916: =item $Max: scalar, the maximum Y value to use in the plot
12917: If $Max is < any data point, the graph will not be rendered.
12918: 
12919: =item $colors: Array ref containing the hex color codes for the data to be 
12920: plotted in.  If undefined, default values will be used.
12921: 
12922: =item $Xlabels: Array ref containing the labels to be used for the X-axis.
12923: 
12924: =item $Ydata: Array ref containing Array refs.  
12925: Each of the contained arrays will be plotted as a separate curve.
12926: 
12927: =item %Values: hash indicating or overriding any default values which are 
12928: passed to graph.png.  
12929: Possible values are: width, xskip, x_ticks, x_tick_offset, among others.
12930: 
12931: =back
12932: 
12933: Returns:
12934: 
12935: An <img> tag which references graph.png and the appropriate identifying
12936: information for the plot.
12937: 
12938: =cut
12939: 
12940: ############################################################
12941: ############################################################
12942: sub DrawXYGraph {
12943:     my ($Title,$xlabel,$ylabel,$Max,$colors,$Xlabels,$Ydata,%Values)=@_;
12944:     #
12945:     # Create the identifier for the graph
12946:     my $identifier = &get_cgi_id();
12947:     my $id = 'cgi.'.$identifier;
12948:     #
12949:     $Title  = '' if (! defined($Title));
12950:     $xlabel = '' if (! defined($xlabel));
12951:     $ylabel = '' if (! defined($ylabel));
12952:     my %ValuesHash = 
12953:         (
12954:          $id.'.title'  => &escape($Title),
12955:          $id.'.xlabel' => &escape($xlabel),
12956:          $id.'.ylabel' => &escape($ylabel),
12957:          $id.'.y_max_value'=> $Max,
12958:          $id.'.labels'     => join(',',@$Xlabels),
12959:          $id.'.PlotType'   => 'XY',
12960:          );
12961:     #
12962:     if (defined($colors) && ref($colors) eq 'ARRAY') {
12963:         $ValuesHash{$id.'.Colors'}   = join(',',@{$colors});
12964:     }
12965:     #
12966:     if (! ref($Ydata) || ref($Ydata) ne 'ARRAY') {
12967:         return '';
12968:     }
12969:     my $NumSets=1;
12970:     foreach my $array (@{$Ydata}){
12971:         next if (! ref($array));
12972:         $ValuesHash{$id.'.data.'.$NumSets++} = join(',',@$array);
12973:     }
12974:     $ValuesHash{$id.'.NumSets'} = $NumSets-1;
12975:     #
12976:     # Deal with other parameters
12977:     while (my ($key,$value) = each(%Values)) {
12978:         $ValuesHash{$id.'.'.$key} = $value;
12979:     }
12980:     #
12981:     &Apache::lonnet::appenv(\%ValuesHash);
12982:     return '<img src="/cgi-bin/graph.png?'.$identifier.'" border="1" />';
12983: }
12984: 
12985: ############################################################
12986: ############################################################
12987: 
12988: =pod
12989: 
12990: =item * &DrawXYYGraph()
12991: 
12992: Facilitates the plotting of data in an XY graph with two Y axes.
12993: Puts plot definition data into the users environment in order for 
12994: graph.png to plot it.  Returns an <img> tag for the plot.
12995: 
12996: Inputs:
12997: 
12998: =over 4
12999: 
13000: =item $Title: string, the title of the plot
13001: 
13002: =item $xlabel: string, text describing the X-axis of the plot
13003: 
13004: =item $ylabel: string, text describing the Y-axis of the plot
13005: 
13006: =item $colors: Array ref containing the hex color codes for the data to be 
13007: plotted in.  If undefined, default values will be used.
13008: 
13009: =item $Xlabels: Array ref containing the labels to be used for the X-axis.
13010: 
13011: =item $Ydata1: The first data set
13012: 
13013: =item $Min1: The minimum value of the left Y-axis
13014: 
13015: =item $Max1: The maximum value of the left Y-axis
13016: 
13017: =item $Ydata2: The second data set
13018: 
13019: =item $Min2: The minimum value of the right Y-axis
13020: 
13021: =item $Max2: The maximum value of the left Y-axis
13022: 
13023: =item %Values: hash indicating or overriding any default values which are 
13024: passed to graph.png.  
13025: Possible values are: width, xskip, x_ticks, x_tick_offset, among others.
13026: 
13027: =back
13028: 
13029: Returns:
13030: 
13031: An <img> tag which references graph.png and the appropriate identifying
13032: information for the plot.
13033: 
13034: =cut
13035: 
13036: ############################################################
13037: ############################################################
13038: sub DrawXYYGraph {
13039:     my ($Title,$xlabel,$ylabel,$colors,$Xlabels,$Ydata1,$Min1,$Max1,
13040:                                         $Ydata2,$Min2,$Max2,%Values)=@_;
13041:     #
13042:     # Create the identifier for the graph
13043:     my $identifier = &get_cgi_id();
13044:     my $id = 'cgi.'.$identifier;
13045:     #
13046:     $Title  = '' if (! defined($Title));
13047:     $xlabel = '' if (! defined($xlabel));
13048:     $ylabel = '' if (! defined($ylabel));
13049:     my %ValuesHash = 
13050:         (
13051:          $id.'.title'  => &escape($Title),
13052:          $id.'.xlabel' => &escape($xlabel),
13053:          $id.'.ylabel' => &escape($ylabel),
13054:          $id.'.labels' => join(',',@$Xlabels),
13055:          $id.'.PlotType' => 'XY',
13056:          $id.'.NumSets' => 2,
13057:          $id.'.two_axes' => 1,
13058:          $id.'.y1_max_value' => $Max1,
13059:          $id.'.y1_min_value' => $Min1,
13060:          $id.'.y2_max_value' => $Max2,
13061:          $id.'.y2_min_value' => $Min2,
13062:          );
13063:     #
13064:     if (defined($colors) && ref($colors) eq 'ARRAY') {
13065:         $ValuesHash{$id.'.Colors'}   = join(',',@{$colors});
13066:     }
13067:     #
13068:     if (! ref($Ydata1) || ref($Ydata1) ne 'ARRAY' ||
13069:         ! ref($Ydata2) || ref($Ydata2) ne 'ARRAY'){
13070:         return '';
13071:     }
13072:     my $NumSets=1;
13073:     foreach my $array ($Ydata1,$Ydata2){
13074:         next if (! ref($array));
13075:         $ValuesHash{$id.'.data.'.$NumSets++} = join(',',@$array);
13076:     }
13077:     #
13078:     # Deal with other parameters
13079:     while (my ($key,$value) = each(%Values)) {
13080:         $ValuesHash{$id.'.'.$key} = $value;
13081:     }
13082:     #
13083:     &Apache::lonnet::appenv(\%ValuesHash);
13084:     return '<img src="/cgi-bin/graph.png?'.$identifier.'" border="1" />';
13085: }
13086: 
13087: ############################################################
13088: ############################################################
13089: 
13090: =pod
13091: 
13092: =back 
13093: 
13094: =head1 Statistics helper routines?  
13095: 
13096: Bad place for them but what the hell.
13097: 
13098: =over 4
13099: 
13100: =item * &chartlink()
13101: 
13102: Returns a link to the chart for a specific student.  
13103: 
13104: Inputs:
13105: 
13106: =over 4
13107: 
13108: =item $linktext: The text of the link
13109: 
13110: =item $sname: The students username
13111: 
13112: =item $sdomain: The students domain
13113: 
13114: =back
13115: 
13116: =back
13117: 
13118: =cut
13119: 
13120: ############################################################
13121: ############################################################
13122: sub chartlink {
13123:     my ($linktext, $sname, $sdomain) = @_;
13124:     my $link = '<a href="/adm/statistics?reportSelected=student_assessment'.
13125:         '&amp;SelectedStudent='.&escape($sname.':'.$sdomain).
13126:         '&amp;chartoutputmode='.HTML::Entities::encode('html, with all links').
13127:        '">'.$linktext.'</a>';
13128: }
13129: 
13130: #######################################################
13131: #######################################################
13132: 
13133: =pod
13134: 
13135: =head1 Course Environment Routines
13136: 
13137: =over 4
13138: 
13139: =item * &restore_course_settings()
13140: 
13141: =item * &store_course_settings()
13142: 
13143: Restores/Store indicated form parameters from the course environment.
13144: Will not overwrite existing values of the form parameters.
13145: 
13146: Inputs: 
13147: a scalar describing the data (e.g. 'chart', 'problem_analysis')
13148: 
13149: a hash ref describing the data to be stored.  For example:
13150:    
13151: %Save_Parameters = ('Status' => 'scalar',
13152:     'chartoutputmode' => 'scalar',
13153:     'chartoutputdata' => 'scalar',
13154:     'Section' => 'array',
13155:     'Group' => 'array',
13156:     'StudentData' => 'array',
13157:     'Maps' => 'array');
13158: 
13159: Returns: both routines return nothing
13160: 
13161: =back
13162: 
13163: =cut
13164: 
13165: #######################################################
13166: #######################################################
13167: sub store_course_settings {
13168:     return &store_settings($env{'request.course.id'},@_);
13169: }
13170: 
13171: sub store_settings {
13172:     # save to the environment
13173:     # appenv the same items, just to be safe
13174:     my $udom  = $env{'user.domain'};
13175:     my $uname = $env{'user.name'};
13176:     my ($context,$prefix,$Settings) = @_;
13177:     my %SaveHash;
13178:     my %AppHash;
13179:     while (my ($setting,$type) = each(%$Settings)) {
13180:         my $basename = join('.','internal',$context,$prefix,$setting);
13181:         my $envname = 'environment.'.$basename;
13182:         if (exists($env{'form.'.$setting})) {
13183:             # Save this value away
13184:             if ($type eq 'scalar' &&
13185:                 (! exists($env{$envname}) || 
13186:                  $env{$envname} ne $env{'form.'.$setting})) {
13187:                 $SaveHash{$basename} = $env{'form.'.$setting};
13188:                 $AppHash{$envname}   = $env{'form.'.$setting};
13189:             } elsif ($type eq 'array') {
13190:                 my $stored_form;
13191:                 if (ref($env{'form.'.$setting})) {
13192:                     $stored_form = join(',',
13193:                                         map {
13194:                                             &escape($_);
13195:                                         } sort(@{$env{'form.'.$setting}}));
13196:                 } else {
13197:                     $stored_form = 
13198:                         &escape($env{'form.'.$setting});
13199:                 }
13200:                 # Determine if the array contents are the same.
13201:                 if ($stored_form ne $env{$envname}) {
13202:                     $SaveHash{$basename} = $stored_form;
13203:                     $AppHash{$envname}   = $stored_form;
13204:                 }
13205:             }
13206:         }
13207:     }
13208:     my $put_result = &Apache::lonnet::put('environment',\%SaveHash,
13209:                                           $udom,$uname);
13210:     if ($put_result !~ /^(ok|delayed)/) {
13211:         &Apache::lonnet::logthis('unable to save form parameters, '.
13212:                                  'got error:'.$put_result);
13213:     }
13214:     # Make sure these settings stick around in this session, too
13215:     &Apache::lonnet::appenv(\%AppHash);
13216:     return;
13217: }
13218: 
13219: sub restore_course_settings {
13220:     return &restore_settings($env{'request.course.id'},@_);
13221: }
13222: 
13223: sub restore_settings {
13224:     my ($context,$prefix,$Settings) = @_;
13225:     while (my ($setting,$type) = each(%$Settings)) {
13226:         next if (exists($env{'form.'.$setting}));
13227:         my $envname = 'environment.internal.'.$context.'.'.$prefix.
13228:             '.'.$setting;
13229:         if (exists($env{$envname})) {
13230:             if ($type eq 'scalar') {
13231:                 $env{'form.'.$setting} = $env{$envname};
13232:             } elsif ($type eq 'array') {
13233:                 $env{'form.'.$setting} = [ 
13234:                                            map { 
13235:                                                &unescape($_); 
13236:                                            } split(',',$env{$envname})
13237:                                            ];
13238:             }
13239:         }
13240:     }
13241: }
13242: 
13243: #######################################################
13244: #######################################################
13245: 
13246: =pod
13247: 
13248: =head1 Domain E-mail Routines  
13249: 
13250: =over 4
13251: 
13252: =item * &build_recipient_list()
13253: 
13254: Build recipient lists for following types of e-mail:
13255: (a) Error Reports, (b) Package Updates, (c) lonstatus warnings/errors
13256: (d) Help requests, (e) Course requests needing approval, (f) loncapa
13257: module change checking, student/employee ID conflict checks, as
13258: generated by lonerrorhandler.pm, CHECKRPMS, loncron,
13259: lonsupportreq.pm, loncoursequeueadmin.pm, searchcat.pl respectively.
13260: 
13261: Inputs:
13262: defmail (scalar - email address of default recipient), 
13263: mailing type (scalar: errormail, packagesmail, helpdeskmail,
13264: requestsmail, updatesmail, or idconflictsmail).
13265: 
13266: defdom (domain for which to retrieve configuration settings),
13267: 
13268: origmail (scalar - email address of recipient from loncapa.conf, 
13269: i.e., predates configuration by DC via domainprefs.pm 
13270: 
13271: Returns: comma separated list of addresses to which to send e-mail.
13272: 
13273: =back
13274: 
13275: =cut
13276: 
13277: ############################################################
13278: ############################################################
13279: sub build_recipient_list {
13280:     my ($defmail,$mailing,$defdom,$origmail) = @_;
13281:     my @recipients;
13282:     my $otheremails;
13283:     my %domconfig =
13284:          &Apache::lonnet::get_dom('configuration',['contacts'],$defdom);
13285:     if (ref($domconfig{'contacts'}) eq 'HASH') {
13286:         if (exists($domconfig{'contacts'}{$mailing})) {
13287:             if (ref($domconfig{'contacts'}{$mailing}) eq 'HASH') {
13288:                 my @contacts = ('adminemail','supportemail');
13289:                 foreach my $item (@contacts) {
13290:                     if ($domconfig{'contacts'}{$mailing}{$item}) {
13291:                         my $addr = $domconfig{'contacts'}{$item}; 
13292:                         if (!grep(/^\Q$addr\E$/,@recipients)) {
13293:                             push(@recipients,$addr);
13294:                         }
13295:                     }
13296:                     $otheremails = $domconfig{'contacts'}{$mailing}{'others'};
13297:                 }
13298:             }
13299:         } elsif ($origmail ne '') {
13300:             push(@recipients,$origmail);
13301:         }
13302:     } elsif ($origmail ne '') {
13303:         push(@recipients,$origmail);
13304:     }
13305:     if (defined($defmail)) {
13306:         if ($defmail ne '') {
13307:             push(@recipients,$defmail);
13308:         }
13309:     }
13310:     if ($otheremails) {
13311:         my @others;
13312:         if ($otheremails =~ /,/) {
13313:             @others = split(/,/,$otheremails);
13314:         } else {
13315:             push(@others,$otheremails);
13316:         }
13317:         foreach my $addr (@others) {
13318:             if (!grep(/^\Q$addr\E$/,@recipients)) {
13319:                 push(@recipients,$addr);
13320:             }
13321:         }
13322:     }
13323:     my $recipientlist = join(',',@recipients); 
13324:     return $recipientlist;
13325: }
13326: 
13327: ############################################################
13328: ############################################################
13329: 
13330: =pod
13331: 
13332: =head1 Course Catalog Routines
13333: 
13334: =over 4
13335: 
13336: =item * &gather_categories()
13337: 
13338: Converts category definitions - keys of categories hash stored in  
13339: coursecategories in configuration.db on the primary library server in a 
13340: domain - to an array.  Also generates javascript and idx hash used to 
13341: generate Domain Coordinator interface for editing Course Categories.
13342: 
13343: Inputs:
13344: 
13345: categories (reference to hash of category definitions).
13346: 
13347: cats (reference to array of arrays/hashes which encapsulates hierarchy of
13348:       categories and subcategories).
13349: 
13350: idx (reference to hash of counters used in Domain Coordinator interface for 
13351:       editing Course Categories).
13352: 
13353: jsarray (reference to array of categories used to create Javascript arrays for
13354:          Domain Coordinator interface for editing Course Categories).
13355: 
13356: Returns: nothing
13357: 
13358: Side effects: populates cats, idx and jsarray. 
13359: 
13360: =cut
13361: 
13362: sub gather_categories {
13363:     my ($categories,$cats,$idx,$jsarray) = @_;
13364:     my %counters;
13365:     my $num = 0;
13366:     foreach my $item (keys(%{$categories})) {
13367:         my ($cat,$container,$depth) = map { &unescape($_); } split(/:/,$item);
13368:         if ($container eq '' && $depth == 0) {
13369:             $cats->[$depth][$categories->{$item}] = $cat;
13370:         } else {
13371:             $cats->[$depth]{$container}[$categories->{$item}] = $cat;
13372:         }
13373:         my ($escitem,$tail) = split(/:/,$item,2);
13374:         if ($counters{$tail} eq '') {
13375:             $counters{$tail} = $num;
13376:             $num ++;
13377:         }
13378:         if (ref($idx) eq 'HASH') {
13379:             $idx->{$item} = $counters{$tail};
13380:         }
13381:         if (ref($jsarray) eq 'ARRAY') {
13382:             push(@{$jsarray->[$counters{$tail}]},$item);
13383:         }
13384:     }
13385:     return;
13386: }
13387: 
13388: =pod
13389: 
13390: =item * &extract_categories()
13391: 
13392: Used to generate breadcrumb trails for course categories.
13393: 
13394: Inputs:
13395: 
13396: categories (reference to hash of category definitions).
13397: 
13398: cats (reference to array of arrays/hashes which encapsulates hierarchy of
13399:       categories and subcategories).
13400: 
13401: trails (reference to array of breacrumb trails for each category).
13402: 
13403: allitems (reference to hash - key is category key 
13404:          (format: escaped(name):escaped(parent category):depth in hierarchy).
13405: 
13406: idx (reference to hash of counters used in Domain Coordinator interface for
13407:       editing Course Categories).
13408: 
13409: jsarray (reference to array of categories used to create Javascript arrays for
13410:          Domain Coordinator interface for editing Course Categories).
13411: 
13412: subcats (reference to hash of arrays containing all subcategories within each 
13413:          category, -recursive)
13414: 
13415: Returns: nothing
13416: 
13417: Side effects: populates trails and allitems hash references.
13418: 
13419: =cut
13420: 
13421: sub extract_categories {
13422:     my ($categories,$cats,$trails,$allitems,$idx,$jsarray,$subcats) = @_;
13423:     if (ref($categories) eq 'HASH') {
13424:         &gather_categories($categories,$cats,$idx,$jsarray);
13425:         if (ref($cats->[0]) eq 'ARRAY') {
13426:             for (my $i=0; $i<@{$cats->[0]}; $i++) {
13427:                 my $name = $cats->[0][$i];
13428:                 my $item = &escape($name).'::0';
13429:                 my $trailstr;
13430:                 if ($name eq 'instcode') {
13431:                     $trailstr = &mt('Official courses (with institutional codes)');
13432:                 } elsif ($name eq 'communities') {
13433:                     $trailstr = &mt('Communities');
13434:                 } else {
13435:                     $trailstr = $name;
13436:                 }
13437:                 if ($allitems->{$item} eq '') {
13438:                     push(@{$trails},$trailstr);
13439:                     $allitems->{$item} = scalar(@{$trails})-1;
13440:                 }
13441:                 my @parents = ($name);
13442:                 if (ref($cats->[1]{$name}) eq 'ARRAY') {
13443:                     for (my $j=0; $j<@{$cats->[1]{$name}}; $j++) {
13444:                         my $category = $cats->[1]{$name}[$j];
13445:                         if (ref($subcats) eq 'HASH') {
13446:                             push(@{$subcats->{$item}},&escape($category).':'.&escape($name).':1');
13447:                         }
13448:                         &recurse_categories($cats,2,$category,$trails,$allitems,\@parents,$subcats);
13449:                     }
13450:                 } else {
13451:                     if (ref($subcats) eq 'HASH') {
13452:                         $subcats->{$item} = [];
13453:                     }
13454:                 }
13455:             }
13456:         }
13457:     }
13458:     return;
13459: }
13460: 
13461: =pod
13462: 
13463: =item * &recurse_categories()
13464: 
13465: Recursively used to generate breadcrumb trails for course categories.
13466: 
13467: Inputs:
13468: 
13469: cats (reference to array of arrays/hashes which encapsulates hierarchy of
13470:       categories and subcategories).
13471: 
13472: depth (current depth in hierarchy of categories and sub-categories - 0 indexed).
13473: 
13474: category (current course category, for which breadcrumb trail is being generated).
13475: 
13476: trails (reference to array of breadcrumb trails for each category).
13477: 
13478: allitems (reference to hash - key is category key
13479:          (format: escaped(name):escaped(parent category):depth in hierarchy).
13480: 
13481: parents (array containing containers directories for current category, 
13482:          back to top level). 
13483: 
13484: Returns: nothing
13485: 
13486: Side effects: populates trails and allitems hash references
13487: 
13488: =cut
13489: 
13490: sub recurse_categories {
13491:     my ($cats,$depth,$category,$trails,$allitems,$parents,$subcats) = @_;
13492:     my $shallower = $depth - 1;
13493:     if (ref($cats->[$depth]{$category}) eq 'ARRAY') {
13494:         for (my $k=0; $k<@{$cats->[$depth]{$category}}; $k++) {
13495:             my $name = $cats->[$depth]{$category}[$k];
13496:             my $item = &escape($category).':'.&escape($parents->[-1]).':'.$shallower;
13497:             my $trailstr = join(' -&gt; ',(@{$parents},$category));
13498:             if ($allitems->{$item} eq '') {
13499:                 push(@{$trails},$trailstr);
13500:                 $allitems->{$item} = scalar(@{$trails})-1;
13501:             }
13502:             my $deeper = $depth+1;
13503:             push(@{$parents},$category);
13504:             if (ref($subcats) eq 'HASH') {
13505:                 my $subcat = &escape($name).':'.$category.':'.$depth;
13506:                 for (my $j=@{$parents}; $j>=0; $j--) {
13507:                     my $higher;
13508:                     if ($j > 0) {
13509:                         $higher = &escape($parents->[$j]).':'.
13510:                                   &escape($parents->[$j-1]).':'.$j;
13511:                     } else {
13512:                         $higher = &escape($parents->[$j]).'::'.$j;
13513:                     }
13514:                     push(@{$subcats->{$higher}},$subcat);
13515:                 }
13516:             }
13517:             &recurse_categories($cats,$deeper,$name,$trails,$allitems,$parents,
13518:                                 $subcats);
13519:             pop(@{$parents});
13520:         }
13521:     } else {
13522:         my $item = &escape($category).':'.&escape($parents->[-1]).':'.$shallower;
13523:         my $trailstr = join(' -&gt; ',(@{$parents},$category));
13524:         if ($allitems->{$item} eq '') {
13525:             push(@{$trails},$trailstr);
13526:             $allitems->{$item} = scalar(@{$trails})-1;
13527:         }
13528:     }
13529:     return;
13530: }
13531: 
13532: =pod
13533: 
13534: =item * &assign_categories_table()
13535: 
13536: Create a datatable for display of hierarchical categories in a domain,
13537: with checkboxes to allow a course to be categorized. 
13538: 
13539: Inputs:
13540: 
13541: cathash - reference to hash of categories defined for the domain (from
13542:           configuration.db)
13543: 
13544: currcat - scalar with an & separated list of categories assigned to a course. 
13545: 
13546: type    - scalar contains course type (Course or Community).
13547: 
13548: Returns: $output (markup to be displayed) 
13549: 
13550: =cut
13551: 
13552: sub assign_categories_table {
13553:     my ($cathash,$currcat,$type) = @_;
13554:     my $output;
13555:     if (ref($cathash) eq 'HASH') {
13556:         my (@cats,@trails,%allitems,%idx,@jsarray,@path,$maxdepth);
13557:         &extract_categories($cathash,\@cats,\@trails,\%allitems,\%idx,\@jsarray);
13558:         $maxdepth = scalar(@cats);
13559:         if (@cats > 0) {
13560:             my $itemcount = 0;
13561:             if (ref($cats[0]) eq 'ARRAY') {
13562:                 my @currcategories;
13563:                 if ($currcat ne '') {
13564:                     @currcategories = split('&',$currcat);
13565:                 }
13566:                 my $table;
13567:                 for (my $i=0; $i<@{$cats[0]}; $i++) {
13568:                     my $parent = $cats[0][$i];
13569:                     next if ($parent eq 'instcode');
13570:                     if ($type eq 'Community') {
13571:                         next unless ($parent eq 'communities');
13572:                     } else {
13573:                         next if ($parent eq 'communities');
13574:                     }
13575:                     my $css_class = $itemcount%2?' class="LC_odd_row"':'';
13576:                     my $item = &escape($parent).'::0';
13577:                     my $checked = '';
13578:                     if (@currcategories > 0) {
13579:                         if (grep(/^\Q$item\E$/,@currcategories)) {
13580:                             $checked = ' checked="checked"';
13581:                         }
13582:                     }
13583:                     my $parent_title = $parent;
13584:                     if ($parent eq 'communities') {
13585:                         $parent_title = &mt('Communities');
13586:                     }
13587:                     $table .= '<tr '.$css_class.'><td><span class="LC_nobreak">'.
13588:                               '<input type="checkbox" name="usecategory" value="'.
13589:                               $item.'"'.$checked.' />'.$parent_title.'</span>'.
13590:                               '<input type="hidden" name="catname" value="'.$parent.'" /></td>';
13591:                     my $depth = 1;
13592:                     push(@path,$parent);
13593:                     $table .= &assign_category_rows($itemcount,\@cats,$depth,$parent,\@path,\@currcategories);
13594:                     pop(@path);
13595:                     $table .= '</tr><tr><td colspan="'.$maxdepth.'" class="LC_row_separator"></td></tr>';
13596:                     $itemcount ++;
13597:                 }
13598:                 if ($itemcount) {
13599:                     $output = &Apache::loncommon::start_data_table().
13600:                               $table.
13601:                               &Apache::loncommon::end_data_table();
13602:                 }
13603:             }
13604:         }
13605:     }
13606:     return $output;
13607: }
13608: 
13609: =pod
13610: 
13611: =item * &assign_category_rows()
13612: 
13613: Create a datatable row for display of nested categories in a domain,
13614: with checkboxes to allow a course to be categorized,called recursively.
13615: 
13616: Inputs:
13617: 
13618: itemcount - track row number for alternating colors
13619: 
13620: cats - reference to array of arrays/hashes which encapsulates hierarchy of
13621:       categories and subcategories.
13622: 
13623: depth - current depth in hierarchy of categories and sub-categories - 0 indexed.
13624: 
13625: parent - parent of current category item
13626: 
13627: path - Array containing all categories back up through the hierarchy from the
13628:        current category to the top level.
13629: 
13630: currcategories - reference to array of current categories assigned to the course
13631: 
13632: Returns: $output (markup to be displayed).
13633: 
13634: =cut
13635: 
13636: sub assign_category_rows {
13637:     my ($itemcount,$cats,$depth,$parent,$path,$currcategories) = @_;
13638:     my ($text,$name,$item,$chgstr);
13639:     if (ref($cats) eq 'ARRAY') {
13640:         my $maxdepth = scalar(@{$cats});
13641:         if (ref($cats->[$depth]) eq 'HASH') {
13642:             if (ref($cats->[$depth]{$parent}) eq 'ARRAY') {
13643:                 my $numchildren = @{$cats->[$depth]{$parent}};
13644:                 my $css_class = $itemcount%2?' class="LC_odd_row"':'';
13645:                 $text .= '<td><table class="LC_data_table">';
13646:                 for (my $j=0; $j<$numchildren; $j++) {
13647:                     $name = $cats->[$depth]{$parent}[$j];
13648:                     $item = &escape($name).':'.&escape($parent).':'.$depth;
13649:                     my $deeper = $depth+1;
13650:                     my $checked = '';
13651:                     if (ref($currcategories) eq 'ARRAY') {
13652:                         if (@{$currcategories} > 0) {
13653:                             if (grep(/^\Q$item\E$/,@{$currcategories})) {
13654:                                 $checked = ' checked="checked"';
13655:                             }
13656:                         }
13657:                     }
13658:                     $text .= '<tr><td><span class="LC_nobreak"><label>'.
13659:                              '<input type="checkbox" name="usecategory" value="'.
13660:                              $item.'"'.$checked.' />'.$name.'</label></span>'.
13661:                              '<input type="hidden" name="catname" value="'.$name.'" />'.
13662:                              '</td><td>';
13663:                     if (ref($path) eq 'ARRAY') {
13664:                         push(@{$path},$name);
13665:                         $text .= &assign_category_rows($itemcount,$cats,$deeper,$name,$path,$currcategories);
13666:                         pop(@{$path});
13667:                     }
13668:                     $text .= '</td></tr>';
13669:                 }
13670:                 $text .= '</table></td>';
13671:             }
13672:         }
13673:     }
13674:     return $text;
13675: }
13676: 
13677: =pod
13678: 
13679: =back
13680: 
13681: =cut
13682: 
13683: ############################################################
13684: ############################################################
13685: 
13686: 
13687: sub commit_customrole {
13688:     my ($udom,$uname,$url,$three,$four,$five,$start,$end,$context) = @_;
13689:     my $output = &mt('Assigning custom role').' "'.$five.'" by '.$four.':'.$three.' in '.$url.
13690:                          ($start?', '.&mt('starting').' '.localtime($start):'').
13691:                          ($end?', ending '.localtime($end):'').': <b>'.
13692:               &Apache::lonnet::assigncustomrole(
13693:                  $udom,$uname,$url,$three,$four,$five,$end,$start,undef,undef,$context).
13694:                  '</b><br />';
13695:     return $output;
13696: }
13697: 
13698: sub commit_standardrole {
13699:     my ($udom,$uname,$url,$three,$start,$end,$one,$two,$sec,$context,$credits) = @_;
13700:     my ($output,$logmsg,$linefeed);
13701:     if ($context eq 'auto') {
13702:         $linefeed = "\n";
13703:     } else {
13704:         $linefeed = "<br />\n";
13705:     }  
13706:     if ($three eq 'st') {
13707:         my $result = &commit_studentrole(\$logmsg,$udom,$uname,$url,$three,$start,$end,
13708:                                          $one,$two,$sec,$context,$credits);
13709:         if (($result =~ /^error/) || ($result eq 'not_in_class') || 
13710:             ($result eq 'unknown_course') || ($result eq 'refused')) {
13711:             $output = $logmsg.' '.&mt('Error: ').$result."\n"; 
13712:         } else {
13713:             $output = $logmsg.$linefeed.&mt('Assigning').' '.$three.' in '.$url.
13714:                ($start?', '.&mt('starting').' '.localtime($start):'').
13715:                ($end?', '.&mt('ending').' '.localtime($end):'').': ';
13716:             if ($context eq 'auto') {
13717:                 $output .= $result.$linefeed.&mt('Add to classlist').': ok';
13718:             } else {
13719:                $output .= '<b>'.$result.'</b>'.$linefeed.
13720:                &mt('Add to classlist').': <b>ok</b>';
13721:             }
13722:             $output .= $linefeed;
13723:         }
13724:     } else {
13725:         $output = &mt('Assigning').' '.$three.' in '.$url.
13726:                ($start?', '.&mt('starting').' '.localtime($start):'').
13727:                ($end?', '.&mt('ending').' '.localtime($end):'').': ';
13728:         my $result = &Apache::lonnet::assignrole($udom,$uname,$url,$three,$end,$start,'','',$context);
13729:         if ($context eq 'auto') {
13730:             $output .= $result.$linefeed;
13731:         } else {
13732:             $output .= '<b>'.$result.'</b>'.$linefeed;
13733:         }
13734:     }
13735:     return $output;
13736: }
13737: 
13738: sub commit_studentrole {
13739:     my ($logmsg,$udom,$uname,$url,$three,$start,$end,$one,$two,$sec,$context,
13740:         $credits) = @_;
13741:     my ($result,$linefeed,$oldsecurl,$newsecurl);
13742:     if ($context eq 'auto') {
13743:         $linefeed = "\n";
13744:     } else {
13745:         $linefeed = '<br />'."\n";
13746:     }
13747:     if (defined($one) && defined($two)) {
13748:         my $cid=$one.'_'.$two;
13749:         my $oldsec=&Apache::lonnet::getsection($udom,$uname,$cid);
13750:         my $secchange = 0;
13751:         my $expire_role_result;
13752:         my $modify_section_result;
13753:         if ($oldsec ne '-1') { 
13754:             if ($oldsec ne $sec) {
13755:                 $secchange = 1;
13756:                 my $now = time;
13757:                 my $uurl='/'.$cid;
13758:                 $uurl=~s/\_/\//g;
13759:                 if ($oldsec) {
13760:                     $uurl.='/'.$oldsec;
13761:                 }
13762:                 $oldsecurl = $uurl;
13763:                 $expire_role_result = 
13764:                     &Apache::lonnet::assignrole($udom,$uname,$uurl,'st',$now,'','',$context);
13765:                 if ($env{'request.course.sec'} ne '') { 
13766:                     if ($expire_role_result eq 'refused') {
13767:                         my @roles = ('st');
13768:                         my @statuses = ('previous');
13769:                         my @roledoms = ($one);
13770:                         my $withsec = 1;
13771:                         my %roleshash = 
13772:                             &Apache::lonnet::get_my_roles($uname,$udom,'userroles',
13773:                                               \@statuses,\@roles,\@roledoms,$withsec);
13774:                         if (defined ($roleshash{$two.':'.$one.':st:'.$oldsec})) {
13775:                             my ($oldstart,$oldend) = 
13776:                                 split(':',$roleshash{$two.':'.$one.':st:'.$oldsec});
13777:                             if ($oldend > 0 && $oldend <= $now) {
13778:                                 $expire_role_result = 'ok';
13779:                             }
13780:                         }
13781:                     }
13782:                 }
13783:                 $result = $expire_role_result;
13784:             }
13785:         }
13786:         if (($expire_role_result eq 'ok') || ($secchange == 0)) {
13787:             $modify_section_result = 
13788:                 &Apache::lonnet::modify_student_enrollment($udom,$uname,undef,undef,
13789:                                                            undef,undef,undef,$sec,
13790:                                                            $end,$start,'','',$cid,
13791:                                                            '',$context,$credits);
13792:             if ($modify_section_result =~ /^ok/) {
13793:                 if ($secchange == 1) {
13794:                     if ($sec eq '') {
13795:                         $$logmsg .= &mt('Section for [_1] switched from (possibly expired) old section: [_2] to student role without a section.',$uname,$oldsec).$linefeed;
13796:                     } else {
13797:                         $$logmsg .= &mt('Section for [_1] switched from (possibly expired) old section: [_2] to new section: [_3].',$uname,$oldsec,$sec).$linefeed;
13798:                     }
13799:                 } elsif ($oldsec eq '-1') {
13800:                     if ($sec eq '') {
13801:                         $$logmsg .= &mt('New student role without a section for [_1] in course [_2].',$uname,$cid).$linefeed;
13802:                     } else {
13803:                         $$logmsg .= &mt('New student role for [_1] in section [_2] in course [_3].',$uname,$sec,$cid).$linefeed;
13804:                     }
13805:                 } else {
13806:                     if ($sec eq '') {
13807:                         $$logmsg .= &mt('Student [_1] assigned to course [_2] without a section.',$uname,$cid).$linefeed;
13808:                     } else {
13809:                         $$logmsg .= &mt('Student [_1] assigned to section [_2] in course [_3].',$uname,$sec,$cid).$linefeed;
13810:                     }
13811:                 }
13812:             } else {
13813:                 if ($secchange) { 
13814:                     $$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;
13815:                 } else {
13816:                     $$logmsg .= &mt('Error when attempting to modify role for [_1] for section: "[_2]" in course [_3] -error:',$uname,$sec,$cid).' '.$modify_section_result.$linefeed;
13817:                 }
13818:             }
13819:             $result = $modify_section_result;
13820:         } elsif ($secchange == 1) {
13821:             if ($oldsec eq '') {
13822:                 $$logmsg .= &mt('Error when attempting to expire existing role without a section for [_1] in course [_2] -error: ',$uname,$cid).' '.$expire_role_result.$linefeed;
13823:             } else {
13824:                 $$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;
13825:             }
13826:             if ($expire_role_result eq 'refused') {
13827:                 my $newsecurl = '/'.$cid;
13828:                 $newsecurl =~ s/\_/\//g;
13829:                 if ($sec ne '') {
13830:                     $newsecurl.='/'.$sec;
13831:                 }
13832:                 if (&Apache::lonnet::allowed('cst',$newsecurl) && !(&Apache::lonnet::allowed('cst',$oldsecurl))) {
13833:                     if ($sec eq '') {
13834:                         $$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;
13835:                     } else {
13836:                         $$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;
13837:                     }
13838:                 }
13839:             }
13840:         }
13841:     } else {
13842:         $$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;
13843:         $result = "error: incomplete course id\n";
13844:     }
13845:     return $result;
13846: }
13847: 
13848: sub show_role_extent {
13849:     my ($scope,$context,$role) = @_;
13850:     $scope =~ s{^/}{};
13851:     my @courseroles = &Apache::lonuserutils::roles_by_context('course',1);
13852:     push(@courseroles,'co');
13853:     my @authorroles = &Apache::lonuserutils::roles_by_context('author');
13854:     if (($context eq 'course') || (grep(/^\Q$role\E/,@courseroles))) {
13855:         $scope =~ s{/}{_};
13856:         return '<span class="LC_cusr_emph">'.$env{'course.'.$scope.'.description'}.'</span>';
13857:     } elsif (($context eq 'author') || (grep(/^\Q$role\E/,@authorroles))) {
13858:         my ($audom,$auname) = split(/\//,$scope);
13859:         return &mt('[_1] Author Space','<span class="LC_cusr_emph">'.
13860:                    &Apache::loncommon::plainname($auname,$audom).'</span>');
13861:     } else {
13862:         $scope =~ s{/$}{};
13863:         return &mt('Domain: [_1]','<span class="LC_cusr_emph">'.
13864:                    &Apache::lonnet::domain($scope,'description').'</span>');
13865:     }
13866: }
13867: 
13868: ############################################################
13869: ############################################################
13870: 
13871: sub check_clone {
13872:     my ($args,$linefeed) = @_;
13873:     my $cloneid='/'.$args->{'clonedomain'}.'/'.$args->{'clonecourse'};
13874:     my ($clonecrsudom,$clonecrsunum)= &LONCAPA::split_courseid($cloneid);
13875:     my $clonehome=&Apache::lonnet::homeserver($clonecrsunum,$clonecrsudom);
13876:     my $clonemsg;
13877:     my $can_clone = 0;
13878:     my $lctype = lc($args->{'crstype'});
13879:     if ($lctype ne 'community') {
13880:         $lctype = 'course';
13881:     }
13882:     if ($clonehome eq 'no_host') {
13883:         if ($args->{'crstype'} eq 'Community') {
13884:             $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'});
13885:         } else {
13886:             $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'});
13887:         }     
13888:     } else {
13889: 	my %clonedesc = &Apache::lonnet::coursedescription($cloneid,{'one_time' => 1});
13890:         if ($args->{'crstype'} eq 'Community') {
13891:             if ($clonedesc{'type'} ne 'Community') {
13892:                  $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'});
13893:                 return ($can_clone, $clonemsg, $cloneid, $clonehome);
13894:             }
13895:         }
13896: 	if (($env{'request.role.domain'} eq $args->{'clonedomain'}) && 
13897:             (&Apache::lonnet::allowed('ccc',$env{'request.role.domain'}))) {
13898: 	    $can_clone = 1;
13899: 	} else {
13900: 	    my %clonehash = &Apache::lonnet::get('environment',['cloners'],
13901: 						 $args->{'clonedomain'},$args->{'clonecourse'});
13902: 	    my @cloners = split(/,/,$clonehash{'cloners'});
13903:             if (grep(/^\*$/,@cloners)) {
13904:                 $can_clone = 1;
13905:             } elsif (grep(/^\*\:\Q$args->{'ccdomain'}\E$/,@cloners)) {
13906:                 $can_clone = 1;
13907:             } else {
13908:                 my $ccrole = 'cc';
13909:                 if ($args->{'crstype'} eq 'Community') {
13910:                     $ccrole = 'co';
13911:                 }
13912: 	        my %roleshash =
13913: 		    &Apache::lonnet::get_my_roles($args->{'ccuname'},
13914: 					 $args->{'ccdomain'},
13915:                                          'userroles',['active'],[$ccrole],
13916: 					 [$args->{'clonedomain'}]);
13917: 	        if (($roleshash{$args->{'clonecourse'}.':'.$args->{'clonedomain'}.':'.$ccrole}) || (grep(/^\Q$args->{'ccuname'}\E:\Q$args->{'ccdomain'}\E$/,@cloners))) {
13918:                     $can_clone = 1;
13919:                 } elsif (&Apache::lonnet::is_course_owner($args->{'clonedomain'},$args->{'clonecourse'},$args->{'ccuname'},$args->{'ccdomain'})) {
13920:                     $can_clone = 1;
13921:                 } else {
13922:                     if ($args->{'crstype'} eq 'Community') {
13923:                         $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'});
13924:                     } else {
13925:                         $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'});
13926:                     }
13927: 	        }
13928: 	    }
13929:         }
13930:     }
13931:     return ($can_clone, $clonemsg, $cloneid, $clonehome);
13932: }
13933: 
13934: sub construct_course {
13935:     my ($args,$logmsg,$courseid,$crsudom,$crsunum,$udom,$uname,$context,$cnum,$category,$coderef) = @_;
13936:     my $outcome;
13937:     my $linefeed =  '<br />'."\n";
13938:     if ($context eq 'auto') {
13939:         $linefeed = "\n";
13940:     }
13941: 
13942: #
13943: # Are we cloning?
13944: #
13945:     my ($can_clone, $clonemsg, $cloneid, $clonehome);
13946:     if (($args->{'clonecourse'}) && ($args->{'clonedomain'})) {
13947: 	($can_clone, $clonemsg, $cloneid, $clonehome) = &check_clone($args,$linefeed);
13948: 	if ($context ne 'auto') {
13949:             if ($clonemsg ne '') {
13950: 	        $clonemsg = '<span class="LC_error">'.$clonemsg.'</span>';
13951:             }
13952: 	}
13953: 	$outcome .= $clonemsg.$linefeed;
13954: 
13955:         if (!$can_clone) {
13956: 	    return (0,$outcome);
13957: 	}
13958:     }
13959: 
13960: #
13961: # Open course
13962: #
13963:     my $crstype = lc($args->{'crstype'});
13964:     my %cenv=();
13965:     $$courseid=&Apache::lonnet::createcourse($args->{'course_domain'},
13966:                                              $args->{'cdescr'},
13967:                                              $args->{'curl'},
13968:                                              $args->{'course_home'},
13969:                                              $args->{'nonstandard'},
13970:                                              $args->{'crscode'},
13971:                                              $args->{'ccuname'}.':'.
13972:                                              $args->{'ccdomain'},
13973:                                              $args->{'crstype'},
13974:                                              $cnum,$context,$category);
13975: 
13976:     # Note: The testing routines depend on this being output; see 
13977:     # Utils::Course. This needs to at least be output as a comment
13978:     # if anyone ever decides to not show this, and Utils::Course::new
13979:     # will need to be suitably modified.
13980:     $outcome .= &mt('New LON-CAPA [_1] ID: [_2]',$crstype,$$courseid).$linefeed;
13981:     if ($$courseid =~ /^error:/) {
13982:         return (0,$outcome);
13983:     }
13984: 
13985: #
13986: # Check if created correctly
13987: #
13988:     ($$crsudom,$$crsunum)= &LONCAPA::split_courseid($$courseid);
13989:     my $crsuhome=&Apache::lonnet::homeserver($$crsunum,$$crsudom);
13990:     if ($crsuhome eq 'no_host') {
13991:         $outcome .= &mt('Course creation failed, unrecognized course home server.').$linefeed;
13992:         return (0,$outcome);
13993:     }
13994:     $outcome .= &mt('Created on').': '.$crsuhome.$linefeed;
13995: 
13996: #
13997: # Do the cloning
13998: #   
13999:     if ($can_clone && $cloneid) {
14000: 	$clonemsg = &mt('Cloning [_1] from [_2]',$crstype,$clonehome);
14001: 	if ($context ne 'auto') {
14002: 	    $clonemsg = '<span class="LC_success">'.$clonemsg.'</span>';
14003: 	}
14004: 	$outcome .= $clonemsg.$linefeed;
14005: 	my %oldcenv=&Apache::lonnet::dump('environment',$$crsudom,$$crsunum);
14006: # Copy all files
14007: 	&Apache::lonclonecourse::copycoursefiles($cloneid,$$courseid,$args->{'datemode'},$args->{'dateshift'});
14008: # Restore URL
14009: 	$cenv{'url'}=$oldcenv{'url'};
14010: # Restore title
14011: 	$cenv{'description'}=$oldcenv{'description'};
14012: # Restore creation date, creator and creation context.
14013:         $cenv{'internal.created'}=$oldcenv{'internal.created'};
14014:         $cenv{'internal.creator'}=$oldcenv{'internal.creator'};
14015:         $cenv{'internal.creationcontext'}=$oldcenv{'internal.creationcontext'};
14016: # Mark as cloned
14017: 	$cenv{'clonedfrom'}=$cloneid;
14018: # Need to clone grading mode
14019:         my %newenv=&Apache::lonnet::get('environment',['grading'],$$crsudom,$$crsunum);
14020:         $cenv{'grading'}=$newenv{'grading'};
14021: # Do not clone these environment entries
14022:         &Apache::lonnet::del('environment',
14023:                   ['default_enrollment_start_date',
14024:                    'default_enrollment_end_date',
14025:                    'question.email',
14026:                    'policy.email',
14027:                    'comment.email',
14028:                    'pch.users.denied',
14029:                    'plc.users.denied',
14030:                    'hidefromcat',
14031:                    'checkforpriv',
14032:                    'categories',
14033:                    'internal.uniquecode'],
14034:                    $$crsudom,$$crsunum);
14035:         if ($args->{'textbook'}) {
14036:             $cenv{'internal.textbook'} = $args->{'textbook'};
14037:         }
14038:     }
14039: 
14040: #
14041: # Set environment (will override cloned, if existing)
14042: #
14043:     my @sections = ();
14044:     my @xlists = ();
14045:     if ($args->{'crstype'}) {
14046:         $cenv{'type'}=$args->{'crstype'};
14047:     }
14048:     if ($args->{'crsid'}) {
14049:         $cenv{'courseid'}=$args->{'crsid'};
14050:     }
14051:     if ($args->{'crscode'}) {
14052:         $cenv{'internal.coursecode'}=$args->{'crscode'};
14053:     }
14054:     if ($args->{'crsquota'} ne '') {
14055:         $cenv{'internal.coursequota'}=$args->{'crsquota'};
14056:     } else {
14057:         $cenv{'internal.coursequota'}=$args->{'crsquota'} = 20;
14058:     }
14059:     if ($args->{'ccuname'}) {
14060:         $cenv{'internal.courseowner'} = $args->{'ccuname'}.
14061:                                         ':'.$args->{'ccdomain'};
14062:     } else {
14063:         $cenv{'internal.courseowner'} = $args->{'curruser'};
14064:     }
14065:     if ($args->{'defaultcredits'}) {
14066:         $cenv{'internal.defaultcredits'} = $args->{'defaultcredits'};
14067:     }
14068:     my @badclasses = (); # Used to accumulate sections/crosslistings that did not pass classlist access check for course owner.
14069:     if ($args->{'crssections'}) {
14070:         $cenv{'internal.sectionnums'} = '';
14071:         if ($args->{'crssections'} =~ m/,/) {
14072:             @sections = split/,/,$args->{'crssections'};
14073:         } else {
14074:             $sections[0] = $args->{'crssections'};
14075:         }
14076:         if (@sections > 0) {
14077:             foreach my $item (@sections) {
14078:                 my ($sec,$gp) = split/:/,$item;
14079:                 my $class = $args->{'crscode'}.$sec;
14080:                 my $addcheck = &Apache::lonnet::auto_new_course($$crsunum,$$crsudom,$class,$cenv{'internal.courseowner'});
14081:                 $cenv{'internal.sectionnums'} .= $item.',';
14082:                 unless ($addcheck eq 'ok') {
14083:                     push @badclasses, $class;
14084:                 }
14085:             }
14086:             $cenv{'internal.sectionnums'} =~ s/,$//;
14087:         }
14088:     }
14089: # do not hide course coordinator from staff listing, 
14090: # even if privileged
14091:     $cenv{'nothideprivileged'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
14092: # add course coordinator's domain to domains to check for privileged users
14093: # if different to course domain
14094:     if ($$crsudom ne $args->{'ccdomain'}) {
14095:         $cenv{'checkforpriv'} = $args->{'ccdomain'};
14096:     }
14097: # add crosslistings
14098:     if ($args->{'crsxlist'}) {
14099:         $cenv{'internal.crosslistings'}='';
14100:         if ($args->{'crsxlist'} =~ m/,/) {
14101:             @xlists = split/,/,$args->{'crsxlist'};
14102:         } else {
14103:             $xlists[0] = $args->{'crsxlist'};
14104:         }
14105:         if (@xlists > 0) {
14106:             foreach my $item (@xlists) {
14107:                 my ($xl,$gp) = split/:/,$item;
14108:                 my $addcheck =  &Apache::lonnet::auto_new_course($$crsunum,$$crsudom,$xl,$cenv{'internal.courseowner'});
14109:                 $cenv{'internal.crosslistings'} .= $item.',';
14110:                 unless ($addcheck eq 'ok') {
14111:                     push @badclasses, $xl;
14112:                 }
14113:             }
14114:             $cenv{'internal.crosslistings'} =~ s/,$//;
14115:         }
14116:     }
14117:     if ($args->{'autoadds'}) {
14118:         $cenv{'internal.autoadds'}=$args->{'autoadds'};
14119:     }
14120:     if ($args->{'autodrops'}) {
14121:         $cenv{'internal.autodrops'}=$args->{'autodrops'};
14122:     }
14123: # check for notification of enrollment changes
14124:     my @notified = ();
14125:     if ($args->{'notify_owner'}) {
14126:         if ($args->{'ccuname'} ne '') {
14127:             push(@notified,$args->{'ccuname'}.':'.$args->{'ccdomain'});
14128:         }
14129:     }
14130:     if ($args->{'notify_dc'}) {
14131:         if ($uname ne '') { 
14132:             push(@notified,$uname.':'.$udom);
14133:         }
14134:     }
14135:     if (@notified > 0) {
14136:         my $notifylist;
14137:         if (@notified > 1) {
14138:             $notifylist = join(',',@notified);
14139:         } else {
14140:             $notifylist = $notified[0];
14141:         }
14142:         $cenv{'internal.notifylist'} = $notifylist;
14143:     }
14144:     if (@badclasses > 0) {
14145:         my %lt=&Apache::lonlocal::texthash(
14146:                 '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',
14147:                 'dnhr' => 'does not have rights to access enrollment in these classes',
14148:                 'adby' => 'as determined by the policies of your institution on access to official classlists'
14149:         );
14150:         my $badclass_msg = $cenv{'internal.courseowner'}.') - '.$lt{'dnhr'}.
14151:                            ' ('.$lt{'adby'}.')';
14152:         if ($context eq 'auto') {
14153:             $outcome .= $badclass_msg.$linefeed;
14154:             $outcome .= '<div class="LC_warning">'.$badclass_msg.$linefeed.'<ul>'."\n";
14155:             foreach my $item (@badclasses) {
14156:                 if ($context eq 'auto') {
14157:                     $outcome .= " - $item\n";
14158:                 } else {
14159:                     $outcome .= "<li>$item</li>\n";
14160:                 }
14161:             }
14162:             if ($context eq 'auto') {
14163:                 $outcome .= $linefeed;
14164:             } else {
14165:                 $outcome .= "</ul><br /><br /></div>\n";
14166:             }
14167:         } 
14168:     }
14169:     if ($args->{'no_end_date'}) {
14170:         $args->{'endaccess'} = 0;
14171:     }
14172:     $cenv{'internal.autostart'}=$args->{'enrollstart'};
14173:     $cenv{'internal.autoend'}=$args->{'enrollend'};
14174:     $cenv{'default_enrollment_start_date'}=$args->{'startaccess'};
14175:     $cenv{'default_enrollment_end_date'}=$args->{'endaccess'};
14176:     if ($args->{'showphotos'}) {
14177:       $cenv{'internal.showphotos'}=$args->{'showphotos'};
14178:     }
14179:     $cenv{'internal.authtype'} = $args->{'authtype'};
14180:     $cenv{'internal.autharg'} = $args->{'autharg'}; 
14181:     if ( ($cenv{'internal.authtype'} =~ /^krb/) && ($cenv{'internal.autoadds'} == 1)) {
14182:         if (! defined($cenv{'internal.autharg'}) || $cenv{'internal.autharg'}  eq '') {
14183:             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'); 
14184:             if ($context eq 'auto') {
14185:                 $outcome .= $krb_msg;
14186:             } else {
14187:                 $outcome .= '<span class="LC_error">'.$krb_msg.'</span>';
14188:             }
14189:             $outcome .= $linefeed;
14190:         }
14191:     }
14192:     if (($args->{'ccdomain'}) && ($args->{'ccuname'})) {
14193:        if ($args->{'setpolicy'}) {
14194:            $cenv{'policy.email'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
14195:        }
14196:        if ($args->{'setcontent'}) {
14197:            $cenv{'question.email'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
14198:        }
14199:     }
14200:     if ($args->{'reshome'}) {
14201: 	$cenv{'reshome'}=$args->{'reshome'}.'/';
14202: 	$cenv{'reshome'}=~s/\/+$/\//;
14203:     }
14204: #
14205: # course has keyed access
14206: #
14207:     if ($args->{'setkeys'}) {
14208:        $cenv{'keyaccess'}='yes';
14209:     }
14210: # if specified, key authority is not course, but user
14211: # only active if keyaccess is yes
14212:     if ($args->{'keyauth'}) {
14213: 	my ($user,$domain) = split(':',$args->{'keyauth'});
14214: 	$user = &LONCAPA::clean_username($user);
14215: 	$domain = &LONCAPA::clean_username($domain);
14216: 	if ($user ne '' && $domain ne '') {
14217: 	    $cenv{'keyauth'}=$user.':'.$domain;
14218: 	}
14219:     }
14220: 
14221: #
14222: #  generate and store uniquecode (available to course requester), if course should have one.
14223: #
14224:     if ($args->{'uniquecode'}) {
14225:         my ($code,$error) = &make_unique_code($$crsudom,$$crsunum);
14226:         if ($code) {
14227:             $cenv{'internal.uniquecode'} = $code;
14228:             my %crsinfo =
14229:                 &Apache::lonnet::courseiddump($$crsudom,'.',1,'.','.',$$crsunum,undef,undef,'.');
14230:             if (ref($crsinfo{$$crsudom.'_'.$$crsunum}) eq 'HASH') {
14231:                 $crsinfo{$$crsudom.'_'.$$crsunum}{'uniquecode'} = $code;
14232:                 my $putres = &Apache::lonnet::courseidput($$crsudom,\%crsinfo,$crsuhome,'notime');
14233:             } 
14234:             if (ref($coderef)) {
14235:                 $$coderef = $code;
14236:             }
14237:         }
14238:     }
14239: 
14240:     if ($args->{'disresdis'}) {
14241:         $cenv{'pch.roles.denied'}='st';
14242:     }
14243:     if ($args->{'disablechat'}) {
14244:         $cenv{'plc.roles.denied'}='st';
14245:     }
14246: 
14247:     # Record we've not yet viewed the Course Initialization Helper for this 
14248:     # course
14249:     $cenv{'course.helper.not.run'} = 1;
14250:     #
14251:     # Use new Randomseed
14252:     #
14253:     $cenv{'rndseed'}=&Apache::lonnet::latest_rnd_algorithm_id();;
14254:     $cenv{'receiptalg'}=&Apache::lonnet::latest_receipt_algorithm_id();;
14255:     #
14256:     # The encryption code and receipt prefix for this course
14257:     #
14258:     $cenv{'internal.encseed'}=$Apache::lonnet::perlvar{'lonReceipt'}.$$.time.int(rand(9999));
14259:     $cenv{'internal.encpref'}=100+int(9*rand(99));
14260:     #
14261:     # By default, use standard grading
14262:     if (!defined($cenv{'grading'})) { $cenv{'grading'} = 'standard'; }
14263: 
14264:     $outcome .= $linefeed.&mt('Setting environment').': '.                 
14265:           &Apache::lonnet::put('environment',\%cenv,$$crsudom,$$crsunum).$linefeed;
14266: #
14267: # Open all assignments
14268: #
14269:     if ($args->{'openall'}) {
14270:        my $storeunder=$$crsudom.'_'.$$crsunum.'.0.opendate';
14271:        my %storecontent = ($storeunder         => time,
14272:                            $storeunder.'.type' => 'date_start');
14273:        
14274:        $outcome .= &mt('Opening all assignments').': '.&Apache::lonnet::cput
14275:                  ('resourcedata',\%storecontent,$$crsudom,$$crsunum).$linefeed;
14276:    }
14277: #
14278: # Set first page
14279: #
14280:     unless (($args->{'nonstandard'}) || ($args->{'firstres'} eq 'blank')
14281: 	    || ($cloneid)) {
14282: 	use LONCAPA::map;
14283: 	$outcome .= &mt('Setting first resource').': ';
14284: 
14285: 	my $map = '/uploaded/'.$$crsudom.'/'.$$crsunum.'/default.sequence';
14286:         my ($errtext,$fatal)=&LONCAPA::map::mapread($map);
14287: 
14288:         $outcome .= ($fatal?$errtext:'read ok').' - ';
14289:         my $title; my $url;
14290:         if ($args->{'firstres'} eq 'syl') {
14291: 	    $title=&mt('Syllabus');
14292:             $url='/public/'.$$crsudom.'/'.$$crsunum.'/syllabus';
14293:         } else {
14294:             $title=&mt('Table of Contents');
14295:             $url='/adm/navmaps';
14296:         }
14297: 
14298:         $LONCAPA::map::resources[1]=$title.':'.$url.':false:start:res';
14299: 	(my $outtext,$errtext) = &LONCAPA::map::storemap($map,1);
14300: 
14301: 	if ($errtext) { $fatal=2; }
14302:         $outcome .= ($fatal?$errtext:'write ok').$linefeed;
14303:     }
14304: 
14305:     return (1,$outcome);
14306: }
14307: 
14308: sub make_unique_code {
14309:     my ($cdom,$cnum) = @_;
14310:     # get lock on uniquecodes db
14311:     my $lockhash = {
14312:                       $cnum."\0".'uniquecodes' => $env{'user.name'}.
14313:                                                   ':'.$env{'user.domain'},
14314:                    };
14315:     my $tries = 0;
14316:     my $gotlock = &Apache::lonnet::newput_dom('uniquecodes',$lockhash,$cdom);
14317:     my ($code,$error);
14318:   
14319:     while (($gotlock ne 'ok') && ($tries<3)) {
14320:         $tries ++;
14321:         sleep 1;
14322:         $gotlock = &Apache::lonnet::newput_dom('uniquecodes',$lockhash,$cdom);
14323:     }
14324:     if ($gotlock eq 'ok') {
14325:         my %currcodes = &Apache::lonnet::dump_dom('uniquecodes',$cdom);
14326:         my $gotcode;
14327:         my $attempts = 0;
14328:         while ((!$gotcode) && ($attempts < 100)) {
14329:             $code = &generate_code();
14330:             if (!exists($currcodes{$code})) {
14331:                 $gotcode = 1;
14332:                 unless (&Apache::lonnet::newput_dom('uniquecodes',{ $code => $cnum },$cdom) eq 'ok') {
14333:                     $error = 'nostore';
14334:                 }
14335:             }
14336:             $attempts ++;
14337:         }
14338:         my @del_lock = ($cnum."\0".'uniquecodes');
14339:         my $dellockoutcome = &Apache::lonnet::del_dom('uniquecodes',\@del_lock,$cdom);
14340:     } else {
14341:         $error = 'nolock';
14342:     }
14343:     return ($code,$error);
14344: }
14345: 
14346: sub generate_code {
14347:     my $code;
14348:     my @letts = qw(B C D G H J K M N P Q R S T V W X Z);
14349:     for (my $i=0; $i<6; $i++) {
14350:         my $lettnum = int (rand 2);
14351:         my $item = '';
14352:         if ($lettnum) {
14353:             $item = $letts[int( rand(18) )];
14354:         } else {
14355:             $item = 1+int( rand(8) );
14356:         }
14357:         $code .= $item;
14358:     }
14359:     return $code;
14360: }
14361: 
14362: ############################################################
14363: ############################################################
14364: 
14365: #SD
14366: # only Community and Course, or anything else?
14367: sub course_type {
14368:     my ($cid) = @_;
14369:     if (!defined($cid)) {
14370:         $cid = $env{'request.course.id'};
14371:     }
14372:     if (defined($env{'course.'.$cid.'.type'})) {
14373:         return $env{'course.'.$cid.'.type'};
14374:     } else {
14375:         return 'Course';
14376:     }
14377: }
14378: 
14379: sub group_term {
14380:     my $crstype = &course_type();
14381:     my %names = (
14382:                   'Course' => 'group',
14383:                   'Community' => 'group',
14384:                 );
14385:     return $names{$crstype};
14386: }
14387: 
14388: sub course_types {
14389:     my @types = ('official','unofficial','community','textbook');
14390:     my %typename = (
14391:                          official   => 'Official course',
14392:                          unofficial => 'Unofficial course',
14393:                          community  => 'Community',
14394:                          textbook   => 'Textbook course',
14395:                    );
14396:     return (\@types,\%typename);
14397: }
14398: 
14399: sub icon {
14400:     my ($file)=@_;
14401:     my $curfext = lc((split(/\./,$file))[-1]);
14402:     my $iconname=$Apache::lonnet::perlvar{'lonIconsURL'}.'/unknown.gif';
14403:     my $embstyle = &Apache::loncommon::fileembstyle($curfext);
14404:     if (!(!defined($embstyle) || $embstyle eq 'unk' || $embstyle eq 'hdn')) {
14405: 	if (-e  $Apache::lonnet::perlvar{'lonDocRoot'}.'/'.
14406: 	          $Apache::lonnet::perlvar{'lonIconsURL'}.'/'.
14407: 	            $curfext.".gif") {
14408: 	    $iconname=$Apache::lonnet::perlvar{'lonIconsURL'}.'/'.
14409: 		$curfext.".gif";
14410: 	}
14411:     }
14412:     return &lonhttpdurl($iconname);
14413: } 
14414: 
14415: sub lonhttpdurl {
14416: #
14417: # Had been used for "small fry" static images on separate port 8080.
14418: # Modify here if lightweight http functionality desired again.
14419: # Currently eliminated due to increasing firewall issues.
14420: #
14421:     my ($url)=@_;
14422:     return $url;
14423: }
14424: 
14425: sub connection_aborted {
14426:     my ($r)=@_;
14427:     $r->print(" ");$r->rflush();
14428:     my $c = $r->connection;
14429:     return $c->aborted();
14430: }
14431: 
14432: #    Escapes strings that may have embedded 's that will be put into
14433: #    strings as 'strings'.
14434: sub escape_single {
14435:     my ($input) = @_;
14436:     $input =~ s/\\/\\\\/g;	# Escape the \'s..(must be first)>
14437:     $input =~ s/\'/\\\'/g;	# Esacpe the 's....
14438:     return $input;
14439: }
14440: 
14441: #  Same as escape_single, but escape's "'s  This 
14442: #  can be used for  "strings"
14443: sub escape_double {
14444:     my ($input) = @_;
14445:     $input =~ s/\\/\\\\/g;	# Escape the /'s..(must be first)>
14446:     $input =~ s/\"/\\\"/g;	# Esacpe the "s....
14447:     return $input;
14448: }
14449:  
14450: #   Escapes the last element of a full URL.
14451: sub escape_url {
14452:     my ($url)   = @_;
14453:     my @urlslices = split(/\//, $url,-1);
14454:     my $lastitem = &escape(pop(@urlslices));
14455:     return join('/',@urlslices).'/'.$lastitem;
14456: }
14457: 
14458: sub compare_arrays {
14459:     my ($arrayref1,$arrayref2) = @_;
14460:     my (@difference,%count);
14461:     @difference = ();
14462:     %count = ();
14463:     if ((ref($arrayref1) eq 'ARRAY') && (ref($arrayref2) eq 'ARRAY')) {
14464:         foreach my $element (@{$arrayref1}, @{$arrayref2}) { $count{$element}++; }
14465:         foreach my $element (keys(%count)) {
14466:             if ($count{$element} == 1) {
14467:                 push(@difference,$element);
14468:             }
14469:         }
14470:     }
14471:     return @difference;
14472: }
14473: 
14474: # -------------------------------------------------------- Initialize user login
14475: sub init_user_environment {
14476:     my ($r, $username, $domain, $authhost, $form, $args) = @_;
14477:     my $lonids=$Apache::lonnet::perlvar{'lonIDsDir'};
14478: 
14479:     my $public=($username eq 'public' && $domain eq 'public');
14480: 
14481: # See if old ID present, if so, remove
14482: 
14483:     my ($filename,$cookie,$userroles,$firstaccenv,$timerintenv);
14484:     my $now=time;
14485: 
14486:     if ($public) {
14487: 	my $max_public=100;
14488: 	my $oldest;
14489: 	my $oldest_time=0;
14490: 	for(my $next=1;$next<=$max_public;$next++) {
14491: 	    if (-e $lonids."/publicuser_$next.id") {
14492: 		my $mtime=(stat($lonids."/publicuser_$next.id"))[9];
14493: 		if ($mtime<$oldest_time || !$oldest_time) {
14494: 		    $oldest_time=$mtime;
14495: 		    $oldest=$next;
14496: 		}
14497: 	    } else {
14498: 		$cookie="publicuser_$next";
14499: 		last;
14500: 	    }
14501: 	}
14502: 	if (!$cookie) { $cookie="publicuser_$oldest"; }
14503:     } else {
14504: 	# if this isn't a robot, kill any existing non-robot sessions
14505: 	if (!$args->{'robot'}) {
14506: 	    opendir(DIR,$lonids);
14507: 	    while ($filename=readdir(DIR)) {
14508: 		if ($filename=~/^$username\_\d+\_$domain\_$authhost\.id$/) {
14509: 		    unlink($lonids.'/'.$filename);
14510: 		}
14511: 	    }
14512: 	    closedir(DIR);
14513: 	}
14514: # Give them a new cookie
14515: 	my $id = ($args->{'robot'} ? 'robot'.$args->{'robot'}
14516: 		                   : $now.$$.int(rand(10000)));
14517: 	$cookie="$username\_$id\_$domain\_$authhost";
14518:     
14519: # Initialize roles
14520: 
14521: 	($userroles,$firstaccenv,$timerintenv) = 
14522:             &Apache::lonnet::rolesinit($domain,$username,$authhost);
14523:     }
14524: # ------------------------------------ Check browser type and MathML capability
14525: 
14526:     my ($httpbrowser,$clientbrowser,$clientversion,$clientmathml,
14527:         $clientunicode,$clientos,$clientmobile,$clientinfo) = &decode_user_agent($r);
14528: 
14529: # ------------------------------------------------------------- Get environment
14530: 
14531:     my %userenv = &Apache::lonnet::dump('environment',$domain,$username);
14532:     my ($tmp) = keys(%userenv);
14533:     if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
14534:     } else {
14535: 	undef(%userenv);
14536:     }
14537:     if (($userenv{'interface'}) && (!$form->{'interface'})) {
14538: 	$form->{'interface'}=$userenv{'interface'};
14539:     }
14540:     if ($userenv{'texengine'} eq 'ttm') { $clientmathml=1; }
14541: 
14542: # --------------- Do not trust query string to be put directly into environment
14543:     foreach my $option ('interface','localpath','localres') {
14544:         $form->{$option}=~s/[\n\r\=]//gs;
14545:     }
14546: # --------------------------------------------------------- Write first profile
14547: 
14548:     {
14549: 	my %initial_env = 
14550: 	    ("user.name"          => $username,
14551: 	     "user.domain"        => $domain,
14552: 	     "user.home"          => $authhost,
14553: 	     "browser.type"       => $clientbrowser,
14554: 	     "browser.version"    => $clientversion,
14555: 	     "browser.mathml"     => $clientmathml,
14556: 	     "browser.unicode"    => $clientunicode,
14557: 	     "browser.os"         => $clientos,
14558:              "browser.mobile"     => $clientmobile,
14559:              "browser.info"       => $clientinfo,
14560: 	     "server.domain"      => $Apache::lonnet::perlvar{'lonDefDomain'},
14561: 	     "request.course.fn"  => '',
14562: 	     "request.course.uri" => '',
14563: 	     "request.course.sec" => '',
14564: 	     "request.role"       => 'cm',
14565: 	     "request.role.adv"   => $env{'user.adv'},
14566: 	     "request.host"       => $ENV{'REMOTE_ADDR'},);
14567: 
14568:         if ($form->{'localpath'}) {
14569: 	    $initial_env{"browser.localpath"}  = $form->{'localpath'};
14570: 	    $initial_env{"browser.localres"}   = $form->{'localres'};
14571:         }
14572: 	
14573: 	if ($form->{'interface'}) {
14574: 	    $form->{'interface'}=~s/\W//gs;
14575: 	    $initial_env{"browser.interface"} = $form->{'interface'};
14576: 	    $env{'browser.interface'}=$form->{'interface'};
14577: 	}
14578: 
14579:         if ($form->{'iptoken'}) {
14580:             my $lonhost = $r->dir_config('lonHostID');
14581:             $initial_env{"user.noloadbalance"} = $lonhost;
14582:             $env{'user.noloadbalance'} = $lonhost;
14583:         }
14584: 
14585:         my %is_adv = ( is_adv => $env{'user.adv'} );
14586:         my %domdef;
14587:         unless ($domain eq 'public') {
14588:             %domdef = &Apache::lonnet::get_domain_defaults($domain);
14589:         }
14590: 
14591:         foreach my $tool ('aboutme','blog','webdav','portfolio') {
14592:             $userenv{'availabletools.'.$tool} = 
14593:                 &Apache::lonnet::usertools_access($username,$domain,$tool,'reload',
14594:                                                   undef,\%userenv,\%domdef,\%is_adv);
14595:         }
14596: 
14597:         foreach my $crstype ('official','unofficial','community','textbook') {
14598:             $userenv{'canrequest.'.$crstype} =
14599:                 &Apache::lonnet::usertools_access($username,$domain,$crstype,
14600:                                                   'reload','requestcourses',
14601:                                                   \%userenv,\%domdef,\%is_adv);
14602:         }
14603: 
14604:         $userenv{'canrequest.author'} =
14605:             &Apache::lonnet::usertools_access($username,$domain,'requestauthor',
14606:                                         'reload','requestauthor',
14607:                                         \%userenv,\%domdef,\%is_adv);
14608:         my %reqauthor = &Apache::lonnet::get('requestauthor',['author_status','author'],
14609:                                              $domain,$username);
14610:         my $reqstatus = $reqauthor{'author_status'};
14611:         if ($reqstatus eq 'approval' || $reqstatus eq 'approved') { 
14612:             if (ref($reqauthor{'author'}) eq 'HASH') {
14613:                 $userenv{'requestauthorqueued'} = $reqstatus.':'.
14614:                                                   $reqauthor{'author'}{'timestamp'};
14615:             }
14616:         }
14617: 
14618: 	$env{'user.environment'} = "$lonids/$cookie.id";
14619: 
14620: 	if (tie(my %disk_env,'GDBM_File',"$lonids/$cookie.id",
14621: 		 &GDBM_WRCREAT(),0640)) {
14622: 	    &_add_to_env(\%disk_env,\%initial_env);
14623: 	    &_add_to_env(\%disk_env,\%userenv,'environment.');
14624: 	    &_add_to_env(\%disk_env,$userroles);
14625:             if (ref($firstaccenv) eq 'HASH') {
14626:                 &_add_to_env(\%disk_env,$firstaccenv);
14627:             }
14628:             if (ref($timerintenv) eq 'HASH') {
14629:                 &_add_to_env(\%disk_env,$timerintenv);
14630:             }
14631: 	    if (ref($args->{'extra_env'})) {
14632: 		&_add_to_env(\%disk_env,$args->{'extra_env'});
14633: 	    }
14634: 	    untie(%disk_env);
14635: 	} else {
14636: 	    &Apache::lonnet::logthis("<span style=\"color:blue;\">WARNING: ".
14637: 			   'Could not create environment storage in lonauth: '.$!.'</span>');
14638: 	    return 'error: '.$!;
14639: 	}
14640:     }
14641:     $env{'request.role'}='cm';
14642:     $env{'request.role.adv'}=$env{'user.adv'};
14643:     $env{'browser.type'}=$clientbrowser;
14644: 
14645:     return $cookie;
14646: 
14647: }
14648: 
14649: sub _add_to_env {
14650:     my ($idf,$env_data,$prefix) = @_;
14651:     if (ref($env_data) eq 'HASH') {
14652:         while (my ($key,$value) = each(%$env_data)) {
14653: 	    $idf->{$prefix.$key} = $value;
14654: 	    $env{$prefix.$key}   = $value;
14655:         }
14656:     }
14657: }
14658: 
14659: # --- Get the symbolic name of a problem and the url
14660: sub get_symb {
14661:     my ($request,$silent) = @_;
14662:     (my $url=$env{'form.url'}) =~ s-^https?\://($ENV{'SERVER_NAME'}|$ENV{'HTTP_HOST'})--;
14663:     my $symb=($env{'form.symb'} ne '' ? $env{'form.symb'} : (&Apache::lonnet::symbread($url)));
14664:     if ($symb eq '') {
14665:         if (!$silent) {
14666:             if (ref($request)) { 
14667:                 $request->print("Unable to handle ambiguous references:$url:.");
14668:             }
14669:             return ();
14670:         }
14671:     }
14672:     &Apache::lonenc::check_decrypt(\$symb);
14673:     return ($symb);
14674: }
14675: 
14676: # --------------------------------------------------------------Get annotation
14677: 
14678: sub get_annotation {
14679:     my ($symb,$enc) = @_;
14680: 
14681:     my $key = $symb;
14682:     if (!$enc) {
14683:         $key =
14684:             &Apache::lonnet::clutter((&Apache::lonnet::decode_symb($symb))[2]);
14685:     }
14686:     my %annotation=&Apache::lonnet::get('nohist_annotations',[$key]);
14687:     return $annotation{$key};
14688: }
14689: 
14690: sub clean_symb {
14691:     my ($symb,$delete_enc) = @_;
14692: 
14693:     &Apache::lonenc::check_decrypt(\$symb);
14694:     my $enc = $env{'request.enc'};
14695:     if ($delete_enc) {
14696:         delete($env{'request.enc'});
14697:     }
14698: 
14699:     return ($symb,$enc);
14700: }
14701: 
14702: ############################################################
14703: ############################################################
14704: 
14705: =pod
14706: 
14707: =head1 Routines for building display used to search for courses
14708: 
14709: 
14710: =over 4
14711: 
14712: =item * &build_filters()
14713: 
14714: Create markup for a table used to set filters to use when selecting
14715: courses in a domain.  Used by lonpickcourse.pm, lonmodifycourse.pm
14716: and quotacheck.pl
14717: 
14718: 
14719: Inputs:
14720: 
14721: filterlist - anonymous array of fields to include as potential filters 
14722: 
14723: crstype - course type
14724: 
14725: roleelement - fifth arg in selectcourse_link() populates fifth arg in javascript: opencrsbrowser() function, used
14726:               to pop-open a course selector (will contain "extra element"). 
14727: 
14728: multelement - if multiple course selections will be allowed, this will be a hidden form element: name: multiple; value: 1
14729: 
14730: filter - anonymous hash of criteria and their values
14731: 
14732: action - form action
14733: 
14734: numfiltersref - ref to scalar (count of number of elements in institutional codes -- e.g., 4 for year, semester, department, and number)
14735: 
14736: caller - caller context (e.g., set to 'modifycourse' when routine is called from lonmodifycourse.pm)
14737: 
14738: cloneruname - username of owner of new course who wants to clone
14739: 
14740: clonerudom - domain of owner of new course who wants to clone
14741: 
14742: typeelem - text to use for left column in row containing course type (i.e., Course, Community or Course/Community) 
14743: 
14744: codetitlesref - reference to array of titles of components in institutional codes (official courses)
14745: 
14746: codedom - domain
14747: 
14748: formname - value of form element named "form". 
14749: 
14750: fixeddom - domain, if fixed.
14751: 
14752: prevphase - value to assign to form element named "phase" when going back to the previous screen  
14753: 
14754: cnameelement - name of form element in form on opener page which will receive title of selected course 
14755: 
14756: cnumelement - name of form element in form on opener page which will receive courseID  of selected course
14757: 
14758: cdomelement - name of form element in form on opener page which will receive domain of selected course
14759: 
14760: setroles - includes access constraint identifier when setting a roles-based condition for acces to a portfolio file
14761: 
14762: clonetext - hidden form elements containing list of courses cloneable by intended course owner when DC creates a course
14763: 
14764: clonewarning - warning message about missing information for intended course owner when DC creates a course
14765: 
14766: 
14767: Returns: $output - HTML for display of search criteria, and hidden form elements.
14768: 
14769: 
14770: Side Effects: None
14771: 
14772: =cut
14773: 
14774: # ---------------------------------------------- search for courses based on last activity etc.
14775: 
14776: sub build_filters {
14777:     my ($filterlist,$crstype,$roleelement,$multelement,$filter,$action,
14778:         $numtitlesref,$caller,$cloneruname,$clonerudom,$typeelement,
14779:         $codetitlesref,$codedom,$formname,$fixeddom,$prevphase,
14780:         $cnameelement,$cnumelement,$cdomelement,$setroles,
14781:         $clonetext,$clonewarning) = @_;
14782:     my ($list,$jscript);
14783:     my $onchange = 'javascript:updateFilters(this)';
14784:     my ($domainselectform,$sincefilterform,$createdfilterform,
14785:         $ownerdomselectform,$persondomselectform,$instcodeform,
14786:         $typeselectform,$instcodetitle);
14787:     if ($formname eq '') {
14788:         $formname = $caller;
14789:     }
14790:     foreach my $item (@{$filterlist}) {
14791:         unless (($item eq 'descriptfilter') || ($item eq 'instcodefilter') ||
14792:                 ($item eq 'sincefilter') || ($item eq 'createdfilter')) {
14793:             if ($item eq 'domainfilter') {
14794:                 $filter->{$item} = &LONCAPA::clean_domain($filter->{$item});
14795:             } elsif ($item eq 'coursefilter') {
14796:                 $filter->{$item} = &LONCAPA::clean_courseid($filter->{$item});
14797:             } elsif ($item eq 'ownerfilter') {
14798:                 $filter->{$item} = &LONCAPA::clean_username($filter->{$item});
14799:             } elsif ($item eq 'ownerdomfilter') {
14800:                 $filter->{'ownerdomfilter'} =
14801:                     &LONCAPA::clean_domain($filter->{$item});
14802:                 $ownerdomselectform = &select_dom_form($filter->{'ownerdomfilter'},
14803:                                                        'ownerdomfilter',1);
14804:             } elsif ($item eq 'personfilter') {
14805:                 $filter->{$item} = &LONCAPA::clean_username($filter->{$item});
14806:             } elsif ($item eq 'persondomfilter') {
14807:                 $persondomselectform = &select_dom_form($filter->{'persondomfilter'},
14808:                                                         'persondomfilter',1);
14809:             } else {
14810:                 $filter->{$item} =~ s/\W//g;
14811:             }
14812:             if (!$filter->{$item}) {
14813:                 $filter->{$item} = '';
14814:             }
14815:         }
14816:         if ($item eq 'domainfilter') {
14817:             my $allow_blank = 1;
14818:             if ($formname eq 'portform') {
14819:                 $allow_blank=0;
14820:             } elsif ($formname eq 'studentform') {
14821:                 $allow_blank=0;
14822:             }
14823:             if ($fixeddom) {
14824:                 $domainselectform = '<input type="hidden" name="domainfilter"'.
14825:                                     ' value="'.$codedom.'" />'.
14826:                                     &Apache::lonnet::domain($codedom,'description');
14827:             } else {
14828:                 $domainselectform = &select_dom_form($filter->{$item},
14829:                                                      'domainfilter',
14830:                                                       $allow_blank,'',$onchange);
14831:             }
14832:         } else {
14833:             $list->{$item} = &HTML::Entities::encode($filter->{$item},'<>&"');
14834:         }
14835:     }
14836: 
14837:     # last course activity filter and selection
14838:     $sincefilterform = &timebased_select_form('sincefilter',$filter);
14839: 
14840:     # course created filter and selection
14841:     if (exists($filter->{'createdfilter'})) {
14842:         $createdfilterform = &timebased_select_form('createdfilter',$filter);
14843:     }
14844: 
14845:     my %lt = &Apache::lonlocal::texthash(
14846:                 'cac' => "$crstype Activity",
14847:                 'ccr' => "$crstype Created",
14848:                 'cde' => "$crstype Title",
14849:                 'cdo' => "$crstype Domain",
14850:                 'ins' => 'Institutional Code',
14851:                 'inc' => 'Institutional Categorization',
14852:                 'cow' => "$crstype Owner/Co-owner",
14853:                 'cop' => "$crstype Personnel Includes",
14854:                 'cog' => 'Type',
14855:              );
14856: 
14857:     if (($formname eq 'ccrs') || ($formname eq 'requestcrs')) {
14858:         my $typeval = 'Course';
14859:         if ($crstype eq 'Community') {
14860:             $typeval = 'Community';
14861:         }
14862:         $typeselectform = '<input type="hidden" name="type" value="'.$typeval.'" />';
14863:     } else {
14864:         $typeselectform =  '<select name="type" size="1"';
14865:         if ($onchange) {
14866:             $typeselectform .= ' onchange="'.$onchange.'"';
14867:         }
14868:         $typeselectform .= '>'."\n";
14869:         foreach my $posstype ('Course','Community') {
14870:             $typeselectform.='<option value="'.$posstype.'"'.
14871:                 ($posstype eq $crstype ? ' selected="selected" ' : ''). ">".&mt($posstype)."</option>\n";
14872:         }
14873:         $typeselectform.="</select>";
14874:     }
14875: 
14876:     my ($cloneableonlyform,$cloneabletitle);
14877:     if (exists($filter->{'cloneableonly'})) {
14878:         my $cloneableon = '';
14879:         my $cloneableoff = ' checked="checked"';
14880:         if ($filter->{'cloneableonly'}) {
14881:             $cloneableon = $cloneableoff;
14882:             $cloneableoff = '';
14883:         }
14884:         $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>';
14885:         if ($formname eq 'ccrs') {
14886:             $cloneabletitle = &mt('Cloneable for [_1]',$cloneruname.':'.$clonerudom);
14887:         } else {
14888:             $cloneabletitle = &mt('Cloneable by you');
14889:         }
14890:     }
14891:     my $officialjs;
14892:     if ($crstype eq 'Course') {
14893:         if (exists($filter->{'instcodefilter'})) {
14894: #            if (($fixeddom) || ($formname eq 'requestcrs') ||
14895: #                ($formname eq 'modifycourse') || ($formname eq 'filterpicker')) {
14896:             if ($codedom) { 
14897:                 $officialjs = 1;
14898:                 ($instcodeform,$jscript,$$numtitlesref) =
14899:                     &Apache::courseclassifier::instcode_selectors($codedom,'filterpicker',
14900:                                                                   $officialjs,$codetitlesref);
14901:                 if ($jscript) {
14902:                     $jscript = '<script type="text/javascript">'."\n".
14903:                                '// <![CDATA['."\n".
14904:                                $jscript."\n".
14905:                                '// ]]>'."\n".
14906:                                '</script>'."\n";
14907:                 }
14908:             }
14909:             if ($instcodeform eq '') {
14910:                 $instcodeform =
14911:                     '<input type="text" name="instcodefilter" size="10" value="'.
14912:                     $list->{'instcodefilter'}.'" />';
14913:                 $instcodetitle = $lt{'ins'};
14914:             } else {
14915:                 $instcodetitle = $lt{'inc'};
14916:             }
14917:             if ($fixeddom) {
14918:                 $instcodetitle .= '<br />('.$codedom.')';
14919:             }
14920:         }
14921:     }
14922:     my $output = qq|
14923: <form method="post" name="filterpicker" action="$action">
14924: <input type="hidden" name="form" value="$formname" />
14925: |;
14926:     if ($formname eq 'modifycourse') {
14927:         $output .= '<input type="hidden" name="phase" value="courselist" />'."\n".
14928:                    '<input type="hidden" name="prevphase" value="'.
14929:                    $prevphase.'" />'."\n";
14930:     } elsif ($formname ne 'quotacheck') {
14931:         my $name_input;
14932:         if ($cnameelement ne '') {
14933:             $name_input = '<input type="hidden" name="cnameelement" value="'.
14934:                           $cnameelement.'" />';
14935:         }
14936:         $output .= qq|
14937: <input type="hidden" name="cnumelement" value="$cnumelement" />
14938: <input type="hidden" name="cdomelement" value="$cdomelement" />
14939: $name_input
14940: $roleelement
14941: $multelement
14942: $typeelement
14943: |;
14944:         if ($formname eq 'portform') {
14945:             $output .= '<input type="hidden" name="setroles" value="'.$setroles.'" />'."\n";
14946:         }
14947:     }
14948:     if ($fixeddom) {
14949:         $output .= '<input type="hidden" name="fixeddom" value="'.$fixeddom.'" />'."\n";
14950:     }
14951:     $output .= "<br />\n".&Apache::lonhtmlcommon::start_pick_box();
14952:     if ($sincefilterform) {
14953:         $output .= &Apache::lonhtmlcommon::row_title($lt{'cac'})
14954:                   .$sincefilterform
14955:                   .&Apache::lonhtmlcommon::row_closure();
14956:     }
14957:     if ($createdfilterform) {
14958:         $output .= &Apache::lonhtmlcommon::row_title($lt{'ccr'})
14959:                   .$createdfilterform
14960:                   .&Apache::lonhtmlcommon::row_closure();
14961:     }
14962:     if ($domainselectform) {
14963:         $output .= &Apache::lonhtmlcommon::row_title($lt{'cdo'})
14964:                   .$domainselectform
14965:                   .&Apache::lonhtmlcommon::row_closure();
14966:     }
14967:     if ($typeselectform) {
14968:         if (($formname eq 'ccrs') || ($formname eq 'requestcrs')) {
14969:             $output .= $typeselectform;
14970:         } else {
14971:             $output .= &Apache::lonhtmlcommon::row_title($lt{'cog'})
14972:                       .$typeselectform
14973:                       .&Apache::lonhtmlcommon::row_closure();
14974:         }
14975:     }
14976:     if ($instcodeform) {
14977:         $output .= &Apache::lonhtmlcommon::row_title($instcodetitle)
14978:                   .$instcodeform
14979:                   .&Apache::lonhtmlcommon::row_closure();
14980:     }
14981:     if (exists($filter->{'ownerfilter'})) {
14982:         $output .= &Apache::lonhtmlcommon::row_title($lt{'cow'}).
14983:                    '<table><tr><td>'.&mt('Username').'<br />'.
14984:                    '<input type="text" name="ownerfilter" size="20" value="'.
14985:                    $list->{'ownerfilter'}.'" /></td><td>'.&mt('Domain').'<br />'.
14986:                    $ownerdomselectform.'</td></tr></table>'.
14987:                    &Apache::lonhtmlcommon::row_closure();
14988:     }
14989:     if (exists($filter->{'personfilter'})) {
14990:         $output .= &Apache::lonhtmlcommon::row_title($lt{'cop'}).
14991:                    '<table><tr><td>'.&mt('Username').'<br />'.
14992:                    '<input type="text" name="personfilter" size="20" value="'.
14993:                    $list->{'personfilter'}.'" /></td><td>'.&mt('Domain').'<br />'.
14994:                    $persondomselectform.'</td></tr></table>'.
14995:                    &Apache::lonhtmlcommon::row_closure();
14996:     }
14997:     if (exists($filter->{'coursefilter'})) {
14998:         $output .= &Apache::lonhtmlcommon::row_title(&mt('LON-CAPA course ID'))
14999:                   .'<input type="text" name="coursefilter" size="25" value="'
15000:                   .$list->{'coursefilter'}.'" />'
15001:                   .&Apache::lonhtmlcommon::row_closure();
15002:     }
15003:     if ($cloneableonlyform) {
15004:         $output .= &Apache::lonhtmlcommon::row_title($cloneabletitle).
15005:                    $cloneableonlyform.&Apache::lonhtmlcommon::row_closure();
15006:     }
15007:     if (exists($filter->{'descriptfilter'})) {
15008:         $output .= &Apache::lonhtmlcommon::row_title($lt{'cde'})
15009:                   .'<input type="text" name="descriptfilter" size="40" value="'
15010:                   .$list->{'descriptfilter'}.'" />'
15011:                   .&Apache::lonhtmlcommon::row_closure(1);
15012:     }
15013:     $output .= &Apache::lonhtmlcommon::end_pick_box().'<p>'.$clonetext."\n".
15014:                '<input type="hidden" name="updater" value="" />'."\n".
15015:                '<input type="submit" name="gosearch" value="'.
15016:                &mt('Search').'" /></p>'."\n".'</form>'."\n".'<hr />'."\n";
15017:     return $jscript.$clonewarning.$output;
15018: }
15019: 
15020: =pod 
15021: 
15022: =item * &timebased_select_form()
15023: 
15024: Create markup for a dropdown list used to select a time-based
15025: filter e.g., Course Activity, Course Created, when searching for courses
15026: or communities
15027: 
15028: Inputs:
15029: 
15030: item - name of form element (sincefilter or createdfilter)
15031: 
15032: filter - anonymous hash of criteria and their values
15033: 
15034: Returns: HTML for a select box contained a blank, then six time selections,
15035:          with value set in incoming form variables currently selected. 
15036: 
15037: Side Effects: None
15038: 
15039: =cut
15040: 
15041: sub timebased_select_form {
15042:     my ($item,$filter) = @_;
15043:     if (ref($filter) eq 'HASH') {
15044:         $filter->{$item} =~ s/[^\d-]//g;
15045:         if (!$filter->{$item}) { $filter->{$item}=-1; }
15046:         return &select_form(
15047:                             $filter->{$item},
15048:                             $item,
15049:                             {      '-1' => '',
15050:                                 '86400' => &mt('today'),
15051:                                '604800' => &mt('last week'),
15052:                               '2592000' => &mt('last month'),
15053:                               '7776000' => &mt('last three months'),
15054:                              '15552000' => &mt('last six months'),
15055:                              '31104000' => &mt('last year'),
15056:                     'select_form_order' =>
15057:                            ['-1','86400','604800','2592000','7776000',
15058:                             '15552000','31104000']});
15059:     }
15060: }
15061: 
15062: =pod
15063: 
15064: =item * &js_changer()
15065: 
15066: Create script tag containing Javascript used to submit course search form
15067: when course type or domain is changed, and also to hide 'Searching ...' on
15068: page load completion for page showing search result.
15069: 
15070: Inputs: None
15071: 
15072: Returns: markup containing updateFilters() and hideSearching() javascript functions. 
15073: 
15074: Side Effects: None
15075: 
15076: =cut
15077: 
15078: sub js_changer {
15079:     return <<ENDJS;
15080: <script type="text/javascript">
15081: // <![CDATA[
15082: function updateFilters(caller) {
15083:     if (typeof(caller) != "undefined") {
15084:         document.filterpicker.updater.value = caller.name;
15085:     }
15086:     document.filterpicker.submit();
15087: }
15088: 
15089: function hideSearching() {
15090:     if (document.getElementById('searching')) {
15091:         document.getElementById('searching').style.display = 'none';
15092:     }
15093:     return;
15094: }
15095: 
15096: // ]]>
15097: </script>
15098: 
15099: ENDJS
15100: }
15101: 
15102: =pod
15103: 
15104: =item * &search_courses()
15105: 
15106: Process selected filters form course search form and pass to lonnet::courseiddump
15107: to retrieve a hash for which keys are courseIDs which match the selected filters.
15108: 
15109: Inputs:
15110: 
15111: dom - domain being searched 
15112: 
15113: type - course type ('Course' or 'Community' or '.' if any).
15114: 
15115: filter - anonymous hash of criteria and their values
15116: 
15117: numtitles - for institutional codes - number of categories
15118: 
15119: cloneruname - optional username of new course owner
15120: 
15121: clonerudom - optional domain of new course owner
15122: 
15123: domcloner - Optional "domcloner" flag; has value=1 if user has ccc priv in domain being filtered by, 
15124:             (used when DC is using course creation form)
15125: 
15126: codetitles - reference to array of titles of components in institutional codes (official courses).
15127: 
15128: 
15129: Returns: %courses - hash of courses satisfying search criteria, keys = course IDs, values are corresponding colon-separated escaped description, institutional code, owner and type.
15130: 
15131: 
15132: Side Effects: None
15133: 
15134: =cut
15135: 
15136: 
15137: sub search_courses {
15138:     my ($dom,$type,$filter,$numtitles,$cloneruname,$clonerudom,$domcloner,$codetitles) = @_;
15139:     my (%courses,%showcourses,$cloner);
15140:     if (($filter->{'ownerfilter'} ne '') ||
15141:         ($filter->{'ownerdomfilter'} ne '')) {
15142:         $filter->{'combownerfilter'} = $filter->{'ownerfilter'}.':'.
15143:                                        $filter->{'ownerdomfilter'};
15144:     }
15145:     foreach my $item ('descriptfilter','coursefilter','combownerfilter') {
15146:         if (!$filter->{$item}) {
15147:             $filter->{$item}='.';
15148:         }
15149:     }
15150:     my $now = time;
15151:     my $timefilter =
15152:        ($filter->{'sincefilter'}==-1?1:$now-$filter->{'sincefilter'});
15153:     my ($createdbefore,$createdafter);
15154:     if (($filter->{'createdfilter'} ne '') && ($filter->{'createdfilter'} !=-1)) {
15155:         $createdbefore = $now;
15156:         $createdafter = $now-$filter->{'createdfilter'};
15157:     }
15158:     my ($instcodefilter,$regexpok);
15159:     if ($numtitles) {
15160:         if ($env{'form.official'} eq 'on') {
15161:             $instcodefilter =
15162:                 &Apache::courseclassifier::instcode_search_str($dom,$numtitles,$codetitles);
15163:             $regexpok = 1;
15164:         } elsif ($env{'form.official'} eq 'off') {
15165:             $instcodefilter = &Apache::courseclassifier::instcode_search_str($dom,$numtitles,$codetitles);
15166:             unless ($instcodefilter eq '') {
15167:                 $regexpok = -1;
15168:             }
15169:         }
15170:     } else {
15171:         $instcodefilter = $filter->{'instcodefilter'};
15172:     }
15173:     if ($instcodefilter eq '') { $instcodefilter = '.'; }
15174:     if ($type eq '') { $type = '.'; }
15175: 
15176:     if (($clonerudom ne '') && ($cloneruname ne '')) {
15177:         $cloner = $cloneruname.':'.$clonerudom;
15178:     }
15179:     %courses = &Apache::lonnet::courseiddump($dom,
15180:                                              $filter->{'descriptfilter'},
15181:                                              $timefilter,
15182:                                              $instcodefilter,
15183:                                              $filter->{'combownerfilter'},
15184:                                              $filter->{'coursefilter'},
15185:                                              undef,undef,$type,$regexpok,undef,undef,
15186:                                              undef,undef,$cloner,$env{'form.cc_clone'},
15187:                                              $filter->{'cloneableonly'},
15188:                                              $createdbefore,$createdafter,undef,
15189:                                              $domcloner);
15190:     if (($filter->{'personfilter'} ne '') && ($filter->{'persondomfilter'} ne '')) {
15191:         my $ccrole;
15192:         if ($type eq 'Community') {
15193:             $ccrole = 'co';
15194:         } else {
15195:             $ccrole = 'cc';
15196:         }
15197:         my %rolehash = &Apache::lonnet::get_my_roles($filter->{'personfilter'},
15198:                                                      $filter->{'persondomfilter'},
15199:                                                      'userroles',undef,
15200:                                                      [$ccrole,'in','ad','ep','ta','cr'],
15201:                                                      $dom);
15202:         foreach my $role (keys(%rolehash)) {
15203:             my ($cnum,$cdom,$courserole) = split(':',$role);
15204:             my $cid = $cdom.'_'.$cnum;
15205:             if (exists($courses{$cid})) {
15206:                 if (ref($courses{$cid}) eq 'HASH') {
15207:                     if (ref($courses{$cid}{roles}) eq 'ARRAY') {
15208:                         if (!grep(/^\Q$courserole\E$/,@{$courses{$cid}{roles}})) {
15209:                             push (@{$courses{$cid}{roles}},$courserole);
15210:                         }
15211:                     } else {
15212:                         $courses{$cid}{roles} = [$courserole];
15213:                     }
15214:                     $showcourses{$cid} = $courses{$cid};
15215:                 }
15216:             }
15217:         }
15218:         %courses = %showcourses;
15219:     }
15220:     return %courses;
15221: }
15222: 
15223: 
15224: =pod
15225: 
15226: =back
15227: 
15228: =cut
15229: 
15230: 
15231: sub build_release_hashes {
15232:     my ($checkparms,$checkresponsetypes,$checkcrstypes,$anonsurvey,$randomizetry) = @_;
15233:     return unless((ref($checkparms) eq 'HASH') && (ref($checkresponsetypes) eq 'HASH') &&
15234:                   (ref($checkcrstypes) eq 'HASH') && (ref($anonsurvey) eq 'HASH') &&
15235:                   (ref($randomizetry) eq 'HASH'));
15236:     foreach my $key (keys(%Apache::lonnet::needsrelease)) {
15237:         my ($item,$name,$value) = split(/:/,$key);
15238:         if ($item eq 'parameter') {
15239:             if (ref($checkparms->{$name}) eq 'ARRAY') {
15240:                 unless(grep(/^\Q$name\E$/,@{$checkparms->{$name}})) {
15241:                     push(@{$checkparms->{$name}},$value);
15242:                 }
15243:             } else {
15244:                 push(@{$checkparms->{$name}},$value);
15245:             }
15246:         } elsif ($item eq 'resourcetag') {
15247:             if ($name eq 'responsetype') {
15248:                 $checkresponsetypes->{$value} = $Apache::lonnet::needsrelease{$key}
15249:             }
15250:         } elsif ($item eq 'course') {
15251:             if ($name eq 'crstype') {
15252:                 $checkcrstypes->{$value} = $Apache::lonnet::needsrelease{$key};
15253:             }
15254:         }
15255:     }
15256:     ($anonsurvey->{major},$anonsurvey->{minor}) = split(/\./,$Apache::lonnet::needsrelease{'parameter:type:anonsurvey'});
15257:     ($randomizetry->{major},$randomizetry->{minor}) = split(/\./,$Apache::lonnet::needsrelease{'parameter:type:randomizetry'});
15258:     return;
15259: }
15260: 
15261: sub update_content_constraints {
15262:     my ($cdom,$cnum,$chome,$cid) = @_;
15263:     my %curr_reqd_hash = &Apache::lonnet::userenvironment($cdom,$cnum,'internal.releaserequired');
15264:     my ($reqdmajor,$reqdminor) = split(/\./,$curr_reqd_hash{'internal.releaserequired'});
15265:     my %checkresponsetypes;
15266:     foreach my $key (keys(%Apache::lonnet::needsrelease)) {
15267:         my ($item,$name,$value) = split(/:/,$key);
15268:         if ($item eq 'resourcetag') {
15269:             if ($name eq 'responsetype') {
15270:                 $checkresponsetypes{$value} = $Apache::lonnet::needsrelease{$key}
15271:             }
15272:         }
15273:     }
15274:     my $navmap = Apache::lonnavmaps::navmap->new();
15275:     if (defined($navmap)) {
15276:         my %allresponses;
15277:         foreach my $res ($navmap->retrieveResources(undef,sub { $_[0]->is_problem() },1,0)) {
15278:             my %responses = $res->responseTypes();
15279:             foreach my $key (keys(%responses)) {
15280:                 next unless(exists($checkresponsetypes{$key}));
15281:                 $allresponses{$key} += $responses{$key};
15282:             }
15283:         }
15284:         foreach my $key (keys(%allresponses)) {
15285:             my ($major,$minor) = split(/\./,$checkresponsetypes{$key});
15286:             if (($major > $reqdmajor) || ($major == $reqdmajor && $minor > $reqdminor)) {
15287:                 ($reqdmajor,$reqdminor) = ($major,$minor);
15288:             }
15289:         }
15290:         undef($navmap);
15291:     }
15292:     unless (($reqdmajor eq '') && ($reqdminor eq '')) {
15293:         &Apache::lonnet::update_released_required($reqdmajor.'.'.$reqdminor,$cdom,$cnum,$chome,$cid);
15294:     }
15295:     return;
15296: }
15297: 
15298: sub allmaps_incourse {
15299:     my ($cdom,$cnum,$chome,$cid) = @_;
15300:     if ($cdom eq '' || $cnum eq '' || $chome eq '' || $cid eq '') {
15301:         $cid = $env{'request.course.id'};
15302:         $cdom = $env{'course.'.$cid.'.domain'};
15303:         $cnum = $env{'course.'.$cid.'.num'};
15304:         $chome = $env{'course.'.$cid.'.home'};
15305:     }
15306:     my %allmaps = ();
15307:     my $lastchange =
15308:         &Apache::lonnet::get_coursechange($cdom,$cnum);
15309:     if ($lastchange > $env{'request.course.tied'}) {
15310:         my ($furl,$ferr) = &Apache::lonuserstate::readmap("$cdom/$cnum");
15311:         unless ($ferr) {
15312:             &update_content_constraints($cdom,$cnum,$chome,$cid);
15313:         }
15314:     }
15315:     my $navmap = Apache::lonnavmaps::navmap->new();
15316:     if (defined($navmap)) {
15317:         foreach my $res ($navmap->retrieveResources(undef,sub { $_[0]->is_map() },1,0,1)) {
15318:             $allmaps{$res->src()} = 1;
15319:         }
15320:     }
15321:     return \%allmaps;
15322: }
15323: 
15324: sub parse_supplemental_title {
15325:     my ($title) = @_;
15326: 
15327:     my ($foldertitle,$renametitle);
15328:     if ($title =~ /&amp;&amp;&amp;/) {
15329:         $title = &HTML::Entites::decode($title);
15330:     }
15331:     if ($title =~ m/^(\d+)___&&&___($match_username)___&&&___($match_domain)___&&&___(.*)$/) {
15332:         $renametitle=$4;
15333:         my ($time,$uname,$udom) = ($1,$2,$3);
15334:         $foldertitle=&Apache::lontexconvert::msgtexconverted($4);
15335:         my $name =  &plainname($uname,$udom);
15336:         $name = &HTML::Entities::encode($name,'"<>&\'');
15337:         $renametitle = &HTML::Entities::encode($renametitle,'"<>&\'');
15338:         $title='<i>'.&Apache::lonlocal::locallocaltime($time).'</i> '.
15339:             $name.': <br />'.$foldertitle;
15340:     }
15341:     if (wantarray) {
15342:         return ($title,$foldertitle,$renametitle);
15343:     }
15344:     return $title;
15345: }
15346: 
15347: sub recurse_supplemental {
15348:     my ($cnum,$cdom,$suppmap,$numfiles,$errors) = @_;
15349:     if ($suppmap) {
15350:         my ($errtext,$fatal) = &LONCAPA::map::mapread('/uploaded/'.$cdom.'/'.$cnum.'/'.$suppmap);
15351:         if ($fatal) {
15352:             $errors ++;
15353:         } else {
15354:             if ($#LONCAPA::map::resources > 0) {
15355:                 foreach my $res (@LONCAPA::map::resources) {
15356:                     my ($title,$src,$ext,$type,$status)=split(/\:/,$res);
15357:                     if (($src ne '') && ($status eq 'res')) {
15358:                         if ($src =~ m{^\Q/uploaded/$cdom/$cnum/\E(supplemental_\d+\.sequence)$}) {
15359:                             ($numfiles,$errors) = &recurse_supplemental($cnum,$cdom,$1,$numfiles,$errors);
15360:                         } else {
15361:                             $numfiles ++;
15362:                         }
15363:                     }
15364:                 }
15365:             }
15366:         }
15367:     }
15368:     return ($numfiles,$errors);
15369: }
15370: 
15371: sub symb_to_docspath {
15372:     my ($symb) = @_;
15373:     return unless ($symb);
15374:     my ($mapurl,$id,$resurl) = &Apache::lonnet::decode_symb($symb);
15375:     if ($resurl=~/\.(sequence|page)$/) {
15376:         $mapurl=$resurl;
15377:     } elsif ($resurl eq 'adm/navmaps') {
15378:         $mapurl=$env{'course.'.$env{'request.course.id'}.'.url'};
15379:     }
15380:     my $mapresobj;
15381:     my $navmap = Apache::lonnavmaps::navmap->new();
15382:     if (ref($navmap)) {
15383:         $mapresobj = $navmap->getResourceByUrl($mapurl);
15384:     }
15385:     $mapurl=~s{^.*/([^/]+)\.(\w+)$}{$1};
15386:     my $type=$2;
15387:     my $path;
15388:     if (ref($mapresobj)) {
15389:         my $pcslist = $mapresobj->map_hierarchy();
15390:         if ($pcslist ne '') {
15391:             foreach my $pc (split(/,/,$pcslist)) {
15392:                 next if ($pc <= 1);
15393:                 my $res = $navmap->getByMapPc($pc);
15394:                 if (ref($res)) {
15395:                     my $thisurl = $res->src();
15396:                     $thisurl=~s{^.*/([^/]+)\.\w+$}{$1};
15397:                     my $thistitle = $res->title();
15398:                     $path .= '&'.
15399:                              &Apache::lonhtmlcommon::entity_encode($thisurl).'&'.
15400:                              &escape($thistitle).
15401:                              ':'.$res->randompick().
15402:                              ':'.$res->randomout().
15403:                              ':'.$res->encrypted().
15404:                              ':'.$res->randomorder().
15405:                              ':'.$res->is_page();
15406:                 }
15407:             }
15408:         }
15409:         $path =~ s/^\&//;
15410:         my $maptitle = $mapresobj->title();
15411:         if ($mapurl eq 'default') {
15412:             $maptitle = 'Main Content';
15413:         }
15414:         $path .= (($path ne '')? '&' : '').
15415:                  &Apache::lonhtmlcommon::entity_encode($mapurl).'&'.
15416:                  &escape($maptitle).
15417:                  ':'.$mapresobj->randompick().
15418:                  ':'.$mapresobj->randomout().
15419:                  ':'.$mapresobj->encrypted().
15420:                  ':'.$mapresobj->randomorder().
15421:                  ':'.$mapresobj->is_page();
15422:     } else {
15423:         my $maptitle = &Apache::lonnet::gettitle($mapurl);
15424:         my $ispage = (($type eq 'page')? 1 : '');
15425:         if ($mapurl eq 'default') {
15426:             $maptitle = 'Main Content';
15427:         }
15428:         $path = &Apache::lonhtmlcommon::entity_encode($mapurl).'&'.
15429:                 &escape($maptitle).':::::'.$ispage;
15430:     }
15431:     unless ($mapurl eq 'default') {
15432:         $path = 'default&'.
15433:                 &escape('Main Content').
15434:                 ':::::&'.$path;
15435:     }
15436:     return $path;
15437: }
15438: 
15439: sub captcha_display {
15440:     my ($context,$lonhost) = @_;
15441:     my ($output,$error);
15442:     my ($captcha,$pubkey,$privkey) = &get_captcha_config($context,$lonhost);
15443:     if ($captcha eq 'original') {
15444:         $output = &create_captcha();
15445:         unless ($output) {
15446:             $error = 'captcha';
15447:         }
15448:     } elsif ($captcha eq 'recaptcha') {
15449:         $output = &create_recaptcha($pubkey);
15450:         unless ($output) {
15451:             $error = 'recaptcha';
15452:         }
15453:     }
15454:     return ($output,$error,$captcha);
15455: }
15456: 
15457: sub captcha_response {
15458:     my ($context,$lonhost) = @_;
15459:     my ($captcha_chk,$captcha_error);
15460:     my ($captcha,$pubkey,$privkey) = &get_captcha_config($context,$lonhost);
15461:     if ($captcha eq 'original') {
15462:         ($captcha_chk,$captcha_error) = &check_captcha();
15463:     } elsif ($captcha eq 'recaptcha') {
15464:         $captcha_chk = &check_recaptcha($privkey);
15465:     } else {
15466:         $captcha_chk = 1;
15467:     }
15468:     return ($captcha_chk,$captcha_error);
15469: }
15470: 
15471: sub get_captcha_config {
15472:     my ($context,$lonhost) = @_;
15473:     my ($captcha,$pubkey,$privkey,$hashtocheck);
15474:     my $hostname = &Apache::lonnet::hostname($lonhost);
15475:     my $serverhomeID = &Apache::lonnet::get_server_homeID($hostname);
15476:     my $serverhomedom = &Apache::lonnet::host_domain($serverhomeID);
15477:     if ($context eq 'usercreation') {
15478:         my %domconfig = &Apache::lonnet::get_dom('configuration',[$context],$serverhomedom);
15479:         if (ref($domconfig{$context}) eq 'HASH') {
15480:             $hashtocheck = $domconfig{$context}{'cancreate'};
15481:             if (ref($hashtocheck) eq 'HASH') {
15482:                 if ($hashtocheck->{'captcha'} eq 'recaptcha') {
15483:                     if (ref($hashtocheck->{'recaptchakeys'}) eq 'HASH') {
15484:                         $pubkey = $hashtocheck->{'recaptchakeys'}{'public'};
15485:                         $privkey = $hashtocheck->{'recaptchakeys'}{'private'};
15486:                     }
15487:                     if ($privkey && $pubkey) {
15488:                         $captcha = 'recaptcha';
15489:                     } else {
15490:                         $captcha = 'original';
15491:                     }
15492:                 } elsif ($hashtocheck->{'captcha'} ne 'notused') {
15493:                     $captcha = 'original';
15494:                 }
15495:             }
15496:         } else {
15497:             $captcha = 'captcha';
15498:         }
15499:     } elsif ($context eq 'login') {
15500:         my %domconfhash = &Apache::loncommon::get_domainconf($serverhomedom);
15501:         if ($domconfhash{$serverhomedom.'.login.captcha'} eq 'recaptcha') {
15502:             $pubkey = $domconfhash{$serverhomedom.'.login.recaptchakeys_public'};
15503:             $privkey = $domconfhash{$serverhomedom.'.login.recaptchakeys_private'};
15504:             if ($privkey && $pubkey) {
15505:                 $captcha = 'recaptcha';
15506:             } else {
15507:                 $captcha = 'original';
15508:             }
15509:         } elsif ($domconfhash{$serverhomedom.'.login.captcha'} eq 'original') {
15510:             $captcha = 'original';
15511:         }
15512:     }
15513:     return ($captcha,$pubkey,$privkey);
15514: }
15515: 
15516: sub create_captcha {
15517:     my %captcha_params = &captcha_settings();
15518:     my ($output,$maxtries,$tries) = ('',10,0);
15519:     while ($tries < $maxtries) {
15520:         $tries ++;
15521:         my $captcha = Authen::Captcha->new (
15522:                                            output_folder => $captcha_params{'output_dir'},
15523:                                            data_folder   => $captcha_params{'db_dir'},
15524:                                           );
15525:         my $md5sum = $captcha->generate_code($captcha_params{'numchars'});
15526: 
15527:         if (-e $Apache::lonnet::perlvar{'lonCaptchaDir'}.'/'.$md5sum.'.png') {
15528:             $output = '<input type="hidden" name="crypt" value="'.$md5sum.'" />'."\n".
15529:                       &mt('Type in the letters/numbers shown below').'&nbsp;'.
15530:                       '<input type="text" size="5" name="code" value="" autocomplete="off" />'.
15531:                       '<br />'.
15532:                       '<img src="'.$captcha_params{'www_output_dir'}.'/'.$md5sum.'.png" alt="captcha" />';
15533:             last;
15534:         }
15535:     }
15536:     return $output;
15537: }
15538: 
15539: sub captcha_settings {
15540:     my %captcha_params = (
15541:                            output_dir     => $Apache::lonnet::perlvar{'lonCaptchaDir'},
15542:                            www_output_dir => "/captchaspool",
15543:                            db_dir         => $Apache::lonnet::perlvar{'lonCaptchaDb'},
15544:                            numchars       => '5',
15545:                          );
15546:     return %captcha_params;
15547: }
15548: 
15549: sub check_captcha {
15550:     my ($captcha_chk,$captcha_error);
15551:     my $code = $env{'form.code'};
15552:     my $md5sum = $env{'form.crypt'};
15553:     my %captcha_params = &captcha_settings();
15554:     my $captcha = Authen::Captcha->new(
15555:                       output_folder => $captcha_params{'output_dir'},
15556:                       data_folder   => $captcha_params{'db_dir'},
15557:                   );
15558:     $captcha_chk = $captcha->check_code($code,$md5sum);
15559:     my %captcha_hash = (
15560:                         0       => 'Code not checked (file error)',
15561:                        -1      => 'Failed: code expired',
15562:                        -2      => 'Failed: invalid code (not in database)',
15563:                        -3      => 'Failed: invalid code (code does not match crypt)',
15564:     );
15565:     if ($captcha_chk != 1) {
15566:         $captcha_error = $captcha_hash{$captcha_chk}
15567:     }
15568:     return ($captcha_chk,$captcha_error);
15569: }
15570: 
15571: sub create_recaptcha {
15572:     my ($pubkey) = @_;
15573:     my $use_ssl;
15574:     if ($ENV{'SERVER_PORT'} == 443) {
15575:         $use_ssl = 1;
15576:     }
15577:     my $captcha = Captcha::reCAPTCHA->new;
15578:     return $captcha->get_options_setter({theme => 'white'})."\n".
15579:            $captcha->get_html($pubkey,undef,$use_ssl).
15580:            &mt('If either word is hard to read, [_1] will replace them.',
15581:                '<img src="/res/adm/pages/refresh.gif" alt="reCAPTCHA refresh" />').
15582:            '<br /><br />';
15583: }
15584: 
15585: sub check_recaptcha {
15586:     my ($privkey) = @_;
15587:     my $captcha_chk;
15588:     my $captcha = Captcha::reCAPTCHA->new;
15589:     my $captcha_result =
15590:         $captcha->check_answer(
15591:                                 $privkey,
15592:                                 $ENV{'REMOTE_ADDR'},
15593:                                 $env{'form.recaptcha_challenge_field'},
15594:                                 $env{'form.recaptcha_response_field'},
15595:                               );
15596:     if ($captcha_result->{is_valid}) {
15597:         $captcha_chk = 1;
15598:     }
15599:     return $captcha_chk;
15600: }
15601: 
15602: sub emailusername_info {
15603:     my @fields = ('firstname','lastname','institution','web','location','officialemail');
15604:     my %titles = &Apache::lonlocal::texthash (
15605:                      lastname      => 'Last Name',
15606:                      firstname     => 'First Name',
15607:                      institution   => 'School/college/university',
15608:                      location      => "School's city, state/province, country",
15609:                      web           => "School's web address",
15610:                      officialemail => 'E-mail address at institution (if different)',
15611:                  );
15612:     return (\@fields,\%titles);
15613: }
15614: 
15615: sub cleanup_html {
15616:     my ($incoming) = @_;
15617:     my $outgoing;
15618:     if ($incoming ne '') {
15619:         $outgoing = $incoming;
15620:         $outgoing =~ s/;/&#059;/g;
15621:         $outgoing =~ s/\#/&#035;/g;
15622:         $outgoing =~ s/\&/&#038;/g;
15623:         $outgoing =~ s/</&#060;/g;
15624:         $outgoing =~ s/>/&#062;/g;
15625:         $outgoing =~ s/\(/&#040/g;
15626:         $outgoing =~ s/\)/&#041;/g;
15627:         $outgoing =~ s/"/&#034;/g;
15628:         $outgoing =~ s/'/&#039;/g;
15629:         $outgoing =~ s/\$/&#036;/g;
15630:         $outgoing =~ s{/}{&#047;}g;
15631:         $outgoing =~ s/=/&#061;/g;
15632:         $outgoing =~ s/\\/&#092;/g
15633:     }
15634:     return $outgoing;
15635: }
15636: 
15637: # Checks for critical messages and returns a redirect url if one exists.
15638: # $interval indicates how often to check for messages.
15639: sub critical_redirect {
15640:     my ($interval) = @_;
15641:     if ((time-$env{'user.criticalcheck.time'})>$interval) {
15642:         my @what=&Apache::lonnet::dump('critical', $env{'user.domain'}, 
15643:                                         $env{'user.name'});
15644:         &Apache::lonnet::appenv({'user.criticalcheck.time'=>time});
15645:         my ($redirecturl,$redirectsymb);
15646:         if ($what[0]) {
15647: 	    if (($what[0] ne 'con_lost') && ($what[0]!~/^error\:/)) {
15648: 	        $redirecturl='/adm/email?critical=display';
15649:             }
15650: 	    my $url=&Apache::lonnet::absolute_url().$redirecturl;
15651:             return (1, $url);
15652:         } 
15653:     } else { return 0; }
15654: }
15655: 
15656: # Use:
15657: #   my $answer=reply("encrypt:passwd:$udom:$uname:$upass",$tryserver);
15658: #
15659: ##################################################
15660: #          password associated functions         #
15661: ##################################################
15662: sub des_keys {
15663:     # Make a new key for DES encryption.
15664:     # Each key has two parts which are returned separately.
15665:     # Please note:  Each key must be passed through the &hex function
15666:     # before it is output to the web browser.  The hex versions cannot
15667:     # be used to decrypt.
15668:     my @hexstr=('0','1','2','3','4','5','6','7',
15669:                 '8','9','a','b','c','d','e','f');
15670:     my $lkey='';
15671:     for (0..7) {
15672:         $lkey.=$hexstr[rand(15)];
15673:     }
15674:     my $ukey='';
15675:     for (0..7) {
15676:         $ukey.=$hexstr[rand(15)];
15677:     }
15678:     return ($lkey,$ukey);
15679: }
15680: 
15681: sub des_decrypt {
15682:     my ($key,$cyphertext) = @_;
15683:     my $keybin=pack("H16",$key);
15684:     my $cypher;
15685:     if ($Crypt::DES::VERSION>=2.03) {
15686:         $cypher=new Crypt::DES $keybin;
15687:     } else {
15688:         $cypher=new DES $keybin;
15689:     }
15690:     my $plaintext=
15691:         $cypher->decrypt(unpack("a8",pack("H16",substr($cyphertext,0,16))));
15692:     $plaintext.=
15693:         $cypher->decrypt(unpack("a8",pack("H16",substr($cyphertext,16,16))));
15694:     $plaintext=substr($plaintext,1,ord(substr($plaintext,0,1)) );
15695:     return $plaintext;
15696: }
15697: 
15698: 1;
15699: __END__;
15700: 

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