File:  [LON-CAPA] / loncom / interface / loncommon.pm
Revision 1.1110: download - view: text, annotated - select for diffs
Wed Jan 9 03:56:27 2013 UTC (11 years, 4 months ago) by raeburn
Branches: MAIN
CVS tags: HEAD
- &get_allmaps() moved form groupsort.pm to loncommon.pm and renamed as
  &allmaps_incourse() to facilitate reuse.

    1: # The LearningOnline Network with CAPA
    2: # a pile of common routines
    3: #
    4: # $Id: loncommon.pm,v 1.1110 2013/01/09 03:56:27 raeburn Exp $
    5: #
    6: # Copyright Michigan State University Board of Trustees
    7: #
    8: # This file is part of the LearningOnline Network with CAPA (LON-CAPA).
    9: #
   10: # LON-CAPA is free software; you can redistribute it and/or modify
   11: # it under the terms of the GNU General Public License as published by
   12: # the Free Software Foundation; either version 2 of the License, or
   13: # (at your option) any later version.
   14: #
   15: # LON-CAPA is distributed in the hope that it will be useful,
   16: # but WITHOUT ANY WARRANTY; without even the implied warranty of
   17: # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   18: # GNU General Public License for more details.
   19: #
   20: # You should have received a copy of the GNU General Public License
   21: # along with LON-CAPA; if not, write to the Free Software
   22: # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
   23: #
   24: # /home/httpd/html/adm/gpl.txt
   25: #
   26: # http://www.lon-capa.org/
   27: #
   28: 
   29: # Makes a table out of the previous attempts
   30: # Inputs result_from_symbread, user, domain, course_id
   31: # Reads in non-network-related .tab files
   32: 
   33: # POD header:
   34: 
   35: =pod
   36: 
   37: =head1 NAME
   38: 
   39: Apache::loncommon - pile of common routines
   40: 
   41: =head1 SYNOPSIS
   42: 
   43: Common routines for manipulating connections, student answers,
   44:     domains, common Javascript fragments, etc.
   45: 
   46: =head1 OVERVIEW
   47: 
   48: A collection of commonly used subroutines that don't have a natural
   49: home anywhere else. This collection helps remove
   50: redundancy from other modules and increase efficiency of memory usage.
   51: 
   52: =cut 
   53: 
   54: # End of POD header
   55: package Apache::loncommon;
   56: 
   57: use strict;
   58: use Apache::lonnet;
   59: use GDBM_File;
   60: use POSIX qw(strftime mktime);
   61: use Apache::lonmenu();
   62: use Apache::lonenc();
   63: use Apache::lonlocal;
   64: use Apache::lonnet();
   65: use HTML::Entities;
   66: use Apache::lonhtmlcommon();
   67: use Apache::loncoursedata();
   68: use Apache::lontexconvert();
   69: use Apache::lonclonecourse();
   70: use Apache::lonuserutils();
   71: use Apache::lonuserstate();
   72: use LONCAPA qw(:DEFAULT :match);
   73: use DateTime::TimeZone;
   74: use DateTime::Locale::Catalog;
   75: use Text::Aspell;
   76: use Authen::Captcha;
   77: use Captcha::reCAPTCHA;
   78: 
   79: # ---------------------------------------------- Designs
   80: use vars qw(%defaultdesign);
   81: 
   82: my $readit;
   83: 
   84: 
   85: ##
   86: ## Global Variables
   87: ##
   88: 
   89: 
   90: # ----------------------------------------------- SSI with retries:
   91: #
   92: 
   93: =pod
   94: 
   95: =head1 Server Side include with retries:
   96: 
   97: =over 4
   98: 
   99: =item * &ssi_with_retries(resource,retries form)
  100: 
  101: Performs an ssi with some number of retries.  Retries continue either
  102: until the result is ok or until the retry count supplied by the
  103: caller is exhausted.  
  104: 
  105: Inputs:
  106: 
  107: =over 4
  108: 
  109: resource   - Identifies the resource to insert.
  110: 
  111: retries    - Count of the number of retries allowed.
  112: 
  113: form       - Hash that identifies the rendering options.
  114: 
  115: =back
  116: 
  117: Returns:
  118: 
  119: =over 4
  120: 
  121: content    - The content of the response.  If retries were exhausted this is empty.
  122: 
  123: response   - The response from the last attempt (which may or may not have been successful.
  124: 
  125: =back
  126: 
  127: =back
  128: 
  129: =cut
  130: 
  131: sub ssi_with_retries {
  132:     my ($resource, $retries, %form) = @_;
  133: 
  134: 
  135:     my $ok = 0;			# True if we got a good response.
  136:     my $content;
  137:     my $response;
  138: 
  139:     # Try to get the ssi done. within the retries count:
  140: 
  141:     do {
  142: 	($content, $response) = &Apache::lonnet::ssi($resource, %form);
  143: 	$ok      = $response->is_success;
  144:         if (!$ok) {
  145:             &Apache::lonnet::logthis("Failed ssi_with_retries on $resource: ".$response->is_success.', '.$response->code.', '.$response->message);
  146:         }
  147: 	$retries--;
  148:     } while (!$ok && ($retries > 0));
  149: 
  150:     if (!$ok) {
  151: 	$content = '';		# On error return an empty content.
  152:     }
  153:     return ($content, $response);
  154: 
  155: }
  156: 
  157: 
  158: 
  159: # ----------------------------------------------- Filetypes/Languages/Copyright
  160: my %language;
  161: my %supported_language;
  162: my %supported_codes;
  163: my %latex_language;		# For choosing hyphenation in <transl..>
  164: my %latex_language_bykey;	# for choosing hyphenation from metadata
  165: my %cprtag;
  166: my %scprtag;
  167: my %fe; my %fd; my %fm;
  168: my %category_extensions;
  169: 
  170: # ---------------------------------------------- Thesaurus variables
  171: #
  172: # %Keywords:
  173: #      A hash used by &keyword to determine if a word is considered a keyword.
  174: # $thesaurus_db_file 
  175: #      Scalar containing the full path to the thesaurus database.
  176: 
  177: my %Keywords;
  178: my $thesaurus_db_file;
  179: 
  180: #
  181: # Initialize values from language.tab, copyright.tab, filetypes.tab,
  182: # thesaurus.tab, and filecategories.tab.
  183: #
  184: BEGIN {
  185:     # Variable initialization
  186:     $thesaurus_db_file = $Apache::lonnet::perlvar{'lonTabDir'}."/thesaurus.db";
  187:     #
  188:     unless ($readit) {
  189: # ------------------------------------------------------------------- languages
  190:     {
  191:         my $langtabfile = $Apache::lonnet::perlvar{'lonTabDir'}.
  192:                                    '/language.tab';
  193:         if ( open(my $fh,"<$langtabfile") ) {
  194:             while (my $line = <$fh>) {
  195:                 next if ($line=~/^\#/);
  196:                 chomp($line);
  197:                 my ($key,$code,$country,$three,$enc,$val,$sup,$latex)=(split(/\t/,$line));
  198:                 $language{$key}=$val.' - '.$enc;
  199:                 if ($sup) {
  200:                     $supported_language{$key}=$sup;
  201: 		    $supported_codes{$key}   = $code;
  202:                 }
  203: 		if ($latex) {
  204: 		    $latex_language_bykey{$key} = $latex;
  205: 		    $latex_language{$code} = $latex;
  206: 		}
  207:             }
  208:             close($fh);
  209:         }
  210:     }
  211: # ------------------------------------------------------------------ copyrights
  212:     {
  213:         my $copyrightfile = $Apache::lonnet::perlvar{'lonIncludes'}.
  214:                                   '/copyright.tab';
  215:         if ( open (my $fh,"<$copyrightfile") ) {
  216:             while (my $line = <$fh>) {
  217:                 next if ($line=~/^\#/);
  218:                 chomp($line);
  219:                 my ($key,$val)=(split(/\s+/,$line,2));
  220:                 $cprtag{$key}=$val;
  221:             }
  222:             close($fh);
  223:         }
  224:     }
  225: # ----------------------------------------------------------- source copyrights
  226:     {
  227:         my $sourcecopyrightfile = $Apache::lonnet::perlvar{'lonIncludes'}.
  228:                                   '/source_copyright.tab';
  229:         if ( open (my $fh,"<$sourcecopyrightfile") ) {
  230:             while (my $line = <$fh>) {
  231:                 next if ($line =~ /^\#/);
  232:                 chomp($line);
  233:                 my ($key,$val)=(split(/\s+/,$line,2));
  234:                 $scprtag{$key}=$val;
  235:             }
  236:             close($fh);
  237:         }
  238:     }
  239: 
  240: # -------------------------------------------------------------- default domain designs
  241:     my $designdir=$Apache::lonnet::perlvar{'lonTabDir'}.'/lonDomColors';
  242:     my $designfile = $designdir.'/default.tab';
  243:     if ( open (my $fh,"<$designfile") ) {
  244:         while (my $line = <$fh>) {
  245:             next if ($line =~ /^\#/);
  246:             chomp($line);
  247:             my ($key,$val)=(split(/\=/,$line));
  248:             if ($val) { $defaultdesign{$key}=$val; }
  249:         }
  250:         close($fh);
  251:     }
  252: 
  253: # ------------------------------------------------------------- file categories
  254:     {
  255:         my $categoryfile = $Apache::lonnet::perlvar{'lonTabDir'}.
  256:                                   '/filecategories.tab';
  257:         if ( open (my $fh,"<$categoryfile") ) {
  258: 	    while (my $line = <$fh>) {
  259: 		next if ($line =~ /^\#/);
  260: 		chomp($line);
  261:                 my ($extension,$category)=(split(/\s+/,$line,2));
  262:                 push @{$category_extensions{lc($category)}},$extension;
  263:             }
  264:             close($fh);
  265:         }
  266: 
  267:     }
  268: # ------------------------------------------------------------------ file types
  269:     {
  270:         my $typesfile = $Apache::lonnet::perlvar{'lonTabDir'}.
  271:                '/filetypes.tab';
  272:         if ( open (my $fh,"<$typesfile") ) {
  273:             while (my $line = <$fh>) {
  274: 		next if ($line =~ /^\#/);
  275: 		chomp($line);
  276:                 my ($ending,$emb,$mime,$descr)=split(/\s+/,$line,4);
  277:                 if ($descr ne '') {
  278:                     $fe{$ending}=lc($emb);
  279:                     $fd{$ending}=$descr;
  280:                     if ($mime ne 'unk') { $fm{$ending}=$mime; }
  281:                 }
  282:             }
  283:             close($fh);
  284:         }
  285:     }
  286:     &Apache::lonnet::logthis(
  287:              "<span style='color:yellow;'>INFO: Read file types</span>");
  288:     $readit=1;
  289:     }  # end of unless($readit) 
  290:     
  291: }
  292: 
  293: ###############################################################
  294: ##           HTML and Javascript Helper Functions            ##
  295: ###############################################################
  296: 
  297: =pod 
  298: 
  299: =head1 HTML and Javascript Functions
  300: 
  301: =over 4
  302: 
  303: =item * &browser_and_searcher_javascript()
  304: 
  305: X<browsing, javascript>X<searching, javascript>Returns a string
  306: containing javascript with two functions, C<openbrowser> and
  307: C<opensearcher>. Returned string does not contain E<lt>scriptE<gt>
  308: tags.
  309: 
  310: =item * &openbrowser(formname,elementname,only,omit) [javascript]
  311: 
  312: inputs: formname, elementname, only, omit
  313: 
  314: formname and elementname indicate the name of the html form and name of
  315: the element that the results of the browsing selection are to be placed in. 
  316: 
  317: Specifying 'only' will restrict the browser to displaying only files
  318: with the given extension.  Can be a comma separated list.
  319: 
  320: Specifying 'omit' will restrict the browser to NOT displaying files
  321: with the given extension.  Can be a comma separated list.
  322: 
  323: =item * &opensearcher(formname,elementname) [javascript]
  324: 
  325: Inputs: formname, elementname
  326: 
  327: formname and elementname specify the name of the html form and the name
  328: of the element the selection from the search results will be placed in.
  329: 
  330: =cut
  331: 
  332: sub browser_and_searcher_javascript {
  333:     my ($mode)=@_;
  334:     if (!defined($mode)) { $mode='edit'; }
  335:     my $resurl=&escape_single(&lastresurl());
  336:     return <<END;
  337: // <!-- BEGIN LON-CAPA Internal
  338:     var editbrowser = null;
  339:     function openbrowser(formname,elementname,only,omit,titleelement) {
  340:         var url = '$resurl/?';
  341:         if (editbrowser == null) {
  342:             url += 'launch=1&';
  343:         }
  344:         url += 'catalogmode=interactive&';
  345:         url += 'mode=$mode&';
  346:         url += 'inhibitmenu=yes&';
  347:         url += 'form=' + formname + '&';
  348:         if (only != null) {
  349:             url += 'only=' + only + '&';
  350:         } else {
  351:             url += 'only=&';
  352: 	}
  353:         if (omit != null) {
  354:             url += 'omit=' + omit + '&';
  355:         } else {
  356:             url += 'omit=&';
  357: 	}
  358:         if (titleelement != null) {
  359:             url += 'titleelement=' + titleelement + '&';
  360:         } else {
  361: 	    url += 'titleelement=&';
  362: 	}
  363:         url += 'element=' + elementname + '';
  364:         var title = 'Browser';
  365:         var options = 'scrollbars=1,resizable=1,menubar=0,toolbar=1,location=1';
  366:         options += ',width=700,height=600';
  367:         editbrowser = open(url,title,options,'1');
  368:         editbrowser.focus();
  369:     }
  370:     var editsearcher;
  371:     function opensearcher(formname,elementname,titleelement) {
  372:         var url = '/adm/searchcat?';
  373:         if (editsearcher == null) {
  374:             url += 'launch=1&';
  375:         }
  376:         url += 'catalogmode=interactive&';
  377:         url += 'mode=$mode&';
  378:         url += 'form=' + formname + '&';
  379:         if (titleelement != null) {
  380:             url += 'titleelement=' + titleelement + '&';
  381:         } else {
  382: 	    url += 'titleelement=&';
  383: 	}
  384:         url += 'element=' + elementname + '';
  385:         var title = 'Search';
  386:         var options = 'scrollbars=1,resizable=1,menubar=0,toolbar=1,location=1';
  387:         options += ',width=700,height=600';
  388:         editsearcher = open(url,title,options,'1');
  389:         editsearcher.focus();
  390:     }
  391: // END LON-CAPA Internal -->
  392: END
  393: }
  394: 
  395: sub lastresurl {
  396:     if ($env{'environment.lastresurl'}) {
  397: 	return $env{'environment.lastresurl'}
  398:     } else {
  399: 	return '/res';
  400:     }
  401: }
  402: 
  403: sub storeresurl {
  404:     my $resurl=&Apache::lonnet::clutter(shift);
  405:     unless ($resurl=~/^\/res/) { return 0; }
  406:     $resurl=~s/\/$//;
  407:     &Apache::lonnet::put('environment',{'lastresurl' => $resurl});
  408:     &Apache::lonnet::appenv({'environment.lastresurl' => $resurl});
  409:     return 1;
  410: }
  411: 
  412: sub studentbrowser_javascript {
  413:    unless (
  414:             (($env{'request.course.id'}) && 
  415:              (&Apache::lonnet::allowed('srm',$env{'request.course.id'})
  416: 	      || &Apache::lonnet::allowed('srm',$env{'request.course.id'}.
  417: 					  '/'.$env{'request.course.sec'})
  418: 	      ))
  419:          || ($env{'request.role'}=~/^(au|dc|su)/)
  420:           ) { return ''; }  
  421:    return (<<'ENDSTDBRW');
  422: <script type="text/javascript" language="Javascript">
  423: // <![CDATA[
  424:     var stdeditbrowser;
  425:     function openstdbrowser(formname,uname,udom,clicker,roleflag,ignorefilter,courseadvonly) {
  426:         var url = '/adm/pickstudent?';
  427:         var filter;
  428: 	if (!ignorefilter) {
  429: 	    eval('filter=document.'+formname+'.'+uname+'.value;');
  430: 	}
  431:         if (filter != null) {
  432:            if (filter != '') {
  433:                url += 'filter='+filter+'&';
  434: 	   }
  435:         }
  436:         url += 'form=' + formname + '&unameelement='+uname+
  437:                                     '&udomelement='+udom+
  438:                                     '&clicker='+clicker;
  439: 	if (roleflag) { url+="&roles=1"; }
  440:         if (courseadvonly) { url+="&courseadvonly=1"; }
  441:         var title = 'Student_Browser';
  442:         var options = 'scrollbars=1,resizable=1,menubar=0';
  443:         options += ',width=700,height=600';
  444:         stdeditbrowser = open(url,title,options,'1');
  445:         stdeditbrowser.focus();
  446:     }
  447: // ]]>
  448: </script>
  449: ENDSTDBRW
  450: }
  451: 
  452: sub resourcebrowser_javascript {
  453:    unless ($env{'request.course.id'}) { return ''; }
  454:    return (<<'ENDRESBRW');
  455: <script type="text/javascript" language="Javascript">
  456: // <![CDATA[
  457:     var reseditbrowser;
  458:     function openresbrowser(formname,reslink) {
  459:         var url = '/adm/pickresource?form='+formname+'&reslink='+reslink;
  460:         var title = 'Resource_Browser';
  461:         var options = 'scrollbars=1,resizable=1,menubar=0';
  462:         options += ',width=700,height=500';
  463:         reseditbrowser = open(url,title,options,'1');
  464:         reseditbrowser.focus();
  465:     }
  466: // ]]>
  467: </script>
  468: ENDRESBRW
  469: }
  470: 
  471: sub selectstudent_link {
  472:    my ($form,$unameele,$udomele,$courseadvonly,$clickerid)=@_;
  473:    my $callargs = "'".&Apache::lonhtmlcommon::entity_encode($form)."','".
  474:                       &Apache::lonhtmlcommon::entity_encode($unameele)."','".
  475:                       &Apache::lonhtmlcommon::entity_encode($udomele)."'";
  476:    if ($env{'request.course.id'}) {  
  477:        if (!&Apache::lonnet::allowed('srm',$env{'request.course.id'})
  478: 	   && !&Apache::lonnet::allowed('srm',$env{'request.course.id'}.
  479: 					'/'.$env{'request.course.sec'})) {
  480: 	   return '';
  481:        }
  482:        $callargs.=",'".&Apache::lonhtmlcommon::entity_encode($clickerid)."'";
  483:        if ($courseadvonly)  {
  484:            $callargs .= ",'',1,1";
  485:        }
  486:        return '<span class="LC_nobreak">'.
  487:               '<a href="javascript:openstdbrowser('.$callargs.');">'.
  488:               &mt('Select User').'</a></span>';
  489:    }
  490:    if ($env{'request.role'}=~/^(au|dc|su)/) {
  491:        $callargs .= ",'',1"; 
  492:        return '<span class="LC_nobreak">'.
  493:               '<a href="javascript:openstdbrowser('.$callargs.');">'.
  494:               &mt('Select User').'</a></span>';
  495:    }
  496:    return '';
  497: }
  498: 
  499: sub selectresource_link {
  500:    my ($form,$reslink,$arg)=@_;
  501:    
  502:    my $callargs = "'".&Apache::lonhtmlcommon::entity_encode($form)."','".
  503:                       &Apache::lonhtmlcommon::entity_encode($reslink)."'";
  504:    unless ($env{'request.course.id'}) { return $arg; }
  505:    return '<span class="LC_nobreak">'.
  506:               '<a href="javascript:openresbrowser('.$callargs.');">'.
  507:               $arg.'</a></span>';
  508: }
  509: 
  510: 
  511: 
  512: sub authorbrowser_javascript {
  513:     return <<"ENDAUTHORBRW";
  514: <script type="text/javascript" language="JavaScript">
  515: // <![CDATA[
  516: var stdeditbrowser;
  517: 
  518: function openauthorbrowser(formname,udom) {
  519:     var url = '/adm/pickauthor?';
  520:     url += 'form='+formname+'&roledom='+udom;
  521:     var title = 'Author_Browser';
  522:     var options = 'scrollbars=1,resizable=1,menubar=0';
  523:     options += ',width=700,height=600';
  524:     stdeditbrowser = open(url,title,options,'1');
  525:     stdeditbrowser.focus();
  526: }
  527: 
  528: // ]]>
  529: </script>
  530: ENDAUTHORBRW
  531: }
  532: 
  533: sub coursebrowser_javascript {
  534:     my ($domainfilter,$sec_element,$formname,$role_element,$crstype) = @_;
  535:     my $wintitle = 'Course_Browser';
  536:     if ($crstype eq 'Community') {
  537:         $wintitle = 'Community_Browser';
  538:     }
  539:     my $id_functions = &javascript_index_functions();
  540:     my $output = '
  541: <script type="text/javascript" language="JavaScript">
  542: // <![CDATA[
  543:     var stdeditbrowser;'."\n";
  544: 
  545:     $output .= <<"ENDSTDBRW";
  546:     function opencrsbrowser(formname,uname,udom,desc,extra_element,multflag,type,type_elem) {
  547:         var url = '/adm/pickcourse?';
  548:         var formid = getFormIdByName(formname);
  549:         var domainfilter = getDomainFromSelectbox(formname,udom);
  550:         if (domainfilter != null) {
  551:            if (domainfilter != '') {
  552:                url += 'domainfilter='+domainfilter+'&';
  553: 	   }
  554:         }
  555:         url += 'form=' + formname + '&cnumelement='+uname+
  556: 	                            '&cdomelement='+udom+
  557:                                     '&cnameelement='+desc;
  558:         if (extra_element !=null && extra_element != '') {
  559:             if (formname == 'rolechoice' || formname == 'studentform') {
  560:                 url += '&roleelement='+extra_element;
  561:                 if (domainfilter == null || domainfilter == '') {
  562:                     url += '&domainfilter='+extra_element;
  563:                 }
  564:             }
  565:             else {
  566:                 if (formname == 'portform') {
  567:                     url += '&setroles='+extra_element;
  568:                 } else {
  569:                     if (formname == 'rules') {
  570:                         url += '&fixeddom='+extra_element; 
  571:                     }
  572:                 }
  573:             }     
  574:         }
  575:         if (type != null && type != '') {
  576:             url += '&type='+type;
  577:         }
  578:         if (type_elem != null && type_elem != '') {
  579:             url += '&typeelement='+type_elem;
  580:         }
  581:         if (formname == 'ccrs') {
  582:             var ownername = document.forms[formid].ccuname.value;
  583:             var ownerdom =  document.forms[formid].ccdomain.options[document.forms[formid].ccdomain.selectedIndex].value;
  584:             url += '&cloner='+ownername+':'+ownerdom;
  585:         }
  586:         if (multflag !=null && multflag != '') {
  587:             url += '&multiple='+multflag;
  588:         }
  589:         var title = '$wintitle';
  590:         var options = 'scrollbars=1,resizable=1,menubar=0';
  591:         options += ',width=700,height=600';
  592:         stdeditbrowser = open(url,title,options,'1');
  593:         stdeditbrowser.focus();
  594:     }
  595: $id_functions
  596: ENDSTDBRW
  597:     if (($sec_element ne '') || ($role_element ne '')) {
  598:         $output .= &setsec_javascript($sec_element,$formname,$role_element);
  599:     }
  600:     $output .= '
  601: // ]]>
  602: </script>';
  603:     return $output;
  604: }
  605: 
  606: sub javascript_index_functions {
  607:     return <<"ENDJS";
  608: 
  609: function getFormIdByName(formname) {
  610:     for (var i=0;i<document.forms.length;i++) {
  611:         if (document.forms[i].name == formname) {
  612:             return i;
  613:         }
  614:     }
  615:     return -1;
  616: }
  617: 
  618: function getIndexByName(formid,item) {
  619:     for (var i=0;i<document.forms[formid].elements.length;i++) {
  620:         if (document.forms[formid].elements[i].name == item) {
  621:             return i;
  622:         }
  623:     }
  624:     return -1;
  625: }
  626: 
  627: function getDomainFromSelectbox(formname,udom) {
  628:     var userdom;
  629:     var formid = getFormIdByName(formname);
  630:     if (formid > -1) {
  631:         var domid = getIndexByName(formid,udom);
  632:         if (domid > -1) {
  633:             if (document.forms[formid].elements[domid].type == 'select-one') {
  634:                 userdom=document.forms[formid].elements[domid].options[document.forms[formid].elements[domid].selectedIndex].value;
  635:             }
  636:             if (document.forms[formid].elements[domid].type == 'hidden') {
  637:                 userdom=document.forms[formid].elements[domid].value;
  638:             }
  639:         }
  640:     }
  641:     return userdom;
  642: }
  643: 
  644: ENDJS
  645: 
  646: }
  647: 
  648: sub javascript_array_indexof {
  649:     return <<ENDJS;
  650: <script type="text/javascript" language="JavaScript">
  651: // <![CDATA[
  652: 
  653: if (!Array.prototype.indexOf) {
  654:     Array.prototype.indexOf = function (searchElement /*, fromIndex */ ) {
  655:         "use strict";
  656:         if (this === void 0 || this === null) {
  657:             throw new TypeError();
  658:         }
  659:         var t = Object(this);
  660:         var len = t.length >>> 0;
  661:         if (len === 0) {
  662:             return -1;
  663:         }
  664:         var n = 0;
  665:         if (arguments.length > 0) {
  666:             n = Number(arguments[1]);
  667:             if (n !== n) { // shortcut for verifying if it is NaN
  668:                 n = 0;
  669:             } else if (n !== 0 && n !== (1 / 0) && n !== -(1 / 0)) {
  670:                 n = (n > 0 || -1) * Math.floor(Math.abs(n));
  671:             }
  672:         }
  673:         if (n >= len) {
  674:             return -1;
  675:         }
  676:         var k = n >= 0 ? n : Math.max(len - Math.abs(n), 0);
  677:         for (; k < len; k++) {
  678:             if (k in t && t[k] === searchElement) {
  679:                 return k;
  680:             }
  681:         }
  682:         return -1;
  683:     }
  684: }
  685: 
  686: // ]]>
  687: </script>
  688: 
  689: ENDJS
  690: 
  691: }
  692: 
  693: sub userbrowser_javascript {
  694:     my $id_functions = &javascript_index_functions();
  695:     return <<"ENDUSERBRW";
  696: 
  697: function openuserbrowser(formname,uname,udom,ulast,ufirst,uemail,hideudom,crsdom,caller) {
  698:     var url = '/adm/pickuser?';
  699:     var userdom = getDomainFromSelectbox(formname,udom);
  700:     if (userdom != null) {
  701:        if (userdom != '') {
  702:            url += 'srchdom='+userdom+'&';
  703:        }
  704:     }
  705:     url += 'form=' + formname + '&unameelement='+uname+
  706:                                 '&udomelement='+udom+
  707:                                 '&ulastelement='+ulast+
  708:                                 '&ufirstelement='+ufirst+
  709:                                 '&uemailelement='+uemail+
  710:                                 '&hideudomelement='+hideudom+
  711:                                 '&coursedom='+crsdom;
  712:     if ((caller != null) && (caller != undefined)) {
  713:         url += '&caller='+caller;
  714:     }
  715:     var title = 'User_Browser';
  716:     var options = 'scrollbars=1,resizable=1,menubar=0';
  717:     options += ',width=700,height=600';
  718:     var stdeditbrowser = open(url,title,options,'1');
  719:     stdeditbrowser.focus();
  720: }
  721: 
  722: function fix_domain (formname,udom,origdom,uname) {
  723:     var formid = getFormIdByName(formname);
  724:     if (formid > -1) {
  725:         var unameid = getIndexByName(formid,uname);
  726:         var domid = getIndexByName(formid,udom);
  727:         var hidedomid = getIndexByName(formid,origdom);
  728:         if (hidedomid > -1) {
  729:             var fixeddom = document.forms[formid].elements[hidedomid].value;
  730:             var unameval = document.forms[formid].elements[unameid].value;
  731:             if ((fixeddom != '') && (fixeddom != undefined) && (fixeddom != null) && (unameval != '') && (unameval != undefined) && (unameval != null)) {
  732:                 if (domid > -1) {
  733:                     var slct = document.forms[formid].elements[domid];
  734:                     if (slct.type == 'select-one') {
  735:                         var i;
  736:                         for (i=0;i<slct.length;i++) {
  737:                             if (slct.options[i].value==fixeddom) { slct.selectedIndex=i; }
  738:                         }
  739:                     }
  740:                     if (slct.type == 'hidden') {
  741:                         slct.value = fixeddom;
  742:                     }
  743:                 }
  744:             }
  745:         }
  746:     }
  747:     return;
  748: }
  749: 
  750: $id_functions
  751: ENDUSERBRW
  752: }
  753: 
  754: sub setsec_javascript {
  755:     my ($sec_element,$formname,$role_element) = @_;
  756:     my (@courserolenames,@communityrolenames,$rolestr,$courserolestr,
  757:         $communityrolestr);
  758:     if ($role_element ne '') {
  759:         my @allroles = ('st','ta','ep','in','ad');
  760:         foreach my $crstype ('Course','Community') {
  761:             if ($crstype eq 'Community') {
  762:                 foreach my $role (@allroles) {
  763:                     push(@communityrolenames,&Apache::lonnet::plaintext($role,$crstype));
  764:                 }
  765:                 push(@communityrolenames,&Apache::lonnet::plaintext('co'));
  766:             } else {
  767:                 foreach my $role (@allroles) {
  768:                     push(@courserolenames,&Apache::lonnet::plaintext($role,$crstype));
  769:                 }
  770:                 push(@courserolenames,&Apache::lonnet::plaintext('cc'));
  771:             }
  772:         }
  773:         $rolestr = '"'.join('","',@allroles).'"';
  774:         $courserolestr = '"'.join('","',@courserolenames).'"';
  775:         $communityrolestr = '"'.join('","',@communityrolenames).'"';
  776:     }
  777:     my $setsections = qq|
  778: function setSect(sectionlist) {
  779:     var sectionsArray = new Array();
  780:     if ((sectionlist != '') && (typeof sectionlist != "undefined")) {
  781:         sectionsArray = sectionlist.split(",");
  782:     }
  783:     var numSections = sectionsArray.length;
  784:     document.$formname.$sec_element.length = 0;
  785:     if (numSections == 0) {
  786:         document.$formname.$sec_element.multiple=false;
  787:         document.$formname.$sec_element.size=1;
  788:         document.$formname.$sec_element.options[0] = new Option('No existing sections','',false,false)
  789:     } else {
  790:         if (numSections == 1) {
  791:             document.$formname.$sec_element.multiple=false;
  792:             document.$formname.$sec_element.size=1;
  793:             document.$formname.$sec_element.options[0] = new Option('Select','',true,true);
  794:             document.$formname.$sec_element.options[1] = new Option('No section','',false,false)
  795:             document.$formname.$sec_element.options[2] = new Option(sectionsArray[0],sectionsArray[0],false,false);
  796:         } else {
  797:             for (var i=0; i<numSections; i++) {
  798:                 document.$formname.$sec_element.options[i] = new Option(sectionsArray[i],sectionsArray[i],false,false)
  799:             }
  800:             document.$formname.$sec_element.multiple=true
  801:             if (numSections < 3) {
  802:                 document.$formname.$sec_element.size=numSections;
  803:             } else {
  804:                 document.$formname.$sec_element.size=3;
  805:             }
  806:             document.$formname.$sec_element.options[0].selected = false
  807:         }
  808:     }
  809: }
  810: 
  811: function setRole(crstype) {
  812: |;
  813:     if ($role_element eq '') {
  814:         $setsections .= '    return;
  815: }
  816: ';
  817:     } else {
  818:         $setsections .= qq|
  819:     var elementLength = document.$formname.$role_element.length;
  820:     var allroles = Array($rolestr);
  821:     var courserolenames = Array($courserolestr);
  822:     var communityrolenames = Array($communityrolestr);
  823:     if (elementLength != undefined) {
  824:         if (document.$formname.$role_element.options[5].value == 'cc') {
  825:             if (crstype == 'Course') {
  826:                 return;
  827:             } else {
  828:                 allroles[5] = 'co';
  829:                 for (var i=0; i<6; i++) {
  830:                     document.$formname.$role_element.options[i].value = allroles[i];
  831:                     document.$formname.$role_element.options[i].text = communityrolenames[i];
  832:                 }
  833:             }
  834:         } else {
  835:             if (crstype == 'Community') {
  836:                 return;
  837:             } else {
  838:                 allroles[5] = 'cc';
  839:                 for (var i=0; i<6; i++) {
  840:                     document.$formname.$role_element.options[i].value = allroles[i];
  841:                     document.$formname.$role_element.options[i].text = courserolenames[i];
  842:                 }
  843:             }
  844:         }
  845:     }
  846:     return;
  847: }
  848: |;
  849:     }
  850:     return $setsections;
  851: }
  852: 
  853: sub selectcourse_link {
  854:    my ($form,$unameele,$udomele,$desc,$extra_element,$multflag,$selecttype,
  855:        $typeelement) = @_;
  856:    my $type = $selecttype;
  857:    my $linktext = &mt('Select Course');
  858:    if ($selecttype eq 'Community') {
  859:        $linktext = &mt('Select Community');
  860:    } elsif ($selecttype eq 'Course/Community') {
  861:        $linktext = &mt('Select Course/Community');
  862:        $type = '';
  863:    } elsif ($selecttype eq 'Select') {
  864:        $linktext = &mt('Select');
  865:        $type = '';
  866:    }
  867:    return '<span class="LC_nobreak">'
  868:          ."<a href='"
  869:          .'javascript:opencrsbrowser("'.$form.'","'.$unameele
  870:          .'","'.$udomele.'","'.$desc.'","'.$extra_element
  871:          .'","'.$multflag.'","'.$type.'","'.$typeelement.'");'
  872:          ."'>".$linktext.'</a>'
  873:          .'</span>';
  874: }
  875: 
  876: sub selectauthor_link {
  877:    my ($form,$udom)=@_;
  878:    return '<a href="javascript:openauthorbrowser('."'$form','$udom'".');">'.
  879:           &mt('Select Author').'</a>';
  880: }
  881: 
  882: sub selectuser_link {
  883:     my ($form,$unameelem,$domelem,$lastelem,$firstelem,$emailelem,$hdomelem,
  884:         $coursedom,$linktext,$caller) = @_;
  885:     return '<a href="javascript:openuserbrowser('."'$form','$unameelem','$domelem',".
  886:            "'$lastelem','$firstelem','$emailelem','$hdomelem','$coursedom','$caller'".
  887:            ');">'.$linktext.'</a>';
  888: }
  889: 
  890: sub check_uncheck_jscript {
  891:     my $jscript = <<"ENDSCRT";
  892: function checkAll(field) {
  893:     if (field.length > 0) {
  894:         for (i = 0; i < field.length; i++) {
  895:             if (!field[i].disabled) { 
  896:                 field[i].checked = true;
  897:             }
  898:         }
  899:     } else {
  900:         if (!field.disabled) { 
  901:             field.checked = true;
  902:         }
  903:     }
  904: }
  905:  
  906: function uncheckAll(field) {
  907:     if (field.length > 0) {
  908:         for (i = 0; i < field.length; i++) {
  909:             field[i].checked = false ;
  910:         }
  911:     } else {
  912:         field.checked = false ;
  913:     }
  914: }
  915: ENDSCRT
  916:     return $jscript;
  917: }
  918: 
  919: sub select_timezone {
  920:    my ($name,$selected,$onchange,$includeempty)=@_;
  921:    my $output='<select name="'.$name.'" '.$onchange.'>'."\n";
  922:    if ($includeempty) {
  923:        $output .= '<option value=""';
  924:        if (($selected eq '') || ($selected eq 'local')) {
  925:            $output .= ' selected="selected" ';
  926:        }
  927:        $output .= '> </option>';
  928:    }
  929:    my @timezones = DateTime::TimeZone->all_names;
  930:    foreach my $tzone (@timezones) {
  931:        $output.= '<option value="'.$tzone.'"';
  932:        if ($tzone eq $selected) {
  933:            $output.=' selected="selected"';
  934:        }
  935:        $output.=">$tzone</option>\n";
  936:    }
  937:    $output.="</select>";
  938:    return $output;
  939: }
  940: 
  941: sub select_datelocale {
  942:     my ($name,$selected,$onchange,$includeempty)=@_;
  943:     my $output='<select name="'.$name.'" '.$onchange.'>'."\n";
  944:     if ($includeempty) {
  945:         $output .= '<option value=""';
  946:         if ($selected eq '') {
  947:             $output .= ' selected="selected" ';
  948:         }
  949:         $output .= '> </option>';
  950:     }
  951:     my (@possibles,%locale_names);
  952:     my @locales = DateTime::Locale::Catalog::Locales;
  953:     foreach my $locale (@locales) {
  954:         if (ref($locale) eq 'HASH') {
  955:             my $id = $locale->{'id'};
  956:             if ($id ne '') {
  957:                 my $en_terr = $locale->{'en_territory'};
  958:                 my $native_terr = $locale->{'native_territory'};
  959:                 my @languages = &Apache::lonlocal::preferred_languages();
  960:                 if (grep(/^en$/,@languages) || !@languages) {
  961:                     if ($en_terr ne '') {
  962:                         $locale_names{$id} = '('.$en_terr.')';
  963:                     } elsif ($native_terr ne '') {
  964:                         $locale_names{$id} = $native_terr;
  965:                     }
  966:                 } else {
  967:                     if ($native_terr ne '') {
  968:                         $locale_names{$id} = $native_terr.' ';
  969:                     } elsif ($en_terr ne '') {
  970:                         $locale_names{$id} = '('.$en_terr.')';
  971:                     }
  972:                 }
  973:                 push (@possibles,$id);
  974:             }
  975:         }
  976:     }
  977:     foreach my $item (sort(@possibles)) {
  978:         $output.= '<option value="'.$item.'"';
  979:         if ($item eq $selected) {
  980:             $output.=' selected="selected"';
  981:         }
  982:         $output.=">$item";
  983:         if ($locale_names{$item} ne '') {
  984:             $output.="  $locale_names{$item}</option>\n";
  985:         }
  986:         $output.="</option>\n";
  987:     }
  988:     $output.="</select>";
  989:     return $output;
  990: }
  991: 
  992: sub select_language {
  993:     my ($name,$selected,$includeempty) = @_;
  994:     my %langchoices;
  995:     if ($includeempty) {
  996:         %langchoices = ('' => 'No language preference');
  997:     }
  998:     foreach my $id (&languageids()) {
  999:         my $code = &supportedlanguagecode($id);
 1000:         if ($code) {
 1001:             $langchoices{$code} = &plainlanguagedescription($id);
 1002:         }
 1003:     }
 1004:     return &select_form($selected,$name,\%langchoices);
 1005: }
 1006: 
 1007: =pod
 1008: 
 1009: 
 1010: =item * &list_languages()
 1011: 
 1012: Returns an array reference that is suitable for use in language prompters.
 1013: Each array element is itself a two element array.  The first element
 1014: is the language code.  The second element a descsriptiuon of the 
 1015: language itself.  This is suitable for use in e.g.
 1016: &Apache::edit::select_arg (once dereferenced that is).
 1017: 
 1018: =cut 
 1019: 
 1020: sub list_languages {
 1021:     my @lang_choices;
 1022: 
 1023:     foreach my $id (&languageids()) {
 1024: 	my $code = &supportedlanguagecode($id);
 1025: 	if ($code) {
 1026: 	    my $selector    = $supported_codes{$id};
 1027: 	    my $description = &plainlanguagedescription($id);
 1028: 	    push (@lang_choices, [$selector, $description]);
 1029: 	}
 1030:     }
 1031:     return \@lang_choices;
 1032: }
 1033: 
 1034: =pod
 1035: 
 1036: =item * &linked_select_forms(...)
 1037: 
 1038: linked_select_forms returns a string containing a <script></script> block
 1039: and html for two <select> menus.  The select menus will be linked in that
 1040: changing the value of the first menu will result in new values being placed
 1041: in the second menu.  The values in the select menu will appear in alphabetical
 1042: order unless a defined order is provided.
 1043: 
 1044: linked_select_forms takes the following ordered inputs:
 1045: 
 1046: =over 4
 1047: 
 1048: =item * $formname, the name of the <form> tag
 1049: 
 1050: =item * $middletext, the text which appears between the <select> tags
 1051: 
 1052: =item * $firstdefault, the default value for the first menu
 1053: 
 1054: =item * $firstselectname, the name of the first <select> tag
 1055: 
 1056: =item * $secondselectname, the name of the second <select> tag
 1057: 
 1058: =item * $hashref, a reference to a hash containing the data for the menus.
 1059: 
 1060: =item * $menuorder, the order of values in the first menu
 1061: 
 1062: =back 
 1063: 
 1064: Below is an example of such a hash.  Only the 'text', 'default', and 
 1065: 'select2' keys must appear as stated.  keys(%menu) are the possible 
 1066: values for the first select menu.  The text that coincides with the 
 1067: first menu value is given in $menu{$choice1}->{'text'}.  The values 
 1068: and text for the second menu are given in the hash pointed to by 
 1069: $menu{$choice1}->{'select2'}.  
 1070: 
 1071:  my %menu = ( A1 => { text =>"Choice A1" ,
 1072:                        default => "B3",
 1073:                        select2 => { 
 1074:                            B1 => "Choice B1",
 1075:                            B2 => "Choice B2",
 1076:                            B3 => "Choice B3",
 1077:                            B4 => "Choice B4"
 1078:                            },
 1079:                        order => ['B4','B3','B1','B2'],
 1080:                    },
 1081:                A2 => { text =>"Choice A2" ,
 1082:                        default => "C2",
 1083:                        select2 => { 
 1084:                            C1 => "Choice C1",
 1085:                            C2 => "Choice C2",
 1086:                            C3 => "Choice C3"
 1087:                            },
 1088:                        order => ['C2','C1','C3'],
 1089:                    },
 1090:                A3 => { text =>"Choice A3" ,
 1091:                        default => "D6",
 1092:                        select2 => { 
 1093:                            D1 => "Choice D1",
 1094:                            D2 => "Choice D2",
 1095:                            D3 => "Choice D3",
 1096:                            D4 => "Choice D4",
 1097:                            D5 => "Choice D5",
 1098:                            D6 => "Choice D6",
 1099:                            D7 => "Choice D7"
 1100:                            },
 1101:                        order => ['D4','D3','D2','D1','D7','D6','D5'],
 1102:                    }
 1103:                );
 1104: 
 1105: =cut
 1106: 
 1107: sub linked_select_forms {
 1108:     my ($formname,
 1109:         $middletext,
 1110:         $firstdefault,
 1111:         $firstselectname,
 1112:         $secondselectname, 
 1113:         $hashref,
 1114:         $menuorder,
 1115:         ) = @_;
 1116:     my $second = "document.$formname.$secondselectname";
 1117:     my $first = "document.$formname.$firstselectname";
 1118:     # output the javascript to do the changing
 1119:     my $result = '';
 1120:     $result.='<script type="text/javascript" language="JavaScript">'."\n";
 1121:     $result.="// <![CDATA[\n";
 1122:     $result.="var select2data = new Object();\n";
 1123:     $" = '","';
 1124:     my $debug = '';
 1125:     foreach my $s1 (sort(keys(%$hashref))) {
 1126:         $result.="select2data.d_$s1 = new Object();\n";        
 1127:         $result.="select2data.d_$s1.def = new String('".
 1128:             $hashref->{$s1}->{'default'}."');\n";
 1129:         $result.="select2data.d_$s1.values = new Array(";
 1130:         my @s2values = sort(keys( %{ $hashref->{$s1}->{'select2'} } ));
 1131:         if (ref($hashref->{$s1}->{'order'}) eq 'ARRAY') {
 1132:             @s2values = @{$hashref->{$s1}->{'order'}};
 1133:         }
 1134:         $result.="\"@s2values\");\n";
 1135:         $result.="select2data.d_$s1.texts = new Array(";        
 1136:         my @s2texts;
 1137:         foreach my $value (@s2values) {
 1138:             push @s2texts, $hashref->{$s1}->{'select2'}->{$value};
 1139:         }
 1140:         $result.="\"@s2texts\");\n";
 1141:     }
 1142:     $"=' ';
 1143:     $result.= <<"END";
 1144: 
 1145: function select1_changed() {
 1146:     // Determine new choice
 1147:     var newvalue = "d_" + $first.value;
 1148:     // update select2
 1149:     var values     = select2data[newvalue].values;
 1150:     var texts      = select2data[newvalue].texts;
 1151:     var select2def = select2data[newvalue].def;
 1152:     var i;
 1153:     // out with the old
 1154:     for (i = 0; i < $second.options.length; i++) {
 1155:         $second.options[i] = null;
 1156:     }
 1157:     // in with the nuclear
 1158:     for (i=0;i<values.length; i++) {
 1159:         $second.options[i] = new Option(values[i]);
 1160:         $second.options[i].value = values[i];
 1161:         $second.options[i].text = texts[i];
 1162:         if (values[i] == select2def) {
 1163:             $second.options[i].selected = true;
 1164:         }
 1165:     }
 1166: }
 1167: // ]]>
 1168: </script>
 1169: END
 1170:     # output the initial values for the selection lists
 1171:     $result .= "<select size=\"1\" name=\"$firstselectname\" onchange=\"select1_changed()\">\n";
 1172:     my @order = sort(keys(%{$hashref}));
 1173:     if (ref($menuorder) eq 'ARRAY') {
 1174:         @order = @{$menuorder};
 1175:     }
 1176:     foreach my $value (@order) {
 1177:         $result.="    <option value=\"$value\" ";
 1178:         $result.=" selected=\"selected\" " if ($value eq $firstdefault);
 1179:         $result.=">".&mt($hashref->{$value}->{'text'})."</option>\n";
 1180:     }
 1181:     $result .= "</select>\n";
 1182:     my %select2 = %{$hashref->{$firstdefault}->{'select2'}};
 1183:     $result .= $middletext;
 1184:     $result .= "<select size=\"1\" name=\"$secondselectname\">\n";
 1185:     my $seconddefault = $hashref->{$firstdefault}->{'default'};
 1186:     
 1187:     my @secondorder = sort(keys(%select2));
 1188:     if (ref($hashref->{$firstdefault}->{'order'}) eq 'ARRAY') {
 1189:         @secondorder = @{$hashref->{$firstdefault}->{'order'}};
 1190:     }
 1191:     foreach my $value (@secondorder) {
 1192:         $result.="    <option value=\"$value\" ";        
 1193:         $result.=" selected=\"selected\" " if ($value eq $seconddefault);
 1194:         $result.=">".&mt($select2{$value})."</option>\n";
 1195:     }
 1196:     $result .= "</select>\n";
 1197:     #    return $debug;
 1198:     return $result;
 1199: }   #  end of sub linked_select_forms {
 1200: 
 1201: =pod
 1202: 
 1203: =item * &help_open_topic($topic,$text,$stayOnPage,$width,$height,$imgid)
 1204: 
 1205: Returns a string corresponding to an HTML link to the given help
 1206: $topic, where $topic corresponds to the name of a .tex file in
 1207: /home/httpd/html/adm/help/tex, with underscores replaced by
 1208: spaces. 
 1209: 
 1210: $text will optionally be linked to the same topic, allowing you to
 1211: link text in addition to the graphic. If you do not want to link
 1212: text, but wish to specify one of the later parameters, pass an
 1213: empty string. 
 1214: 
 1215: $stayOnPage is a value that will be interpreted as a boolean. If true,
 1216: the link will not open a new window. If false, the link will open
 1217: a new window using Javascript. (Default is false.) 
 1218: 
 1219: $width and $height are optional numerical parameters that will
 1220: override the width and height of the popped up window, which may
 1221: be useful for certain help topics with big pictures included.
 1222: 
 1223: $imgid is the id of the img tag used for the help icon. This may be
 1224: used in a javascript call to switch the image src.  See 
 1225: lonhtmlcommon::htmlareaselectactive() for an example.
 1226: 
 1227: =cut
 1228: 
 1229: sub help_open_topic {
 1230:     my ($topic, $text, $stayOnPage, $width, $height, $imgid) = @_;
 1231:     $text = "" if (not defined $text);
 1232:     $stayOnPage = 0 if (not defined $stayOnPage);
 1233:     $width = 500 if (not defined $width);
 1234:     $height = 400 if (not defined $height);
 1235:     my $filename = $topic;
 1236:     $filename =~ s/ /_/g;
 1237: 
 1238:     my $template = "";
 1239:     my $link;
 1240:     
 1241:     $topic=~s/\W/\_/g;
 1242: 
 1243:     if (!$stayOnPage) {
 1244: 	$link = "javascript:openMyModal('/adm/help/${filename}.hlp',$width,$height,'yes');";
 1245:     } elsif ($stayOnPage eq 'popup') {
 1246:         $link = "javascript:void(open('/adm/help/${filename}.hlp', 'Help_for_$topic', 'menubar=0,toolbar=1,scrollbars=1,width=$width,height=$height,resizable=yes'))";
 1247:     } else {
 1248: 	$link = "/adm/help/${filename}.hlp";
 1249:     }
 1250: 
 1251:     # Add the text
 1252:     if ($text ne "") {	
 1253: 	$template.='<span class="LC_help_open_topic">'
 1254:                   .'<a target="_top" href="'.$link.'">'
 1255:                   .$text.'</a>';
 1256:     }
 1257: 
 1258:     # (Always) Add the graphic
 1259:     my $title = &mt('Online Help');
 1260:     my $helpicon=&lonhttpdurl("/adm/help/help.png");
 1261:     if ($imgid ne '') {
 1262:         $imgid = ' id="'.$imgid.'"';
 1263:     }
 1264:     $template.=' <a target="_top" href="'.$link.'" title="'.$title.'">'
 1265:               .'<img src="'.$helpicon.'" border="0"'
 1266:               .' alt="'.&mt('Help: [_1]',$topic).'"'
 1267:               .' title="'.$title.'" style="vertical-align:middle;"'.$imgid 
 1268:               .' /></a>';
 1269:     if ($text ne "") {	
 1270:         $template.='</span>';
 1271:     }
 1272:     return $template;
 1273: 
 1274: }
 1275: 
 1276: # This is a quicky function for Latex cheatsheet editing, since it 
 1277: # appears in at least four places
 1278: sub helpLatexCheatsheet {
 1279:     my ($topic,$text,$not_author,$stayOnPage) = @_;
 1280:     my $out;
 1281:     my $addOther = '';
 1282:     if ($topic) {
 1283: 	$addOther = '<span>'.&help_open_topic($topic,&mt($text),$stayOnPage, undef, 600).'</span> ';
 1284:     }
 1285:     $out = '<span>' # Start cheatsheet
 1286: 	  .$addOther
 1287:           .'<span>'
 1288: 	  .&help_open_topic('Greek_Symbols',&mt('Greek Symbols'),$stayOnPage,undef,600)
 1289: 	  .'</span> <span>'
 1290: 	  .&help_open_topic('Other_Symbols',&mt('Other Symbols'),$stayOnPage,undef,600)
 1291: 	  .'</span>';
 1292:     unless ($not_author) {
 1293:         $out .= ' <span>'
 1294: 	       .&help_open_topic('Authoring_Output_Tags',&mt('Output Tags'),$stayOnPage,undef,600)
 1295: 	       .'</span>';
 1296:     }
 1297:     $out .= '</span>'; # End cheatsheet
 1298:     return $out;
 1299: }
 1300: 
 1301: sub general_help {
 1302:     my $helptopic='Student_Intro';
 1303:     if ($env{'request.role'}=~/^(ca|au)/) {
 1304: 	$helptopic='Authoring_Intro';
 1305:     } elsif ($env{'request.role'}=~/^(cc|co)/) {
 1306: 	$helptopic='Course_Coordination_Intro';
 1307:     } elsif ($env{'request.role'}=~/^dc/) {
 1308:         $helptopic='Domain_Coordination_Intro';
 1309:     }
 1310:     return $helptopic;
 1311: }
 1312: 
 1313: sub update_help_link {
 1314:     my ($topic,$component_help,$faq,$bug,$stayOnPage) = @_;
 1315:     my $origurl = $ENV{'REQUEST_URI'};
 1316:     $origurl=~s|^/~|/priv/|;
 1317:     my $timestamp = time;
 1318:     foreach my $datum (\$topic,\$component_help,\$faq,\$bug,\$origurl) {
 1319:         $$datum = &escape($$datum);
 1320:     }
 1321: 
 1322:     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";
 1323:     my $output .= <<"ENDOUTPUT";
 1324: <script type="text/javascript">
 1325: // <![CDATA[
 1326: banner_link = '$banner_link';
 1327: // ]]>
 1328: </script>
 1329: ENDOUTPUT
 1330:     return $output;
 1331: }
 1332: 
 1333: # now just updates the help link and generates a blue icon
 1334: sub help_open_menu {
 1335:     my ($topic,$component_help,$faq,$bug,$stayOnPage,$width,$height,$text) 
 1336: 	= @_;    
 1337:     $stayOnPage = 1;
 1338:     my $output;
 1339:     if ($component_help) {
 1340: 	if (!$text) {
 1341: 	    $output=&help_open_topic($component_help,undef,$stayOnPage,
 1342: 				       $width,$height);
 1343: 	} else {
 1344: 	    my $help_text;
 1345: 	    $help_text=&unescape($topic);
 1346: 	    $output='<table><tr><td>'.
 1347: 		&help_open_topic($component_help,$help_text,$stayOnPage,
 1348: 				 $width,$height).'</td></tr></table>';
 1349: 	}
 1350:     }
 1351:     my $banner_link = &update_help_link($topic,$component_help,$faq,$bug,$stayOnPage);
 1352:     return $output.$banner_link;
 1353: }
 1354: 
 1355: sub top_nav_help {
 1356:     my ($text) = @_;
 1357:     $text = &mt($text);
 1358:     my $stay_on_page = 1;
 1359: 
 1360:     my $link = ($stay_on_page) ? "javascript:helpMenu('display')"
 1361: 	                     : "javascript:helpMenu('open')";
 1362:     my $banner_link = &update_help_link(undef,undef,undef,undef,$stay_on_page);
 1363: 
 1364:     my $title = &mt('Get help');
 1365: 
 1366:     return <<"END";
 1367: $banner_link
 1368:  <a href="$link" title="$title">$text</a>
 1369: END
 1370: }
 1371: 
 1372: sub help_menu_js {
 1373:     my ($text) = @_;
 1374:     my $stayOnPage = 1;
 1375:     my $width = 620;
 1376:     my $height = 600;
 1377:     my $helptopic=&general_help();
 1378:     my $details_link = '/adm/help/'.$helptopic.'.hlp';
 1379:     my $nothing=&Apache::lonhtmlcommon::javascript_nothing();
 1380:     my $start_page =
 1381:         &Apache::loncommon::start_page('Help Menu', undef,
 1382: 				       {'frameset'    => 1,
 1383: 					'js_ready'    => 1,
 1384: 					'add_entries' => {
 1385: 					    'border' => '0',
 1386: 					    'rows'   => "110,*",},});
 1387:     my $end_page =
 1388:         &Apache::loncommon::end_page({'frameset' => 1,
 1389: 				      'js_ready' => 1,});
 1390: 
 1391:     my $template .= <<"ENDTEMPLATE";
 1392: <script type="text/javascript">
 1393: // <![CDATA[
 1394: // <!-- BEGIN LON-CAPA Internal
 1395: var banner_link = '';
 1396: function helpMenu(target) {
 1397:     var caller = this;
 1398:     if (target == 'open') {
 1399:         var newWindow = null;
 1400:         try {
 1401:             newWindow =  window.open($nothing,"helpmenu","HEIGHT=$height,WIDTH=$width,resizable=yes,scrollbars=yes" )
 1402:         }
 1403:         catch(error) {
 1404:             writeHelp(caller);
 1405:             return;
 1406:         }
 1407:         if (newWindow) {
 1408:             caller = newWindow;
 1409:         }
 1410:     }
 1411:     writeHelp(caller);
 1412:     return;
 1413: }
 1414: function writeHelp(caller) {
 1415:     caller.document.writeln('$start_page\\n<frame name="bannerframe" src="'+banner_link+'" />\\n<frame name="bodyframe" src="$details_link" />\\n$end_page')
 1416:     caller.document.close()
 1417:     caller.focus()
 1418: }
 1419: // END LON-CAPA Internal -->
 1420: // ]]>
 1421: </script>
 1422: ENDTEMPLATE
 1423:     return $template;
 1424: }
 1425: 
 1426: sub help_open_bug {
 1427:     my ($topic, $text, $stayOnPage, $width, $height) = @_;
 1428:     unless ($env{'user.adv'}) { return ''; }
 1429:     unless ($Apache::lonnet::perlvar{'BugzillaHost'}) { return ''; }
 1430:     $text = "" if (not defined $text);
 1431: 	$stayOnPage=1;
 1432:     $width = 600 if (not defined $width);
 1433:     $height = 600 if (not defined $height);
 1434: 
 1435:     $topic=~s/\W+/\+/g;
 1436:     my $link='';
 1437:     my $template='';
 1438:     my $url=$Apache::lonnet::perlvar{'BugzillaHost'}.'enter_bug.cgi?product=LON-CAPA&amp;bug_file_loc='.
 1439: 	&escape($ENV{'REQUEST_URI'}).'&amp;component='.$topic;
 1440:     if (!$stayOnPage)
 1441:     {
 1442: 	$link = "javascript:void(open('$url', 'Bugzilla', 'menubar=0,toolbar=1,scrollbars=1,width=$width,height=$height,resizable=yes'))";
 1443:     }
 1444:     else
 1445:     {
 1446: 	$link = $url;
 1447:     }
 1448:     # Add the text
 1449:     if ($text ne "")
 1450:     {
 1451: 	$template .= 
 1452:   "<table bgcolor='#AA3333' cellspacing='1' cellpadding='1' border='0'><tr>".
 1453:   "<td bgcolor='#FF5555'><a target=\"_top\" href=\"$link\"><span style=\"color:#FFFFFF;font-size:10pt;\">$text</span></a>";
 1454:     }
 1455: 
 1456:     # Add the graphic
 1457:     my $title = &mt('Report a Bug');
 1458:     my $bugicon=&lonhttpdurl("/adm/lonMisc/smallBug.gif");
 1459:     $template .= <<"ENDTEMPLATE";
 1460:  <a target="_top" href="$link" title="$title"><img src="$bugicon" border="0" alt="(Bug: $topic)" /></a>
 1461: ENDTEMPLATE
 1462:     if ($text ne '') { $template.='</td></tr></table>' };
 1463:     return $template;
 1464: 
 1465: }
 1466: 
 1467: sub help_open_faq {
 1468:     my ($topic, $text, $stayOnPage, $width, $height) = @_;
 1469:     unless ($env{'user.adv'}) { return ''; }
 1470:     unless ($Apache::lonnet::perlvar{'FAQHost'}) { return ''; }
 1471:     $text = "" if (not defined $text);
 1472: 	$stayOnPage=1;
 1473:     $width = 350 if (not defined $width);
 1474:     $height = 400 if (not defined $height);
 1475: 
 1476:     $topic=~s/\W+/\+/g;
 1477:     my $link='';
 1478:     my $template='';
 1479:     my $url=$Apache::lonnet::perlvar{'FAQHost'}.'/fom/cache/'.$topic.'.html';
 1480:     if (!$stayOnPage)
 1481:     {
 1482: 	$link = "javascript:void(open('$url', 'FAQ-O-Matic', 'menubar=0,toolbar=1,scrollbars=1,width=$width,height=$height,resizable=yes'))";
 1483:     }
 1484:     else
 1485:     {
 1486: 	$link = $url;
 1487:     }
 1488: 
 1489:     # Add the text
 1490:     if ($text ne "")
 1491:     {
 1492: 	$template .= 
 1493:   "<table bgcolor='#337733' cellspacing='1' cellpadding='1' border='0'><tr>".
 1494:   "<td bgcolor='#448844'><a target=\"_top\" href=\"$link\"><span style=\"color:#FFFFFF; font-size:10pt;\">$text</span></a>";
 1495:     }
 1496: 
 1497:     # Add the graphic
 1498:     my $title = &mt('View the FAQ');
 1499:     my $faqicon=&lonhttpdurl("/adm/lonMisc/smallFAQ.gif");
 1500:     $template .= <<"ENDTEMPLATE";
 1501:  <a target="_top" href="$link" title="$title"><img src="$faqicon" border="0" alt="(FAQ: $topic)" /></a>
 1502: ENDTEMPLATE
 1503:     if ($text ne '') { $template.='</td></tr></table>' };
 1504:     return $template;
 1505: 
 1506: }
 1507: 
 1508: ###############################################################
 1509: ###############################################################
 1510: 
 1511: =pod
 1512: 
 1513: =item * &change_content_javascript():
 1514: 
 1515: This and the next function allow you to create small sections of an
 1516: otherwise static HTML page that you can update on the fly with
 1517: Javascript, even in Netscape 4.
 1518: 
 1519: The Javascript fragment returned by this function (no E<lt>scriptE<gt> tag)
 1520: must be written to the HTML page once. It will prove the Javascript
 1521: function "change(name, content)". Calling the change function with the
 1522: name of the section 
 1523: you want to update, matching the name passed to C<changable_area>, and
 1524: the new content you want to put in there, will put the content into
 1525: that area.
 1526: 
 1527: B<Note>: Netscape 4 only reserves enough space for the changable area
 1528: to contain room for the original contents. You need to "make space"
 1529: for whatever changes you wish to make, and be B<sure> to check your
 1530: code in Netscape 4. This feature in Netscape 4 is B<not> powerful;
 1531: it's adequate for updating a one-line status display, but little more.
 1532: This script will set the space to 100% width, so you only need to
 1533: worry about height in Netscape 4.
 1534: 
 1535: Modern browsers are much less limiting, and if you can commit to the
 1536: user not using Netscape 4, this feature may be used freely with
 1537: pretty much any HTML.
 1538: 
 1539: =cut
 1540: 
 1541: sub change_content_javascript {
 1542:     # If we're on Netscape 4, we need to use Layer-based code
 1543:     if ($env{'browser.type'} eq 'netscape' &&
 1544: 	$env{'browser.version'} =~ /^4\./) {
 1545: 	return (<<NETSCAPE4);
 1546: 	function change(name, content) {
 1547: 	    doc = document.layers[name+"___escape"].layers[0].document;
 1548: 	    doc.open();
 1549: 	    doc.write(content);
 1550: 	    doc.close();
 1551: 	}
 1552: NETSCAPE4
 1553:     } else {
 1554: 	# Otherwise, we need to use semi-standards-compliant code
 1555: 	# (technically, "innerHTML" isn't standard but the equivalent
 1556: 	# is really scary, and every useful browser supports it
 1557: 	return (<<DOMBASED);
 1558: 	function change(name, content) {
 1559: 	    element = document.getElementById(name);
 1560: 	    element.innerHTML = content;
 1561: 	}
 1562: DOMBASED
 1563:     }
 1564: }
 1565: 
 1566: =pod
 1567: 
 1568: =item * &changable_area($name,$origContent):
 1569: 
 1570: This provides a "changable area" that can be modified on the fly via
 1571: the Javascript code provided in C<change_content_javascript>. $name is
 1572: the name you will use to reference the area later; do not repeat the
 1573: same name on a given HTML page more then once. $origContent is what
 1574: the area will originally contain, which can be left blank.
 1575: 
 1576: =cut
 1577: 
 1578: sub changable_area {
 1579:     my ($name, $origContent) = @_;
 1580: 
 1581:     if ($env{'browser.type'} eq 'netscape' &&
 1582: 	$env{'browser.version'} =~ /^4\./) {
 1583: 	# If this is netscape 4, we need to use the Layer tag
 1584: 	return "<ilayer width='100%' id='${name}___escape' overflow='none'><layer width='100%' id='$name' overflow='none'>$origContent</layer></ilayer>";
 1585:     } else {
 1586: 	return "<span id='$name'>$origContent</span>";
 1587:     }
 1588: }
 1589: 
 1590: =pod
 1591: 
 1592: =item * &viewport_geometry_js 
 1593: 
 1594: Provides javascript object (Geometry) which can provide information about the viewport geometry for the client browser.
 1595: 
 1596: =cut
 1597: 
 1598: 
 1599: sub viewport_geometry_js { 
 1600:     return <<"GEOMETRY";
 1601: var Geometry = {};
 1602: function init_geometry() {
 1603:     if (Geometry.init) { return };
 1604:     Geometry.init=1;
 1605:     if (window.innerHeight) {
 1606:         Geometry.getViewportHeight   = function() { return window.innerHeight; };
 1607:         Geometry.getViewportWidth   = function() { return window.innerWidth; };
 1608:         Geometry.getHorizontalScroll = function() { return window.pageXOffset; };
 1609:         Geometry.getVerticalScroll   = function() { return window.pageYOffset; };
 1610:     }
 1611:     else if (document.documentElement && document.documentElement.clientHeight) {
 1612:         Geometry.getViewportHeight =
 1613:             function() { return document.documentElement.clientHeight; };
 1614:         Geometry.getViewportWidth =
 1615:             function() { return document.documentElement.clientWidth; };
 1616: 
 1617:         Geometry.getHorizontalScroll =
 1618:             function() { return document.documentElement.scrollLeft; };
 1619:         Geometry.getVerticalScroll =
 1620:             function() { return document.documentElement.scrollTop; };
 1621:     }
 1622:     else if (document.body.clientHeight) {
 1623:         Geometry.getViewportHeight =
 1624:             function() { return document.body.clientHeight; };
 1625:         Geometry.getViewportWidth =
 1626:             function() { return document.body.clientWidth; };
 1627:         Geometry.getHorizontalScroll =
 1628:             function() { return document.body.scrollLeft; };
 1629:         Geometry.getVerticalScroll =
 1630:             function() { return document.body.scrollTop; };
 1631:     }
 1632: }
 1633: 
 1634: GEOMETRY
 1635: }
 1636: 
 1637: =pod
 1638: 
 1639: =item * &viewport_size_js()
 1640: 
 1641: 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. 
 1642: 
 1643: =cut
 1644: 
 1645: sub viewport_size_js {
 1646:     my $geometry = &viewport_geometry_js();
 1647:     return <<"DIMS";
 1648: 
 1649: $geometry
 1650: 
 1651: function getViewportDims(width,height) {
 1652:     init_geometry();
 1653:     width.value = Geometry.getViewportWidth();
 1654:     height.value = Geometry.getViewportHeight();
 1655:     return;
 1656: }
 1657: 
 1658: DIMS
 1659: }
 1660: 
 1661: =pod
 1662: 
 1663: =item * &resize_textarea_js()
 1664: 
 1665: emits the needed javascript to resize a textarea to be as big as possible
 1666: 
 1667: creates a function resize_textrea that takes two IDs first should be
 1668: the id of the element to resize, second should be the id of a div that
 1669: surrounds everything that comes after the textarea, this routine needs
 1670: to be attached to the <body> for the onload and onresize events.
 1671: 
 1672: =back
 1673: 
 1674: =cut
 1675: 
 1676: sub resize_textarea_js {
 1677:     my $geometry = &viewport_geometry_js();
 1678:     return <<"RESIZE";
 1679:     <script type="text/javascript">
 1680: // <![CDATA[
 1681: $geometry
 1682: 
 1683: function getX(element) {
 1684:     var x = 0;
 1685:     while (element) {
 1686: 	x += element.offsetLeft;
 1687: 	element = element.offsetParent;
 1688:     }
 1689:     return x;
 1690: }
 1691: function getY(element) {
 1692:     var y = 0;
 1693:     while (element) {
 1694: 	y += element.offsetTop;
 1695: 	element = element.offsetParent;
 1696:     }
 1697:     return y;
 1698: }
 1699: 
 1700: 
 1701: function resize_textarea(textarea_id,bottom_id) {
 1702:     init_geometry();
 1703:     var textarea        = document.getElementById(textarea_id);
 1704:     //alert(textarea);
 1705: 
 1706:     var textarea_top    = getY(textarea);
 1707:     var textarea_height = textarea.offsetHeight;
 1708:     var bottom          = document.getElementById(bottom_id);
 1709:     var bottom_top      = getY(bottom);
 1710:     var bottom_height   = bottom.offsetHeight;
 1711:     var window_height   = Geometry.getViewportHeight();
 1712:     var fudge           = 23;
 1713:     var new_height      = window_height-fudge-textarea_top-bottom_height;
 1714:     if (new_height < 300) {
 1715: 	new_height = 300;
 1716:     }
 1717:     textarea.style.height=new_height+'px';
 1718: }
 1719: // ]]>
 1720: </script>
 1721: RESIZE
 1722: 
 1723: }
 1724: 
 1725: =pod
 1726: 
 1727: =head1 Excel and CSV file utility routines
 1728: 
 1729: =over 4
 1730: 
 1731: =cut
 1732: 
 1733: ###############################################################
 1734: ###############################################################
 1735: 
 1736: =pod
 1737: 
 1738: =item * &csv_translate($text) 
 1739: 
 1740: Translate $text to allow it to be output as a 'comma separated values' 
 1741: format.
 1742: 
 1743: =cut
 1744: 
 1745: ###############################################################
 1746: ###############################################################
 1747: sub csv_translate {
 1748:     my $text = shift;
 1749:     $text =~ s/\"/\"\"/g;
 1750:     $text =~ s/\n/ /g;
 1751:     return $text;
 1752: }
 1753: 
 1754: ###############################################################
 1755: ###############################################################
 1756: 
 1757: =pod
 1758: 
 1759: =item * &define_excel_formats()
 1760: 
 1761: Define some commonly used Excel cell formats.
 1762: 
 1763: Currently supported formats:
 1764: 
 1765: =over 4
 1766: 
 1767: =item header
 1768: 
 1769: =item bold
 1770: 
 1771: =item h1
 1772: 
 1773: =item h2
 1774: 
 1775: =item h3
 1776: 
 1777: =item h4
 1778: 
 1779: =item i
 1780: 
 1781: =item date
 1782: 
 1783: =back
 1784: 
 1785: Inputs: $workbook
 1786: 
 1787: Returns: $format, a hash reference.
 1788: 
 1789: 
 1790: =cut
 1791: 
 1792: ###############################################################
 1793: ###############################################################
 1794: sub define_excel_formats {
 1795:     my ($workbook) = @_;
 1796:     my $format;
 1797:     $format->{'header'} = $workbook->add_format(bold      => 1, 
 1798:                                                 bottom    => 1,
 1799:                                                 align     => 'center');
 1800:     $format->{'bold'} = $workbook->add_format(bold=>1);
 1801:     $format->{'h1'}   = $workbook->add_format(bold=>1, size=>18);
 1802:     $format->{'h2'}   = $workbook->add_format(bold=>1, size=>16);
 1803:     $format->{'h3'}   = $workbook->add_format(bold=>1, size=>14);
 1804:     $format->{'h4'}   = $workbook->add_format(bold=>1, size=>12);
 1805:     $format->{'i'}    = $workbook->add_format(italic=>1);
 1806:     $format->{'date'} = $workbook->add_format(num_format=>
 1807:                                             'mm/dd/yyyy hh:mm:ss');
 1808:     return $format;
 1809: }
 1810: 
 1811: ###############################################################
 1812: ###############################################################
 1813: 
 1814: =pod
 1815: 
 1816: =item * &create_workbook()
 1817: 
 1818: Create an Excel worksheet.  If it fails, output message on the
 1819: request object and return undefs.
 1820: 
 1821: Inputs: Apache request object
 1822: 
 1823: Returns (undef) on failure, 
 1824:     Excel worksheet object, scalar with filename, and formats 
 1825:     from &Apache::loncommon::define_excel_formats on success
 1826: 
 1827: =cut
 1828: 
 1829: ###############################################################
 1830: ###############################################################
 1831: sub create_workbook {
 1832:     my ($r) = @_;
 1833:         #
 1834:     # Create the excel spreadsheet
 1835:     my $filename = '/prtspool/'.
 1836:         $env{'user.name'}.'_'.$env{'user.domain'}.'_'.
 1837:         time.'_'.rand(1000000000).'.xls';
 1838:     my $workbook  = Spreadsheet::WriteExcel->new('/home/httpd'.$filename);
 1839:     if (! defined($workbook)) {
 1840:         $r->log_error("Error creating excel spreadsheet $filename: $!");
 1841:         $r->print(
 1842:             '<p class="LC_error">'
 1843:            .&mt('Problems occurred in creating the new Excel file.')
 1844:            .' '.&mt('This error has been logged.')
 1845:            .' '.&mt('Please alert your LON-CAPA administrator.')
 1846:            .'</p>'
 1847:         );
 1848:         return (undef);
 1849:     }
 1850:     #
 1851:     $workbook->set_tempdir(LONCAPA::tempdir());
 1852:     #
 1853:     my $format = &Apache::loncommon::define_excel_formats($workbook);
 1854:     return ($workbook,$filename,$format);
 1855: }
 1856: 
 1857: ###############################################################
 1858: ###############################################################
 1859: 
 1860: =pod
 1861: 
 1862: =item * &create_text_file()
 1863: 
 1864: Create a file to write to and eventually make available to the user.
 1865: If file creation fails, outputs an error message on the request object and 
 1866: return undefs.
 1867: 
 1868: Inputs: Apache request object, and file suffix
 1869: 
 1870: Returns (undef) on failure, 
 1871:     Filehandle and filename on success.
 1872: 
 1873: =cut
 1874: 
 1875: ###############################################################
 1876: ###############################################################
 1877: sub create_text_file {
 1878:     my ($r,$suffix) = @_;
 1879:     if (! defined($suffix)) { $suffix = 'txt'; };
 1880:     my $fh;
 1881:     my $filename = '/prtspool/'.
 1882:         $env{'user.name'}.'_'.$env{'user.domain'}.'_'.
 1883:         time.'_'.rand(1000000000).'.'.$suffix;
 1884:     $fh = Apache::File->new('>/home/httpd'.$filename);
 1885:     if (! defined($fh)) {
 1886:         $r->log_error("Couldn't open $filename for output $!");
 1887:         $r->print(
 1888:             '<p class="LC_error">'
 1889:            .&mt('Problems occurred in creating the output file.')
 1890:            .' '.&mt('This error has been logged.')
 1891:            .' '.&mt('Please alert your LON-CAPA administrator.')
 1892:            .'</p>'
 1893:         );
 1894:     }
 1895:     return ($fh,$filename)
 1896: }
 1897: 
 1898: 
 1899: =pod 
 1900: 
 1901: =back
 1902: 
 1903: =cut
 1904: 
 1905: ###############################################################
 1906: ##        Home server <option> list generating code          ##
 1907: ###############################################################
 1908: 
 1909: # ------------------------------------------
 1910: 
 1911: sub domain_select {
 1912:     my ($name,$value,$multiple)=@_;
 1913:     my %domains=map { 
 1914: 	$_ => $_.' '. &Apache::lonnet::domain($_,'description') 
 1915:     } &Apache::lonnet::all_domains();
 1916:     if ($multiple) {
 1917: 	$domains{''}=&mt('Any domain');
 1918: 	$domains{'select_form_order'} = [sort {lc($a) cmp lc($b) } (keys(%domains))];
 1919: 	return &multiple_select_form($name,$value,4,\%domains);
 1920:     } else {
 1921: 	$domains{'select_form_order'} = [sort {lc($a) cmp lc($b) } (keys(%domains))];
 1922: 	return &select_form($name,$value,\%domains);
 1923:     }
 1924: }
 1925: 
 1926: #-------------------------------------------
 1927: 
 1928: =pod
 1929: 
 1930: =head1 Routines for form select boxes
 1931: 
 1932: =over 4
 1933: 
 1934: =item * &multiple_select_form($name,$value,$size,$hash,$order)
 1935: 
 1936: Returns a string containing a <select> element int multiple mode
 1937: 
 1938: 
 1939: Args:
 1940:   $name - name of the <select> element
 1941:   $value - scalar or array ref of values that should already be selected
 1942:   $size - number of rows long the select element is
 1943:   $hash - the elements should be 'option' => 'shown text'
 1944:           (shown text should already have been &mt())
 1945:   $order - (optional) array ref of the order to show the elements in
 1946: 
 1947: =cut
 1948: 
 1949: #-------------------------------------------
 1950: sub multiple_select_form {
 1951:     my ($name,$value,$size,$hash,$order)=@_;
 1952:     my %selected = map { $_ => 1 } ref($value)?@{$value}:($value);
 1953:     my $output='';
 1954:     if (! defined($size)) {
 1955:         $size = 4;
 1956:         if (scalar(keys(%$hash))<4) {
 1957:             $size = scalar(keys(%$hash));
 1958:         }
 1959:     }
 1960:     $output.="\n".'<select name="'.$name.'" size="'.$size.'" multiple="multiple">';
 1961:     my @order;
 1962:     if (ref($order) eq 'ARRAY')  {
 1963:         @order = @{$order};
 1964:     } else {
 1965:         @order = sort(keys(%$hash));
 1966:     }
 1967:     if (exists($$hash{'select_form_order'})) {
 1968:         @order = @{$$hash{'select_form_order'}};
 1969:     }
 1970:         
 1971:     foreach my $key (@order) {
 1972:         $output.='<option value="'.&HTML::Entities::encode($key,'"<>&').'" ';
 1973:         $output.='selected="selected" ' if ($selected{$key});
 1974:         $output.='>'.$hash->{$key}."</option>\n";
 1975:     }
 1976:     $output.="</select>\n";
 1977:     return $output;
 1978: }
 1979: 
 1980: #-------------------------------------------
 1981: 
 1982: =pod
 1983: 
 1984: =item * &select_form($defdom,$name,$hashref,$onchange)
 1985: 
 1986: Returns a string containing a <select name='$name' size='1'> form to 
 1987: allow a user to select options from a ref to a hash containing:
 1988: option_name => displayed text. An optional $onchange can include
 1989: a javascript onchange item, e.g., onchange="this.form.submit();"  
 1990: 
 1991: See lonrights.pm for an example invocation and use.
 1992: 
 1993: =cut
 1994: 
 1995: #-------------------------------------------
 1996: sub select_form {
 1997:     my ($def,$name,$hashref,$onchange) = @_;
 1998:     return unless (ref($hashref) eq 'HASH');
 1999:     if ($onchange) {
 2000:         $onchange = ' onchange="'.$onchange.'"';
 2001:     }
 2002:     my $selectform = "<select name=\"$name\" size=\"1\"$onchange>\n";
 2003:     my @keys;
 2004:     if (exists($hashref->{'select_form_order'})) {
 2005: 	@keys=@{$hashref->{'select_form_order'}};
 2006:     } else {
 2007: 	@keys=sort(keys(%{$hashref}));
 2008:     }
 2009:     foreach my $key (@keys) {
 2010:         $selectform.=
 2011: 	    '<option value="'.&HTML::Entities::encode($key,'"<>&').'" '.
 2012:             ($key eq $def ? 'selected="selected" ' : '').
 2013:                 ">".$hashref->{$key}."</option>\n";
 2014:     }
 2015:     $selectform.="</select>";
 2016:     return $selectform;
 2017: }
 2018: 
 2019: # For display filters
 2020: 
 2021: sub display_filter {
 2022:     my ($context) = @_;
 2023:     if (!$env{'form.show'}) { $env{'form.show'}=10; }
 2024:     if (!$env{'form.displayfilter'}) { $env{'form.displayfilter'}='currentfolder'; }
 2025:     my $phraseinput = 'hidden';
 2026:     my $includeinput = 'hidden';
 2027:     my ($checked,$includetypestext);
 2028:     if ($env{'form.displayfilter'} eq 'containing') {
 2029:         $phraseinput = 'text'; 
 2030:         if ($context eq 'parmslog') {
 2031:             $includeinput = 'checkbox';
 2032:             if ($env{'form.includetypes'}) {
 2033:                 $checked = ' checked="checked"';
 2034:             }
 2035:             $includetypestext = &mt('Include parameter types');
 2036:         }
 2037:     } else {
 2038:         $includetypestext = '&nbsp;';
 2039:     }
 2040:     my ($additional,$secondid,$thirdid);
 2041:     if ($context eq 'parmslog') {
 2042:         $additional = 
 2043:             '<label><input type="'.$includeinput.'" name="includetypes"'. 
 2044:             $checked.' name="includetypes" value="1" id="includetypes" />'.
 2045:             '&nbsp;<span id="includetypestext">'.$includetypestext.'</span>'.
 2046:             '</label>';
 2047:         $secondid = 'includetypes';
 2048:         $thirdid = 'includetypestext';
 2049:     }
 2050:     my $onchange = "javascript:toggleHistoryOptions(this,'containingphrase','$context',
 2051:                                                     '$secondid','$thirdid')";
 2052:     return '<span class="LC_nobreak"><label>'.&mt('Records: [_1]',
 2053: 			       &Apache::lonmeta::selectbox('show',$env{'form.show'},undef,
 2054: 							   (&mt('all'),10,20,50,100,1000,10000))).
 2055: 	   '</label></span> <span class="LC_nobreak">'.
 2056:            &mt('Filter: [_1]',
 2057: 	   &select_form($env{'form.displayfilter'},
 2058: 			'displayfilter',
 2059: 			{'currentfolder' => 'Current folder/page',
 2060: 			 'containing' => 'Containing phrase',
 2061: 			 'none' => 'None'},$onchange)).'&nbsp;'.
 2062: 			 '<input type="'.$phraseinput.'" name="containingphrase" id="containingphrase" size="30" value="'.
 2063:                          &HTML::Entities::encode($env{'form.containingphrase'}).
 2064:                          '" />'.$additional;
 2065: }
 2066: 
 2067: sub display_filter_js {
 2068:     my $includetext = &mt('Include parameter types');
 2069:     return <<"ENDJS";
 2070:   
 2071: function toggleHistoryOptions(setter,firstid,context,secondid,thirdid) {
 2072:     var firstType = 'hidden';
 2073:     if (setter.options[setter.selectedIndex].value == 'containing') {
 2074:         firstType = 'text';
 2075:     }
 2076:     firstObject = document.getElementById(firstid);
 2077:     if (typeof(firstObject) == 'object') {
 2078:         if (firstObject.type != firstType) {
 2079:             changeInputType(firstObject,firstType);
 2080:         }
 2081:     }
 2082:     if (context == 'parmslog') {
 2083:         var secondType = 'hidden';
 2084:         if (firstType == 'text') {
 2085:             secondType = 'checkbox';
 2086:         }
 2087:         secondObject = document.getElementById(secondid);  
 2088:         if (typeof(secondObject) == 'object') {
 2089:             if (secondObject.type != secondType) {
 2090:                 changeInputType(secondObject,secondType);
 2091:             }
 2092:         }
 2093:         var textItem = document.getElementById(thirdid);
 2094:         var currtext = textItem.innerHTML;
 2095:         var newtext;
 2096:         if (firstType == 'text') {
 2097:             newtext = '$includetext';
 2098:         } else {
 2099:             newtext = '&nbsp;';
 2100:         }
 2101:         if (currtext != newtext) {
 2102:             textItem.innerHTML = newtext;
 2103:         }
 2104:     }
 2105:     return;
 2106: }
 2107: 
 2108: function changeInputType(oldObject,newType) {
 2109:     var newObject = document.createElement('input');
 2110:     newObject.type = newType;
 2111:     if (oldObject.size) {
 2112:         newObject.size = oldObject.size;
 2113:     }
 2114:     if (oldObject.value) {
 2115:         newObject.value = oldObject.value;
 2116:     }
 2117:     if (oldObject.name) {
 2118:         newObject.name = oldObject.name;
 2119:     }
 2120:     if (oldObject.id) {
 2121:         newObject.id = oldObject.id;
 2122:     }
 2123:     oldObject.parentNode.replaceChild(newObject,oldObject);
 2124:     return;
 2125: }
 2126: 
 2127: ENDJS
 2128: }
 2129: 
 2130: sub gradeleveldescription {
 2131:     my $gradelevel=shift;
 2132:     my %gradelevels=(0 => 'Not specified',
 2133: 		     1 => 'Grade 1',
 2134: 		     2 => 'Grade 2',
 2135: 		     3 => 'Grade 3',
 2136: 		     4 => 'Grade 4',
 2137: 		     5 => 'Grade 5',
 2138: 		     6 => 'Grade 6',
 2139: 		     7 => 'Grade 7',
 2140: 		     8 => 'Grade 8',
 2141: 		     9 => 'Grade 9',
 2142: 		     10 => 'Grade 10',
 2143: 		     11 => 'Grade 11',
 2144: 		     12 => 'Grade 12',
 2145: 		     13 => 'Grade 13',
 2146: 		     14 => '100 Level',
 2147: 		     15 => '200 Level',
 2148: 		     16 => '300 Level',
 2149: 		     17 => '400 Level',
 2150: 		     18 => 'Graduate Level');
 2151:     return &mt($gradelevels{$gradelevel});
 2152: }
 2153: 
 2154: sub select_level_form {
 2155:     my ($deflevel,$name)=@_;
 2156:     unless ($deflevel) { $deflevel=0; }
 2157:     my $selectform = "<select name=\"$name\" size=\"1\">\n";
 2158:     for (my $i=0; $i<=18; $i++) {
 2159:         $selectform.="<option value=\"$i\" ".
 2160:             ($i==$deflevel ? 'selected="selected" ' : '').
 2161:                 ">".&gradeleveldescription($i)."</option>\n";
 2162:     }
 2163:     $selectform.="</select>";
 2164:     return $selectform;
 2165: }
 2166: 
 2167: #-------------------------------------------
 2168: 
 2169: =pod
 2170: 
 2171: =item * &select_dom_form($defdom,$name,$includeempty,$showdomdesc,$onchange,$incdoms)
 2172: 
 2173: Returns a string containing a <select name='$name' size='1'> form to 
 2174: allow a user to select the domain to preform an operation in.  
 2175: See loncreateuser.pm for an example invocation and use.
 2176: 
 2177: If the $includeempty flag is set, it also includes an empty choice ("no domain
 2178: selected");
 2179: 
 2180: If the $showdomdesc flag is set, the domain name is followed by the domain description.
 2181: 
 2182: 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.
 2183: 
 2184: The optional $incdoms is a reference to an array of domains which will be the only available options. 
 2185: 
 2186: =cut
 2187: 
 2188: #-------------------------------------------
 2189: sub select_dom_form {
 2190:     my ($defdom,$name,$includeempty,$showdomdesc,$onchange,$incdoms) = @_;
 2191:     if ($onchange) {
 2192:         $onchange = ' onchange="'.$onchange.'"';
 2193:     }
 2194:     my @domains;
 2195:     if (ref($incdoms) eq 'ARRAY') {
 2196:         @domains = sort {lc($a) cmp lc($b)} (@{$incdoms});
 2197:     } else {
 2198:         @domains = sort {lc($a) cmp lc($b)} (&Apache::lonnet::all_domains());
 2199:     }
 2200:     if ($includeempty) { @domains=('',@domains); }
 2201:     my $selectdomain = "<select name=\"$name\" size=\"1\"$onchange>\n";
 2202:     foreach my $dom (@domains) {
 2203:         $selectdomain.="<option value=\"$dom\" ".
 2204:             ($dom eq $defdom ? 'selected="selected" ' : '').'>'.$dom;
 2205:         if ($showdomdesc) {
 2206:             if ($dom ne '') {
 2207:                 my $domdesc = &Apache::lonnet::domain($dom,'description');
 2208:                 if ($domdesc ne '') {
 2209:                     $selectdomain .= ' ('.$domdesc.')';
 2210:                 }
 2211:             } 
 2212:         }
 2213:         $selectdomain .= "</option>\n";
 2214:     }
 2215:     $selectdomain.="</select>";
 2216:     return $selectdomain;
 2217: }
 2218: 
 2219: #-------------------------------------------
 2220: 
 2221: =pod
 2222: 
 2223: =item * &home_server_form_item($domain,$name,$defaultflag)
 2224: 
 2225: input: 4 arguments (two required, two optional) - 
 2226:     $domain - domain of new user
 2227:     $name - name of form element
 2228:     $default - Value of 'default' causes a default item to be first 
 2229:                             option, and selected by default. 
 2230:     $hide - Value of 'hide' causes hiding of the name of the server, 
 2231:                             if 1 server found, or default, if 0 found.
 2232: output: returns 2 items: 
 2233: (a) form element which contains either:
 2234:    (i) <select name="$name">
 2235:         <option value="$hostid1">$hostid $servers{$hostid}</option>
 2236:         <option value="$hostid2">$hostid $servers{$hostid}</option>       
 2237:        </select>
 2238:        form item if there are multiple library servers in $domain, or
 2239:    (ii) an <input type="hidden" name="$name" value="$hostid" /> form item 
 2240:        if there is only one library server in $domain.
 2241: 
 2242: (b) number of library servers found.
 2243: 
 2244: See loncreateuser.pm for example of use.
 2245: 
 2246: =cut
 2247: 
 2248: #-------------------------------------------
 2249: sub home_server_form_item {
 2250:     my ($domain,$name,$default,$hide) = @_;
 2251:     my %servers = &Apache::lonnet::get_servers($domain,'library');
 2252:     my $result;
 2253:     my $numlib = keys(%servers);
 2254:     if ($numlib > 1) {
 2255:         $result .= '<select name="'.$name.'" />'."\n";
 2256:         if ($default) {
 2257:             $result .= '<option value="default" selected="selected">'.&mt('default').
 2258:                        '</option>'."\n";
 2259:         }
 2260:         foreach my $hostid (sort(keys(%servers))) {
 2261:             $result.= '<option value="'.$hostid.'">'.
 2262: 	              $hostid.' '.$servers{$hostid}."</option>\n";
 2263:         }
 2264:         $result .= '</select>'."\n";
 2265:     } elsif ($numlib == 1) {
 2266:         my $hostid;
 2267:         foreach my $item (keys(%servers)) {
 2268:             $hostid = $item;
 2269:         }
 2270:         $result .= '<input type="hidden" name="'.$name.'" value="'.
 2271:                    $hostid.'" />';
 2272:                    if (!$hide) {
 2273:                        $result .= $hostid.' '.$servers{$hostid};
 2274:                    }
 2275:                    $result .= "\n";
 2276:     } elsif ($default) {
 2277:         $result .= '<input type="hidden" name="'.$name.
 2278:                    '" value="default" />';
 2279:                    if (!$hide) {
 2280:                        $result .= &mt('default');
 2281:                    }
 2282:                    $result .= "\n";
 2283:     }
 2284:     return ($result,$numlib);
 2285: }
 2286: 
 2287: =pod
 2288: 
 2289: =back 
 2290: 
 2291: =cut
 2292: 
 2293: ###############################################################
 2294: ##                  Decoding User Agent                      ##
 2295: ###############################################################
 2296: 
 2297: =pod
 2298: 
 2299: =head1 Decoding the User Agent
 2300: 
 2301: =over 4
 2302: 
 2303: =item * &decode_user_agent()
 2304: 
 2305: Inputs: $r
 2306: 
 2307: Outputs:
 2308: 
 2309: =over 4
 2310: 
 2311: =item * $httpbrowser
 2312: 
 2313: =item * $clientbrowser
 2314: 
 2315: =item * $clientversion
 2316: 
 2317: =item * $clientmathml
 2318: 
 2319: =item * $clientunicode
 2320: 
 2321: =item * $clientos
 2322: 
 2323: =back
 2324: 
 2325: =back 
 2326: 
 2327: =cut
 2328: 
 2329: ###############################################################
 2330: ###############################################################
 2331: sub decode_user_agent {
 2332:     my ($r)=@_;
 2333:     my @browsertype=split(/\&/,$Apache::lonnet::perlvar{"lonBrowsDet"});
 2334:     my %mathcap=split(/\&/,$$Apache::lonnet::perlvar{"lonMathML"});
 2335:     my $httpbrowser=$ENV{"HTTP_USER_AGENT"};
 2336:     if (!$httpbrowser && $r) { $httpbrowser=$r->header_in('User-Agent'); }
 2337:     my $clientbrowser='unknown';
 2338:     my $clientversion='0';
 2339:     my $clientmathml='';
 2340:     my $clientunicode='0';
 2341:     for (my $i=0;$i<=$#browsertype;$i++) {
 2342:         my ($bname,$match,$notmatch,$vreg,$minv,$univ)=split(/\:/,$browsertype[$i]);
 2343: 	if (($httpbrowser=~/$match/i)  && ($httpbrowser!~/$notmatch/i)) {
 2344: 	    $clientbrowser=$bname;
 2345:             $httpbrowser=~/$vreg/i;
 2346: 	    $clientversion=$1;
 2347:             $clientmathml=($clientversion>=$minv);
 2348:             $clientunicode=($clientversion>=$univ);
 2349: 	}
 2350:     }
 2351:     my $clientos='unknown';
 2352:     if (($httpbrowser=~/linux/i) ||
 2353:         ($httpbrowser=~/unix/i) ||
 2354:         ($httpbrowser=~/ux/i) ||
 2355:         ($httpbrowser=~/solaris/i)) { $clientos='unix'; }
 2356:     if (($httpbrowser=~/vax/i) ||
 2357:         ($httpbrowser=~/vms/i)) { $clientos='vms'; }
 2358:     if ($httpbrowser=~/next/i) { $clientos='next'; }
 2359:     if (($httpbrowser=~/mac/i) ||
 2360:         ($httpbrowser=~/powerpc/i)) { $clientos='mac'; }
 2361:     if ($httpbrowser=~/win/i) { $clientos='win'; }
 2362:     if ($httpbrowser=~/embed/i) { $clientos='pda'; }
 2363:     return ($httpbrowser,$clientbrowser,$clientversion,$clientmathml,
 2364:             $clientunicode,$clientos,);
 2365: }
 2366: 
 2367: ###############################################################
 2368: ##    Authentication changing form generation subroutines    ##
 2369: ###############################################################
 2370: ##
 2371: ## All of the authform_xxxxxxx subroutines take their inputs in a
 2372: ## hash, and have reasonable default values.
 2373: ##
 2374: ##    formname = the name given in the <form> tag.
 2375: #-------------------------------------------
 2376: 
 2377: =pod
 2378: 
 2379: =head1 Authentication Routines
 2380: 
 2381: =over 4
 2382: 
 2383: =item * &authform_xxxxxx()
 2384: 
 2385: The authform_xxxxxx subroutines provide javascript and html forms which 
 2386: handle some of the conveniences required for authentication forms.  
 2387: This is not an optimal method, but it works.  
 2388: 
 2389: =over 4
 2390: 
 2391: =item * authform_header
 2392: 
 2393: =item * authform_authorwarning
 2394: 
 2395: =item * authform_nochange
 2396: 
 2397: =item * authform_kerberos
 2398: 
 2399: =item * authform_internal
 2400: 
 2401: =item * authform_filesystem
 2402: 
 2403: =back
 2404: 
 2405: See loncreateuser.pm for invocation and use examples.
 2406: 
 2407: =cut
 2408: 
 2409: #-------------------------------------------
 2410: sub authform_header{  
 2411:     my %in = (
 2412:         formname => 'cu',
 2413:         kerb_def_dom => '',
 2414:         @_,
 2415:     );
 2416:     $in{'formname'} = 'document.' . $in{'formname'};
 2417:     my $result='';
 2418: 
 2419: #---------------------------------------------- Code for upper case translation
 2420:     my $Javascript_toUpperCase;
 2421:     unless ($in{kerb_def_dom}) {
 2422:         $Javascript_toUpperCase =<<"END";
 2423:         switch (choice) {
 2424:            case 'krb': currentform.elements[choicearg].value =
 2425:                currentform.elements[choicearg].value.toUpperCase();
 2426:                break;
 2427:            default:
 2428:         }
 2429: END
 2430:     } else {
 2431:         $Javascript_toUpperCase = "";
 2432:     }
 2433: 
 2434:     my $radioval = "'nochange'";
 2435:     if (defined($in{'curr_authtype'})) {
 2436:         if ($in{'curr_authtype'} ne '') {
 2437:             $radioval = "'".$in{'curr_authtype'}."arg'";
 2438:         }
 2439:     }
 2440:     my $argfield = 'null';
 2441:     if (defined($in{'mode'})) {
 2442:         if ($in{'mode'} eq 'modifycourse')  {
 2443:             if (defined($in{'curr_autharg'})) {
 2444:                 if ($in{'curr_autharg'} ne '') {
 2445:                     $argfield = "'$in{'curr_autharg'}'";
 2446:                 }
 2447:             }
 2448:         }
 2449:     }
 2450: 
 2451:     $result.=<<"END";
 2452: var current = new Object();
 2453: current.radiovalue = $radioval;
 2454: current.argfield = $argfield;
 2455: 
 2456: function changed_radio(choice,currentform) {
 2457:     var choicearg = choice + 'arg';
 2458:     // If a radio button in changed, we need to change the argfield
 2459:     if (current.radiovalue != choice) {
 2460:         current.radiovalue = choice;
 2461:         if (current.argfield != null) {
 2462:             currentform.elements[current.argfield].value = '';
 2463:         }
 2464:         if (choice == 'nochange') {
 2465:             current.argfield = null;
 2466:         } else {
 2467:             current.argfield = choicearg;
 2468:             switch(choice) {
 2469:                 case 'krb': 
 2470:                     currentform.elements[current.argfield].value = 
 2471:                         "$in{'kerb_def_dom'}";
 2472:                 break;
 2473:               default:
 2474:                 break;
 2475:             }
 2476:         }
 2477:     }
 2478:     return;
 2479: }
 2480: 
 2481: function changed_text(choice,currentform) {
 2482:     var choicearg = choice + 'arg';
 2483:     if (currentform.elements[choicearg].value !='') {
 2484:         $Javascript_toUpperCase
 2485:         // clear old field
 2486:         if ((current.argfield != choicearg) && (current.argfield != null)) {
 2487:             currentform.elements[current.argfield].value = '';
 2488:         }
 2489:         current.argfield = choicearg;
 2490:     }
 2491:     set_auth_radio_buttons(choice,currentform);
 2492:     return;
 2493: }
 2494: 
 2495: function set_auth_radio_buttons(newvalue,currentform) {
 2496:     var numauthchoices = currentform.login.length;
 2497:     if (typeof numauthchoices  == "undefined") {
 2498:         return;
 2499:     } 
 2500:     var i=0;
 2501:     while (i < numauthchoices) {
 2502:         if (currentform.login[i].value == newvalue) { break; }
 2503:         i++;
 2504:     }
 2505:     if (i == numauthchoices) {
 2506:         return;
 2507:     }
 2508:     current.radiovalue = newvalue;
 2509:     currentform.login[i].checked = true;
 2510:     return;
 2511: }
 2512: END
 2513:     return $result;
 2514: }
 2515: 
 2516: sub authform_authorwarning {
 2517:     my $result='';
 2518:     $result='<i>'.
 2519:         &mt('As a general rule, only authors or co-authors should be '.
 2520:             'filesystem authenticated '.
 2521:             '(which allows access to the server filesystem).')."</i>\n";
 2522:     return $result;
 2523: }
 2524: 
 2525: sub authform_nochange {
 2526:     my %in = (
 2527:               formname => 'document.cu',
 2528:               kerb_def_dom => 'MSU.EDU',
 2529:               @_,
 2530:           );
 2531:     my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
 2532:     my $result;
 2533:     if (!$authnum) {
 2534:         $result = &mt('Under your current role you are not permitted to change login settings for this user');
 2535:     } else {
 2536:         $result = '<label>'.&mt('[_1] Do not change login data',
 2537:                   '<input type="radio" name="login" value="nochange" '.
 2538:                   'checked="checked" onclick="'.
 2539:             "javascript:changed_radio('nochange',$in{'formname'});".'" />').
 2540: 	    '</label>';
 2541:     }
 2542:     return $result;
 2543: }
 2544: 
 2545: sub authform_kerberos {
 2546:     my %in = (
 2547:               formname => 'document.cu',
 2548:               kerb_def_dom => 'MSU.EDU',
 2549:               kerb_def_auth => 'krb4',
 2550:               @_,
 2551:               );
 2552:     my ($check4,$check5,$krbcheck,$krbarg,$krbver,$result,$authtype,
 2553:         $autharg,$jscall);
 2554:     my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
 2555:     if ($in{'kerb_def_auth'} eq 'krb5') {
 2556:        $check5 = ' checked="checked"';
 2557:     } else {
 2558:        $check4 = ' checked="checked"';
 2559:     }
 2560:     $krbarg = $in{'kerb_def_dom'};
 2561:     if (defined($in{'curr_authtype'})) {
 2562:         if ($in{'curr_authtype'} eq 'krb') {
 2563:             $krbcheck = ' checked="checked"';
 2564:             if (defined($in{'mode'})) {
 2565:                 if ($in{'mode'} eq 'modifyuser') {
 2566:                     $krbcheck = '';
 2567:                 }
 2568:             }
 2569:             if (defined($in{'curr_kerb_ver'})) {
 2570:                 if ($in{'curr_krb_ver'} eq '5') {
 2571:                     $check5 = ' checked="checked"';
 2572:                     $check4 = '';
 2573:                 } else {
 2574:                     $check4 = ' checked="checked"';
 2575:                     $check5 = '';
 2576:                 }
 2577:             }
 2578:             if (defined($in{'curr_autharg'})) {
 2579:                 $krbarg = $in{'curr_autharg'};
 2580:             }
 2581:             if (!$can_assign{'krb4'} && !$can_assign{'krb5'}) {
 2582:                 if (defined($in{'curr_autharg'})) {
 2583:                     $result = 
 2584:     &mt('Currently Kerberos authenticated with domain [_1] Version [_2].',
 2585:         $in{'curr_autharg'},$krbver);
 2586:                 } else {
 2587:                     $result =
 2588:     &mt('Currently Kerberos authenticated, Version [_1].',$krbver);
 2589:                 }
 2590:                 return $result; 
 2591:             }
 2592:         }
 2593:     } else {
 2594:         if ($authnum == 1) {
 2595:             $authtype = '<input type="hidden" name="login" value="krb" />';
 2596:         }
 2597:     }
 2598:     if (!$can_assign{'krb4'} && !$can_assign{'krb5'}) {
 2599:         return;
 2600:     } elsif ($authtype eq '') {
 2601:         if (defined($in{'mode'})) {
 2602:             if ($in{'mode'} eq 'modifycourse') {
 2603:                 if ($authnum == 1) {
 2604:                     $authtype = '<input type="radio" name="login" value="krb" />';
 2605:                 }
 2606:             }
 2607:         }
 2608:     }
 2609:     $jscall = "javascript:changed_radio('krb',$in{'formname'});";
 2610:     if ($authtype eq '') {
 2611:         $authtype = '<input type="radio" name="login" value="krb" '.
 2612:                     'onclick="'.$jscall.'" onchange="'.$jscall.'"'.
 2613:                     $krbcheck.' />';
 2614:     }
 2615:     if (($can_assign{'krb4'} && $can_assign{'krb5'}) ||
 2616:         ($can_assign{'krb4'} && !$can_assign{'krb5'} &&
 2617:          $in{'curr_authtype'} eq 'krb5') ||
 2618:         (!$can_assign{'krb4'} && $can_assign{'krb5'} &&
 2619:          $in{'curr_authtype'} eq 'krb4')) {
 2620:         $result .= &mt
 2621:         ('[_1] Kerberos authenticated with domain [_2] '.
 2622:          '[_3] Version 4 [_4] Version 5 [_5]',
 2623:          '<label>'.$authtype,
 2624:          '</label><input type="text" size="10" name="krbarg" '.
 2625:              'value="'.$krbarg.'" '.
 2626:              'onchange="'.$jscall.'" />',
 2627:          '<label><input type="radio" name="krbver" value="4" '.$check4.' />',
 2628:          '</label><label><input type="radio" name="krbver" value="5" '.$check5.' />',
 2629: 	 '</label>');
 2630:     } elsif ($can_assign{'krb4'}) {
 2631:         $result .= &mt
 2632:         ('[_1] Kerberos authenticated with domain [_2] '.
 2633:          '[_3] Version 4 [_4]',
 2634:          '<label>'.$authtype,
 2635:          '</label><input type="text" size="10" name="krbarg" '.
 2636:              'value="'.$krbarg.'" '.
 2637:              'onchange="'.$jscall.'" />',
 2638:          '<label><input type="hidden" name="krbver" value="4" />',
 2639:          '</label>');
 2640:     } elsif ($can_assign{'krb5'}) {
 2641:         $result .= &mt
 2642:         ('[_1] Kerberos authenticated with domain [_2] '.
 2643:          '[_3] Version 5 [_4]',
 2644:          '<label>'.$authtype,
 2645:          '</label><input type="text" size="10" name="krbarg" '.
 2646:              'value="'.$krbarg.'" '.
 2647:              'onchange="'.$jscall.'" />',
 2648:          '<label><input type="hidden" name="krbver" value="5" />',
 2649:          '</label>');
 2650:     }
 2651:     return $result;
 2652: }
 2653: 
 2654: sub authform_internal {
 2655:     my %in = (
 2656:                 formname => 'document.cu',
 2657:                 kerb_def_dom => 'MSU.EDU',
 2658:                 @_,
 2659:                 );
 2660:     my ($intcheck,$intarg,$result,$authtype,$autharg,$jscall);
 2661:     my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
 2662:     if (defined($in{'curr_authtype'})) {
 2663:         if ($in{'curr_authtype'} eq 'int') {
 2664:             if ($can_assign{'int'}) {
 2665:                 $intcheck = 'checked="checked" ';
 2666:                 if (defined($in{'mode'})) {
 2667:                     if ($in{'mode'} eq 'modifyuser') {
 2668:                         $intcheck = '';
 2669:                     }
 2670:                 }
 2671:                 if (defined($in{'curr_autharg'})) {
 2672:                     $intarg = $in{'curr_autharg'};
 2673:                 }
 2674:             } else {
 2675:                 $result = &mt('Currently internally authenticated.');
 2676:                 return $result;
 2677:             }
 2678:         }
 2679:     } else {
 2680:         if ($authnum == 1) {
 2681:             $authtype = '<input type="hidden" name="login" value="int" />';
 2682:         }
 2683:     }
 2684:     if (!$can_assign{'int'}) {
 2685:         return;
 2686:     } elsif ($authtype eq '') {
 2687:         if (defined($in{'mode'})) {
 2688:             if ($in{'mode'} eq 'modifycourse') {
 2689:                 if ($authnum == 1) {
 2690:                     $authtype = '<input type="radio" name="login" value="int" />';
 2691:                 }
 2692:             }
 2693:         }
 2694:     }
 2695:     $jscall = "javascript:changed_radio('int',$in{'formname'});";
 2696:     if ($authtype eq '') {
 2697:         $authtype = '<input type="radio" name="login" value="int" '.$intcheck.
 2698:                     ' onchange="'.$jscall.'" onclick="'.$jscall.'" />';
 2699:     }
 2700:     $autharg = '<input type="password" size="10" name="intarg" value="'.
 2701:                $intarg.'" onchange="'.$jscall.'" />';
 2702:     $result = &mt
 2703:         ('[_1] Internally authenticated (with initial password [_2])',
 2704:          '<label>'.$authtype,'</label>'.$autharg);
 2705:     $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>';
 2706:     return $result;
 2707: }
 2708: 
 2709: sub authform_local {
 2710:     my %in = (
 2711:               formname => 'document.cu',
 2712:               kerb_def_dom => 'MSU.EDU',
 2713:               @_,
 2714:               );
 2715:     my ($loccheck,$locarg,$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 'loc') {
 2719:             if ($can_assign{'loc'}) {
 2720:                 $loccheck = 'checked="checked" ';
 2721:                 if (defined($in{'mode'})) {
 2722:                     if ($in{'mode'} eq 'modifyuser') {
 2723:                         $loccheck = '';
 2724:                     }
 2725:                 }
 2726:                 if (defined($in{'curr_autharg'})) {
 2727:                     $locarg = $in{'curr_autharg'};
 2728:                 }
 2729:             } else {
 2730:                 $result = &mt('Currently using local (institutional) authentication.');
 2731:                 return $result;
 2732:             }
 2733:         }
 2734:     } else {
 2735:         if ($authnum == 1) {
 2736:             $authtype = '<input type="hidden" name="login" value="loc" />';
 2737:         }
 2738:     }
 2739:     if (!$can_assign{'loc'}) {
 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="loc" />';
 2746:                 }
 2747:             }
 2748:         }
 2749:     }
 2750:     $jscall = "javascript:changed_radio('loc',$in{'formname'});";
 2751:     if ($authtype eq '') {
 2752:         $authtype = '<input type="radio" name="login" value="loc" '.
 2753:                     $loccheck.' onchange="'.$jscall.'" onclick="'.
 2754:                     $jscall.'" />';
 2755:     }
 2756:     $autharg = '<input type="text" size="10" name="locarg" value="'.
 2757:                $locarg.'" onchange="'.$jscall.'" />';
 2758:     $result = &mt('[_1] Local Authentication with argument [_2]',
 2759:                   '<label>'.$authtype,'</label>'.$autharg);
 2760:     return $result;
 2761: }
 2762: 
 2763: sub authform_filesystem {
 2764:     my %in = (
 2765:               formname => 'document.cu',
 2766:               kerb_def_dom => 'MSU.EDU',
 2767:               @_,
 2768:               );
 2769:     my ($fsyscheck,$result,$authtype,$autharg,$jscall);
 2770:     my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
 2771:     if (defined($in{'curr_authtype'})) {
 2772:         if ($in{'curr_authtype'} eq 'fsys') {
 2773:             if ($can_assign{'fsys'}) {
 2774:                 $fsyscheck = 'checked="checked" ';
 2775:                 if (defined($in{'mode'})) {
 2776:                     if ($in{'mode'} eq 'modifyuser') {
 2777:                         $fsyscheck = '';
 2778:                     }
 2779:                 }
 2780:             } else {
 2781:                 $result = &mt('Currently Filesystem Authenticated.');
 2782:                 return $result;
 2783:             }           
 2784:         }
 2785:     } else {
 2786:         if ($authnum == 1) {
 2787:             $authtype = '<input type="hidden" name="login" value="fsys" />';
 2788:         }
 2789:     }
 2790:     if (!$can_assign{'fsys'}) {
 2791:         return;
 2792:     } elsif ($authtype eq '') {
 2793:         if (defined($in{'mode'})) {
 2794:             if ($in{'mode'} eq 'modifycourse') {
 2795:                 if ($authnum == 1) {
 2796:                     $authtype = '<input type="radio" name="login" value="fsys" />';
 2797:                 }
 2798:             }
 2799:         }
 2800:     }
 2801:     $jscall = "javascript:changed_radio('fsys',$in{'formname'});";
 2802:     if ($authtype eq '') {
 2803:         $authtype = '<input type="radio" name="login" value="fsys" '.
 2804:                     $fsyscheck.' onchange="'.$jscall.'" onclick="'.
 2805:                     $jscall.'" />';
 2806:     }
 2807:     $autharg = '<input type="text" size="10" name="fsysarg" value=""'.
 2808:                ' onchange="'.$jscall.'" />';
 2809:     $result = &mt
 2810:         ('[_1] Filesystem Authenticated (with initial password [_2])',
 2811:          '<label><input type="radio" name="login" value="fsys" '.
 2812:          $fsyscheck.'onchange="'.$jscall.'" onclick="'.$jscall.'" />',
 2813:          '</label><input type="password" size="10" name="fsysarg" value="" '.
 2814:                   'onchange="'.$jscall.'" />');
 2815:     return $result;
 2816: }
 2817: 
 2818: sub get_assignable_auth {
 2819:     my ($dom) = @_;
 2820:     if ($dom eq '') {
 2821:         $dom = $env{'request.role.domain'};
 2822:     }
 2823:     my %can_assign = (
 2824:                           krb4 => 1,
 2825:                           krb5 => 1,
 2826:                           int  => 1,
 2827:                           loc  => 1,
 2828:                      );
 2829:     my %domconfig = &Apache::lonnet::get_dom('configuration',['usercreation'],$dom);
 2830:     if (ref($domconfig{'usercreation'}) eq 'HASH') {
 2831:         if (ref($domconfig{'usercreation'}{'authtypes'}) eq 'HASH') {
 2832:             my $authhash = $domconfig{'usercreation'}{'authtypes'};
 2833:             my $context;
 2834:             if ($env{'request.role'} =~ /^au/) {
 2835:                 $context = 'author';
 2836:             } elsif ($env{'request.role'} =~ /^dc/) {
 2837:                 $context = 'domain';
 2838:             } elsif ($env{'request.course.id'}) {
 2839:                 $context = 'course';
 2840:             }
 2841:             if ($context) {
 2842:                 if (ref($authhash->{$context}) eq 'HASH') {
 2843:                    %can_assign = %{$authhash->{$context}}; 
 2844:                 }
 2845:             }
 2846:         }
 2847:     }
 2848:     my $authnum = 0;
 2849:     foreach my $key (keys(%can_assign)) {
 2850:         if ($can_assign{$key}) {
 2851:             $authnum ++;
 2852:         }
 2853:     }
 2854:     if ($can_assign{'krb4'} && $can_assign{'krb5'}) {
 2855:         $authnum --;
 2856:     }
 2857:     return ($authnum,%can_assign);
 2858: }
 2859: 
 2860: ###############################################################
 2861: ##    Get Kerberos Defaults for Domain                 ##
 2862: ###############################################################
 2863: ##
 2864: ## Returns default kerberos version and an associated argument
 2865: ## as listed in file domain.tab. If not listed, provides
 2866: ## appropriate default domain and kerberos version.
 2867: ##
 2868: #-------------------------------------------
 2869: 
 2870: =pod
 2871: 
 2872: =item * &get_kerberos_defaults()
 2873: 
 2874: get_kerberos_defaults($target_domain) returns the default kerberos
 2875: version and domain. If not found, it defaults to version 4 and the 
 2876: domain of the server.
 2877: 
 2878: =over 4
 2879: 
 2880: ($def_version, $def_krb_domain) = &get_kerberos_defaults($target_domain);
 2881: 
 2882: =back
 2883: 
 2884: =back
 2885: 
 2886: =cut
 2887: 
 2888: #-------------------------------------------
 2889: sub get_kerberos_defaults {
 2890:     my $domain=shift;
 2891:     my ($krbdef,$krbdefdom);
 2892:     my %domdefaults = &Apache::lonnet::get_domain_defaults($domain);
 2893:     if (($domdefaults{'auth_def'} =~/^krb(4|5)$/) && ($domdefaults{'auth_arg_def'} ne '')) {
 2894:         $krbdef = $domdefaults{'auth_def'};
 2895:         $krbdefdom = $domdefaults{'auth_arg_def'};
 2896:     } else {
 2897:         $ENV{'SERVER_NAME'}=~/(\w+\.\w+)$/;
 2898:         my $krbdefdom=$1;
 2899:         $krbdefdom=~tr/a-z/A-Z/;
 2900:         $krbdef = "krb4";
 2901:     }
 2902:     return ($krbdef,$krbdefdom);
 2903: }
 2904: 
 2905: 
 2906: ###############################################################
 2907: ##                Thesaurus Functions                        ##
 2908: ###############################################################
 2909: 
 2910: =pod
 2911: 
 2912: =head1 Thesaurus Functions
 2913: 
 2914: =over 4
 2915: 
 2916: =item * &initialize_keywords()
 2917: 
 2918: Initializes the package variable %Keywords if it is empty.  Uses the
 2919: package variable $thesaurus_db_file.
 2920: 
 2921: =cut
 2922: 
 2923: ###################################################
 2924: 
 2925: sub initialize_keywords {
 2926:     return 1 if (scalar keys(%Keywords));
 2927:     # If we are here, %Keywords is empty, so fill it up
 2928:     #   Make sure the file we need exists...
 2929:     if (! -e $thesaurus_db_file) {
 2930:         &Apache::lonnet::logthis("Attempt to access $thesaurus_db_file".
 2931:                                  " failed because it does not exist");
 2932:         return 0;
 2933:     }
 2934:     #   Set up the hash as a database
 2935:     my %thesaurus_db;
 2936:     if (! tie(%thesaurus_db,'GDBM_File',
 2937:               $thesaurus_db_file,&GDBM_READER(),0640)){
 2938:         &Apache::lonnet::logthis("Could not tie \%thesaurus_db to ".
 2939:                                  $thesaurus_db_file);
 2940:         return 0;
 2941:     } 
 2942:     #  Get the average number of appearances of a word.
 2943:     my $avecount = $thesaurus_db{'average.count'};
 2944:     #  Put keywords (those that appear > average) into %Keywords
 2945:     while (my ($word,$data)=each (%thesaurus_db)) {
 2946:         my ($count,undef) = split /:/,$data;
 2947:         $Keywords{$word}++ if ($count > $avecount);
 2948:     }
 2949:     untie %thesaurus_db;
 2950:     # Remove special values from %Keywords.
 2951:     foreach my $value ('total.count','average.count') {
 2952:         delete($Keywords{$value}) if (exists($Keywords{$value}));
 2953:   }
 2954:     return 1;
 2955: }
 2956: 
 2957: ###################################################
 2958: 
 2959: =pod
 2960: 
 2961: =item * &keyword($word)
 2962: 
 2963: Returns true if $word is a keyword.  A keyword is a word that appears more 
 2964: than the average number of times in the thesaurus database.  Calls 
 2965: &initialize_keywords
 2966: 
 2967: =cut
 2968: 
 2969: ###################################################
 2970: 
 2971: sub keyword {
 2972:     return if (!&initialize_keywords());
 2973:     my $word=lc(shift());
 2974:     $word=~s/\W//g;
 2975:     return exists($Keywords{$word});
 2976: }
 2977: 
 2978: ###############################################################
 2979: 
 2980: =pod 
 2981: 
 2982: =item * &get_related_words()
 2983: 
 2984: Look up a word in the thesaurus.  Takes a scalar argument and returns
 2985: an array of words.  If the keyword is not in the thesaurus, an empty array
 2986: will be returned.  The order of the words returned is determined by the
 2987: database which holds them.
 2988: 
 2989: Uses global $thesaurus_db_file.
 2990: 
 2991: 
 2992: =cut
 2993: 
 2994: ###############################################################
 2995: sub get_related_words {
 2996:     my $keyword = shift;
 2997:     my %thesaurus_db;
 2998:     if (! -e $thesaurus_db_file) {
 2999:         &Apache::lonnet::logthis("Attempt to access $thesaurus_db_file ".
 3000:                                  "failed because the file does not exist");
 3001:         return ();
 3002:     }
 3003:     if (! tie(%thesaurus_db,'GDBM_File',
 3004:               $thesaurus_db_file,&GDBM_READER(),0640)){
 3005:         return ();
 3006:     } 
 3007:     my @Words=();
 3008:     my $count=0;
 3009:     if (exists($thesaurus_db{$keyword})) {
 3010: 	# The first element is the number of times
 3011: 	# the word appears.  We do not need it now.
 3012: 	my (undef,@RelatedWords) = (split(/:/,$thesaurus_db{$keyword}));
 3013: 	my (undef,$mostfrequentcount)=split(/\,/,$RelatedWords[0]);
 3014: 	my $threshold=$mostfrequentcount/10;
 3015:         foreach my $possibleword (@RelatedWords) {
 3016:             my ($word,$wordcount)=split(/\,/,$possibleword);
 3017:             if ($wordcount>$threshold) {
 3018: 		push(@Words,$word);
 3019:                 $count++;
 3020:                 if ($count>10) { last; }
 3021: 	    }
 3022:         }
 3023:     }
 3024:     untie %thesaurus_db;
 3025:     return @Words;
 3026: }
 3027: ###############################################################
 3028: #
 3029: #  Spell checking
 3030: #
 3031: 
 3032: =pod
 3033: 
 3034: =head1 Spell checking
 3035: 
 3036: =over 4
 3037: 
 3038: =item * &check_spelling($wordlist $language)
 3039: 
 3040: Takes a string containing words and feeds it to an external
 3041: spellcheck program via a pipeline. Returns a string containing
 3042: them mis-spelled words.
 3043: 
 3044: Parameters:
 3045: 
 3046: =over 4
 3047: 
 3048: =item - $wordlist
 3049: 
 3050: String that will be fed into the spellcheck program.
 3051: 
 3052: =item - $language
 3053: 
 3054: Language string that specifies the language for which the spell
 3055: check will be performed.
 3056: 
 3057: =back
 3058: 
 3059: =back
 3060: 
 3061: Note: This sub assumes that aspell is installed.
 3062: 
 3063: 
 3064: =cut
 3065: 
 3066: 
 3067: =pod
 3068: 
 3069: =back
 3070: 
 3071: =cut
 3072: 
 3073: sub check_spelling {
 3074:     my ($wordlist, $language) = @_;
 3075:     my @misspellings;
 3076:     
 3077:     # Generate the speller and set the langauge.
 3078:     # if explicitly selected:
 3079: 
 3080:     my $speller = Text::Aspell->new;
 3081:     if ($language) {
 3082: 	$speller->set_option('lang', $language);
 3083:     }
 3084: 
 3085:     # Turn the word list into an array of words by splittingon whitespace
 3086: 
 3087:     my @words = split(/\s+/, $wordlist);
 3088: 
 3089:     foreach my $word (@words) {
 3090: 	if(! $speller->check($word)) {
 3091: 	    push(@misspellings, $word);
 3092: 	}
 3093:     }
 3094:     return join(' ', @misspellings);
 3095:     
 3096: }
 3097: 
 3098: # -------------------------------------------------------------- Plaintext name
 3099: =pod
 3100: 
 3101: =head1 User Name Functions
 3102: 
 3103: =over 4
 3104: 
 3105: =item * &plainname($uname,$udom,$first)
 3106: 
 3107: Takes a users logon name and returns it as a string in
 3108: "first middle last generation" form 
 3109: if $first is set to 'lastname' then it returns it as
 3110: 'lastname generation, firstname middlename' if their is a lastname
 3111: 
 3112: =cut
 3113: 
 3114: 
 3115: ###############################################################
 3116: sub plainname {
 3117:     my ($uname,$udom,$first)=@_;
 3118:     return if (!defined($uname) || !defined($udom));
 3119:     my %names=&getnames($uname,$udom);
 3120:     my $name=&Apache::lonnet::format_name($names{'firstname'},
 3121: 					  $names{'middlename'},
 3122: 					  $names{'lastname'},
 3123: 					  $names{'generation'},$first);
 3124:     $name=~s/^\s+//;
 3125:     $name=~s/\s+$//;
 3126:     $name=~s/\s+/ /g;
 3127:     if ($name !~ /\S/) { $name=$uname.':'.$udom; }
 3128:     return $name;
 3129: }
 3130: 
 3131: # -------------------------------------------------------------------- Nickname
 3132: =pod
 3133: 
 3134: =item * &nickname($uname,$udom)
 3135: 
 3136: Gets a users name and returns it as a string as
 3137: 
 3138: "&quot;nickname&quot;"
 3139: 
 3140: if the user has a nickname or
 3141: 
 3142: "first middle last generation"
 3143: 
 3144: if the user does not
 3145: 
 3146: =cut
 3147: 
 3148: sub nickname {
 3149:     my ($uname,$udom)=@_;
 3150:     return if (!defined($uname) || !defined($udom));
 3151:     my %names=&getnames($uname,$udom);
 3152:     my $name=$names{'nickname'};
 3153:     if ($name) {
 3154:        $name='&quot;'.$name.'&quot;'; 
 3155:     } else {
 3156:        $name=$names{'firstname'}.' '.$names{'middlename'}.' '.
 3157: 	     $names{'lastname'}.' '.$names{'generation'};
 3158:        $name=~s/\s+$//;
 3159:        $name=~s/\s+/ /g;
 3160:     }
 3161:     return $name;
 3162: }
 3163: 
 3164: sub getnames {
 3165:     my ($uname,$udom)=@_;
 3166:     return if (!defined($uname) || !defined($udom));
 3167:     if ($udom eq 'public' && $uname eq 'public') {
 3168: 	return ('lastname' => &mt('Public'));
 3169:     }
 3170:     my $id=$uname.':'.$udom;
 3171:     my ($names,$cached)=&Apache::lonnet::is_cached_new('namescache',$id);
 3172:     if ($cached) {
 3173: 	return %{$names};
 3174:     } else {
 3175: 	my %loadnames=&Apache::lonnet::get('environment',
 3176:                     ['firstname','middlename','lastname','generation','nickname'],
 3177: 					 $udom,$uname);
 3178: 	&Apache::lonnet::do_cache_new('namescache',$id,\%loadnames);
 3179: 	return %loadnames;
 3180:     }
 3181: }
 3182: 
 3183: # -------------------------------------------------------------------- getemails
 3184: 
 3185: =pod
 3186: 
 3187: =item * &getemails($uname,$udom)
 3188: 
 3189: Gets a user's email information and returns it as a hash with keys:
 3190: notification, critnotification, permanentemail
 3191: 
 3192: For notification and critnotification, values are comma-separated lists 
 3193: of e-mail addresses; for permanentemail, value is a single e-mail address.
 3194:  
 3195: 
 3196: =cut
 3197: 
 3198: 
 3199: sub getemails {
 3200:     my ($uname,$udom)=@_;
 3201:     if ($udom eq 'public' && $uname eq 'public') {
 3202: 	return;
 3203:     }
 3204:     if (!$udom) { $udom=$env{'user.domain'}; }
 3205:     if (!$uname) { $uname=$env{'user.name'}; }
 3206:     my $id=$uname.':'.$udom;
 3207:     my ($names,$cached)=&Apache::lonnet::is_cached_new('emailscache',$id);
 3208:     if ($cached) {
 3209: 	return %{$names};
 3210:     } else {
 3211: 	my %loadnames=&Apache::lonnet::get('environment',
 3212:                     			   ['notification','critnotification',
 3213: 					    'permanentemail'],
 3214: 					   $udom,$uname);
 3215: 	&Apache::lonnet::do_cache_new('emailscache',$id,\%loadnames);
 3216: 	return %loadnames;
 3217:     }
 3218: }
 3219: 
 3220: sub flush_email_cache {
 3221:     my ($uname,$udom)=@_;
 3222:     if (!$udom)  { $udom =$env{'user.domain'}; }
 3223:     if (!$uname) { $uname=$env{'user.name'};   }
 3224:     return if ($udom eq 'public' && $uname eq 'public');
 3225:     my $id=$uname.':'.$udom;
 3226:     &Apache::lonnet::devalidate_cache_new('emailscache',$id);
 3227: }
 3228: 
 3229: # -------------------------------------------------------------------- getlangs
 3230: 
 3231: =pod
 3232: 
 3233: =item * &getlangs($uname,$udom)
 3234: 
 3235: Gets a user's language preference and returns it as a hash with key:
 3236: language.
 3237: 
 3238: =cut
 3239: 
 3240: 
 3241: sub getlangs {
 3242:     my ($uname,$udom) = @_;
 3243:     if (!$udom)  { $udom =$env{'user.domain'}; }
 3244:     if (!$uname) { $uname=$env{'user.name'};   }
 3245:     my $id=$uname.':'.$udom;
 3246:     my ($langs,$cached)=&Apache::lonnet::is_cached_new('userlangs',$id);
 3247:     if ($cached) {
 3248:         return %{$langs};
 3249:     } else {
 3250:         my %loadlangs=&Apache::lonnet::get('environment',['languages'],
 3251:                                            $udom,$uname);
 3252:         &Apache::lonnet::do_cache_new('userlangs',$id,\%loadlangs);
 3253:         return %loadlangs;
 3254:     }
 3255: }
 3256: 
 3257: sub flush_langs_cache {
 3258:     my ($uname,$udom)=@_;
 3259:     if (!$udom)  { $udom =$env{'user.domain'}; }
 3260:     if (!$uname) { $uname=$env{'user.name'};   }
 3261:     return if ($udom eq 'public' && $uname eq 'public');
 3262:     my $id=$uname.':'.$udom;
 3263:     &Apache::lonnet::devalidate_cache_new('userlangs',$id);
 3264: }
 3265: 
 3266: # ------------------------------------------------------------------ Screenname
 3267: 
 3268: =pod
 3269: 
 3270: =item * &screenname($uname,$udom)
 3271: 
 3272: Gets a users screenname and returns it as a string
 3273: 
 3274: =cut
 3275: 
 3276: sub screenname {
 3277:     my ($uname,$udom)=@_;
 3278:     if ($uname eq $env{'user.name'} &&
 3279: 	$udom eq $env{'user.domain'}) {return $env{'environment.screenname'};}
 3280:     my %names=&Apache::lonnet::get('environment',['screenname'],$udom,$uname);
 3281:     return $names{'screenname'};
 3282: }
 3283: 
 3284: 
 3285: # ------------------------------------------------------------- Confirm Wrapper
 3286: =pod
 3287: 
 3288: =item confirmwrapper
 3289: 
 3290: Wrap messages about completion of operation in box
 3291: 
 3292: =cut
 3293: 
 3294: sub confirmwrapper {
 3295:     my ($message)=@_;
 3296:     if ($message) {
 3297:         return "\n".'<div class="LC_confirm_box">'."\n"
 3298:                .$message."\n"
 3299:                .'</div>'."\n";
 3300:     } else {
 3301:         return $message;
 3302:     }
 3303: }
 3304: 
 3305: # ------------------------------------------------------------- Message Wrapper
 3306: 
 3307: sub messagewrapper {
 3308:     my ($link,$username,$domain,$subject,$text)=@_;
 3309:     return 
 3310:         '<a href="/adm/email?compose=individual&amp;'.
 3311:         'recname='.$username.'&amp;recdom='.$domain.
 3312: 	'&amp;subject='.&escape($subject).'&amp;text='.&escape($text).'" '.
 3313:         'title="'.&mt('Send message').'">'.$link.'</a>';
 3314: }
 3315: 
 3316: # --------------------------------------------------------------- Notes Wrapper
 3317: 
 3318: sub noteswrapper {
 3319:     my ($link,$un,$do)=@_;
 3320:     return 
 3321: "<a href='/adm/email?recordftf=retrieve&amp;recname=$un&amp;recdom=$do'>$link</a>";
 3322: }
 3323: 
 3324: # ------------------------------------------------------------- Aboutme Wrapper
 3325: 
 3326: sub aboutmewrapper {
 3327:     my ($link,$username,$domain,$target,$class)=@_;
 3328:     if (!defined($username)  && !defined($domain)) {
 3329:         return;
 3330:     }
 3331:     return '<a href="/adm/'.$domain.'/'.$username.'/aboutme"'.
 3332: 	($target?' target="'.$target.'"':'').($class?' class="'.$class.'"':'').' title="'.&mt("View this user's personal information page").'">'.$link.'</a>';
 3333: }
 3334: 
 3335: # ------------------------------------------------------------ Syllabus Wrapper
 3336: 
 3337: sub syllabuswrapper {
 3338:     my ($linktext,$coursedir,$domain)=@_;
 3339:     return qq{<a href="/public/$domain/$coursedir/syllabus">$linktext</a>};
 3340: }
 3341: 
 3342: # -----------------------------------------------------------------------------
 3343: 
 3344: sub track_student_link {
 3345:     my ($linktext,$sname,$sdom,$target,$start,$only_body) = @_;
 3346:     my $link ="/adm/trackstudent?";
 3347:     my $title = 'View recent activity';
 3348:     if (defined($sname) && $sname !~ /^\s*$/ &&
 3349:         defined($sdom)  && $sdom  !~ /^\s*$/) {
 3350:         $link .= "selected_student=$sname:$sdom";
 3351:         $title .= ' of this student';
 3352:     } 
 3353:     if (defined($target) && $target !~ /^\s*$/) {
 3354:         $target = qq{target="$target"};
 3355:     } else {
 3356:         $target = '';
 3357:     }
 3358:     if ($start) { $link.='&amp;start='.$start; }
 3359:     if ($only_body) { $link .= '&amp;only_body=1'; }
 3360:     $title = &mt($title);
 3361:     $linktext = &mt($linktext);
 3362:     return qq{<a href="$link" title="$title" $target>$linktext</a>}.
 3363: 	&help_open_topic('View_recent_activity');
 3364: }
 3365: 
 3366: sub slot_reservations_link {
 3367:     my ($linktext,$sname,$sdom,$target) = @_;
 3368:     my $link ="/adm/slotrequest?command=showresv&amp;origin=aboutme";
 3369:     my $title = 'View slot reservation history';
 3370:     if (defined($sname) && $sname !~ /^\s*$/ &&
 3371:         defined($sdom)  && $sdom  !~ /^\s*$/) {
 3372:         $link .= "&amp;uname=$sname&amp;udom=$sdom";
 3373:         $title .= ' of this student';
 3374:     }
 3375:     if (defined($target) && $target !~ /^\s*$/) {
 3376:         $target = qq{target="$target"};
 3377:     } else {
 3378:         $target = '';
 3379:     }
 3380:     $title = &mt($title);
 3381:     $linktext = &mt($linktext);
 3382:     return qq{<a href="$link" title="$title" $target>$linktext</a>};
 3383: # FIXME uncomment when help item created: &help_open_topic('Slot_Reservation_History');
 3384: 
 3385: }
 3386: 
 3387: # ===================================================== Display a student photo
 3388: 
 3389: 
 3390: sub student_image_tag {
 3391:     my ($domain,$user)=@_;
 3392:     my $imgsrc=&Apache::lonnet::studentphoto($domain,$user,'jpg');
 3393:     if (($imgsrc) && ($imgsrc ne '/adm/lonKaputt/lonlogo_broken.gif')) {
 3394: 	return '<img src="'.$imgsrc.'" align="right" />';
 3395:     } else {
 3396: 	return '';
 3397:     }
 3398: }
 3399: 
 3400: =pod
 3401: 
 3402: =back
 3403: 
 3404: =head1 Access .tab File Data
 3405: 
 3406: =over 4
 3407: 
 3408: =item * &languageids() 
 3409: 
 3410: returns list of all language ids
 3411: 
 3412: =cut
 3413: 
 3414: sub languageids {
 3415:     return sort(keys(%language));
 3416: }
 3417: 
 3418: =pod
 3419: 
 3420: =item * &languagedescription() 
 3421: 
 3422: returns description of a specified language id
 3423: 
 3424: =cut
 3425: 
 3426: sub languagedescription {
 3427:     my $code=shift;
 3428:     return  ($supported_language{$code}?'* ':'').
 3429:             $language{$code}.
 3430: 	    ($supported_language{$code}?' ('.&mt('interface available').')':'');
 3431: }
 3432: 
 3433: =pod
 3434: 
 3435: =item * &plainlanguagedescription
 3436: 
 3437: Returns both the plain language description (e.g. 'Creoles and Pidgins, English-based (Other)')
 3438: and the language character encoding (e.g. ISO) separated by a ' - ' string.
 3439: 
 3440: =cut
 3441: 
 3442: sub plainlanguagedescription {
 3443:     my $code=shift;
 3444:     return $language{$code};
 3445: }
 3446: 
 3447: =pod
 3448: 
 3449: =item * &supportedlanguagecode
 3450: 
 3451: Returns the supported language code (e.g. sptutf maps to pt) given a language
 3452: code.
 3453: 
 3454: =cut
 3455: 
 3456: sub supportedlanguagecode {
 3457:     my $code=shift;
 3458:     return $supported_language{$code};
 3459: }
 3460: 
 3461: =pod
 3462: 
 3463: =item * &latexlanguage()
 3464: 
 3465: Given a language key code returns the correspondnig language to use
 3466: to select the correct hyphenation on LaTeX printouts.  This is undef if there
 3467: is no supported hyphenation for the language code.
 3468: 
 3469: =cut
 3470: 
 3471: sub latexlanguage {
 3472:     my $code = shift;
 3473:     return $latex_language{$code};
 3474: }
 3475: 
 3476: =pod
 3477: 
 3478: =item * &latexhyphenation()
 3479: 
 3480: Same as above but what's supplied is the language as it might be stored
 3481: in the metadata.
 3482: 
 3483: =cut
 3484: 
 3485: sub latexhyphenation {
 3486:     my $key = shift;
 3487:     return $latex_language_bykey{$key};
 3488: }
 3489: 
 3490: =pod
 3491: 
 3492: =item * &copyrightids() 
 3493: 
 3494: returns list of all copyrights
 3495: 
 3496: =cut
 3497: 
 3498: sub copyrightids {
 3499:     return sort(keys(%cprtag));
 3500: }
 3501: 
 3502: =pod
 3503: 
 3504: =item * &copyrightdescription() 
 3505: 
 3506: returns description of a specified copyright id
 3507: 
 3508: =cut
 3509: 
 3510: sub copyrightdescription {
 3511:     return &mt($cprtag{shift(@_)});
 3512: }
 3513: 
 3514: =pod
 3515: 
 3516: =item * &source_copyrightids() 
 3517: 
 3518: returns list of all source copyrights
 3519: 
 3520: =cut
 3521: 
 3522: sub source_copyrightids {
 3523:     return sort(keys(%scprtag));
 3524: }
 3525: 
 3526: =pod
 3527: 
 3528: =item * &source_copyrightdescription() 
 3529: 
 3530: returns description of a specified source copyright id
 3531: 
 3532: =cut
 3533: 
 3534: sub source_copyrightdescription {
 3535:     return &mt($scprtag{shift(@_)});
 3536: }
 3537: 
 3538: =pod
 3539: 
 3540: =item * &filecategories() 
 3541: 
 3542: returns list of all file categories
 3543: 
 3544: =cut
 3545: 
 3546: sub filecategories {
 3547:     return sort(keys(%category_extensions));
 3548: }
 3549: 
 3550: =pod
 3551: 
 3552: =item * &filecategorytypes() 
 3553: 
 3554: returns list of file types belonging to a given file
 3555: category
 3556: 
 3557: =cut
 3558: 
 3559: sub filecategorytypes {
 3560:     my ($cat) = @_;
 3561:     return @{$category_extensions{lc($cat)}};
 3562: }
 3563: 
 3564: =pod
 3565: 
 3566: =item * &fileembstyle() 
 3567: 
 3568: returns embedding style for a specified file type
 3569: 
 3570: =cut
 3571: 
 3572: sub fileembstyle {
 3573:     return $fe{lc(shift(@_))};
 3574: }
 3575: 
 3576: sub filemimetype {
 3577:     return $fm{lc(shift(@_))};
 3578: }
 3579: 
 3580: 
 3581: sub filecategoryselect {
 3582:     my ($name,$value)=@_;
 3583:     return &select_form($value,$name,
 3584:                         {'' => &mt('Any category'), map { $_,$_ } sort(keys(%category_extensions))});
 3585: }
 3586: 
 3587: =pod
 3588: 
 3589: =item * &filedescription() 
 3590: 
 3591: returns description for a specified file type
 3592: 
 3593: =cut
 3594: 
 3595: sub filedescription {
 3596:     my $file_description = $fd{lc(shift())};
 3597:     $file_description =~ s:([\[\]]):~$1:g;
 3598:     return &mt($file_description);
 3599: }
 3600: 
 3601: =pod
 3602: 
 3603: =item * &filedescriptionex() 
 3604: 
 3605: returns description for a specified file type with
 3606: extra formatting
 3607: 
 3608: =cut
 3609: 
 3610: sub filedescriptionex {
 3611:     my $ex=shift;
 3612:     my $file_description = $fd{lc($ex)};
 3613:     $file_description =~ s:([\[\]]):~$1:g;
 3614:     return '.'.$ex.' '.&mt($file_description);
 3615: }
 3616: 
 3617: # End of .tab access
 3618: =pod
 3619: 
 3620: =back
 3621: 
 3622: =cut
 3623: 
 3624: # ------------------------------------------------------------------ File Types
 3625: sub fileextensions {
 3626:     return sort(keys(%fe));
 3627: }
 3628: 
 3629: # ----------------------------------------------------------- Display Languages
 3630: # returns a hash with all desired display languages
 3631: #
 3632: 
 3633: sub display_languages {
 3634:     my %languages=();
 3635:     foreach my $lang (&Apache::lonlocal::preferred_languages()) {
 3636: 	$languages{$lang}=1;
 3637:     }
 3638:     &get_unprocessed_cgi($ENV{'QUERY_STRING'},['displaylanguage']);
 3639:     if ($env{'form.displaylanguage'}) {
 3640: 	foreach my $lang (split(/\s*(\,|\;|\:)\s*/,$env{'form.displaylanguage'})) {
 3641: 	    $languages{$lang}=1;
 3642:         }
 3643:     }
 3644:     return %languages;
 3645: }
 3646: 
 3647: sub languages {
 3648:     my ($possible_langs) = @_;
 3649:     my @preferred_langs = &Apache::lonlocal::preferred_languages();
 3650:     if (!ref($possible_langs)) {
 3651: 	if( wantarray ) {
 3652: 	    return @preferred_langs;
 3653: 	} else {
 3654: 	    return $preferred_langs[0];
 3655: 	}
 3656:     }
 3657:     my %possibilities = map { $_ => 1 } (@$possible_langs);
 3658:     my @preferred_possibilities;
 3659:     foreach my $preferred_lang (@preferred_langs) {
 3660: 	if (exists($possibilities{$preferred_lang})) {
 3661: 	    push(@preferred_possibilities, $preferred_lang);
 3662: 	}
 3663:     }
 3664:     if( wantarray ) {
 3665: 	return @preferred_possibilities;
 3666:     }
 3667:     return $preferred_possibilities[0];
 3668: }
 3669: 
 3670: sub user_lang {
 3671:     my ($touname,$toudom,$fromcid) = @_;
 3672:     my @userlangs;
 3673:     if (($fromcid ne '') && ($env{'course.'.$fromcid.'.languages'} ne '')) {
 3674:         @userlangs=(@userlangs,split(/\s*(\,|\;|\:)\s*/,
 3675:                     $env{'course.'.$fromcid.'.languages'}));
 3676:     } else {
 3677:         my %langhash = &getlangs($touname,$toudom);
 3678:         if ($langhash{'languages'} ne '') {
 3679:             @userlangs = split(/\s*(\,|\;|\:)\s*/,$langhash{'languages'});
 3680:         } else {
 3681:             my %domdefs = &Apache::lonnet::get_domain_defaults($toudom);
 3682:             if ($domdefs{'lang_def'} ne '') {
 3683:                 @userlangs = ($domdefs{'lang_def'});
 3684:             }
 3685:         }
 3686:     }
 3687:     my @languages=&Apache::lonlocal::get_genlanguages(@userlangs);
 3688:     my $user_lh = Apache::localize->get_handle(@languages);
 3689:     return $user_lh;
 3690: }
 3691: 
 3692: 
 3693: ###############################################################
 3694: ##               Student Answer Attempts                     ##
 3695: ###############################################################
 3696: 
 3697: =pod
 3698: 
 3699: =head1 Alternate Problem Views
 3700: 
 3701: =over 4
 3702: 
 3703: =item * &get_previous_attempt($symb, $username, $domain, $course,
 3704:     $getattempt, $regexp, $gradesub)
 3705: 
 3706: Return string with previous attempt on problem. Arguments:
 3707: 
 3708: =over 4
 3709: 
 3710: =item * $symb: Problem, including path
 3711: 
 3712: =item * $username: username of the desired student
 3713: 
 3714: =item * $domain: domain of the desired student
 3715: 
 3716: =item * $course: Course ID
 3717: 
 3718: =item * $getattempt: Leave blank for all attempts, otherwise put
 3719:     something
 3720: 
 3721: =item * $regexp: if string matches this regexp, the string will be
 3722:     sent to $gradesub
 3723: 
 3724: =item * $gradesub: routine that processes the string if it matches $regexp
 3725: 
 3726: =back
 3727: 
 3728: The output string is a table containing all desired attempts, if any.
 3729: 
 3730: =cut
 3731: 
 3732: sub get_previous_attempt {
 3733:   my ($symb,$username,$domain,$course,$getattempt,$regexp,$gradesub)=@_;
 3734:   my $prevattempts='';
 3735:   no strict 'refs';
 3736:   if ($symb) {
 3737:     my (%returnhash)=
 3738:       &Apache::lonnet::restore($symb,$course,$domain,$username);
 3739:     if ($returnhash{'version'}) {
 3740:       my %lasthash=();
 3741:       my $version;
 3742:       for ($version=1;$version<=$returnhash{'version'};$version++) {
 3743:         foreach my $key (sort(split(/\:/,$returnhash{$version.':keys'}))) {
 3744: 	  $lasthash{$key}=$returnhash{$version.':'.$key};
 3745:         }
 3746:       }
 3747:       $prevattempts=&start_data_table().&start_data_table_header_row();
 3748:       $prevattempts.='<th>'.&mt('History').'</th>';
 3749:       my (%typeparts,%lasthidden);
 3750:       my $showsurv=&Apache::lonnet::allowed('vas',$env{'request.course.id'});
 3751:       foreach my $key (sort(keys(%lasthash))) {
 3752: 	my ($ign,@parts) = split(/\./,$key);
 3753: 	if ($#parts > 0) {
 3754: 	  my $data=$parts[-1];
 3755:           next if ($data eq 'foilorder');
 3756: 	  pop(@parts);
 3757:           $prevattempts.='<th>'.&mt('Part ').join('.',@parts).'<br />'.$data.'&nbsp;</th>';
 3758:           if ($data eq 'type') {
 3759:               unless ($showsurv) {
 3760:                   my $id = join(',',@parts);
 3761:                   $typeparts{$ign.'.'.$id} = $lasthash{$key};
 3762:                   if (($lasthash{$key} eq 'anonsurvey') || ($lasthash{$key} eq 'anonsurveycred')) {
 3763:                       $lasthidden{$ign.'.'.$id} = 1;
 3764:                   }
 3765:               }
 3766:           } 
 3767: 	} else {
 3768: 	  if ($#parts == 0) {
 3769: 	    $prevattempts.='<th>'.$parts[0].'</th>';
 3770: 	  } else {
 3771: 	    $prevattempts.='<th>'.$ign.'</th>';
 3772: 	  }
 3773: 	}
 3774:       }
 3775:       $prevattempts.=&end_data_table_header_row();
 3776:       if ($getattempt eq '') {
 3777: 	for ($version=1;$version<=$returnhash{'version'};$version++) {
 3778:             my @hidden;
 3779:             if (%typeparts) {
 3780:                 foreach my $id (keys(%typeparts)) {
 3781:                     if (($returnhash{$version.':'.$id.'.type'} eq 'anonsurvey') || ($returnhash{$version.':'.$id.'.type'} eq 'anonsurveycred')) {
 3782:                         push(@hidden,$id);
 3783:                     }
 3784:                 }
 3785:             }
 3786:             $prevattempts.=&start_data_table_row().
 3787:                            '<td>'.&mt('Transaction [_1]',$version).'</td>';
 3788:             if (@hidden) {
 3789:                 foreach my $key (sort(keys(%lasthash))) {
 3790:                     next if ($key =~ /\.foilorder$/);
 3791:                     my $hide;
 3792:                     foreach my $id (@hidden) {
 3793:                         if ($key =~ /^\Q$id\E/) {
 3794:                             $hide = 1;
 3795:                             last;
 3796:                         }
 3797:                     }
 3798:                     if ($hide) {
 3799:                         my ($id,$data) = ($key =~ /^(.+)\.([^.]+)$/);
 3800:                         if (($data eq 'award') || ($data eq 'awarddetail')) {
 3801:                             my $value = &format_previous_attempt_value($key,
 3802:                                              $returnhash{$version.':'.$key});
 3803:                             $prevattempts.='<td>'.$value.'&nbsp;</td>';
 3804:                         } else {
 3805:                             $prevattempts.='<td>&nbsp;</td>';
 3806:                         }
 3807:                     } else {
 3808:                         if ($key =~ /\./) {
 3809:                             my $value = &format_previous_attempt_value($key,
 3810:                                               $returnhash{$version.':'.$key});
 3811:                             $prevattempts.='<td>'.$value.'&nbsp;</td>';
 3812:                         } else {
 3813:                             $prevattempts.='<td>&nbsp;</td>';
 3814:                         }
 3815:                     }
 3816:                 }
 3817:             } else {
 3818: 	        foreach my $key (sort(keys(%lasthash))) {
 3819:                     next if ($key =~ /\.foilorder$/);
 3820: 		    my $value = &format_previous_attempt_value($key,
 3821: 			            $returnhash{$version.':'.$key});
 3822: 		    $prevattempts.='<td>'.$value.'&nbsp;</td>';
 3823: 	        }
 3824:             }
 3825: 	    $prevattempts.=&end_data_table_row();
 3826: 	 }
 3827:       }
 3828:       my @currhidden = keys(%lasthidden);
 3829:       $prevattempts.=&start_data_table_row().'<td>'.&mt('Current').'</td>';
 3830:       foreach my $key (sort(keys(%lasthash))) {
 3831:           next if ($key =~ /\.foilorder$/);
 3832:           if (%typeparts) {
 3833:               my $hidden;
 3834:               foreach my $id (@currhidden) {
 3835:                   if ($key =~ /^\Q$id\E/) {
 3836:                       $hidden = 1;
 3837:                       last;
 3838:                   }
 3839:               }
 3840:               if ($hidden) {
 3841:                   my ($id,$data) = ($key =~ /^(.+)\.([^.]+)$/);
 3842:                   if (($data eq 'award') || ($data eq 'awarddetail')) {
 3843:                       my $value = &format_previous_attempt_value($key,$lasthash{$key});
 3844:                       if ($key =~/$regexp$/ && (defined &$gradesub)) {
 3845:                           $value = &$gradesub($value);
 3846:                       }
 3847:                       $prevattempts.='<td>'.$value.'&nbsp;</td>';
 3848:                   } else {
 3849:                       $prevattempts.='<td>&nbsp;</td>';
 3850:                   }
 3851:               } else {
 3852:                   my $value = &format_previous_attempt_value($key,$lasthash{$key});
 3853:                   if ($key =~/$regexp$/ && (defined &$gradesub)) {
 3854:                       $value = &$gradesub($value);
 3855:                   }
 3856:                   $prevattempts.='<td>'.$value.'&nbsp;</td>';
 3857:               }
 3858:           } else {
 3859: 	      my $value = &format_previous_attempt_value($key,$lasthash{$key});
 3860: 	      if ($key =~/$regexp$/ && (defined &$gradesub)) {
 3861:                   $value = &$gradesub($value);
 3862:               }
 3863: 	      $prevattempts.='<td>'.$value.'&nbsp;</td>';
 3864:           }
 3865:       }
 3866:       $prevattempts.= &end_data_table_row().&end_data_table();
 3867:     } else {
 3868:       $prevattempts=
 3869: 	  &start_data_table().&start_data_table_row().
 3870: 	  '<td>'.&mt('Nothing submitted - no attempts.').'</td>'.
 3871: 	  &end_data_table_row().&end_data_table();
 3872:     }
 3873:   } else {
 3874:     $prevattempts=
 3875: 	  &start_data_table().&start_data_table_row().
 3876: 	  '<td>'.&mt('No data.').'</td>'.
 3877: 	  &end_data_table_row().&end_data_table();
 3878:   }
 3879: }
 3880: 
 3881: sub format_previous_attempt_value {
 3882:     my ($key,$value) = @_;
 3883:     if (($key =~ /timestamp/) || ($key=~/duedate/)) {
 3884: 	$value = &Apache::lonlocal::locallocaltime($value);
 3885:     } elsif (ref($value) eq 'ARRAY') {
 3886: 	$value = '('.join(', ', @{ $value }).')';
 3887:     } elsif ($key =~ /answerstring$/) {
 3888:         my %answers = &Apache::lonnet::str2hash($value);
 3889:         my @anskeys = sort(keys(%answers));
 3890:         if (@anskeys == 1) {
 3891:             my $answer = $answers{$anskeys[0]};
 3892:             if ($answer =~ m{\0}) {
 3893:                 $answer =~ s{\0}{,}g;
 3894:             }
 3895:             my $tag_internal_answer_name = 'INTERNAL';
 3896:             if ($anskeys[0] eq $tag_internal_answer_name) {
 3897:                 $value = $answer; 
 3898:             } else {
 3899:                 $value = $anskeys[0].'='.$answer;
 3900:             }
 3901:         } else {
 3902:             foreach my $ans (@anskeys) {
 3903:                 my $answer = $answers{$ans};
 3904:                 if ($answer =~ m{\0}) {
 3905:                     $answer =~ s{\0}{,}g;
 3906:                 }
 3907:                 $value .=  $ans.'='.$answer.'<br />';;
 3908:             } 
 3909:         }
 3910:     } else {
 3911: 	$value = &unescape($value);
 3912:     }
 3913:     return $value;
 3914: }
 3915: 
 3916: 
 3917: sub relative_to_absolute {
 3918:     my ($url,$output)=@_;
 3919:     my $parser=HTML::TokeParser->new(\$output);
 3920:     my $token;
 3921:     my $thisdir=$url;
 3922:     my @rlinks=();
 3923:     while ($token=$parser->get_token) {
 3924: 	if ($token->[0] eq 'S') {
 3925: 	    if ($token->[1] eq 'a') {
 3926: 		if ($token->[2]->{'href'}) {
 3927: 		    $rlinks[$#rlinks+1]=$token->[2]->{'href'};
 3928: 		}
 3929: 	    } elsif ($token->[1] eq 'img' || $token->[1] eq 'embed' ) {
 3930: 		$rlinks[$#rlinks+1]=$token->[2]->{'src'};
 3931: 	    } elsif ($token->[1] eq 'base') {
 3932: 		$thisdir=$token->[2]->{'href'};
 3933: 	    }
 3934: 	}
 3935:     }
 3936:     $thisdir=~s-/[^/]*$--;
 3937:     foreach my $link (@rlinks) {
 3938: 	unless (($link=~/^https?\:\/\//i) ||
 3939: 		($link=~/^\//) ||
 3940: 		($link=~/^javascript:/i) ||
 3941: 		($link=~/^mailto:/i) ||
 3942: 		($link=~/^\#/)) {
 3943: 	    my $newlocation=&Apache::lonnet::hreflocation($thisdir,$link);
 3944: 	    $output=~s/(\"|\'|\=\s*)\Q$link\E(\"|\'|\s|\>)/$1$newlocation$2/;
 3945: 	}
 3946:     }
 3947: # -------------------------------------------------- Deal with Applet codebases
 3948:     $output=~s/(\<applet[^\>]+)(codebase\=[^\S\>]+)*([^\>]*)\>/$1.($2?$2:' codebase="'.$thisdir.'"').$3.'>'/gei;
 3949:     return $output;
 3950: }
 3951: 
 3952: =pod
 3953: 
 3954: =item * &get_student_view()
 3955: 
 3956: show a snapshot of what student was looking at
 3957: 
 3958: =cut
 3959: 
 3960: sub get_student_view {
 3961:   my ($symb,$username,$domain,$courseid,$target,$moreenv) = @_;
 3962:   my ($map,$id,$feedurl) = &Apache::lonnet::decode_symb($symb);
 3963:   my (%form);
 3964:   my @elements=('symb','courseid','domain','username');
 3965:   foreach my $element (@elements) {
 3966:       $form{'grade_'.$element}=eval '$'.$element #'
 3967:   }
 3968:   if (defined($moreenv)) {
 3969:       %form=(%form,%{$moreenv});
 3970:   }
 3971:   if (defined($target)) { $form{'grade_target'} = $target; }
 3972:   $feedurl=&Apache::lonnet::clutter($feedurl);
 3973:   my ($userview,$response)=&Apache::lonnet::ssi_body($feedurl,%form);
 3974:   $userview=~s/\<body[^\>]*\>//gi;
 3975:   $userview=~s/\<\/body\>//gi;
 3976:   $userview=~s/\<html\>//gi;
 3977:   $userview=~s/\<\/html\>//gi;
 3978:   $userview=~s/\<head\>//gi;
 3979:   $userview=~s/\<\/head\>//gi;
 3980:   $userview=~s/action\s*\=/would_be_action\=/gi;
 3981:   $userview=&relative_to_absolute($feedurl,$userview);
 3982:   if (wantarray) {
 3983:      return ($userview,$response);
 3984:   } else {
 3985:      return $userview;
 3986:   }
 3987: }
 3988: 
 3989: sub get_student_view_with_retries {
 3990:   my ($symb,$retries,$username,$domain,$courseid,$target,$moreenv) = @_;
 3991: 
 3992:     my $ok = 0;                 # True if we got a good response.
 3993:     my $content;
 3994:     my $response;
 3995: 
 3996:     # Try to get the student_view done. within the retries count:
 3997:     
 3998:     do {
 3999:          ($content, $response) = &get_student_view($symb,$username,$domain,$courseid,$target,$moreenv);
 4000:          $ok      = $response->is_success;
 4001:          if (!$ok) {
 4002:             &Apache::lonnet::logthis("Failed get_student_view_with_retries on $symb: ".$response->is_success.', '.$response->code.', '.$response->message);
 4003:          }
 4004:          $retries--;
 4005:     } while (!$ok && ($retries > 0));
 4006:     
 4007:     if (!$ok) {
 4008:        $content = '';          # On error return an empty content.
 4009:     }
 4010:     if (wantarray) {
 4011:        return ($content, $response);
 4012:     } else {
 4013:        return $content;
 4014:     }
 4015: }
 4016: 
 4017: =pod
 4018: 
 4019: =item * &get_student_answers() 
 4020: 
 4021: show a snapshot of how student was answering problem
 4022: 
 4023: =cut
 4024: 
 4025: sub get_student_answers {
 4026:   my ($symb,$username,$domain,$courseid,%form) = @_;
 4027:   my ($map,$id,$feedurl) = &Apache::lonnet::decode_symb($symb);
 4028:   my (%moreenv);
 4029:   my @elements=('symb','courseid','domain','username');
 4030:   foreach my $element (@elements) {
 4031:     $moreenv{'grade_'.$element}=eval '$'.$element #'
 4032:   }
 4033:   $moreenv{'grade_target'}='answer';
 4034:   %moreenv=(%form,%moreenv);
 4035:   $feedurl = &Apache::lonnet::clutter($feedurl);
 4036:   my $userview=&Apache::lonnet::ssi($feedurl,%moreenv);
 4037:   return $userview;
 4038: }
 4039: 
 4040: =pod
 4041: 
 4042: =item * &submlink()
 4043: 
 4044: Inputs: $text $uname $udom $symb $target
 4045: 
 4046: Returns: A link to grades.pm such as to see the SUBM view of a student
 4047: 
 4048: =cut
 4049: 
 4050: ###############################################
 4051: sub submlink {
 4052:     my ($text,$uname,$udom,$symb,$target)=@_;
 4053:     if (!($uname && $udom)) {
 4054: 	(my $cursymb, my $courseid,$udom,$uname)=
 4055: 	    &Apache::lonnet::whichuser($symb);
 4056: 	if (!$symb) { $symb=$cursymb; }
 4057:     }
 4058:     if (!$symb) { $symb=&Apache::lonnet::symbread(); }
 4059:     $symb=&escape($symb);
 4060:     if ($target) { $target=" target=\"$target\""; }
 4061:     return
 4062:         '<a href="/adm/grades?command=submission'.
 4063:         '&amp;symb='.$symb.
 4064:         '&amp;student='.$uname.
 4065:         '&amp;userdom='.$udom.'"'.
 4066:         $target.'>'.$text.'</a>';
 4067: }
 4068: ##############################################
 4069: 
 4070: =pod
 4071: 
 4072: =item * &pgrdlink()
 4073: 
 4074: Inputs: $text $uname $udom $symb $target
 4075: 
 4076: Returns: A link to grades.pm such as to see the PGRD view of a student
 4077: 
 4078: =cut
 4079: 
 4080: ###############################################
 4081: sub pgrdlink {
 4082:     my $link=&submlink(@_);
 4083:     $link=~s/(&command=submission)/$1&showgrading=yes/;
 4084:     return $link;
 4085: }
 4086: ##############################################
 4087: 
 4088: =pod
 4089: 
 4090: =item * &pprmlink()
 4091: 
 4092: Inputs: $text $uname $udom $symb $target
 4093: 
 4094: Returns: A link to parmset.pm such as to see the PPRM view of a
 4095: student and a specific resource
 4096: 
 4097: =cut
 4098: 
 4099: ###############################################
 4100: sub pprmlink {
 4101:     my ($text,$uname,$udom,$symb,$target)=@_;
 4102:     if (!($uname && $udom)) {
 4103: 	(my $cursymb, my $courseid,$udom,$uname)=
 4104: 	    &Apache::lonnet::whichuser($symb);
 4105: 	if (!$symb) { $symb=$cursymb; }
 4106:     }
 4107:     if (!$symb) { $symb=&Apache::lonnet::symbread(); }
 4108:     $symb=&escape($symb);
 4109:     if ($target) { $target="target=\"$target\""; }
 4110:     return '<a href="/adm/parmset?command=set&amp;'.
 4111: 	'symb='.$symb.'&amp;uname='.$uname.
 4112: 	'&amp;udom='.$udom.'" '.$target.'>'.$text.'</a>';
 4113: }
 4114: ##############################################
 4115: 
 4116: =pod
 4117: 
 4118: =back
 4119: 
 4120: =cut
 4121: 
 4122: ###############################################
 4123: 
 4124: 
 4125: sub timehash {
 4126:     my ($thistime) = @_;
 4127:     my $timezone = &Apache::lonlocal::gettimezone();
 4128:     my $dt = DateTime->from_epoch(epoch => $thistime)
 4129:                      ->set_time_zone($timezone);
 4130:     my $wday = $dt->day_of_week();
 4131:     if ($wday == 7) { $wday = 0; }
 4132:     return ( 'second' => $dt->second(),
 4133:              'minute' => $dt->minute(),
 4134:              'hour'   => $dt->hour(),
 4135:              'day'     => $dt->day_of_month(),
 4136:              'month'   => $dt->month(),
 4137:              'year'    => $dt->year(),
 4138:              'weekday' => $wday,
 4139:              'dayyear' => $dt->day_of_year(),
 4140:              'dlsav'   => $dt->is_dst() );
 4141: }
 4142: 
 4143: sub utc_string {
 4144:     my ($date)=@_;
 4145:     return strftime("%Y%m%dT%H%M%SZ",gmtime($date));
 4146: }
 4147: 
 4148: sub maketime {
 4149:     my %th=@_;
 4150:     my ($epoch_time,$timezone,$dt);
 4151:     $timezone = &Apache::lonlocal::gettimezone();
 4152:     eval {
 4153:         $dt = DateTime->new( year   => $th{'year'},
 4154:                              month  => $th{'month'},
 4155:                              day    => $th{'day'},
 4156:                              hour   => $th{'hour'},
 4157:                              minute => $th{'minute'},
 4158:                              second => $th{'second'},
 4159:                              time_zone => $timezone,
 4160:                          );
 4161:     };
 4162:     if (!$@) {
 4163:         $epoch_time = $dt->epoch;
 4164:         if ($epoch_time) {
 4165:             return $epoch_time;
 4166:         }
 4167:     }
 4168:     return POSIX::mktime(
 4169:         ($th{'seconds'},$th{'minutes'},$th{'hours'},
 4170:          $th{'day'},$th{'month'}-1,$th{'year'}-1900,0,0,-1));
 4171: }
 4172: 
 4173: #########################################
 4174: 
 4175: sub findallcourses {
 4176:     my ($roles,$uname,$udom) = @_;
 4177:     my %roles;
 4178:     if (ref($roles)) { %roles = map { $_ => 1 } @{$roles}; }
 4179:     my %courses;
 4180:     my $now=time;
 4181:     if (!defined($uname)) {
 4182:         $uname = $env{'user.name'};
 4183:     }
 4184:     if (!defined($udom)) {
 4185:         $udom = $env{'user.domain'};
 4186:     }
 4187:     if (($uname ne $env{'user.name'}) || ($udom ne $env{'user.domain'})) {
 4188:         my %roleshash = &Apache::lonnet::dump('roles',$udom,$uname);
 4189:         if (!%roles) {
 4190:             %roles = (
 4191:                        cc => 1,
 4192:                        co => 1,
 4193:                        in => 1,
 4194:                        ep => 1,
 4195:                        ta => 1,
 4196:                        cr => 1,
 4197:                        st => 1,
 4198:              );
 4199:         }
 4200:         foreach my $entry (keys(%roleshash)) {
 4201:             my ($trole,$tend,$tstart) = split(/_/,$roleshash{$entry});
 4202:             if ($trole =~ /^cr/) { 
 4203:                 next if (!exists($roles{$trole}) && !exists($roles{'cr'}));
 4204:             } else {
 4205:                 next if (!exists($roles{$trole}));
 4206:             }
 4207:             if ($tend) {
 4208:                 next if ($tend < $now);
 4209:             }
 4210:             if ($tstart) {
 4211:                 next if ($tstart > $now);
 4212:             }
 4213:             my ($cdom,$cnum,$sec,$cnumpart,$secpart,$role);
 4214:             (undef,$cdom,$cnumpart,$secpart) = split(/\//,$entry);
 4215:             my $value = $trole.'/'.$cdom.'/';
 4216:             if ($secpart eq '') {
 4217:                 ($cnum,$role) = split(/_/,$cnumpart); 
 4218:                 $sec = 'none';
 4219:                 $value .= $cnum.'/';
 4220:             } else {
 4221:                 $cnum = $cnumpart;
 4222:                 ($sec,$role) = split(/_/,$secpart);
 4223:                 $value .= $cnum.'/'.$sec;
 4224:             }
 4225:             if (ref($courses{$cdom.'_'.$cnum}{$sec}) eq 'ARRAY') {
 4226:                 unless (grep(/^\Q$value\E$/,@{$courses{$cdom.'_'.$cnum}{$sec}})) {
 4227:                     push(@{$courses{$cdom.'_'.$cnum}{$sec}},$value);
 4228:                 }
 4229:             } else {
 4230:                 @{$courses{$cdom.'_'.$cnum}{$sec}} = ($value);
 4231:             }
 4232:         }
 4233:     } else {
 4234:         foreach my $key (keys(%env)) {
 4235: 	    if ( $key=~m{^user\.role\.(\w+)\./($match_domain)/($match_courseid)/?(\w*)$} ||
 4236:                  $key=~m{^user\.role\.(cr/$match_domain/$match_username/\w+)\./($match_domain)/($match_courseid)/?(\w*)$}) {
 4237: 	        my ($role,$cdom,$cnum,$sec) = ($1,$2,$3,$4);
 4238: 	        next if ($role eq 'ca' || $role eq 'aa');
 4239: 	        next if (%roles && !exists($roles{$role}));
 4240: 	        my ($starttime,$endtime)=split(/\./,$env{$key});
 4241:                 my $active=1;
 4242:                 if ($starttime) {
 4243: 		    if ($now<$starttime) { $active=0; }
 4244:                 }
 4245:                 if ($endtime) {
 4246:                     if ($now>$endtime) { $active=0; }
 4247:                 }
 4248:                 if ($active) {
 4249:                     my $value = $role.'/'.$cdom.'/'.$cnum.'/';
 4250:                     if ($sec eq '') {
 4251:                         $sec = 'none';
 4252:                     } else {
 4253:                         $value .= $sec;
 4254:                     }
 4255:                     if (ref($courses{$cdom.'_'.$cnum}{$sec}) eq 'ARRAY') {
 4256:                         unless (grep(/^\Q$value\E$/,@{$courses{$cdom.'_'.$cnum}{$sec}})) {
 4257:                             push(@{$courses{$cdom.'_'.$cnum}{$sec}},$value);
 4258:                         }
 4259:                     } else {
 4260:                         @{$courses{$cdom.'_'.$cnum}{$sec}} = ($value);
 4261:                     }
 4262:                 }
 4263:             }
 4264:         }
 4265:     }
 4266:     return %courses;
 4267: }
 4268: 
 4269: ###############################################
 4270: 
 4271: sub blockcheck {
 4272:     my ($setters,$activity,$uname,$udom,$url) = @_;
 4273: 
 4274:     if (!defined($udom)) {
 4275:         $udom = $env{'user.domain'};
 4276:     }
 4277:     if (!defined($uname)) {
 4278:         $uname = $env{'user.name'};
 4279:     }
 4280: 
 4281:     # If uname and udom are for a course, check for blocks in the course.
 4282: 
 4283:     if (&Apache::lonnet::is_course($udom,$uname)) {
 4284:         my ($startblock,$endblock,$triggerblock) = 
 4285:             &get_blocks($setters,$activity,$udom,$uname,$url);
 4286:         return ($startblock,$endblock,$triggerblock);
 4287:     }
 4288: 
 4289:     my $startblock = 0;
 4290:     my $endblock = 0;
 4291:     my $triggerblock = '';
 4292:     my %live_courses = &findallcourses(undef,$uname,$udom);
 4293: 
 4294:     # If uname is for a user, and activity is course-specific, i.e.,
 4295:     # boards, chat or groups, check for blocking in current course only.
 4296: 
 4297:     if (($activity eq 'boards' || $activity eq 'chat' ||
 4298:          $activity eq 'groups') && ($env{'request.course.id'})) {
 4299:         foreach my $key (keys(%live_courses)) {
 4300:             if ($key ne $env{'request.course.id'}) {
 4301:                 delete($live_courses{$key});
 4302:             }
 4303:         }
 4304:     }
 4305: 
 4306:     my $otheruser = 0;
 4307:     my %own_courses;
 4308:     if ((($uname ne $env{'user.name'})) || ($udom ne $env{'user.domain'})) {
 4309:         # Resource belongs to user other than current user.
 4310:         $otheruser = 1;
 4311:         # Gather courses for current user
 4312:         %own_courses = 
 4313:             &findallcourses(undef,$env{'user.name'},$env{'user.domain'});
 4314:     }
 4315: 
 4316:     # Gather active course roles - course coordinator, instructor, 
 4317:     # exam proctor, ta, student, or custom role.
 4318: 
 4319:     foreach my $course (keys(%live_courses)) {
 4320:         my ($cdom,$cnum);
 4321:         if ((defined($env{'course.'.$course.'.domain'})) && (defined($env{'course.'.$course.'.num'}))) {
 4322:             $cdom = $env{'course.'.$course.'.domain'};
 4323:             $cnum = $env{'course.'.$course.'.num'};
 4324:         } else {
 4325:             ($cdom,$cnum) = split(/_/,$course); 
 4326:         }
 4327:         my $no_ownblock = 0;
 4328:         my $no_userblock = 0;
 4329:         if ($otheruser && $activity ne 'com') {
 4330:             # Check if current user has 'evb' priv for this
 4331:             if (defined($own_courses{$course})) {
 4332:                 foreach my $sec (keys(%{$own_courses{$course}})) {
 4333:                     my $checkrole = 'cm./'.$cdom.'/'.$cnum;
 4334:                     if ($sec ne 'none') {
 4335:                         $checkrole .= '/'.$sec;
 4336:                     }
 4337:                     if (&Apache::lonnet::allowed('evb',undef,undef,$checkrole)) {
 4338:                         $no_ownblock = 1;
 4339:                         last;
 4340:                     }
 4341:                 }
 4342:             }
 4343:             # if they have 'evb' priv and are currently not playing student
 4344:             next if (($no_ownblock) &&
 4345:                  ($env{'request.role'} !~ m{^st\./$cdom/$cnum}));
 4346:         }
 4347:         foreach my $sec (keys(%{$live_courses{$course}})) {
 4348:             my $checkrole = 'cm./'.$cdom.'/'.$cnum;
 4349:             if ($sec ne 'none') {
 4350:                 $checkrole .= '/'.$sec;
 4351:             }
 4352:             if ($otheruser) {
 4353:                 # Resource belongs to user other than current user.
 4354:                 # Assemble privs for that user, and check for 'evb' priv.
 4355:                 my (%allroles,%userroles);
 4356:                 if (ref($live_courses{$course}{$sec}) eq 'ARRAY') {
 4357:                     foreach my $entry (@{$live_courses{$course}{$sec}}) { 
 4358:                         my ($trole,$tdom,$tnum,$tsec);
 4359:                         if ($entry =~ /^cr/) {
 4360:                             ($trole,$tdom,$tnum,$tsec) = 
 4361:                                 ($entry =~ m|^(cr/$match_domain/$match_username/\w+)\./($match_domain)/($match_username)/?(\w*)$|);
 4362:                         } else {
 4363:                            ($trole,$tdom,$tnum,$tsec) = split(/\//,$entry);
 4364:                         }
 4365:                         my ($spec,$area,$trest);
 4366:                         $area = '/'.$tdom.'/'.$tnum;
 4367:                         $trest = $tnum;
 4368:                         if ($tsec ne '') {
 4369:                             $area .= '/'.$tsec;
 4370:                             $trest .= '/'.$tsec;
 4371:                         }
 4372:                         $spec = $trole.'.'.$area;
 4373:                         if ($trole =~ /^cr/) {
 4374:                             &Apache::lonnet::custom_roleprivs(\%allroles,$trole,
 4375:                                                               $tdom,$spec,$trest,$area);
 4376:                         } else {
 4377:                             &Apache::lonnet::standard_roleprivs(\%allroles,$trole,
 4378:                                                                 $tdom,$spec,$trest,$area);
 4379:                         }
 4380:                     }
 4381:                     my ($author,$adv) = &Apache::lonnet::set_userprivs(\%userroles,\%allroles);
 4382:                     if ($userroles{'user.priv.'.$checkrole} =~ /evb\&([^\:]*)/) {
 4383:                         if ($1) {
 4384:                             $no_userblock = 1;
 4385:                             last;
 4386:                         }
 4387:                     }
 4388:                 }
 4389:             } else {
 4390:                 # Resource belongs to current user
 4391:                 # Check for 'evb' priv via lonnet::allowed().
 4392:                 if (&Apache::lonnet::allowed('evb',undef,undef,$checkrole)) {
 4393:                     $no_ownblock = 1;
 4394:                     last;
 4395:                 }
 4396:             }
 4397:         }
 4398:         # if they have the evb priv and are currently not playing student
 4399:         next if (($no_ownblock) &&
 4400:                  ($env{'request.role'} !~ m{^st\./\Q$cdom\E/\Q$cnum\E}));
 4401:         next if ($no_userblock);
 4402: 
 4403:         # Retrieve blocking times and identity of locker for course
 4404:         # of specified user, unless user has 'evb' privilege.
 4405:         
 4406:         my ($start,$end,$trigger) = 
 4407:             &get_blocks($setters,$activity,$cdom,$cnum,$url);
 4408:         if (($start != 0) && 
 4409:             (($startblock == 0) || ($startblock > $start))) {
 4410:             $startblock = $start;
 4411:             if ($trigger ne '') {
 4412:                 $triggerblock = $trigger;
 4413:             }
 4414:         }
 4415:         if (($end != 0)  &&
 4416:             (($endblock == 0) || ($endblock < $end))) {
 4417:             $endblock = $end;
 4418:             if ($trigger ne '') {
 4419:                 $triggerblock = $trigger;
 4420:             }
 4421:         }
 4422:     }
 4423:     return ($startblock,$endblock,$triggerblock);
 4424: }
 4425: 
 4426: sub get_blocks {
 4427:     my ($setters,$activity,$cdom,$cnum,$url) = @_;
 4428:     my $startblock = 0;
 4429:     my $endblock = 0;
 4430:     my $triggerblock = '';
 4431:     my $course = $cdom.'_'.$cnum;
 4432:     $setters->{$course} = {};
 4433:     $setters->{$course}{'staff'} = [];
 4434:     $setters->{$course}{'times'} = [];
 4435:     $setters->{$course}{'triggers'} = [];
 4436:     my (@blockers,%triggered);
 4437:     my $now = time;
 4438:     my %commblocks = &Apache::lonnet::get_comm_blocks($cdom,$cnum);
 4439:     if ($activity eq 'docs') {
 4440:         @blockers = &Apache::lonnet::has_comm_blocking('bre',undef,$url,\%commblocks);
 4441:         foreach my $block (@blockers) {
 4442:             if ($block =~ /^firstaccess____(.+)$/) {
 4443:                 my $item = $1;
 4444:                 my $type = 'map';
 4445:                 my $timersymb = $item;
 4446:                 if ($item eq 'course') {
 4447:                     $type = 'course';
 4448:                 } elsif ($item =~ /___\d+___/) {
 4449:                     $type = 'resource';
 4450:                 } else {
 4451:                     $timersymb = &Apache::lonnet::symbread($item);
 4452:                 }
 4453:                 my $start = $env{'course.'.$cdom.'_'.$cnum.'.firstaccess.'.$timersymb};
 4454:                 my $end = $start + $env{'course.'.$cdom.'_'.$cnum.'.timerinterval.'.$timersymb};
 4455:                 $triggered{$block} = {
 4456:                                        start => $start,
 4457:                                        end   => $end,
 4458:                                        type  => $type,
 4459:                                      };
 4460:             }
 4461:         }
 4462:     } else {
 4463:         foreach my $block (keys(%commblocks)) {
 4464:             if ($block =~ m/^(\d+)____(\d+)$/) { 
 4465:                 my ($start,$end) = ($1,$2);
 4466:                 if ($start <= time && $end >= time) {
 4467:                     if (ref($commblocks{$block}) eq 'HASH') {
 4468:                         if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
 4469:                             if ($commblocks{$block}{'blocks'}{$activity} eq 'on') {
 4470:                                 unless(grep(/^\Q$block\E$/,@blockers)) {
 4471:                                     push(@blockers,$block);
 4472:                                 }
 4473:                             }
 4474:                         }
 4475:                     }
 4476:                 }
 4477:             } elsif ($block =~ /^firstaccess____(.+)$/) {
 4478:                 my $item = $1;
 4479:                 my $timersymb = $item; 
 4480:                 my $type = 'map';
 4481:                 if ($item eq 'course') {
 4482:                     $type = 'course';
 4483:                 } elsif ($item =~ /___\d+___/) {
 4484:                     $type = 'resource';
 4485:                 } else {
 4486:                     $timersymb = &Apache::lonnet::symbread($item);
 4487:                 }
 4488:                 my $start = $env{'course.'.$cdom.'_'.$cnum.'.firstaccess.'.$timersymb};
 4489:                 my $end = $start + $env{'course.'.$cdom.'_'.$cnum.'.timerinterval.'.$timersymb}; 
 4490:                 if ($start && $end) {
 4491:                     if (($start <= time) && ($end >= time)) {
 4492:                         unless (grep(/^\Q$block\E$/,@blockers)) {
 4493:                             push(@blockers,$block);
 4494:                             $triggered{$block} = {
 4495:                                                    start => $start,
 4496:                                                    end   => $end,
 4497:                                                    type  => $type,
 4498:                                                  };
 4499:                         }
 4500:                     }
 4501:                 }
 4502:             }
 4503:         }
 4504:     }
 4505:     foreach my $blocker (@blockers) {
 4506:         my ($staff_name,$staff_dom,$title,$blocks) =
 4507:             &parse_block_record($commblocks{$blocker});
 4508:         push(@{$$setters{$course}{'staff'}},[$staff_name,$staff_dom]);
 4509:         my ($start,$end,$triggertype);
 4510:         if ($blocker =~ m/^(\d+)____(\d+)$/) {
 4511:             ($start,$end) = ($1,$2);
 4512:         } elsif (ref($triggered{$blocker}) eq 'HASH') {
 4513:             $start = $triggered{$blocker}{'start'};
 4514:             $end = $triggered{$blocker}{'end'};
 4515:             $triggertype = $triggered{$blocker}{'type'};
 4516:         }
 4517:         if ($start) {
 4518:             push(@{$$setters{$course}{'times'}}, [$start,$end]);
 4519:             if ($triggertype) {
 4520:                 push(@{$$setters{$course}{'triggers'}},$triggertype);
 4521:             } else {
 4522:                 push(@{$$setters{$course}{'triggers'}},0);
 4523:             }
 4524:             if ( ($startblock == 0) || ($startblock > $start) ) {
 4525:                 $startblock = $start;
 4526:                 if ($triggertype) {
 4527:                     $triggerblock = $blocker;
 4528:                 }
 4529:             }
 4530:             if ( ($endblock == 0) || ($endblock < $end) ) {
 4531:                $endblock = $end;
 4532:                if ($triggertype) {
 4533:                    $triggerblock = $blocker;
 4534:                }
 4535:             }
 4536:         }
 4537:     }
 4538:     return ($startblock,$endblock,$triggerblock);
 4539: }
 4540: 
 4541: sub parse_block_record {
 4542:     my ($record) = @_;
 4543:     my ($setuname,$setudom,$title,$blocks);
 4544:     if (ref($record) eq 'HASH') {
 4545:         ($setuname,$setudom) = split(/:/,$record->{'setter'});
 4546:         $title = &unescape($record->{'event'});
 4547:         $blocks = $record->{'blocks'};
 4548:     } else {
 4549:         my @data = split(/:/,$record,3);
 4550:         if (scalar(@data) eq 2) {
 4551:             $title = $data[1];
 4552:             ($setuname,$setudom) = split(/@/,$data[0]);
 4553:         } else {
 4554:             ($setuname,$setudom,$title) = @data;
 4555:         }
 4556:         $blocks = { 'com' => 'on' };
 4557:     }
 4558:     return ($setuname,$setudom,$title,$blocks);
 4559: }
 4560: 
 4561: sub blocking_status {
 4562:     my ($activity,$uname,$udom,$url) = @_;
 4563:     my %setters;
 4564: 
 4565: # check for active blocking
 4566:     my ($startblock,$endblock,$triggerblock) = 
 4567:         &blockcheck(\%setters,$activity,$uname,$udom,$url);
 4568:     my $blocked = 0;
 4569:     if ($startblock && $endblock) {
 4570:         $blocked = 1;
 4571:     }
 4572: 
 4573: # caller just wants to know whether a block is active
 4574:     if (!wantarray) { return $blocked; }
 4575: 
 4576: # build a link to a popup window containing the details
 4577:     my $querystring  = "?activity=$activity";
 4578: # $uname and $udom decide whose portfolio the user is trying to look at
 4579:     if ($activity eq 'port') {
 4580:         $querystring .= "&amp;udom=$udom"      if $udom;
 4581:         $querystring .= "&amp;uname=$uname"    if $uname;
 4582:     } elsif ($activity eq 'docs') {
 4583:         $querystring .= '&amp;url='.&HTML::Entities::encode($url,'&"');
 4584:     }
 4585: 
 4586:     my $output .= <<'END_MYBLOCK';
 4587: function openWindow(url, wdwName, w, h, toolbar,scrollbar) {
 4588:     var options = "width=" + w + ",height=" + h + ",";
 4589:     options += "resizable=yes,scrollbars="+scrollbar+",status=no,";
 4590:     options += "menubar=no,toolbar="+toolbar+",location=no,directories=no";
 4591:     var newWin = window.open(url, wdwName, options);
 4592:     newWin.focus();
 4593: }
 4594: END_MYBLOCK
 4595: 
 4596:     $output = Apache::lonhtmlcommon::scripttag($output);
 4597:   
 4598:     my $popupUrl = "/adm/blockingstatus/$querystring";
 4599:     my $text = &mt('Communication Blocked');
 4600:     if ($activity eq 'docs') {
 4601:         $text = &mt('Content Access Blocked');
 4602:     } elsif ($activity eq 'printout') {
 4603:         $text = &mt('Printing Blocked');
 4604:     }
 4605:     $output .= <<"END_BLOCK";
 4606: <div class='LC_comblock'>
 4607:   <a onclick='openWindow("$popupUrl","Blocking Table",600,300,"no","no");return false;' href='/adm/blockingstatus/$querystring'
 4608:   title='$text'>
 4609:   <img class='LC_noBorder LC_middle' title='$text' src='/res/adm/pages/comblock.png' alt='$text'/></a>
 4610:   <a onclick='openWindow("$popupUrl","Blocking Table",600,300,"no","no");return false;' href='/adm/blockingstatus/$querystring' 
 4611:   title='$text'>$text</a>
 4612: </div>
 4613: 
 4614: END_BLOCK
 4615: 
 4616:     return ($blocked, $output);
 4617: }
 4618: 
 4619: ###############################################
 4620: 
 4621: sub check_ip_acc {
 4622:     my ($acc)=@_;
 4623:     &Apache::lonxml::debug("acc is $acc");
 4624:     if (!defined($acc) || $acc =~ /^\s*$/ || $acc =~/^\s*no\s*$/i) {
 4625:         return 1;
 4626:     }
 4627:     my $allowed=0;
 4628:     my $ip=$env{'request.host'} || $ENV{'REMOTE_ADDR'};
 4629: 
 4630:     my $name;
 4631:     foreach my $pattern (split(',',$acc)) {
 4632:         $pattern =~ s/^\s*//;
 4633:         $pattern =~ s/\s*$//;
 4634:         if ($pattern =~ /\*$/) {
 4635:             #35.8.*
 4636:             $pattern=~s/\*//;
 4637:             if ($ip =~ /^\Q$pattern\E/) { $allowed=1; }
 4638:         } elsif ($pattern =~ /(\d+\.\d+\.\d+)\.\[(\d+)-(\d+)\]$/) {
 4639:             #35.8.3.[34-56]
 4640:             my $low=$2;
 4641:             my $high=$3;
 4642:             $pattern=$1;
 4643:             if ($ip =~ /^\Q$pattern\E/) {
 4644:                 my $last=(split(/\./,$ip))[3];
 4645:                 if ($last <=$high && $last >=$low) { $allowed=1; }
 4646:             }
 4647:         } elsif ($pattern =~ /^\*/) {
 4648:             #*.msu.edu
 4649:             $pattern=~s/\*//;
 4650:             if (!defined($name)) {
 4651:                 use Socket;
 4652:                 my $netaddr=inet_aton($ip);
 4653:                 ($name)=gethostbyaddr($netaddr,AF_INET);
 4654:             }
 4655:             if ($name =~ /\Q$pattern\E$/i) { $allowed=1; }
 4656:         } elsif ($pattern =~ /\d+\.\d+\.\d+\.\d+/) {
 4657:             #127.0.0.1
 4658:             if ($ip =~ /^\Q$pattern\E/) { $allowed=1; }
 4659:         } else {
 4660:             #some.name.com
 4661:             if (!defined($name)) {
 4662:                 use Socket;
 4663:                 my $netaddr=inet_aton($ip);
 4664:                 ($name)=gethostbyaddr($netaddr,AF_INET);
 4665:             }
 4666:             if ($name =~ /\Q$pattern\E$/i) { $allowed=1; }
 4667:         }
 4668:         if ($allowed) { last; }
 4669:     }
 4670:     return $allowed;
 4671: }
 4672: 
 4673: ###############################################
 4674: 
 4675: =pod
 4676: 
 4677: =head1 Domain Template Functions
 4678: 
 4679: =over 4
 4680: 
 4681: =item * &determinedomain()
 4682: 
 4683: Inputs: $domain (usually will be undef)
 4684: 
 4685: Returns: Determines which domain should be used for designs
 4686: 
 4687: =cut
 4688: 
 4689: ###############################################
 4690: sub determinedomain {
 4691:     my $domain=shift;
 4692:     if (! $domain) {
 4693:         # Determine domain if we have not been given one
 4694:         $domain = &Apache::lonnet::default_login_domain();
 4695:         if ($env{'user.domain'}) { $domain=$env{'user.domain'}; }
 4696:         if ($env{'request.role.domain'}) { 
 4697:             $domain=$env{'request.role.domain'}; 
 4698:         }
 4699:     }
 4700:     return $domain;
 4701: }
 4702: ###############################################
 4703: 
 4704: sub devalidate_domconfig_cache {
 4705:     my ($udom)=@_;
 4706:     &Apache::lonnet::devalidate_cache_new('domainconfig',$udom);
 4707: }
 4708: 
 4709: # ---------------------- Get domain configuration for a domain
 4710: sub get_domainconf {
 4711:     my ($udom) = @_;
 4712:     my $cachetime=1800;
 4713:     my ($result,$cached)=&Apache::lonnet::is_cached_new('domainconfig',$udom);
 4714:     if (defined($cached)) { return %{$result}; }
 4715: 
 4716:     my %domconfig = &Apache::lonnet::get_dom('configuration',
 4717: 					     ['login','rolecolors','autoenroll'],$udom);
 4718:     my (%designhash,%legacy);
 4719:     if (keys(%domconfig) > 0) {
 4720:         if (ref($domconfig{'login'}) eq 'HASH') {
 4721:             if (keys(%{$domconfig{'login'}})) {
 4722:                 foreach my $key (keys(%{$domconfig{'login'}})) {
 4723:                     if (ref($domconfig{'login'}{$key}) eq 'HASH') {
 4724:                         if ($key eq 'loginvia') {
 4725:                             if (ref($domconfig{'login'}{'loginvia'}) eq 'HASH') {
 4726:                                 foreach my $hostname (keys(%{$domconfig{'login'}{'loginvia'}})) {
 4727:                                     if (ref($domconfig{'login'}{'loginvia'}{$hostname}) eq 'HASH') {
 4728:                                         if ($domconfig{'login'}{'loginvia'}{$hostname}{'server'}) {
 4729:                                             my $server = $domconfig{'login'}{'loginvia'}{$hostname}{'server'};
 4730:                                             $designhash{$udom.'.login.loginvia'} = $server;
 4731:                                             if ($domconfig{'login'}{'loginvia'}{$hostname}{'serverpath'} eq 'custom') {
 4732: 
 4733:                                                 $designhash{$udom.'.login.loginvia_'.$hostname} = $server.':'.$domconfig{'login'}{'loginvia'}{$hostname}{'custompath'};
 4734:                                             } else {
 4735:                                                 $designhash{$udom.'.login.loginvia_'.$hostname} = $server.':'.$domconfig{'login'}{'loginvia'}{$hostname}{'serverpath'};
 4736:                                             }
 4737:                                             if ($domconfig{'login'}{'loginvia'}{$hostname}{'exempt'}) {
 4738:                                                 $designhash{$udom.'.login.loginvia_exempt_'.$hostname} = $domconfig{'login'}{'loginvia'}{$hostname}{'exempt'};
 4739:                                             }
 4740:                                         }
 4741:                                     }
 4742:                                 }
 4743:                             }
 4744:                         } else {
 4745:                             foreach my $img (keys(%{$domconfig{'login'}{$key}})) {
 4746:                                 $designhash{$udom.'.login.'.$key.'_'.$img} = 
 4747:                                     $domconfig{'login'}{$key}{$img};
 4748:                             }
 4749:                         }
 4750:                     } else {
 4751:                         $designhash{$udom.'.login.'.$key}=$domconfig{'login'}{$key};
 4752:                     }
 4753:                 }
 4754:             } else {
 4755:                 $legacy{'login'} = 1;
 4756:             }
 4757:         } else {
 4758:             $legacy{'login'} = 1;
 4759:         }
 4760:         if (ref($domconfig{'rolecolors'}) eq 'HASH') {
 4761:             if (keys(%{$domconfig{'rolecolors'}})) {
 4762:                 foreach my $role (keys(%{$domconfig{'rolecolors'}})) {
 4763:                     if (ref($domconfig{'rolecolors'}{$role}) eq 'HASH') {
 4764:                         foreach my $item (keys(%{$domconfig{'rolecolors'}{$role}})) {
 4765:                             $designhash{$udom.'.'.$role.'.'.$item}=$domconfig{'rolecolors'}{$role}{$item};
 4766:                         }
 4767:                     }
 4768:                 }
 4769:             } else {
 4770:                 $legacy{'rolecolors'} = 1;
 4771:             }
 4772:         } else {
 4773:             $legacy{'rolecolors'} = 1;
 4774:         }
 4775:         if (ref($domconfig{'autoenroll'}) eq 'HASH') {
 4776:             if ($domconfig{'autoenroll'}{'co-owners'}) {
 4777:                 $designhash{$udom.'.autoassign.co-owners'}=$domconfig{'autoenroll'}{'co-owners'};
 4778:             }
 4779:         }
 4780:         if (keys(%legacy) > 0) {
 4781:             my %legacyhash = &get_legacy_domconf($udom);
 4782:             foreach my $item (keys(%legacyhash)) {
 4783:                 if ($item =~ /^\Q$udom\E\.login/) {
 4784:                     if ($legacy{'login'}) { 
 4785:                         $designhash{$item} = $legacyhash{$item};
 4786:                     }
 4787:                 } else {
 4788:                     if ($legacy{'rolecolors'}) {
 4789:                         $designhash{$item} = $legacyhash{$item};
 4790:                     }
 4791:                 }
 4792:             }
 4793:         }
 4794:     } else {
 4795:         %designhash = &get_legacy_domconf($udom); 
 4796:     }
 4797:     &Apache::lonnet::do_cache_new('domainconfig',$udom,\%designhash,
 4798: 				  $cachetime);
 4799:     return %designhash;
 4800: }
 4801: 
 4802: sub get_legacy_domconf {
 4803:     my ($udom) = @_;
 4804:     my %legacyhash;
 4805:     my $designdir=$Apache::lonnet::perlvar{'lonTabDir'}.'/lonDomColors';
 4806:     my $designfile =  $designdir.'/'.$udom.'.tab';
 4807:     if (-e $designfile) {
 4808:         if ( open (my $fh,"<$designfile") ) {
 4809:             while (my $line = <$fh>) {
 4810:                 next if ($line =~ /^\#/);
 4811:                 chomp($line);
 4812:                 my ($key,$val)=(split(/\=/,$line));
 4813:                 if ($val) { $legacyhash{$udom.'.'.$key}=$val; }
 4814:             }
 4815:             close($fh);
 4816:         }
 4817:     }
 4818:     if (-e $Apache::lonnet::perlvar{'lonDocRoot'}.'/adm/lonDomLogos/'.$udom.'.gif') {
 4819:         $legacyhash{$udom.'.login.domlogo'} = "/adm/lonDomLogos/$udom.gif";
 4820:     }
 4821:     return %legacyhash;
 4822: }
 4823: 
 4824: =pod
 4825: 
 4826: =item * &domainlogo()
 4827: 
 4828: Inputs: $domain (usually will be undef)
 4829: 
 4830: Returns: A link to a domain logo, if the domain logo exists.
 4831: If the domain logo does not exist, a description of the domain.
 4832: 
 4833: =cut
 4834: 
 4835: ###############################################
 4836: sub domainlogo {
 4837:     my $domain = &determinedomain(shift);
 4838:     my %designhash = &get_domainconf($domain);    
 4839:     # See if there is a logo
 4840:     if ($designhash{$domain.'.login.domlogo'} ne '') {
 4841:         my $imgsrc = $designhash{$domain.'.login.domlogo'};
 4842:         if ($imgsrc =~ m{^/(adm|res)/}) {
 4843: 	    if ($imgsrc =~ m{^/res/}) {
 4844: 		my $local_name = &Apache::lonnet::filelocation('',$imgsrc);
 4845: 		&Apache::lonnet::repcopy($local_name);
 4846: 	    }
 4847: 	   $imgsrc = &lonhttpdurl($imgsrc);
 4848:         } 
 4849:         return '<img src="'.$imgsrc.'" alt="'.$domain.'" />';
 4850:     } elsif (defined(&Apache::lonnet::domain($domain,'description'))) {
 4851:         return &Apache::lonnet::domain($domain,'description');
 4852:     } else {
 4853:         return '';
 4854:     }
 4855: }
 4856: ##############################################
 4857: 
 4858: =pod
 4859: 
 4860: =item * &designparm()
 4861: 
 4862: Inputs: $which parameter; $domain (usually will be undef)
 4863: 
 4864: Returns: value of designparamter $which
 4865: 
 4866: =cut
 4867: 
 4868: 
 4869: ##############################################
 4870: sub designparm {
 4871:     my ($which,$domain)=@_;
 4872:     if (exists($env{'environment.color.'.$which})) {
 4873:         return $env{'environment.color.'.$which};
 4874:     }
 4875:     $domain=&determinedomain($domain);
 4876:     my %domdesign;
 4877:     unless ($domain eq 'public') {
 4878:         %domdesign = &get_domainconf($domain);
 4879:     }
 4880:     my $output;
 4881:     if ($domdesign{$domain.'.'.$which} ne '') {
 4882:         $output = $domdesign{$domain.'.'.$which};
 4883:     } else {
 4884:         $output = $defaultdesign{$which};
 4885:     }
 4886:     if (($which =~ /^(student|coordinator|author|admin)\.img$/) ||
 4887:         ($which =~ /login\.(img|logo|domlogo|login)/)) {
 4888:         if ($output =~ m{^/(adm|res)/}) {
 4889:             if ($output =~ m{^/res/}) {
 4890:                 my $local_name = &Apache::lonnet::filelocation('',$output);
 4891:                 &Apache::lonnet::repcopy($local_name);
 4892:             }
 4893:             $output = &lonhttpdurl($output);
 4894:         }
 4895:     }
 4896:     return $output;
 4897: }
 4898: 
 4899: ##############################################
 4900: =pod
 4901: 
 4902: =item * &authorspace()
 4903: 
 4904: Inputs: $url (usually will be undef).
 4905: 
 4906: Returns: Path to Construction Space containing the resource or 
 4907:          directory being viewed (or for which action is being taken). 
 4908:          If $url is provided, and begins /priv/<domain>/<uname>
 4909:          the path will be that portion of the $context argument.
 4910:          Otherwise the path will be for the author space of the current
 4911:          user when the current role is author, or for that of the 
 4912:          co-author/assistant co-author space when the current role 
 4913:          is co-author or assistant co-author.
 4914: 
 4915: =cut
 4916: 
 4917: sub authorspace {
 4918:     my ($url) = @_;
 4919:     if ($url ne '') {
 4920:         if ($url =~ m{^(/priv/$match_domain/$match_username/)}) {
 4921:            return $1;
 4922:         }
 4923:     }
 4924:     my $caname = '';
 4925:     my $cadom = '';
 4926:     if ($env{'request.role'} =~ /^(?:ca|aa)/) {
 4927:         ($cadom,$caname) =
 4928:             ($env{'request.role'}=~/($match_domain)\/($match_username)$/);
 4929:     } elsif ($env{'request.role'} =~ m{^au\./($match_domain)/}) {
 4930:         $caname = $env{'user.name'};
 4931:         $cadom = $env{'user.domain'};
 4932:     }
 4933:     if (($caname ne '') && ($cadom ne '')) {
 4934:         return "/priv/$cadom/$caname/";
 4935:     }
 4936:     return;
 4937: }
 4938: 
 4939: ##############################################
 4940: =pod
 4941: 
 4942: =item * &head_subbox()
 4943: 
 4944: Inputs: $content (contains HTML code with page functions, etc.)
 4945: 
 4946: Returns: HTML div with $content
 4947:          To be included in page header
 4948: 
 4949: =cut
 4950: 
 4951: sub head_subbox {
 4952:     my ($content)=@_;
 4953:     my $output =
 4954:         '<div class="LC_head_subbox">'
 4955:        .$content
 4956:        .'</div>'
 4957: }
 4958: 
 4959: ##############################################
 4960: =pod
 4961: 
 4962: =item * &CSTR_pageheader()
 4963: 
 4964: Input: (optional) filename from which breadcrumb trail is built.
 4965:        In most cases no input as needed, as $env{'request.filename'}
 4966:        is appropriate for use in building the breadcrumb trail.
 4967: 
 4968: Returns: HTML div with CSTR path and recent box
 4969:          To be included on Construction Space pages
 4970: 
 4971: =cut
 4972: 
 4973: sub CSTR_pageheader {
 4974:     my ($trailfile) = @_;
 4975:     if ($trailfile eq '') {
 4976:         $trailfile = $env{'request.filename'};
 4977:     }
 4978: 
 4979: # this is for resources; directories have customtitle, and crumbs
 4980: # and select recent are created in lonpubdir.pm
 4981: 
 4982:     my $londocroot = $Apache::lonnet::perlvar{'lonDocRoot'};
 4983:     my ($udom,$uname,$thisdisfn)=
 4984:         ($trailfile =~ m{^\Q$londocroot\E/priv/([^/]+)/([^/]+)/(.*)$});
 4985:     my $formaction = "/priv/$udom/$uname/$thisdisfn";
 4986:     $formaction =~ s{/+}{/}g;
 4987: 
 4988:     my $parentpath = '';
 4989:     my $lastitem = '';
 4990:     if ($thisdisfn =~ m-(.+/)([^/]*)$-) {
 4991:         $parentpath = $1;
 4992:         $lastitem = $2;
 4993:     } else {
 4994:         $lastitem = $thisdisfn;
 4995:     }
 4996: 
 4997:     my $output =
 4998:          '<div>'
 4999:         .&Apache::loncommon::help_open_menu('','',3,'Authoring') #FIXME: Broken? Where is it?
 5000:         .'<b>'.&mt('Construction Space:').'</b> '
 5001:         .'<form name="dirs" method="post" action="'.$formaction
 5002:         .'" target="_top">' #FIXME lonpubdir: target="_parent"
 5003:         .&Apache::lonhtmlcommon::crumbs($uname.'/'.$parentpath,'_top','/priv/'.$udom,undef,undef);
 5004: 
 5005:     if ($lastitem) {
 5006:         $output .=
 5007:              '<span class="LC_filename">'
 5008:             .$lastitem
 5009:             .'</span>';
 5010:     }
 5011:     $output .=
 5012:          '<br />'
 5013:         #FIXME lonpubdir: &Apache::lonhtmlcommon::crumbs($uname.$thisdisfn.'/','_top','/priv','','+1',1)."</b></tt><br />"
 5014:         .&Apache::lonhtmlcommon::select_recent('construct','recent','this.form.action=this.form.recent.value;this.form.submit()')
 5015:         .'</form>'
 5016:         .&Apache::lonmenu::constspaceform()
 5017:         .'</div>';
 5018: 
 5019:     return $output;
 5020: }
 5021: 
 5022: ###############################################
 5023: ###############################################
 5024: 
 5025: =pod
 5026: 
 5027: =back
 5028: 
 5029: =head1 HTML Helpers
 5030: 
 5031: =over 4
 5032: 
 5033: =item * &bodytag()
 5034: 
 5035: Returns a uniform header for LON-CAPA web pages.
 5036: 
 5037: Inputs: 
 5038: 
 5039: =over 4
 5040: 
 5041: =item * $title, A title to be displayed on the page.
 5042: 
 5043: =item * $function, the current role (can be undef).
 5044: 
 5045: =item * $addentries, extra parameters for the <body> tag.
 5046: 
 5047: =item * $bodyonly, if defined, only return the <body> tag.
 5048: 
 5049: =item * $domain, if defined, force a given domain.
 5050: 
 5051: =item * $forcereg, if page should register as content page (relevant for 
 5052:             text interface only)
 5053: 
 5054: =item * $no_nav_bar, if true, keep the 'what is this' info but remove the
 5055:                      navigational links
 5056: 
 5057: =item * $bgcolor, used to override the bgcolor on a webpage to a specific value
 5058: 
 5059: =item * $args, optional argument valid values are
 5060:             no_auto_mt_title -> prevents &mt()ing the title arg
 5061:             inherit_jsmath -> when creating popup window in a page,
 5062:                               should it have jsmath forced on by the
 5063:                               current page
 5064: 
 5065: =item * $advtoolsref, optional argument, ref to an array containing
 5066:             inlineremote items to be added in "Functions" menu below
 5067:             breadcrumbs.
 5068: 
 5069: =back
 5070: 
 5071: Returns: A uniform header for LON-CAPA web pages.  
 5072: If $bodyonly is nonzero, a string containing a <body> tag will be returned.
 5073: If $bodyonly is undef or zero, an html string containing a <body> tag and 
 5074: other decorations will be returned.
 5075: 
 5076: =cut
 5077: 
 5078: sub bodytag {
 5079:     my ($title,$function,$addentries,$bodyonly,$domain,$forcereg,
 5080:         $no_nav_bar,$bgcolor,$args,$advtoolsref)=@_;
 5081: 
 5082:     my $public;
 5083:     if ((($env{'user.name'} eq 'public') && ($env{'user.domain'} eq 'public'))
 5084:         || ($env{'user.name'} eq '') && ($env{'user.domain'} eq '')) {
 5085:         $public = 1;
 5086:     }
 5087:     if (!$args->{'no_auto_mt_title'}) { $title = &mt($title); }
 5088: 
 5089:     $function = &get_users_function() if (!$function);
 5090:     my $img =    &designparm($function.'.img',$domain);
 5091:     my $font =   &designparm($function.'.font',$domain);
 5092:     my $pgbg   = $bgcolor || &designparm($function.'.pgbg',$domain);
 5093: 
 5094:     my %design = ( 'style'   => 'margin-top: 0',
 5095: 		   'bgcolor' => $pgbg,
 5096: 		   'text'    => $font,
 5097:                    'alink'   => &designparm($function.'.alink',$domain),
 5098: 		   'vlink'   => &designparm($function.'.vlink',$domain),
 5099: 		   'link'    => &designparm($function.'.link',$domain),);
 5100:     @design{keys(%$addentries)} = @$addentries{keys(%$addentries)}; 
 5101: 
 5102:  # role and realm
 5103:     my ($role,$realm) = split(/\./,$env{'request.role'},2);
 5104:     if ($role  eq 'ca') {
 5105:         my ($rdom,$rname) = ($realm =~ m{^/($match_domain)/($match_username)$});
 5106:         $realm = &plainname($rname,$rdom);
 5107:     } 
 5108: # realm
 5109:     if ($env{'request.course.id'}) {
 5110:         if ($env{'request.role'} !~ /^cr/) {
 5111:             $role = &Apache::lonnet::plaintext($role,&course_type());
 5112:         }
 5113:         if ($env{'request.course.sec'}) {
 5114:             $role .= ('&nbsp;'x2).'-&nbsp;'.&mt('section:').'&nbsp;'.$env{'request.course.sec'};
 5115:         }   
 5116: 	$realm = $env{'course.'.$env{'request.course.id'}.'.description'};
 5117:     } else {
 5118:         $role = &Apache::lonnet::plaintext($role);
 5119:     }
 5120: 
 5121:     if (!$realm) { $realm='&nbsp;'; }
 5122: 
 5123:     my $extra_body_attr = &make_attr_string($forcereg,\%design);
 5124: 
 5125: # construct main body tag
 5126:     my $bodytag = "<body $extra_body_attr>".
 5127: 	&Apache::lontexconvert::init_math_support($args->{'inherit_jsmath'});
 5128: 
 5129:     if ($bodyonly) {
 5130:         return $bodytag;
 5131:     } 
 5132: 
 5133:     my $name = &plainname($env{'user.name'},$env{'user.domain'});
 5134:     if ($public) {
 5135: 	undef($role);
 5136:     } else {
 5137: 	$name = &aboutmewrapper($name,$env{'user.name'},$env{'user.domain'},
 5138:                                 undef,'LC_menubuttons_link');
 5139:     }
 5140:     
 5141:     my $titleinfo = '<h1>'.$title.'</h1>';
 5142:     #
 5143:     # Extra info if you are the DC
 5144:     my $dc_info = '';
 5145:     if ($env{'user.adv'} && exists($env{'user.role.dc./'.
 5146:                         $env{'course.'.$env{'request.course.id'}.
 5147:                                  '.domain'}.'/'})) {
 5148:         my $cid = $env{'request.course.id'};
 5149:         $dc_info = $cid.' '.$env{'course.'.$cid.'.internal.coursecode'};
 5150:         $dc_info =~ s/\s+$//;
 5151:     }
 5152: 
 5153:     $role = '<span class="LC_nobreak">('.$role.')</span>' if $role;
 5154:     &get_unprocessed_cgi($ENV{'QUERY_STRING'}, ['inhibitmenu']);
 5155: 
 5156:         if ($no_nav_bar || $env{'form.inhibitmenu'} eq 'yes') { 
 5157:             return $bodytag; 
 5158:         } 
 5159: 
 5160:         if ($env{'request.state'} eq 'construct') { $forcereg=1; }
 5161: 
 5162:         #    if ($env{'request.state'} eq 'construct') {
 5163:         #        $titleinfo = &CSTR_pageheader(); #FIXME: Will be removed once all scripts have their own calls
 5164:         #    }
 5165: 
 5166: 
 5167: 
 5168:         if ($env{'request.noversionuri'} =~ m{^/res/adm/pages/}) {
 5169:              if ($dc_info) {
 5170:                  $dc_info = qq|<span class="LC_cusr_subheading">$dc_info</span>|;
 5171:              }
 5172:              $bodytag .= qq|<div id="LC_nav_bar">$name $role<br />
 5173:                 <em>$realm</em> $dc_info</div>|;
 5174:             return $bodytag;
 5175:         }
 5176: 
 5177:         unless ($env{'request.symb'} =~ m/\.page___\d+___/) {
 5178:             $bodytag .= qq|<div id="LC_nav_bar">$name $role</div>|;
 5179:         }
 5180: 
 5181:         $bodytag .= Apache::lonhtmlcommon::scripttag(
 5182:             Apache::lonmenu::utilityfunctions(), 'start');
 5183: 
 5184:         $bodytag .= Apache::lonmenu::primary_menu();
 5185: 
 5186:         if ($dc_info) {
 5187:             $dc_info = &dc_courseid_toggle($dc_info);
 5188:         }
 5189:         $bodytag .= qq|<div id="LC_realm">$realm $dc_info</div>|;
 5190: 
 5191:         #don't show menus for public users
 5192:         if (!$public){
 5193:             $bodytag .= Apache::lonmenu::secondary_menu();
 5194:             $bodytag .= Apache::lonmenu::serverform();
 5195:             $bodytag .= Apache::lonhtmlcommon::scripttag('', 'end');
 5196:             if ($env{'request.state'} eq 'construct') {
 5197:                 $bodytag .= &Apache::lonmenu::innerregister($forcereg,
 5198:                                 $args->{'bread_crumbs'});
 5199:             } elsif ($forcereg) {
 5200:                 $bodytag .= &Apache::lonmenu::innerregister($forcereg,undef,
 5201:                                                             $args->{'group'});
 5202:             } else {
 5203:                 $bodytag .= 
 5204:                     &Apache::lonmenu::prepare_functions($env{'request.noversionuri'},
 5205:                                                         $forcereg,$args->{'group'},
 5206:                                                         $args->{'bread_crumbs'},
 5207:                                                         $advtoolsref);
 5208:             }
 5209:         }else{
 5210:             # this is to seperate menu from content when there's no secondary
 5211:             # menu. Especially needed for public accessible ressources.
 5212:             $bodytag .= '<hr style="clear:both" />';
 5213:             $bodytag .= Apache::lonhtmlcommon::scripttag('', 'end'); 
 5214:         }
 5215: 
 5216:         return $bodytag;
 5217: }
 5218: 
 5219: sub dc_courseid_toggle {
 5220:     my ($dc_info) = @_;
 5221:     return ' <span id="dccidtext" class="LC_cusr_subheading LC_nobreak">'.
 5222:            '<a href="javascript:showCourseID();" class="LC_menubuttons_link">'.
 5223:            &mt('(More ...)').'</a></span>'.
 5224:            '<div id="dccid" class="LC_dccid">'.$dc_info.'</div>';
 5225: }
 5226: 
 5227: sub make_attr_string {
 5228:     my ($register,$attr_ref) = @_;
 5229: 
 5230:     if ($attr_ref && !ref($attr_ref)) {
 5231: 	die("addentries Must be a hash ref ".
 5232: 	    join(':',caller(1))." ".
 5233: 	    join(':',caller(0))." ");
 5234:     }
 5235: 
 5236:     if ($register) {
 5237: 	my ($on_load,$on_unload);
 5238: 	foreach my $key (keys(%{$attr_ref})) {
 5239: 	    if      (lc($key) eq 'onload') {
 5240: 		$on_load.=$attr_ref->{$key}.';';
 5241: 		delete($attr_ref->{$key});
 5242: 
 5243: 	    } elsif (lc($key) eq 'onunload') {
 5244: 		$on_unload.=$attr_ref->{$key}.';';
 5245: 		delete($attr_ref->{$key});
 5246: 	    }
 5247: 	}
 5248: 	$attr_ref->{'onload'}  = $on_load;
 5249: 	$attr_ref->{'onunload'}= $on_unload;
 5250:     }
 5251: 
 5252:     my $attr_string;
 5253:     foreach my $attr (keys(%$attr_ref)) {
 5254: 	$attr_string .= " $attr=\"".$attr_ref->{$attr}.'" ';
 5255:     }
 5256:     return $attr_string;
 5257: }
 5258: 
 5259: 
 5260: ###############################################
 5261: ###############################################
 5262: 
 5263: =pod
 5264: 
 5265: =item * &endbodytag()
 5266: 
 5267: Returns a uniform footer for LON-CAPA web pages.
 5268: 
 5269: Inputs: 1 - optional reference to an args hash
 5270: If in the hash, key for noredirectlink has a value which evaluates to true,
 5271: a 'Continue' link is not displayed if the page contains an
 5272: internal redirect in the <head></head> section,
 5273: i.e., $env{'internal.head.redirect'} exists   
 5274: 
 5275: =cut
 5276: 
 5277: sub endbodytag {
 5278:     my ($args) = @_;
 5279:     my $endbodytag;
 5280:     unless ((ref($args) eq 'HASH') && ($args->{'notbody'})) {
 5281:         $endbodytag='</body>';
 5282:     }
 5283:     $endbodytag=&Apache::lontexconvert::jsMath_process()."\n".$endbodytag;
 5284:     if ( exists( $env{'internal.head.redirect'} ) ) {
 5285:         if (!(ref($args) eq 'HASH' && $args->{'noredirectlink'})) {
 5286: 	    $endbodytag=
 5287: 	        "<br /><a href=\"$env{'internal.head.redirect'}\">".
 5288: 	        &mt('Continue').'</a>'.
 5289: 	        $endbodytag;
 5290:         }
 5291:     }
 5292:     return $endbodytag;
 5293: }
 5294: 
 5295: =pod
 5296: 
 5297: =item * &standard_css()
 5298: 
 5299: Returns a style sheet
 5300: 
 5301: Inputs: (all optional)
 5302:             domain         -> force to color decorate a page for a specific
 5303:                                domain
 5304:             function       -> force usage of a specific rolish color scheme
 5305:             bgcolor        -> override the default page bgcolor
 5306: 
 5307: =cut
 5308: 
 5309: sub standard_css {
 5310:     my ($function,$domain,$bgcolor) = @_;
 5311:     $function  = &get_users_function() if (!$function);
 5312:     my $img    = &designparm($function.'.img',   $domain);
 5313:     my $tabbg  = &designparm($function.'.tabbg', $domain);
 5314:     my $font   = &designparm($function.'.font',  $domain);
 5315:     my $fontmenu = &designparm($function.'.fontmenu', $domain);
 5316: #second colour for later usage
 5317:     my $sidebg = &designparm($function.'.sidebg',$domain);
 5318:     my $pgbg_or_bgcolor =
 5319: 	         $bgcolor ||
 5320: 	         &designparm($function.'.pgbg',  $domain);
 5321:     my $pgbg   = &designparm($function.'.pgbg',  $domain);
 5322:     my $alink  = &designparm($function.'.alink', $domain);
 5323:     my $vlink  = &designparm($function.'.vlink', $domain);
 5324:     my $link   = &designparm($function.'.link',  $domain);
 5325: 
 5326:     my $sans                 = 'Verdana,Arial,Helvetica,sans-serif';
 5327:     my $mono                 = 'monospace';
 5328:     my $data_table_head      = $sidebg;
 5329:     my $data_table_light     = '#FAFAFA';
 5330:     my $data_table_dark      = '#E0E0E0';
 5331:     my $data_table_darker    = '#CCCCCC';
 5332:     my $data_table_highlight = '#FFFF00';
 5333:     my $mail_new             = '#FFBB77';
 5334:     my $mail_new_hover       = '#DD9955';
 5335:     my $mail_read            = '#BBBB77';
 5336:     my $mail_read_hover      = '#999944';
 5337:     my $mail_replied         = '#AAAA88';
 5338:     my $mail_replied_hover   = '#888855';
 5339:     my $mail_other           = '#99BBBB';
 5340:     my $mail_other_hover     = '#669999';
 5341:     my $table_header         = '#DDDDDD';
 5342:     my $feedback_link_bg     = '#BBBBBB';
 5343:     my $lg_border_color      = '#C8C8C8';
 5344:     my $button_hover         = '#BF2317';
 5345: 
 5346:     my $border = ($env{'browser.type'} eq 'explorer' ||
 5347:       $env{'browser.type'} eq 'safari'     ) ? '0 2px 0 2px'
 5348:                                              : '0 3px 0 4px';
 5349: 
 5350: 
 5351:     return <<END;
 5352: 
 5353: /* needed for iframe to allow 100% height in FF */
 5354: body, html { 
 5355:     margin: 0;
 5356:     padding: 0 0.5%;
 5357:     height: 99%; /* to avoid scrollbars */
 5358: }
 5359: 
 5360: body {
 5361:   font-family: $sans;
 5362:   line-height:130%;
 5363:   font-size:0.83em;
 5364:   color:$font;
 5365: }
 5366: 
 5367: a:focus,
 5368: a:focus img {
 5369:   color: red;
 5370: }
 5371: 
 5372: form, .inline {
 5373:   display: inline;
 5374: }
 5375: 
 5376: .LC_right {
 5377:   text-align:right;
 5378: }
 5379: 
 5380: .LC_middle {
 5381:   vertical-align:middle;
 5382: }
 5383: 
 5384: .LC_400Box {
 5385:   width:400px;
 5386: }
 5387: 
 5388: .LC_iframecontainer {
 5389:     width: 98%;
 5390:     margin: 0;
 5391:     position: fixed;
 5392:     top: 8.5em;
 5393:     bottom: 0;
 5394: }
 5395: 
 5396: .LC_iframecontainer iframe{
 5397:     border: none;
 5398:     width: 100%;
 5399:     height: 100%;
 5400: }
 5401: 
 5402: .LC_filename {
 5403:   font-family: $mono;
 5404:   white-space:pre;
 5405:   font-size: 120%;
 5406: }
 5407: 
 5408: .LC_fileicon {
 5409:   border: none;
 5410:   height: 1.3em;
 5411:   vertical-align: text-bottom;
 5412:   margin-right: 0.3em;
 5413:   text-decoration:none;
 5414: }
 5415: 
 5416: .LC_setting {
 5417:   text-decoration:underline;
 5418: }
 5419: 
 5420: .LC_error {
 5421:   color: red;
 5422: }
 5423: 
 5424: .LC_warning {
 5425:   color: darkorange;
 5426: }
 5427: 
 5428: .LC_diff_removed {
 5429:   color: red;
 5430: }
 5431: 
 5432: .LC_info,
 5433: .LC_success,
 5434: .LC_diff_added {
 5435:   color: green;
 5436: }
 5437: 
 5438: div.LC_confirm_box {
 5439:   background-color: #FAFAFA;
 5440:   border: 1px solid $lg_border_color;
 5441:   margin-right: 0;
 5442:   padding: 5px;
 5443: }
 5444: 
 5445: div.LC_confirm_box .LC_error img,
 5446: div.LC_confirm_box .LC_success img {
 5447:   vertical-align: middle;
 5448: }
 5449: 
 5450: .LC_icon {
 5451:   border: none;
 5452:   vertical-align: middle;
 5453: }
 5454: 
 5455: .LC_docs_spacer {
 5456:   width: 25px;
 5457:   height: 1px;
 5458:   border: none;
 5459: }
 5460: 
 5461: .LC_internal_info {
 5462:   color: #999999;
 5463: }
 5464: 
 5465: .LC_discussion {
 5466:   background: $data_table_dark;
 5467:   border: 1px solid black;
 5468:   margin: 2px;
 5469: }
 5470: 
 5471: .LC_disc_action_left {
 5472:   background: $sidebg;
 5473:   text-align: left;
 5474:   padding: 4px;
 5475:   margin: 2px;
 5476: }
 5477: 
 5478: .LC_disc_action_right {
 5479:   background: $sidebg;
 5480:   text-align: right;
 5481:   padding: 4px;
 5482:   margin: 2px;
 5483: }
 5484: 
 5485: .LC_disc_new_item {
 5486:   background: white;
 5487:   border: 2px solid red;
 5488:   margin: 4px;
 5489:   padding: 4px;
 5490: }
 5491: 
 5492: .LC_disc_old_item {
 5493:   background: white;
 5494:   margin: 4px;
 5495:   padding: 4px;
 5496: }
 5497: 
 5498: table.LC_pastsubmission {
 5499:   border: 1px solid black;
 5500:   margin: 2px;
 5501: }
 5502: 
 5503: table#LC_menubuttons {
 5504:   width: 100%;
 5505:   background: $pgbg;
 5506:   border: 2px;
 5507:   border-collapse: separate;
 5508:   padding: 0;
 5509: }
 5510: 
 5511: table#LC_title_bar a {
 5512:   color: $fontmenu;
 5513: }
 5514: 
 5515: table#LC_title_bar {
 5516:   clear: both;
 5517:   display: none;
 5518: }
 5519: 
 5520: table#LC_title_bar,
 5521: table.LC_breadcrumbs, /* obsolete? */
 5522: table#LC_title_bar.LC_with_remote {
 5523:   width: 100%;
 5524:   border-color: $pgbg;
 5525:   border-style: solid;
 5526:   border-width: $border;
 5527:   background: $pgbg;
 5528:   color: $fontmenu;
 5529:   border-collapse: collapse;
 5530:   padding: 0;
 5531:   margin: 0;
 5532: }
 5533: 
 5534: ul.LC_breadcrumb_tools_outerlist {
 5535:     margin: 0;
 5536:     padding: 0;
 5537:     position: relative;
 5538:     list-style: none;
 5539: }
 5540: ul.LC_breadcrumb_tools_outerlist li {
 5541:     display: inline;
 5542: }
 5543: 
 5544: .LC_breadcrumb_tools_navigation {
 5545:     padding: 0;
 5546:     margin: 0;
 5547:     float: left;
 5548: }
 5549: .LC_breadcrumb_tools_tools {
 5550:     padding: 0;
 5551:     margin: 0;
 5552:     float: right;
 5553: }
 5554: 
 5555: table#LC_title_bar td {
 5556:   background: $tabbg;
 5557: }
 5558: 
 5559: table#LC_menubuttons img {
 5560:   border: none;
 5561: }
 5562: 
 5563: .LC_breadcrumbs_component {
 5564:   float: right;
 5565:   margin: 0 1em;
 5566: }
 5567: .LC_breadcrumbs_component img {
 5568:   vertical-align: middle;
 5569: }
 5570: 
 5571: td.LC_table_cell_checkbox {
 5572:   text-align: center;
 5573: }
 5574: 
 5575: .LC_fontsize_small {
 5576:   font-size: 70%;
 5577: }
 5578: 
 5579: #LC_breadcrumbs {
 5580:   clear:both;
 5581:   background: $sidebg;
 5582:   border-bottom: 1px solid $lg_border_color;
 5583:   line-height: 2.5em;
 5584:   overflow: hidden;
 5585:   margin: 0;
 5586:   padding: 0;
 5587:   text-align: left;
 5588: }
 5589: 
 5590: .LC_head_subbox, .LC_actionbox {
 5591:   clear:both;
 5592:   background: #F8F8F8; /* $sidebg; */
 5593:   border: 1px solid $sidebg;
 5594:   margin: 0 0 10px 0;
 5595:   padding: 3px;
 5596:   text-align: left;
 5597: }
 5598: 
 5599: .LC_fontsize_medium {
 5600:   font-size: 85%;
 5601: }
 5602: 
 5603: .LC_fontsize_large {
 5604:   font-size: 120%;
 5605: }
 5606: 
 5607: .LC_menubuttons_inline_text {
 5608:   color: $font;
 5609:   font-size: 90%;
 5610:   padding-left:3px;
 5611: }
 5612: 
 5613: .LC_menubuttons_inline_text img{
 5614:   vertical-align: middle;
 5615: }
 5616: 
 5617: li.LC_menubuttons_inline_text img {
 5618:   cursor:pointer;
 5619:   text-decoration: none;
 5620: }
 5621: 
 5622: .LC_menubuttons_link {
 5623:   text-decoration: none;
 5624: }
 5625: 
 5626: .LC_menubuttons_category {
 5627:   color: $font;
 5628:   background: $pgbg;
 5629:   font-size: larger;
 5630:   font-weight: bold;
 5631: }
 5632: 
 5633: td.LC_menubuttons_text {
 5634:   color: $font;
 5635: }
 5636: 
 5637: .LC_current_location {
 5638:   background: $tabbg;
 5639: }
 5640: 
 5641: table.LC_data_table {
 5642:   border: 1px solid #000000;
 5643:   border-collapse: separate;
 5644:   border-spacing: 1px;
 5645:   background: $pgbg;
 5646: }
 5647: 
 5648: .LC_data_table_dense {
 5649:   font-size: small;
 5650: }
 5651: 
 5652: table.LC_nested_outer {
 5653:   border: 1px solid #000000;
 5654:   border-collapse: collapse;
 5655:   border-spacing: 0;
 5656:   width: 100%;
 5657: }
 5658: 
 5659: table.LC_innerpickbox,
 5660: table.LC_nested {
 5661:   border: none;
 5662:   border-collapse: collapse;
 5663:   border-spacing: 0;
 5664:   width: 100%;
 5665: }
 5666: 
 5667: table.LC_data_table tr th,
 5668: table.LC_calendar tr th,
 5669: table.LC_prior_tries tr th,
 5670: table.LC_innerpickbox tr th {
 5671:   font-weight: bold;
 5672:   background-color: $data_table_head;
 5673:   color:$fontmenu;
 5674:   font-size:90%;
 5675: }
 5676: 
 5677: table.LC_innerpickbox tr th,
 5678: table.LC_innerpickbox tr td {
 5679:   vertical-align: top;
 5680: }
 5681: 
 5682: table.LC_data_table tr.LC_info_row > td {
 5683:   background-color: #CCCCCC;
 5684:   font-weight: bold;
 5685:   text-align: left;
 5686: }
 5687: 
 5688: table.LC_data_table tr.LC_odd_row > td {
 5689:   background-color: $data_table_light;
 5690:   padding: 2px;
 5691:   vertical-align: top;
 5692: }
 5693: 
 5694: table.LC_pick_box tr > td.LC_odd_row {
 5695:   background-color: $data_table_light;
 5696:   vertical-align: top;
 5697: }
 5698: 
 5699: table.LC_data_table tr.LC_even_row > td {
 5700:   background-color: $data_table_dark;
 5701:   padding: 2px;
 5702:   vertical-align: top;
 5703: }
 5704: 
 5705: table.LC_pick_box tr > td.LC_even_row {
 5706:   background-color: $data_table_dark;
 5707:   vertical-align: top;
 5708: }
 5709: 
 5710: table.LC_data_table tr.LC_data_table_highlight td {
 5711:   background-color: $data_table_darker;
 5712: }
 5713: 
 5714: table.LC_data_table tr td.LC_leftcol_header {
 5715:   background-color: $data_table_head;
 5716:   font-weight: bold;
 5717: }
 5718: 
 5719: table.LC_data_table tr.LC_empty_row td,
 5720: table.LC_nested tr.LC_empty_row td {
 5721:   font-weight: bold;
 5722:   font-style: italic;
 5723:   text-align: center;
 5724:   padding: 8px;
 5725: }
 5726: 
 5727: table.LC_data_table tr.LC_empty_row td {
 5728:   background-color: $sidebg;
 5729: }
 5730: 
 5731: table.LC_nested tr.LC_empty_row td {
 5732:   background-color: #FFFFFF;
 5733: }
 5734: 
 5735: table.LC_caption {
 5736: }
 5737: 
 5738: table.LC_nested tr.LC_empty_row td {
 5739:   padding: 4ex
 5740: }
 5741: 
 5742: table.LC_nested_outer tr th {
 5743:   font-weight: bold;
 5744:   color:$fontmenu;
 5745:   background-color: $data_table_head;
 5746:   font-size: small;
 5747:   border-bottom: 1px solid #000000;
 5748: }
 5749: 
 5750: table.LC_nested_outer tr td.LC_subheader {
 5751:   background-color: $data_table_head;
 5752:   font-weight: bold;
 5753:   font-size: small;
 5754:   border-bottom: 1px solid #000000;
 5755:   text-align: right;
 5756: }
 5757: 
 5758: table.LC_nested tr.LC_info_row td {
 5759:   background-color: #CCCCCC;
 5760:   font-weight: bold;
 5761:   font-size: small;
 5762:   text-align: center;
 5763: }
 5764: 
 5765: table.LC_nested tr.LC_info_row td.LC_left_item,
 5766: table.LC_nested_outer tr th.LC_left_item {
 5767:   text-align: left;
 5768: }
 5769: 
 5770: table.LC_nested td {
 5771:   background-color: #FFFFFF;
 5772:   font-size: small;
 5773: }
 5774: 
 5775: table.LC_nested_outer tr th.LC_right_item,
 5776: table.LC_nested tr.LC_info_row td.LC_right_item,
 5777: table.LC_nested tr.LC_odd_row td.LC_right_item,
 5778: table.LC_nested tr td.LC_right_item {
 5779:   text-align: right;
 5780: }
 5781: 
 5782: table.LC_nested tr.LC_odd_row td {
 5783:   background-color: #EEEEEE;
 5784: }
 5785: 
 5786: table.LC_createuser {
 5787: }
 5788: 
 5789: table.LC_createuser tr.LC_section_row td {
 5790:   font-size: small;
 5791: }
 5792: 
 5793: table.LC_createuser tr.LC_info_row td  {
 5794:   background-color: #CCCCCC;
 5795:   font-weight: bold;
 5796:   text-align: center;
 5797: }
 5798: 
 5799: table.LC_calendar {
 5800:   border: 1px solid #000000;
 5801:   border-collapse: collapse;
 5802:   width: 98%;
 5803: }
 5804: 
 5805: table.LC_calendar_pickdate {
 5806:   font-size: xx-small;
 5807: }
 5808: 
 5809: table.LC_calendar tr td {
 5810:   border: 1px solid #000000;
 5811:   vertical-align: top;
 5812:   width: 14%;
 5813: }
 5814: 
 5815: table.LC_calendar tr td.LC_calendar_day_empty {
 5816:   background-color: $data_table_dark;
 5817: }
 5818: 
 5819: table.LC_calendar tr td.LC_calendar_day_current {
 5820:   background-color: $data_table_highlight;
 5821: }
 5822: 
 5823: table.LC_data_table tr td.LC_mail_new {
 5824:   background-color: $mail_new;
 5825: }
 5826: 
 5827: table.LC_data_table tr.LC_mail_new:hover {
 5828:   background-color: $mail_new_hover;
 5829: }
 5830: 
 5831: table.LC_data_table tr td.LC_mail_read {
 5832:   background-color: $mail_read;
 5833: }
 5834: 
 5835: /*
 5836: table.LC_data_table tr.LC_mail_read:hover {
 5837:   background-color: $mail_read_hover;
 5838: }
 5839: */
 5840: 
 5841: table.LC_data_table tr td.LC_mail_replied {
 5842:   background-color: $mail_replied;
 5843: }
 5844: 
 5845: /*
 5846: table.LC_data_table tr.LC_mail_replied:hover {
 5847:   background-color: $mail_replied_hover;
 5848: }
 5849: */
 5850: 
 5851: table.LC_data_table tr td.LC_mail_other {
 5852:   background-color: $mail_other;
 5853: }
 5854: 
 5855: /*
 5856: table.LC_data_table tr.LC_mail_other:hover {
 5857:   background-color: $mail_other_hover;
 5858: }
 5859: */
 5860: 
 5861: table.LC_data_table tr > td.LC_browser_file,
 5862: table.LC_data_table tr > td.LC_browser_file_published {
 5863:   background: #AAEE77;
 5864: }
 5865: 
 5866: table.LC_data_table tr > td.LC_browser_file_locked,
 5867: table.LC_data_table tr > td.LC_browser_file_unpublished {
 5868:   background: #FFAA99;
 5869: }
 5870: 
 5871: table.LC_data_table tr > td.LC_browser_file_obsolete {
 5872:   background: #888888;
 5873: }
 5874: 
 5875: table.LC_data_table tr > td.LC_browser_file_modified,
 5876: table.LC_data_table tr > td.LC_browser_file_metamodified {
 5877:   background: #F8F866;
 5878: }
 5879: 
 5880: table.LC_data_table tr.LC_browser_folder > td {
 5881:   background: #E0E8FF;
 5882: }
 5883: 
 5884: table.LC_data_table tr > td.LC_roles_is {
 5885:   /* background: #77FF77; */
 5886: }
 5887: 
 5888: table.LC_data_table tr > td.LC_roles_future {
 5889:   border-right: 8px solid #FFFF77;
 5890: }
 5891: 
 5892: table.LC_data_table tr > td.LC_roles_will {
 5893:   border-right: 8px solid #FFAA77;
 5894: }
 5895: 
 5896: table.LC_data_table tr > td.LC_roles_expired {
 5897:   border-right: 8px solid #FF7777;
 5898: }
 5899: 
 5900: table.LC_data_table tr > td.LC_roles_will_not {
 5901:   border-right: 8px solid #AAFF77;
 5902: }
 5903: 
 5904: table.LC_data_table tr > td.LC_roles_selected {
 5905:   border-right: 8px solid #11CC55;
 5906: }
 5907: 
 5908: span.LC_current_location {
 5909:   font-size:larger;
 5910:   background: $pgbg;
 5911: }
 5912: 
 5913: span.LC_current_nav_location {
 5914:   font-weight:bold;
 5915:   background: $sidebg;
 5916: }
 5917: 
 5918: span.LC_parm_menu_item {
 5919:   font-size: larger;
 5920: }
 5921: 
 5922: span.LC_parm_scope_all {
 5923:   color: red;
 5924: }
 5925: 
 5926: span.LC_parm_scope_folder {
 5927:   color: green;
 5928: }
 5929: 
 5930: span.LC_parm_scope_resource {
 5931:   color: orange;
 5932: }
 5933: 
 5934: span.LC_parm_part {
 5935:   color: blue;
 5936: }
 5937: 
 5938: span.LC_parm_folder,
 5939: span.LC_parm_symb {
 5940:   font-size: x-small;
 5941:   font-family: $mono;
 5942:   color: #AAAAAA;
 5943: }
 5944: 
 5945: ul.LC_parm_parmlist li {
 5946:   display: inline-block;
 5947:   padding: 0.3em 0.8em;
 5948:   vertical-align: top;
 5949:   width: 150px;
 5950:   border-top:1px solid $lg_border_color;
 5951: }
 5952: 
 5953: td.LC_parm_overview_level_menu,
 5954: td.LC_parm_overview_map_menu,
 5955: td.LC_parm_overview_parm_selectors,
 5956: td.LC_parm_overview_restrictions  {
 5957:   border: 1px solid black;
 5958:   border-collapse: collapse;
 5959: }
 5960: 
 5961: table.LC_parm_overview_restrictions td {
 5962:   border-width: 1px 4px 1px 4px;
 5963:   border-style: solid;
 5964:   border-color: $pgbg;
 5965:   text-align: center;
 5966: }
 5967: 
 5968: table.LC_parm_overview_restrictions th {
 5969:   background: $tabbg;
 5970:   border-width: 1px 4px 1px 4px;
 5971:   border-style: solid;
 5972:   border-color: $pgbg;
 5973: }
 5974: 
 5975: table#LC_helpmenu {
 5976:   border: none;
 5977:   height: 55px;
 5978:   border-spacing: 0;
 5979: }
 5980: 
 5981: table#LC_helpmenu fieldset legend {
 5982:   font-size: larger;
 5983: }
 5984: 
 5985: table#LC_helpmenu_links {
 5986:   width: 100%;
 5987:   border: 1px solid black;
 5988:   background: $pgbg;
 5989:   padding: 0;
 5990:   border-spacing: 1px;
 5991: }
 5992: 
 5993: table#LC_helpmenu_links tr td {
 5994:   padding: 1px;
 5995:   background: $tabbg;
 5996:   text-align: center;
 5997:   font-weight: bold;
 5998: }
 5999: 
 6000: table#LC_helpmenu_links a:link,
 6001: table#LC_helpmenu_links a:visited,
 6002: table#LC_helpmenu_links a:active {
 6003:   text-decoration: none;
 6004:   color: $font;
 6005: }
 6006: 
 6007: table#LC_helpmenu_links a:hover {
 6008:   text-decoration: underline;
 6009:   color: $vlink;
 6010: }
 6011: 
 6012: .LC_chrt_popup_exists {
 6013:   border: 1px solid #339933;
 6014:   margin: -1px;
 6015: }
 6016: 
 6017: .LC_chrt_popup_up {
 6018:   border: 1px solid yellow;
 6019:   margin: -1px;
 6020: }
 6021: 
 6022: .LC_chrt_popup {
 6023:   border: 1px solid #8888FF;
 6024:   background: #CCCCFF;
 6025: }
 6026: 
 6027: table.LC_pick_box {
 6028:   border-collapse: separate;
 6029:   background: white;
 6030:   border: 1px solid black;
 6031:   border-spacing: 1px;
 6032: }
 6033: 
 6034: table.LC_pick_box td.LC_pick_box_title {
 6035:   background: $sidebg;
 6036:   font-weight: bold;
 6037:   text-align: left;
 6038:   vertical-align: top;
 6039:   width: 184px;
 6040:   padding: 8px;
 6041: }
 6042: 
 6043: table.LC_pick_box td.LC_pick_box_value {
 6044:   text-align: left;
 6045:   padding: 8px;
 6046: }
 6047: 
 6048: table.LC_pick_box td.LC_pick_box_select {
 6049:   text-align: left;
 6050:   padding: 8px;
 6051: }
 6052: 
 6053: table.LC_pick_box td.LC_pick_box_separator {
 6054:   padding: 0;
 6055:   height: 1px;
 6056:   background: black;
 6057: }
 6058: 
 6059: table.LC_pick_box td.LC_pick_box_submit {
 6060:   text-align: right;
 6061: }
 6062: 
 6063: table.LC_pick_box td.LC_evenrow_value {
 6064:   text-align: left;
 6065:   padding: 8px;
 6066:   background-color: $data_table_light;
 6067: }
 6068: 
 6069: table.LC_pick_box td.LC_oddrow_value {
 6070:   text-align: left;
 6071:   padding: 8px;
 6072:   background-color: $data_table_light;
 6073: }
 6074: 
 6075: span.LC_helpform_receipt_cat {
 6076:   font-weight: bold;
 6077: }
 6078: 
 6079: table.LC_group_priv_box {
 6080:   background: white;
 6081:   border: 1px solid black;
 6082:   border-spacing: 1px;
 6083: }
 6084: 
 6085: table.LC_group_priv_box td.LC_pick_box_title {
 6086:   background: $tabbg;
 6087:   font-weight: bold;
 6088:   text-align: right;
 6089:   width: 184px;
 6090: }
 6091: 
 6092: table.LC_group_priv_box td.LC_groups_fixed {
 6093:   background: $data_table_light;
 6094:   text-align: center;
 6095: }
 6096: 
 6097: table.LC_group_priv_box td.LC_groups_optional {
 6098:   background: $data_table_dark;
 6099:   text-align: center;
 6100: }
 6101: 
 6102: table.LC_group_priv_box td.LC_groups_functionality {
 6103:   background: $data_table_darker;
 6104:   text-align: center;
 6105:   font-weight: bold;
 6106: }
 6107: 
 6108: table.LC_group_priv td {
 6109:   text-align: left;
 6110:   padding: 0;
 6111: }
 6112: 
 6113: .LC_navbuttons {
 6114:   margin: 2ex 0ex 2ex 0ex;
 6115: }
 6116: 
 6117: .LC_topic_bar {
 6118:   font-weight: bold;
 6119:   background: $tabbg;
 6120:   margin: 1em 0em 1em 2em;
 6121:   padding: 3px;
 6122:   font-size: 1.2em;
 6123: }
 6124: 
 6125: .LC_topic_bar span {
 6126:   left: 0.5em;
 6127:   position: absolute;
 6128:   vertical-align: middle;
 6129:   font-size: 1.2em;
 6130: }
 6131: 
 6132: table.LC_course_group_status {
 6133:   margin: 20px;
 6134: }
 6135: 
 6136: table.LC_status_selector td {
 6137:   vertical-align: top;
 6138:   text-align: center;
 6139:   padding: 4px;
 6140: }
 6141: 
 6142: div.LC_feedback_link {
 6143:   clear: both;
 6144:   background: $sidebg;
 6145:   width: 100%;
 6146:   padding-bottom: 10px;
 6147:   border: 1px $tabbg solid;
 6148:   height: 22px;
 6149:   line-height: 22px;
 6150:   padding-top: 5px;
 6151: }
 6152: 
 6153: div.LC_feedback_link img {
 6154:   height: 22px;
 6155:   vertical-align:middle;
 6156: }
 6157: 
 6158: div.LC_feedback_link a {
 6159:   text-decoration: none;
 6160: }
 6161: 
 6162: div.LC_comblock {
 6163:   display:inline;
 6164:   color:$font;
 6165:   font-size:90%;
 6166: }
 6167: 
 6168: div.LC_feedback_link div.LC_comblock {
 6169:   padding-left:5px;
 6170: }
 6171: 
 6172: div.LC_feedback_link div.LC_comblock a {
 6173:   color:$font;
 6174: }
 6175: 
 6176: span.LC_feedback_link {
 6177:   /* background: $feedback_link_bg; */
 6178:   font-size: larger;
 6179: }
 6180: 
 6181: span.LC_message_link {
 6182:   /* background: $feedback_link_bg; */
 6183:   font-size: larger;
 6184:   position: absolute;
 6185:   right: 1em;
 6186: }
 6187: 
 6188: table.LC_prior_tries {
 6189:   border: 1px solid #000000;
 6190:   border-collapse: separate;
 6191:   border-spacing: 1px;
 6192: }
 6193: 
 6194: table.LC_prior_tries td {
 6195:   padding: 2px;
 6196: }
 6197: 
 6198: .LC_answer_correct {
 6199:   background: lightgreen;
 6200:   color: darkgreen;
 6201:   padding: 6px;
 6202: }
 6203: 
 6204: .LC_answer_charged_try {
 6205:   background: #FFAAAA;
 6206:   color: darkred;
 6207:   padding: 6px;
 6208: }
 6209: 
 6210: .LC_answer_not_charged_try,
 6211: .LC_answer_no_grade,
 6212: .LC_answer_late {
 6213:   background: lightyellow;
 6214:   color: black;
 6215:   padding: 6px;
 6216: }
 6217: 
 6218: .LC_answer_previous {
 6219:   background: lightblue;
 6220:   color: darkblue;
 6221:   padding: 6px;
 6222: }
 6223: 
 6224: .LC_answer_no_message {
 6225:   background: #FFFFFF;
 6226:   color: black;
 6227:   padding: 6px;
 6228: }
 6229: 
 6230: .LC_answer_unknown {
 6231:   background: orange;
 6232:   color: black;
 6233:   padding: 6px;
 6234: }
 6235: 
 6236: span.LC_prior_numerical,
 6237: span.LC_prior_string,
 6238: span.LC_prior_custom,
 6239: span.LC_prior_reaction,
 6240: span.LC_prior_math {
 6241:   font-family: $mono;
 6242:   white-space: pre;
 6243: }
 6244: 
 6245: span.LC_prior_string {
 6246:   font-family: $mono;
 6247:   white-space: pre;
 6248: }
 6249: 
 6250: table.LC_prior_option {
 6251:   width: 100%;
 6252:   border-collapse: collapse;
 6253: }
 6254: 
 6255: table.LC_prior_rank,
 6256: table.LC_prior_match {
 6257:   border-collapse: collapse;
 6258: }
 6259: 
 6260: table.LC_prior_option tr td,
 6261: table.LC_prior_rank tr td,
 6262: table.LC_prior_match tr td {
 6263:   border: 1px solid #000000;
 6264: }
 6265: 
 6266: .LC_nobreak {
 6267:   white-space: nowrap;
 6268: }
 6269: 
 6270: span.LC_cusr_emph {
 6271:   font-style: italic;
 6272: }
 6273: 
 6274: span.LC_cusr_subheading {
 6275:   font-weight: normal;
 6276:   font-size: 85%;
 6277: }
 6278: 
 6279: div.LC_docs_entry_move {
 6280:   border: 1px solid #BBBBBB;
 6281:   background: #DDDDDD;
 6282:   width: 22px;
 6283:   padding: 1px;
 6284:   margin: 0;
 6285: }
 6286: 
 6287: table.LC_data_table tr > td.LC_docs_entry_commands,
 6288: table.LC_data_table tr > td.LC_docs_entry_parameter {
 6289:   font-size: x-small;
 6290: }
 6291: 
 6292: .LC_docs_entry_parameter {
 6293:   white-space: nowrap;
 6294: }
 6295: 
 6296: .LC_docs_copy {
 6297:   color: #000099;
 6298: }
 6299: 
 6300: .LC_docs_cut {
 6301:   color: #550044;
 6302: }
 6303: 
 6304: .LC_docs_rename {
 6305:   color: #009900;
 6306: }
 6307: 
 6308: .LC_docs_remove {
 6309:   color: #990000;
 6310: }
 6311: 
 6312: .LC_docs_reinit_warn,
 6313: .LC_docs_ext_edit {
 6314:   font-size: x-small;
 6315: }
 6316: 
 6317: table.LC_docs_adddocs td,
 6318: table.LC_docs_adddocs th {
 6319:   border: 1px solid #BBBBBB;
 6320:   padding: 4px;
 6321:   background: #DDDDDD;
 6322: }
 6323: 
 6324: table.LC_sty_begin {
 6325:   background: #BBFFBB;
 6326: }
 6327: 
 6328: table.LC_sty_end {
 6329:   background: #FFBBBB;
 6330: }
 6331: 
 6332: table.LC_double_column {
 6333:   border-width: 0;
 6334:   border-collapse: collapse;
 6335:   width: 100%;
 6336:   padding: 2px;
 6337: }
 6338: 
 6339: table.LC_double_column tr td.LC_left_col {
 6340:   top: 2px;
 6341:   left: 2px;
 6342:   width: 47%;
 6343:   vertical-align: top;
 6344: }
 6345: 
 6346: table.LC_double_column tr td.LC_right_col {
 6347:   top: 2px;
 6348:   right: 2px;
 6349:   width: 47%;
 6350:   vertical-align: top;
 6351: }
 6352: 
 6353: div.LC_left_float {
 6354:   float: left;
 6355:   padding-right: 5%;
 6356:   padding-bottom: 4px;
 6357: }
 6358: 
 6359: div.LC_clear_float_header {
 6360:   padding-bottom: 2px;
 6361: }
 6362: 
 6363: div.LC_clear_float_footer {
 6364:   padding-top: 10px;
 6365:   clear: both;
 6366: }
 6367: 
 6368: div.LC_grade_show_user {
 6369: /*  border-left: 5px solid $sidebg; */
 6370:   border-top: 5px solid #000000;
 6371:   margin: 50px 0 0 0;
 6372:   padding: 15px 0 5px 10px;
 6373: }
 6374: 
 6375: div.LC_grade_show_user_odd_row {
 6376: /*  border-left: 5px solid #000000; */
 6377: }
 6378: 
 6379: div.LC_grade_show_user div.LC_Box {
 6380:   margin-right: 50px;
 6381: }
 6382: 
 6383: div.LC_grade_submissions,
 6384: div.LC_grade_message_center,
 6385: div.LC_grade_info_links {
 6386:   margin: 5px;
 6387:   width: 99%;
 6388:   background: #FFFFFF;
 6389: }
 6390: 
 6391: div.LC_grade_submissions_header,
 6392: div.LC_grade_message_center_header {
 6393:   font-weight: bold;
 6394:   font-size: large;
 6395: }
 6396: 
 6397: div.LC_grade_submissions_body,
 6398: div.LC_grade_message_center_body {
 6399:   border: 1px solid black;
 6400:   width: 99%;
 6401:   background: #FFFFFF;
 6402: }
 6403: 
 6404: table.LC_scantron_action {
 6405:   width: 100%;
 6406: }
 6407: 
 6408: table.LC_scantron_action tr th {
 6409:   font-weight:bold;
 6410:   font-style:normal;
 6411: }
 6412: 
 6413: .LC_edit_problem_header,
 6414: div.LC_edit_problem_footer {
 6415:   font-weight: normal;
 6416:   font-size:  medium;
 6417:   margin: 2px;
 6418:   background-color: $sidebg;
 6419: }
 6420: 
 6421: div.LC_edit_problem_header,
 6422: div.LC_edit_problem_header div,
 6423: div.LC_edit_problem_footer,
 6424: div.LC_edit_problem_footer div,
 6425: div.LC_edit_problem_editxml_header,
 6426: div.LC_edit_problem_editxml_header div {
 6427:   margin-top: 5px;
 6428: }
 6429: 
 6430: div.LC_edit_problem_header_title {
 6431:   font-weight: bold;
 6432:   font-size: larger;
 6433:   background: $tabbg;
 6434:   padding: 3px;
 6435:   margin: 0 0 5px 0;
 6436: }
 6437: 
 6438: table.LC_edit_problem_header_title {
 6439:   width: 100%;
 6440:   background: $tabbg;
 6441: }
 6442: 
 6443: div.LC_edit_problem_discards {
 6444:   float: left;
 6445:   padding-bottom: 5px;
 6446: }
 6447: 
 6448: div.LC_edit_problem_saves {
 6449:   float: right;
 6450:   padding-bottom: 5px;
 6451: }
 6452: 
 6453: img.stift {
 6454:   border-width: 0;
 6455:   vertical-align: middle;
 6456: }
 6457: 
 6458: table td.LC_mainmenu_col_fieldset {
 6459:   vertical-align: top;
 6460: }
 6461: 
 6462: div.LC_createcourse {
 6463:   margin: 10px 10px 10px 10px;
 6464: }
 6465: 
 6466: .LC_dccid {
 6467:   margin: 0.2em 0 0 0;
 6468:   padding: 0;
 6469:   font-size: 90%;
 6470:   display:none;
 6471: }
 6472: 
 6473: ol.LC_primary_menu a:hover,
 6474: ol#LC_MenuBreadcrumbs a:hover,
 6475: ol#LC_PathBreadcrumbs a:hover,
 6476: ul#LC_secondary_menu a:hover,
 6477: .LC_FormSectionClearButton input:hover
 6478: ul.LC_TabContent   li:hover a {
 6479:   color:$button_hover;
 6480:   text-decoration:none;
 6481: }
 6482: 
 6483: h1 {
 6484:   padding: 0;
 6485:   line-height:130%;
 6486: }
 6487: 
 6488: h2,
 6489: h3,
 6490: h4,
 6491: h5,
 6492: h6 {
 6493:   margin: 5px 0 5px 0;
 6494:   padding: 0;
 6495:   line-height:130%;
 6496: }
 6497: 
 6498: .LC_hcell {
 6499:   padding:3px 15px 3px 15px;
 6500:   margin: 0;
 6501:   background-color:$tabbg;
 6502:   color:$fontmenu;
 6503:   border-bottom:solid 1px $lg_border_color;
 6504: }
 6505: 
 6506: .LC_Box > .LC_hcell {
 6507:   margin: 0 -10px 10px -10px;
 6508: }
 6509: 
 6510: .LC_noBorder {
 6511:   border: 0;
 6512: }
 6513: 
 6514: .LC_FormSectionClearButton input {
 6515:   background-color:transparent;
 6516:   border: none;
 6517:   cursor:pointer;
 6518:   text-decoration:underline;
 6519: }
 6520: 
 6521: .LC_help_open_topic {
 6522:   color: #FFFFFF;
 6523:   background-color: #EEEEFF;
 6524:   margin: 1px;
 6525:   padding: 4px;
 6526:   border: 1px solid #000033;
 6527:   white-space: nowrap;
 6528:   /* vertical-align: middle; */
 6529: }
 6530: 
 6531: dl,
 6532: ul,
 6533: div,
 6534: fieldset {
 6535:   margin: 10px 10px 10px 0;
 6536:   /* overflow: hidden; */
 6537: }
 6538: 
 6539: fieldset > legend {
 6540:   font-weight: bold;
 6541:   padding: 0 5px 0 5px;
 6542: }
 6543: 
 6544: #LC_nav_bar {
 6545:   float: left;
 6546:   background-color: $pgbg_or_bgcolor;
 6547:   margin: 0 0 2px 0;
 6548: }
 6549: 
 6550: #LC_realm {
 6551:   margin: 0.2em 0 0 0;
 6552:   padding: 0;
 6553:   font-weight: bold;
 6554:   text-align: center;
 6555:   background-color: $pgbg_or_bgcolor;
 6556: }
 6557: 
 6558: #LC_nav_bar em {
 6559:   font-weight: bold;
 6560:   font-style: normal;
 6561: }
 6562: 
 6563: ol.LC_primary_menu {
 6564:   float: right;
 6565:   margin: 0;
 6566:   padding: 0;
 6567:   background-color: $pgbg_or_bgcolor;
 6568: }
 6569: 
 6570: ol#LC_PathBreadcrumbs {
 6571:   margin: 0;
 6572: }
 6573: 
 6574: ol.LC_primary_menu li {
 6575:   color: RGB(80, 80, 80);
 6576:   vertical-align: middle;
 6577:   text-align: left;
 6578:   list-style: none;
 6579:   float: left;
 6580: }
 6581: 
 6582: ol.LC_primary_menu li a {
 6583:   display: block;
 6584:   margin: 0;
 6585:   padding: 0 5px 0 10px;
 6586:   text-decoration: none;
 6587: }
 6588: 
 6589: ol.LC_primary_menu li ul {
 6590:   display: none;
 6591:   width: 10em;
 6592:   background-color: $data_table_light;
 6593: }
 6594: 
 6595: ol.LC_primary_menu li:hover ul, ol.LC_primary_menu li.hover ul {
 6596:   display: block;
 6597:   position: absolute;
 6598:   margin: 0;
 6599:   padding: 0;
 6600:   z-index: 2;
 6601: }
 6602: 
 6603: ol.LC_primary_menu li:hover li, ol.LC_primary_menu li.hover li {
 6604:   font-size: 90%;
 6605:   vertical-align: top;
 6606:   float: none;
 6607:   border-left: 1px solid black;
 6608:   border-right: 1px solid black;
 6609: }
 6610: 
 6611: ol.LC_primary_menu li:hover li a, ol.LC_primary_menu li.hover li a {
 6612:   background-color:$data_table_light;
 6613: }
 6614: 
 6615: ol.LC_primary_menu li li a:hover {
 6616:    color:$button_hover;
 6617:    background-color:$data_table_dark;
 6618: }
 6619: 
 6620: ol.LC_primary_menu li img {
 6621:   vertical-align: bottom;
 6622:   height: 1.1em;
 6623:   margin: 0.2em 0 0 0;
 6624: }
 6625: 
 6626: ol.LC_primary_menu a {
 6627:   color: RGB(80, 80, 80);
 6628:   text-decoration: none;
 6629: }
 6630: 
 6631: ol.LC_primary_menu a.LC_new_message {
 6632:   font-weight:bold;
 6633:   color: darkred;
 6634: }
 6635: 
 6636: ol.LC_docs_parameters {
 6637:   margin-left: 0;
 6638:   padding: 0;
 6639:   list-style: none;
 6640: }
 6641: 
 6642: ol.LC_docs_parameters li {
 6643:   margin: 0;
 6644:   padding-right: 20px;
 6645:   display: inline;
 6646: }
 6647: 
 6648: ol.LC_docs_parameters li:before {
 6649:   content: "\\002022 \\0020";
 6650: }
 6651: 
 6652: li.LC_docs_parameters_title {
 6653:   font-weight: bold;
 6654: }
 6655: 
 6656: ol.LC_docs_parameters li.LC_docs_parameters_title:before {
 6657:   content: "";
 6658: }
 6659: 
 6660: ul#LC_secondary_menu {
 6661:   clear: right;
 6662:   color: $fontmenu;
 6663:   background: $tabbg;
 6664:   list-style: none;
 6665:   padding: 0;
 6666:   margin: 0;
 6667:   width: 100%;
 6668:   text-align: left;
 6669:   float: left;
 6670: }
 6671: 
 6672: ul#LC_secondary_menu li {
 6673:   font-weight: bold;
 6674:   line-height: 1.8em;
 6675:   border-right: 1px solid black;
 6676:   float: left;
 6677: }
 6678: 
 6679: ul#LC_secondary_menu li.LC_hoverable:hover, ul#LC_secondary_menu li.hover {
 6680:   background-color: $data_table_light;
 6681: }
 6682: 
 6683: ul#LC_secondary_menu li a {
 6684:   padding: 0 0.8em;
 6685: }
 6686: 
 6687: ul#LC_secondary_menu li ul {
 6688:   display: none;
 6689: }
 6690: 
 6691: ul#LC_secondary_menu li:hover ul, ul#LC_secondary_menu li.hover ul {
 6692:   display: block;
 6693:   position: absolute;
 6694:   margin: 0;
 6695:   padding: 0;
 6696:   list-style:none;
 6697:   float: none;
 6698:   background-color: $data_table_light;
 6699:   z-index: 2;
 6700:   margin-left: -1px;
 6701: }
 6702: 
 6703: ul#LC_secondary_menu li ul li {
 6704:   font-size: 90%;
 6705:   vertical-align: top;
 6706:   border-left: 1px solid black;
 6707:   border-right: 1px solid black;
 6708:   background-color: $data_table_light
 6709:   list-style:none;
 6710:   float: none;
 6711: }
 6712: 
 6713: ul#LC_secondary_menu li ul li:hover, ul#LC_secondary_menu li ul li.hover {
 6714:   background-color: $data_table_dark;
 6715: }
 6716: 
 6717: ul.LC_TabContent {
 6718:   display:block;
 6719:   background: $sidebg;
 6720:   border-bottom: solid 1px $lg_border_color;
 6721:   list-style:none;
 6722:   margin: -1px -10px 0 -10px;
 6723:   padding: 0;
 6724: }
 6725: 
 6726: ul.LC_TabContent li,
 6727: ul.LC_TabContentBigger li {
 6728:   float:left;
 6729: }
 6730: 
 6731: ul#LC_secondary_menu li a {
 6732:   color: $fontmenu;
 6733:   text-decoration: none;
 6734: }
 6735: 
 6736: ul.LC_TabContent {
 6737:   min-height:20px;
 6738: }
 6739: 
 6740: ul.LC_TabContent li {
 6741:   vertical-align:middle;
 6742:   padding: 0 16px 0 10px;
 6743:   background-color:$tabbg;
 6744:   border-bottom:solid 1px $lg_border_color;
 6745:   border-left: solid 1px $font;
 6746: }
 6747: 
 6748: ul.LC_TabContent .right {
 6749:   float:right;
 6750: }
 6751: 
 6752: ul.LC_TabContent li a,
 6753: ul.LC_TabContent li {
 6754:   color:rgb(47,47,47);
 6755:   text-decoration:none;
 6756:   font-size:95%;
 6757:   font-weight:bold;
 6758:   min-height:20px;
 6759: }
 6760: 
 6761: ul.LC_TabContent li a:hover,
 6762: ul.LC_TabContent li a:focus {
 6763:   color: $button_hover;
 6764:   background:none;
 6765:   outline:none;
 6766: }
 6767: 
 6768: ul.LC_TabContent li:hover {
 6769:   color: $button_hover;
 6770:   cursor:pointer;
 6771: }
 6772: 
 6773: ul.LC_TabContent li.active {
 6774:   color: $font;
 6775:   background:#FFFFFF url(/adm/lonIcons/open.gif) no-repeat scroll right center;
 6776:   border-bottom:solid 1px #FFFFFF;
 6777:   cursor: default;
 6778: }
 6779: 
 6780: ul.LC_TabContent li.active a {
 6781:   color:$font;
 6782:   background:#FFFFFF;
 6783:   outline: none;
 6784: }
 6785: 
 6786: ul.LC_TabContent li.goback {
 6787:   float: left;
 6788:   border-left: none;
 6789: }
 6790: 
 6791: #maincoursedoc {
 6792:   clear:both;
 6793: }
 6794: 
 6795: ul.LC_TabContentBigger {
 6796:   display:block;
 6797:   list-style:none;
 6798:   padding: 0;
 6799: }
 6800: 
 6801: ul.LC_TabContentBigger li {
 6802:   vertical-align:bottom;
 6803:   height: 30px;
 6804:   font-size:110%;
 6805:   font-weight:bold;
 6806:   color: #737373;
 6807: }
 6808: 
 6809: ul.LC_TabContentBigger li.active {
 6810:   position: relative;
 6811:   top: 1px;
 6812: }
 6813: 
 6814: ul.LC_TabContentBigger li a {
 6815:   background:url('/adm/lonIcons/tabbgleft.gif') left bottom no-repeat;
 6816:   height: 30px;
 6817:   line-height: 30px;
 6818:   text-align: center;
 6819:   display: block;
 6820:   text-decoration: none;
 6821:   outline: none;  
 6822: }
 6823: 
 6824: ul.LC_TabContentBigger li.active a {
 6825:   background:url('/adm/lonIcons/tabbgleft.gif') left top no-repeat;
 6826:   color:$font;
 6827: }
 6828: 
 6829: ul.LC_TabContentBigger li b {
 6830:   background: url('/adm/lonIcons/tabbgright.gif') no-repeat right bottom;
 6831:   display: block;
 6832:   float: left;
 6833:   padding: 0 30px;
 6834:   border-bottom: 1px solid $lg_border_color;
 6835: }
 6836: 
 6837: ul.LC_TabContentBigger li:hover b {
 6838:   color:$button_hover;
 6839: }
 6840: 
 6841: ul.LC_TabContentBigger li.active b {
 6842:   background:url('/adm/lonIcons/tabbgright.gif') right top no-repeat;
 6843:   color:$font;
 6844:   border: 0;
 6845: }
 6846: 
 6847: 
 6848: ul.LC_CourseBreadcrumbs {
 6849:   background: $sidebg;
 6850:   height: 2em;
 6851:   padding-left: 10px;
 6852:   margin: 0;
 6853:   list-style-position: inside;
 6854: }
 6855: 
 6856: ol#LC_MenuBreadcrumbs,
 6857: ol#LC_PathBreadcrumbs {
 6858:   padding-left: 10px;
 6859:   margin: 0;
 6860:   height: 2.5em;  /* equal to #LC_breadcrumbs line-height */
 6861: }
 6862: 
 6863: ol#LC_MenuBreadcrumbs li,
 6864: ol#LC_PathBreadcrumbs li,
 6865: ul.LC_CourseBreadcrumbs li {
 6866:   display: inline;
 6867:   white-space: normal;  
 6868: }
 6869: 
 6870: ol#LC_MenuBreadcrumbs li a,
 6871: ul.LC_CourseBreadcrumbs li a {
 6872:   text-decoration: none;
 6873:   font-size:90%;
 6874: }
 6875: 
 6876: ol#LC_MenuBreadcrumbs h1 {
 6877:   display: inline;
 6878:   font-size: 90%;
 6879:   line-height: 2.5em;
 6880:   margin: 0;
 6881:   padding: 0;
 6882: }
 6883: 
 6884: ol#LC_PathBreadcrumbs li a {
 6885:   text-decoration:none;
 6886:   font-size:100%;
 6887:   font-weight:bold;
 6888: }
 6889: 
 6890: .LC_Box {
 6891:   border: solid 1px $lg_border_color;
 6892:   padding: 0 10px 10px 10px;
 6893: }
 6894: 
 6895: .LC_DocsBox {
 6896:   border: solid 1px $lg_border_color;
 6897:   padding: 0 0 10px 10px;
 6898: }
 6899: 
 6900: .LC_AboutMe_Image {
 6901:   float:left;
 6902:   margin-right:10px;
 6903: }
 6904: 
 6905: .LC_Clear_AboutMe_Image {
 6906:   clear:left;
 6907: }
 6908: 
 6909: dl.LC_ListStyleClean dt {
 6910:   padding-right: 5px;
 6911:   display: table-header-group;
 6912: }
 6913: 
 6914: dl.LC_ListStyleClean dd {
 6915:   display: table-row;
 6916: }
 6917: 
 6918: .LC_ListStyleClean,
 6919: .LC_ListStyleSimple,
 6920: .LC_ListStyleNormal,
 6921: .LC_ListStyleSpecial {
 6922:   /* display:block; */
 6923:   list-style-position: inside;
 6924:   list-style-type: none;
 6925:   overflow: hidden;
 6926:   padding: 0;
 6927: }
 6928: 
 6929: .LC_ListStyleSimple li,
 6930: .LC_ListStyleSimple dd,
 6931: .LC_ListStyleNormal li,
 6932: .LC_ListStyleNormal dd,
 6933: .LC_ListStyleSpecial li,
 6934: .LC_ListStyleSpecial dd {
 6935:   margin: 0;
 6936:   padding: 5px 5px 5px 10px;
 6937:   clear: both;
 6938: }
 6939: 
 6940: .LC_ListStyleClean li,
 6941: .LC_ListStyleClean dd {
 6942:   padding-top: 0;
 6943:   padding-bottom: 0;
 6944: }
 6945: 
 6946: .LC_ListStyleSimple dd,
 6947: .LC_ListStyleSimple li {
 6948:   border-bottom: solid 1px $lg_border_color;
 6949: }
 6950: 
 6951: .LC_ListStyleSpecial li,
 6952: .LC_ListStyleSpecial dd {
 6953:   list-style-type: none;
 6954:   background-color: RGB(220, 220, 220);
 6955:   margin-bottom: 4px;
 6956: }
 6957: 
 6958: table.LC_SimpleTable {
 6959:   margin:5px;
 6960:   border:solid 1px $lg_border_color;
 6961: }
 6962: 
 6963: table.LC_SimpleTable tr {
 6964:   padding: 0;
 6965:   border:solid 1px $lg_border_color;
 6966: }
 6967: 
 6968: table.LC_SimpleTable thead {
 6969:   background:rgb(220,220,220);
 6970: }
 6971: 
 6972: div.LC_columnSection {
 6973:   display: block;
 6974:   clear: both;
 6975:   overflow: hidden;
 6976:   margin: 0;
 6977: }
 6978: 
 6979: div.LC_columnSection>* {
 6980:   float: left;
 6981:   margin: 10px 20px 10px 0;
 6982:   overflow:hidden;
 6983: }
 6984: 
 6985: table em {
 6986:   font-weight: bold;
 6987:   font-style: normal;
 6988: }
 6989: 
 6990: table.LC_tableBrowseRes,
 6991: table.LC_tableOfContent {
 6992:   border:none;
 6993:   border-spacing: 1px;
 6994:   padding: 3px;
 6995:   background-color: #FFFFFF;
 6996:   font-size: 90%;
 6997: }
 6998: 
 6999: table.LC_tableOfContent {
 7000:   border-collapse: collapse;
 7001: }
 7002: 
 7003: table.LC_tableBrowseRes a,
 7004: table.LC_tableOfContent a {
 7005:   background-color: transparent;
 7006:   text-decoration: none;
 7007: }
 7008: 
 7009: table.LC_tableOfContent img {
 7010:   border: none;
 7011:   height: 1.3em;
 7012:   vertical-align: text-bottom;
 7013:   margin-right: 0.3em;
 7014: }
 7015: 
 7016: a#LC_content_toolbar_firsthomework {
 7017:   background-image:url(/res/adm/pages/open-first-problem.gif);
 7018: }
 7019: 
 7020: a#LC_content_toolbar_everything {
 7021:   background-image:url(/res/adm/pages/show-all.gif);
 7022: }
 7023: 
 7024: a#LC_content_toolbar_uncompleted {
 7025:   background-image:url(/res/adm/pages/show-incomplete-problems.gif);
 7026: }
 7027: 
 7028: #LC_content_toolbar_clearbubbles {
 7029:   background-image:url(/res/adm/pages/mark-discussionentries-read.gif);
 7030: }
 7031: 
 7032: a#LC_content_toolbar_changefolder {
 7033:   background : url(/res/adm/pages/close-all-folders.gif) top center ;
 7034: }
 7035: 
 7036: a#LC_content_toolbar_changefolder_toggled {
 7037:   background-image:url(/res/adm/pages/open-all-folders.gif);
 7038: }
 7039: 
 7040: a#LC_content_toolbar_edittoplevel {
 7041:   background-image:url(/res/adm/pages/edittoplevel.gif);
 7042: }
 7043: 
 7044: ul#LC_toolbar li a:hover {
 7045:   background-position: bottom center;
 7046: }
 7047: 
 7048: ul#LC_toolbar {
 7049:   padding: 0;
 7050:   margin: 2px;
 7051:   list-style:none;
 7052:   position:relative;
 7053:   background-color:white;
 7054:   overflow: auto;
 7055: }
 7056: 
 7057: ul#LC_toolbar li {
 7058:   border:1px solid white;
 7059:   padding: 0;
 7060:   margin: 0;
 7061:   float: left;
 7062:   display:inline;
 7063:   vertical-align:middle;
 7064:   white-space: nowrap;
 7065: }
 7066: 
 7067: 
 7068: a.LC_toolbarItem {
 7069:   display:block;
 7070:   padding: 0;
 7071:   margin: 0;
 7072:   height: 32px;
 7073:   width: 32px;
 7074:   color:white;
 7075:   border: none;
 7076:   background-repeat:no-repeat;
 7077:   background-color:transparent;
 7078: }
 7079: 
 7080: ul.LC_funclist {
 7081:     margin: 0;
 7082:     padding: 0.5em 1em 0.5em 0;
 7083: }
 7084: 
 7085: ul.LC_funclist > li:first-child {
 7086:     font-weight:bold; 
 7087:     margin-left:0.8em;
 7088: }
 7089: 
 7090: ul.LC_funclist + ul.LC_funclist {
 7091:     /* 
 7092:        left border as a seperator if we have more than
 7093:        one list 
 7094:     */
 7095:     border-left: 1px solid $sidebg;
 7096:     /* 
 7097:        this hides the left border behind the border of the 
 7098:        outer box if element is wrapped to the next 'line' 
 7099:     */
 7100:     margin-left: -1px;
 7101: }
 7102: 
 7103: ul.LC_funclist li {
 7104:   display: inline;
 7105:   white-space: nowrap;
 7106:   margin: 0 0 0 25px;
 7107:   line-height: 150%;
 7108: }
 7109: 
 7110: .LC_hidden {
 7111:   display: none;
 7112: }
 7113: 
 7114: .LCmodal-overlay {
 7115: 		position:fixed;
 7116: 		top:0;
 7117: 		right:0;
 7118: 		bottom:0;
 7119: 		left:0;
 7120: 		height:100%;
 7121: 		width:100%;
 7122: 		margin:0;
 7123: 		padding:0;
 7124: 		background:#999;
 7125: 		opacity:.75;
 7126: 		filter: alpha(opacity=75);
 7127: 		-moz-opacity: 0.75;
 7128: 		z-index:101;
 7129: }
 7130: 
 7131: * html .LCmodal-overlay {   
 7132: 		position: absolute;
 7133: 		height: expression(document.body.scrollHeight > document.body.offsetHeight ? document.body.scrollHeight : document.body.offsetHeight + 'px');
 7134: }
 7135: 
 7136: .LCmodal-window {
 7137: 		position:fixed;
 7138: 		top:50%;
 7139: 		left:50%;
 7140: 		margin:0;
 7141: 		padding:0;
 7142: 		z-index:102;
 7143: 	}
 7144: 
 7145: * html .LCmodal-window {
 7146: 		position:absolute;
 7147: }
 7148: 
 7149: .LCclose-window {
 7150: 		position:absolute;
 7151: 		width:32px;
 7152: 		height:32px;
 7153: 		right:8px;
 7154: 		top:8px;
 7155: 		background:transparent url('/res/adm/pages/process-stop.png') no-repeat scroll right top;
 7156: 		text-indent:-99999px;
 7157: 		overflow:hidden;
 7158: 		cursor:pointer;
 7159: }
 7160: 
 7161: /*
 7162:   styles used by TTH when "Default set of options to pass to tth/m
 7163:   when converting TeX" in course settings has been set
 7164: 
 7165:   option passed: -t
 7166: 
 7167: */
 7168: 
 7169: td div.comp { margin-top: -0.6ex; margin-bottom: -1ex;}
 7170: td div.comb { margin-top: -0.6ex; margin-bottom: -.6ex;}
 7171: td div.hrcomp { line-height: 0.9; margin-top: -0.8ex; margin-bottom: -1ex;}
 7172: td div.norm {line-height:normal;}
 7173: 
 7174: /*
 7175:   option passed -y3
 7176: */
 7177: 
 7178: span.roman {font-family: serif; font-style: normal; font-weight: normal;}
 7179: span.overacc2 {position: relative;  left: .8em; top: -1.2ex;}
 7180: span.overacc1 {position: relative;  left: .6em; top: -1.2ex;}
 7181: 
 7182: END
 7183: }
 7184: 
 7185: =pod
 7186: 
 7187: =item * &headtag()
 7188: 
 7189: Returns a uniform footer for LON-CAPA web pages.
 7190: 
 7191: Inputs: $title - optional title for the head
 7192:         $head_extra - optional extra HTML to put inside the <head>
 7193:         $args - optional arguments
 7194:             force_register - if is true call registerurl so the remote is 
 7195:                              informed
 7196:             redirect       -> array ref of
 7197:                                    1- seconds before redirect occurs
 7198:                                    2- url to redirect to
 7199:                                    3- whether the side effect should occur
 7200:                            (side effect of setting 
 7201:                                $env{'internal.head.redirect'} to the url 
 7202:                                redirected too)
 7203:             domain         -> force to color decorate a page for a specific
 7204:                                domain
 7205:             function       -> force usage of a specific rolish color scheme
 7206:             bgcolor        -> override the default page bgcolor
 7207:             no_auto_mt_title
 7208:                            -> prevent &mt()ing the title arg
 7209: 
 7210: =cut
 7211: 
 7212: sub headtag {
 7213:     my ($title,$head_extra,$args) = @_;
 7214:     
 7215:     my $function = $args->{'function'} || &get_users_function();
 7216:     my $domain   = $args->{'domain'}   || &determinedomain();
 7217:     my $bgcolor  = $args->{'bgcolor'}  || &designparm($function.'.pgbg',$domain);
 7218:     my $url = join(':',$env{'user.name'},$env{'user.domain'},
 7219: 		   $Apache::lonnet::perlvar{'lonVersion'},
 7220: 		   #time(),
 7221: 		   $env{'environment.color.timestamp'},
 7222: 		   $function,$domain,$bgcolor);
 7223: 
 7224:     $url = '/adm/css/'.&escape($url).'.css';
 7225: 
 7226:     my $result =
 7227: 	'<head>'.
 7228: 	&font_settings();
 7229: 
 7230:     my $inhibitprint = &print_suppression();
 7231: 
 7232:     if (!$args->{'frameset'}) {
 7233: 	$result .= &Apache::lonhtmlcommon::htmlareaheaders();
 7234:     }
 7235:     if ($args->{'force_register'} && $env{'request.noversionuri'} !~ m{^/res/adm/pages/}) {
 7236:         $result .= Apache::lonxml::display_title();
 7237:     }
 7238:     if (!$args->{'no_nav_bar'} 
 7239: 	&& !$args->{'only_body'}
 7240: 	&& !$args->{'frameset'}) {
 7241: 	$result .= &help_menu_js();
 7242:         $result.=&modal_window();
 7243:         $result.=&togglebox_script();
 7244:         $result.=&wishlist_window();
 7245:         $result.=&LCprogressbarUpdate_script();
 7246:     } else {
 7247:         if ($args->{'add_modal'}) {
 7248:            $result.=&modal_window();
 7249:         }
 7250:         if ($args->{'add_wishlist'}) {
 7251:            $result.=&wishlist_window();
 7252:         }
 7253:         if ($args->{'add_togglebox'}) {
 7254:            $result.=&togglebox_script();
 7255:         }
 7256:         if ($args->{'add_progressbar'}) {
 7257:            $result.=&LCprogressbarUpdate_script();
 7258:         }
 7259:     }
 7260:     if (ref($args->{'redirect'})) {
 7261: 	my ($time,$url,$inhibit_continue) = @{$args->{'redirect'}};
 7262: 	$url = &Apache::lonenc::check_encrypt($url);
 7263: 	if (!$inhibit_continue) {
 7264: 	    $env{'internal.head.redirect'} = $url;
 7265: 	}
 7266: 	$result.=<<ADDMETA
 7267: <meta http-equiv="pragma" content="no-cache" />
 7268: <meta http-equiv="Refresh" content="$time; url=$url" />
 7269: ADDMETA
 7270:     }
 7271:     if (!defined($title)) {
 7272: 	$title = 'The LearningOnline Network with CAPA';
 7273:     }
 7274:     if (!$args->{'no_auto_mt_title'}) { $title = &mt($title); }
 7275:     $result .= '<title> LON-CAPA '.$title.'</title>'
 7276: 	.'<link rel="stylesheet" type="text/css" href="'.$url.'" />'
 7277:         .$inhibitprint
 7278: 	.$head_extra;
 7279:     return $result.'</head>';
 7280: }
 7281: 
 7282: =pod
 7283: 
 7284: =item * &font_settings()
 7285: 
 7286: Returns neccessary <meta> to set the proper encoding
 7287: 
 7288: Inputs: none
 7289: 
 7290: =cut
 7291: 
 7292: sub font_settings {
 7293:     my $headerstring='';
 7294:     if (!$env{'browser.mathml'} && $env{'browser.unicode'}) {
 7295: 	$headerstring.=
 7296: 	    '<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />';
 7297:     }
 7298:     return $headerstring;
 7299: }
 7300: 
 7301: =pod
 7302: 
 7303: =item * &print_suppression()
 7304: 
 7305: In course context returns css which causes the body to be blank when media="print",
 7306: if printout generation is unavailable for the current resource.
 7307: 
 7308: This could be because:
 7309: 
 7310: (a) printstartdate is in the future
 7311: 
 7312: (b) printenddate is in the past
 7313: 
 7314: (c) there is an active exam block with "printout"
 7315: functionality blocked
 7316: 
 7317: Users with pav, pfo or evb privileges are exempt.
 7318: 
 7319: Inputs: none
 7320: 
 7321: =cut
 7322: 
 7323: 
 7324: sub print_suppression {
 7325:     my $noprint;
 7326:     if ($env{'request.course.id'}) {
 7327:         my $scope = $env{'request.course.id'};
 7328:         if ((&Apache::lonnet::allowed('pav',$scope)) ||
 7329:             (&Apache::lonnet::allowed('pfo',$scope))) {
 7330:             return;
 7331:         }
 7332:         if ($env{'request.course.sec'} ne '') {
 7333:             $scope .= "/$env{'request.course.sec'}";
 7334:             if ((&Apache::lonnet::allowed('pav',$scope)) ||
 7335:                 (&Apache::lonnet::allowed('pfo',$scope))) {
 7336:                 return;
 7337:             }
 7338:         }
 7339:         my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 7340:         my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 7341:         my $blocked = &blocking_status('printout',$cnum,$cdom);
 7342:         if ($blocked) {
 7343:             my $checkrole = "cm./$cdom/$cnum";
 7344:             if ($env{'request.course.sec'} ne '') {
 7345:                 $checkrole .= "/$env{'request.course.sec'}";
 7346:             }
 7347:             unless ((&Apache::lonnet::allowed('evb',undef,undef,$checkrole)) &&
 7348:                     ($env{'request.role'} !~ m{^st\./$cdom/$cnum})) {
 7349:                 $noprint = 1;
 7350:             }
 7351:         }
 7352:         unless ($noprint) {
 7353:             my $symb = &Apache::lonnet::symbread();
 7354:             if ($symb ne '') {
 7355:                 my $navmap = Apache::lonnavmaps::navmap->new();
 7356:                 if (ref($navmap)) {
 7357:                     my $res = $navmap->getBySymb($symb);
 7358:                     if (ref($res)) {
 7359:                         if (!$res->resprintable()) {
 7360:                             $noprint = 1;
 7361:                         }
 7362:                     }
 7363:                 }
 7364:             }
 7365:         }
 7366:         if ($noprint) {
 7367:             return <<"ENDSTYLE";
 7368: <style type="text/css" media="print">
 7369:     body { display:none }
 7370: </style>
 7371: ENDSTYLE
 7372:         }
 7373:     }
 7374:     return;
 7375: }
 7376: 
 7377: =pod
 7378: 
 7379: =item * &xml_begin()
 7380: 
 7381: Returns the needed doctype and <html>
 7382: 
 7383: Inputs: none
 7384: 
 7385: =cut
 7386: 
 7387: sub xml_begin {
 7388:     my $output='';
 7389: 
 7390:     if ($env{'browser.mathml'}) {
 7391: 	$output='<?xml version="1.0"?>'
 7392:             #.'<?xml-stylesheet type="text/css" href="/adm/MathML/mathml.css"?>'."\n"
 7393: #            .'<!DOCTYPE html SYSTEM "/adm/MathML/mathml.dtd" '
 7394:             
 7395: #	    .'<!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">] >'
 7396: 	    .'<!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">'
 7397:             .'<html xmlns:math="http://www.w3.org/1998/Math/MathML" ' 
 7398: 	    .'xmlns="http://www.w3.org/1999/xhtml">';
 7399:     } else {
 7400: 	$output='<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">'
 7401:            .'<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">';
 7402:     }
 7403:     return $output;
 7404: }
 7405: 
 7406: =pod
 7407: 
 7408: =item * &start_page()
 7409: 
 7410: Returns a complete <html> .. <body> section for LON-CAPA web pages.
 7411: 
 7412: Inputs:
 7413: 
 7414: =over 4
 7415: 
 7416: $title - optional title for the page
 7417: 
 7418: $head_extra - optional extra HTML to incude inside the <head>
 7419: 
 7420: $args - additional optional args supported are:
 7421: 
 7422: =over 8
 7423: 
 7424:              only_body      -> is true will set &bodytag() onlybodytag
 7425:                                     arg on
 7426:              no_nav_bar     -> is true will set &bodytag() no_nav_bar arg on
 7427:              add_entries    -> additional attributes to add to the  <body>
 7428:              domain         -> force to color decorate a page for a 
 7429:                                     specific domain
 7430:              function       -> force usage of a specific rolish color
 7431:                                     scheme
 7432:              redirect       -> see &headtag()
 7433:              bgcolor        -> override the default page bg color
 7434:              js_ready       -> return a string ready for being used in 
 7435:                                     a javascript writeln
 7436:              html_encode    -> return a string ready for being used in 
 7437:                                     a html attribute
 7438:              force_register -> if is true will turn on the &bodytag()
 7439:                                     $forcereg arg
 7440:              frameset       -> if true will start with a <frameset>
 7441:                                     rather than <body>
 7442:              skip_phases    -> hash ref of 
 7443:                                     head -> skip the <html><head> generation
 7444:                                     body -> skip all <body> generation
 7445:              no_auto_mt_title -> prevent &mt()ing the title arg
 7446:              inherit_jsmath -> when creating popup window in a page,
 7447:                                     should it have jsmath forced on by the
 7448:                                     current page
 7449:              bread_crumbs ->             Array containing breadcrumbs
 7450:              bread_crumbs_component ->  if exists show it as headline else show only the breadcrumbs
 7451:              group          -> includes the current group, if page is for a 
 7452:                                specific group  
 7453: 
 7454: =back
 7455: 
 7456: =back
 7457: 
 7458: =cut
 7459: 
 7460: sub start_page {
 7461:     my ($title,$head_extra,$args) = @_;
 7462:     #&Apache::lonnet::logthis("start_page ".join(':',caller(0)));
 7463: 
 7464:     $env{'internal.start_page'}++;
 7465:     my ($result,@advtools);
 7466: 
 7467:     if (! exists($args->{'skip_phases'}{'head'}) ) {
 7468:         $result .= &xml_begin() . &headtag($title, $head_extra, $args);
 7469:     }
 7470:     
 7471:     if (! exists($args->{'skip_phases'}{'body'}) ) {
 7472: 	if ($args->{'frameset'}) {
 7473: 	    my $attr_string = &make_attr_string($args->{'force_register'},
 7474: 						$args->{'add_entries'});
 7475: 	    $result .= "\n<frameset $attr_string>\n";
 7476:         } else {
 7477:             $result .=
 7478:                 &bodytag($title, 
 7479:                          $args->{'function'},       $args->{'add_entries'},
 7480:                          $args->{'only_body'},      $args->{'domain'},
 7481:                          $args->{'force_register'}, $args->{'no_nav_bar'},
 7482:                          $args->{'bgcolor'},        $args,
 7483:                          \@advtools);
 7484:         }
 7485:     }
 7486: 
 7487:     if ($args->{'js_ready'}) {
 7488: 		$result = &js_ready($result);
 7489:     }
 7490:     if ($args->{'html_encode'}) {
 7491: 		$result = &html_encode($result);
 7492:     }
 7493: 
 7494:     # Preparation for new and consistent functionlist at top of screen
 7495:     # if ($args->{'functionlist'}) {
 7496:     #            $result .= &build_functionlist();
 7497:     #}
 7498: 
 7499:     # Don't add anything more if only_body wanted or in const space
 7500:     return $result if    $args->{'only_body'} 
 7501:                       || $env{'request.state'} eq 'construct';
 7502: 
 7503:     #Breadcrumbs
 7504:     if (exists($args->{'bread_crumbs'}) or exists($args->{'bread_crumbs_component'})) {
 7505: 		&Apache::lonhtmlcommon::clear_breadcrumbs();
 7506: 		#if any br links exists, add them to the breadcrumbs
 7507: 		if (exists($args->{'bread_crumbs'}) and ref($args->{'bread_crumbs'}) eq 'ARRAY') {         
 7508: 			foreach my $crumb (@{$args->{'bread_crumbs'}}){
 7509: 				&Apache::lonhtmlcommon::add_breadcrumb($crumb);
 7510: 			}
 7511: 		}
 7512:                 # if @advtools array contains items add then to the breadcrumbs
 7513:                 if (@advtools > 0) {
 7514:                     &Apache::lonmenu::advtools_crumbs(@advtools);
 7515:                 }
 7516: 
 7517: 		#if bread_crumbs_component exists show it as headline else show only the breadcrumbs
 7518: 		if(exists($args->{'bread_crumbs_component'})){
 7519: 			$result .= &Apache::lonhtmlcommon::breadcrumbs($args->{'bread_crumbs_component'});
 7520: 		}else{
 7521: 			$result .= &Apache::lonhtmlcommon::breadcrumbs();
 7522: 		}
 7523:     }
 7524:     return $result;
 7525: }
 7526: 
 7527: sub end_page {
 7528:     my ($args) = @_;
 7529:     $env{'internal.end_page'}++;
 7530:     my $result;
 7531:     if ($args->{'discussion'}) {
 7532: 	my ($target,$parser);
 7533: 	if (ref($args->{'discussion'})) {
 7534: 	    ($target,$parser) =($args->{'discussion'}{'target'},
 7535: 				$args->{'discussion'}{'parser'});
 7536: 	}
 7537: 	$result .= &Apache::lonxml::xmlend($target,$parser);
 7538:     }
 7539:     if ($args->{'frameset'}) {
 7540: 	$result .= '</frameset>';
 7541:     } else {
 7542: 	$result .= &endbodytag($args);
 7543:     }
 7544:     unless ($args->{'notbody'}) {
 7545:         $result .= "\n</html>";
 7546:     }
 7547: 
 7548:     if ($args->{'js_ready'}) {
 7549: 	$result = &js_ready($result);
 7550:     }
 7551: 
 7552:     if ($args->{'html_encode'}) {
 7553: 	$result = &html_encode($result);
 7554:     }
 7555: 
 7556:     return $result;
 7557: }
 7558: 
 7559: sub wishlist_window {
 7560:     return(<<'ENDWISHLIST');
 7561: <script type="text/javascript">
 7562: // <![CDATA[
 7563: // <!-- BEGIN LON-CAPA Internal
 7564: function set_wishlistlink(title, path) {
 7565:     if (!title) {
 7566:         title = document.title;
 7567:         title = title.replace(/^LON-CAPA /,'');
 7568:     }
 7569:     if (!path) {
 7570:         path = location.pathname;
 7571:     }
 7572:     Win = window.open('/adm/wishlist?mode=newLink&setTitle='+title+'&setPath='+path,
 7573:                       'wishlistNewLink','width=560,height=350,scrollbars=0');
 7574: }
 7575: // END LON-CAPA Internal -->
 7576: // ]]>
 7577: </script>
 7578: ENDWISHLIST
 7579: }
 7580: 
 7581: sub modal_window {
 7582:     return(<<'ENDMODAL');
 7583: <script type="text/javascript">
 7584: // <![CDATA[
 7585: // <!-- BEGIN LON-CAPA Internal
 7586: var modalWindow = {
 7587: 	parent:"body",
 7588: 	windowId:null,
 7589: 	content:null,
 7590: 	width:null,
 7591: 	height:null,
 7592: 	close:function()
 7593: 	{
 7594: 	        $(".LCmodal-window").remove();
 7595: 	        $(".LCmodal-overlay").remove();
 7596: 	},
 7597: 	open:function()
 7598: 	{
 7599: 		var modal = "";
 7600: 		modal += "<div class=\"LCmodal-overlay\"></div>";
 7601: 		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;\">";
 7602: 		modal += this.content;
 7603: 		modal += "</div>";	
 7604: 
 7605: 		$(this.parent).append(modal);
 7606: 
 7607: 		$(".LCmodal-window").append("<a class=\"LCclose-window\"></a>");
 7608: 		$(".LCclose-window").click(function(){modalWindow.close();});
 7609: 		$(".LCmodal-overlay").click(function(){modalWindow.close();});
 7610: 	}
 7611: };
 7612: 	var openMyModal = function(source,width,height,scrolling)
 7613: 	{
 7614: 		modalWindow.windowId = "myModal";
 7615: 		modalWindow.width = width;
 7616: 		modalWindow.height = height;
 7617: 		modalWindow.content = "<iframe width='"+width+"' height='"+height+"' frameborder='0' scrolling='"+scrolling+"' allowtransparency='true' src='" + source + "'>&lt/iframe>";
 7618: 		modalWindow.open();
 7619: 	};	
 7620: // END LON-CAPA Internal -->
 7621: // ]]>
 7622: </script>
 7623: ENDMODAL
 7624: }
 7625: 
 7626: sub modal_link {
 7627:     my ($link,$linktext,$width,$height,$target,$scrolling,$title)=@_;
 7628:     unless ($width) { $width=480; }
 7629:     unless ($height) { $height=400; }
 7630:     unless ($scrolling) { $scrolling='yes'; }
 7631:     my $target_attr;
 7632:     if (defined($target)) {
 7633:         $target_attr = 'target="'.$target.'"';
 7634:     }
 7635:     return <<"ENDLINK";
 7636: <a href="$link" $target_attr title="$title" onclick="javascript:openMyModal('$link',$width,$height,'$scrolling'); return false;">
 7637:            $linktext</a>
 7638: ENDLINK
 7639: }
 7640: 
 7641: sub modal_adhoc_script {
 7642:     my ($funcname,$width,$height,$content)=@_;
 7643:     return (<<ENDADHOC);
 7644: <script type="text/javascript">
 7645: // <![CDATA[
 7646:         var $funcname = function()
 7647:         {
 7648:                 modalWindow.windowId = "myModal";
 7649:                 modalWindow.width = $width;
 7650:                 modalWindow.height = $height;
 7651:                 modalWindow.content = '$content';
 7652:                 modalWindow.open();
 7653:         };  
 7654: // ]]>
 7655: </script>
 7656: ENDADHOC
 7657: }
 7658: 
 7659: sub modal_adhoc_inner {
 7660:     my ($funcname,$width,$height,$content)=@_;
 7661:     my $innerwidth=$width-20;
 7662:     $content=&js_ready(
 7663:                &start_page('Dialog',undef,{'only_body'=>1,'bgcolor'=>'#FFFFFF'}).
 7664:                  &start_scrollbox($width.'px',$innerwidth.'px',$height.'px').
 7665:                     $content.
 7666:                  &end_scrollbox().
 7667:                &end_page()
 7668:              );
 7669:     return &modal_adhoc_script($funcname,$width,$height,$content);
 7670: }
 7671: 
 7672: sub modal_adhoc_window {
 7673:     my ($funcname,$width,$height,$content,$linktext)=@_;
 7674:     return &modal_adhoc_inner($funcname,$width,$height,$content).
 7675:            "<a href=\"javascript:$funcname();void(0);\">".$linktext."</a>";
 7676: }
 7677: 
 7678: sub modal_adhoc_launch {
 7679:     my ($funcname,$width,$height,$content)=@_;
 7680:     return &modal_adhoc_inner($funcname,$width,$height,$content).(<<ENDLAUNCH);
 7681: <script type="text/javascript">
 7682: // <![CDATA[
 7683: $funcname();
 7684: // ]]>
 7685: </script>
 7686: ENDLAUNCH
 7687: }
 7688: 
 7689: sub modal_adhoc_close {
 7690:     return (<<ENDCLOSE);
 7691: <script type="text/javascript">
 7692: // <![CDATA[
 7693: modalWindow.close();
 7694: // ]]>
 7695: </script>
 7696: ENDCLOSE
 7697: }
 7698: 
 7699: sub togglebox_script {
 7700:    return(<<ENDTOGGLE);
 7701: <script type="text/javascript"> 
 7702: // <![CDATA[
 7703: function LCtoggleDisplay(id,hidetext,showtext) {
 7704:    link = document.getElementById(id + "link").childNodes[0];
 7705:    with (document.getElementById(id).style) {
 7706:       if (display == "none" ) {
 7707:           display = "inline";
 7708:           link.nodeValue = hidetext;
 7709:         } else {
 7710:           display = "none";
 7711:           link.nodeValue = showtext;
 7712:        }
 7713:    }
 7714: }
 7715: // ]]>
 7716: </script>
 7717: ENDTOGGLE
 7718: }
 7719: 
 7720: sub start_togglebox {
 7721:     my ($id,$heading,$headerbg,$hidetext,$showtext)=@_;
 7722:     unless ($heading) { $heading=''; } else { $heading.=' '; }
 7723:     unless ($showtext) { $showtext=&mt('show'); }
 7724:     unless ($hidetext) { $hidetext=&mt('hide'); }
 7725:     unless ($headerbg) { $headerbg='#FFFFFF'; }
 7726:     return &start_data_table().
 7727:            &start_data_table_header_row().
 7728:            '<td bgcolor="'.$headerbg.'">'.$heading.
 7729:            '[<a id="'.$id.'link" href="javascript:LCtoggleDisplay(\''.$id.'\',\''.$hidetext.'\',\''.
 7730:            $showtext.'\')">'.$showtext.'</a>]</td>'.
 7731:            &end_data_table_header_row().
 7732:            '<tr id="'.$id.'" style="display:none""><td>';
 7733: }
 7734: 
 7735: sub end_togglebox {
 7736:     return '</td></tr>'.&end_data_table();
 7737: }
 7738: 
 7739: sub LCprogressbar_script {
 7740:    my ($id)=@_;
 7741:    return(<<ENDPROGRESS);
 7742: <script type="text/javascript">
 7743: // <![CDATA[
 7744: \$('#progressbar$id').progressbar({
 7745:   value: 0,
 7746:   change: function(event, ui) {
 7747:     var newVal = \$(this).progressbar('option', 'value');
 7748:     \$('.pblabel', this).text(LCprogressTxt);
 7749:   }
 7750: });
 7751: // ]]>
 7752: </script>
 7753: ENDPROGRESS
 7754: }
 7755: 
 7756: sub LCprogressbarUpdate_script {
 7757:    return(<<ENDPROGRESSUPDATE);
 7758: <style type="text/css">
 7759: .ui-progressbar { position:relative; }
 7760: .pblabel { position: absolute; width: 100%; text-align: center; line-height: 1.9em; }
 7761: </style>
 7762: <script type="text/javascript">
 7763: // <![CDATA[
 7764: var LCprogressTxt='---';
 7765: 
 7766: function LCupdateProgress(percent,progresstext,id) {
 7767:    LCprogressTxt=progresstext;
 7768:    \$('#progressbar'+id).progressbar('value',percent);
 7769: }
 7770: // ]]>
 7771: </script>
 7772: ENDPROGRESSUPDATE
 7773: }
 7774: 
 7775: my $LClastpercent;
 7776: my $LCidcnt;
 7777: my $LCcurrentid;
 7778: 
 7779: sub LCprogressbar {
 7780:     my ($r)=(@_);
 7781:     $LClastpercent=0;
 7782:     $LCidcnt++;
 7783:     $LCcurrentid=$$.'_'.$LCidcnt;
 7784:     my $starting=&mt('Starting');
 7785:     my $content=(<<ENDPROGBAR);
 7786: <p>
 7787:   <div id="progressbar$LCcurrentid">
 7788:     <span class="pblabel">$starting</span>
 7789:   </div>
 7790: </p>
 7791: ENDPROGBAR
 7792:     &r_print($r,$content.&LCprogressbar_script($LCcurrentid));
 7793: }
 7794: 
 7795: sub LCprogressbarUpdate {
 7796:     my ($r,$val,$text)=@_;
 7797:     unless ($val) { 
 7798:        if ($LClastpercent) {
 7799:            $val=$LClastpercent;
 7800:        } else {
 7801:            $val=0;
 7802:        }
 7803:     }
 7804:     if ($val<0) { $val=0; }
 7805:     if ($val>100) { $val=0; }
 7806:     $LClastpercent=$val;
 7807:     unless ($text) { $text=$val.'%'; }
 7808:     $text=&js_ready($text);
 7809:     &r_print($r,<<ENDUPDATE);
 7810: <script type="text/javascript">
 7811: // <![CDATA[
 7812: LCupdateProgress($val,'$text','$LCcurrentid');
 7813: // ]]>
 7814: </script>
 7815: ENDUPDATE
 7816: }
 7817: 
 7818: sub LCprogressbarClose {
 7819:     my ($r)=@_;
 7820:     $LClastpercent=0;
 7821:     &r_print($r,<<ENDCLOSE);
 7822: <script type="text/javascript">
 7823: // <![CDATA[
 7824: \$("#progressbar$LCcurrentid").hide('slow'); 
 7825: // ]]>
 7826: </script>
 7827: ENDCLOSE
 7828: }
 7829: 
 7830: sub r_print {
 7831:     my ($r,$to_print)=@_;
 7832:     if ($r) {
 7833:       $r->print($to_print);
 7834:       $r->rflush();
 7835:     } else {
 7836:       print($to_print);
 7837:     }
 7838: }
 7839: 
 7840: sub html_encode {
 7841:     my ($result) = @_;
 7842: 
 7843:     $result = &HTML::Entities::encode($result,'<>&"');
 7844:     
 7845:     return $result;
 7846: }
 7847: 
 7848: sub js_ready {
 7849:     my ($result) = @_;
 7850: 
 7851:     $result =~ s/[\n\r]/ /xmsg;
 7852:     $result =~ s/\\/\\\\/xmsg;
 7853:     $result =~ s/'/\\'/xmsg;
 7854:     $result =~ s{</}{<\\/}xmsg;
 7855:     
 7856:     return $result;
 7857: }
 7858: 
 7859: sub validate_page {
 7860:     if (  exists($env{'internal.start_page'})
 7861: 	  &&     $env{'internal.start_page'} > 1) {
 7862: 	&Apache::lonnet::logthis('start_page called multiple times '.
 7863: 				 $env{'internal.start_page'}.' '.
 7864: 				 $ENV{'request.filename'});
 7865:     }
 7866:     if (  exists($env{'internal.end_page'})
 7867: 	  &&     $env{'internal.end_page'} > 1) {
 7868: 	&Apache::lonnet::logthis('end_page called multiple times '.
 7869: 				 $env{'internal.end_page'}.' '.
 7870: 				 $env{'request.filename'});
 7871:     }
 7872:     if (     exists($env{'internal.start_page'})
 7873: 	&& ! exists($env{'internal.end_page'})) {
 7874: 	&Apache::lonnet::logthis('start_page called without end_page '.
 7875: 				 $env{'request.filename'});
 7876:     }
 7877:     if (   ! exists($env{'internal.start_page'})
 7878: 	&&   exists($env{'internal.end_page'})) {
 7879: 	&Apache::lonnet::logthis('end_page called without start_page'.
 7880: 				 $env{'request.filename'});
 7881:     }
 7882: }
 7883: 
 7884: 
 7885: sub start_scrollbox {
 7886:     my ($outerwidth,$width,$height,$id,$bgcolor)=@_;
 7887:     unless ($outerwidth) { $outerwidth='520px'; }
 7888:     unless ($width) { $width='500px'; }
 7889:     unless ($height) { $height='200px'; }
 7890:     my ($table_id,$div_id,$tdcol);
 7891:     if ($id ne '') {
 7892:         $table_id = " id='table_$id'";
 7893:         $div_id = " id='div_$id'";
 7894:     }
 7895:     if ($bgcolor ne '') {
 7896:         $tdcol = "background-color: $bgcolor;";
 7897:     }
 7898:     return <<"END";
 7899: <table style="width: $outerwidth; border: 1px solid none;"$table_id><tr><td style="width: $width;$tdcol"><div style="overflow:auto; width:$width; height: $height;"$div_id>
 7900: END
 7901: }
 7902: 
 7903: sub end_scrollbox {
 7904:     return '</div></td></tr></table>';
 7905: }
 7906: 
 7907: sub simple_error_page {
 7908:     my ($r,$title,$msg) = @_;
 7909:     my $page =
 7910: 	&Apache::loncommon::start_page($title).
 7911: 	'<p class="LC_error">'.&mt($msg).'</p>'.
 7912: 	&Apache::loncommon::end_page();
 7913:     if (ref($r)) {
 7914: 	$r->print($page);
 7915: 	return;
 7916:     }
 7917:     return $page;
 7918: }
 7919: 
 7920: {
 7921:     my @row_count;
 7922: 
 7923:     sub start_data_table_count {
 7924:         unshift(@row_count, 0);
 7925:         return;
 7926:     }
 7927: 
 7928:     sub end_data_table_count {
 7929:         shift(@row_count);
 7930:         return;
 7931:     }
 7932: 
 7933:     sub start_data_table {
 7934: 	my ($add_class,$id) = @_;
 7935: 	my $css_class = (join(' ','LC_data_table',$add_class));
 7936:         my $table_id;
 7937:         if (defined($id)) {
 7938:             $table_id = ' id="'.$id.'"';
 7939:         }
 7940: 	&start_data_table_count();
 7941: 	return '<table class="'.$css_class.'"'.$table_id.'>'."\n";
 7942:     }
 7943: 
 7944:     sub end_data_table {
 7945: 	&end_data_table_count();
 7946: 	return '</table>'."\n";;
 7947:     }
 7948: 
 7949:     sub start_data_table_row {
 7950: 	my ($add_class, $id) = @_;
 7951: 	$row_count[0]++;
 7952: 	my $css_class = ($row_count[0] % 2)?'LC_odd_row':'LC_even_row';
 7953: 	$css_class = (join(' ',$css_class,$add_class)) unless ($add_class eq '');
 7954:         $id = (' id="'.$id.'"') unless ($id eq '');
 7955:         return  '<tr class="'.$css_class.'"'.$id.'>'."\n";
 7956:     }
 7957:     
 7958:     sub continue_data_table_row {
 7959: 	my ($add_class, $id) = @_;
 7960: 	my $css_class = ($row_count[0] % 2)?'LC_odd_row':'LC_even_row';
 7961: 	$css_class = (join(' ',$css_class,$add_class)) unless ($add_class eq '');
 7962:         $id = (' id="'.$id.'"') unless ($id eq '');
 7963:         return  '<tr class="'.$css_class.'"'.$id.'>'."\n";
 7964:     }
 7965: 
 7966:     sub end_data_table_row {
 7967: 	return '</tr>'."\n";;
 7968:     }
 7969: 
 7970:     sub start_data_table_empty_row {
 7971: #	$row_count[0]++;
 7972: 	return  '<tr class="LC_empty_row" >'."\n";;
 7973:     }
 7974: 
 7975:     sub end_data_table_empty_row {
 7976: 	return '</tr>'."\n";;
 7977:     }
 7978: 
 7979:     sub start_data_table_header_row {
 7980: 	return  '<tr class="LC_header_row">'."\n";;
 7981:     }
 7982: 
 7983:     sub end_data_table_header_row {
 7984: 	return '</tr>'."\n";;
 7985:     }
 7986: 
 7987:     sub data_table_caption {
 7988:         my $caption = shift;
 7989:         return "<caption class=\"LC_caption\">$caption</caption>";
 7990:     }
 7991: }
 7992: 
 7993: =pod
 7994: 
 7995: =item * &inhibit_menu_check($arg)
 7996: 
 7997: Checks for a inhibitmenu state and generates output to preserve it
 7998: 
 7999: Inputs:         $arg - can be any of
 8000:                      - undef - in which case the return value is a string 
 8001:                                to add  into arguments list of a uri
 8002:                      - 'input' - in which case the return value is a HTML
 8003:                                  <form> <input> field of type hidden to
 8004:                                  preserve the value
 8005:                      - a url - in which case the return value is the url with
 8006:                                the neccesary cgi args added to preserve the
 8007:                                inhibitmenu state
 8008:                      - a ref to a url - no return value, but the string is
 8009:                                         updated to include the neccessary cgi
 8010:                                         args to preserve the inhibitmenu state
 8011: 
 8012: =cut
 8013: 
 8014: sub inhibit_menu_check {
 8015:     my ($arg) = @_;
 8016:     &get_unprocessed_cgi($ENV{'QUERY_STRING'}, ['inhibitmenu']);
 8017:     if ($arg eq 'input') {
 8018: 	if ($env{'form.inhibitmenu'}) {
 8019: 	    return '<input type="hidden" name="inhibitmenu" value="'.$env{'form.inhibitmenu'}.'" />';
 8020: 	} else {
 8021: 	    return
 8022: 	}
 8023:     }
 8024:     if ($env{'form.inhibitmenu'}) {
 8025: 	if (ref($arg)) {
 8026: 	    $$arg .= '?inhibitmenu='.$env{'form.inhibitmenu'};
 8027: 	} elsif ($arg eq '') {
 8028: 	    $arg .= 'inhibitmenu='.$env{'form.inhibitmenu'};
 8029: 	} else {
 8030: 	    $arg .= '?inhibitmenu='.$env{'form.inhibitmenu'};
 8031: 	}
 8032:     }
 8033:     if (!ref($arg)) {
 8034: 	return $arg;
 8035:     }
 8036: }
 8037: 
 8038: ###############################################
 8039: 
 8040: =pod
 8041: 
 8042: =back
 8043: 
 8044: =head1 User Information Routines
 8045: 
 8046: =over 4
 8047: 
 8048: =item * &get_users_function()
 8049: 
 8050: Used by &bodytag to determine the current users primary role.
 8051: Returns either 'student','coordinator','admin', or 'author'.
 8052: 
 8053: =cut
 8054: 
 8055: ###############################################
 8056: sub get_users_function {
 8057:     my $function = 'norole';
 8058:     if ($env{'request.role'}=~/^(st)/) {
 8059:         $function='student';
 8060:     }
 8061:     if ($env{'request.role'}=~/^(cc|co|in|ta|ep)/) {
 8062:         $function='coordinator';
 8063:     }
 8064:     if ($env{'request.role'}=~/^(su|dc|ad|li)/) {
 8065:         $function='admin';
 8066:     }
 8067:     if (($env{'request.role'}=~/^(au|ca|aa)/) ||
 8068:         ($ENV{'REQUEST_URI'}=~ m{/^(/priv)})) {
 8069:         $function='author';
 8070:     }
 8071:     return $function;
 8072: }
 8073: 
 8074: ###############################################
 8075: 
 8076: =pod
 8077: 
 8078: =item * &show_course()
 8079: 
 8080: Used by lonmenu.pm and lonroles.pm to determine whether to use the word
 8081: 'Courses' or 'Roles' in inline navigation and on screen displaying user's roles.
 8082: 
 8083: Inputs:
 8084: None
 8085: 
 8086: Outputs:
 8087: Scalar: 1 if 'Course' to be used, 0 otherwise.
 8088: 
 8089: =cut
 8090: 
 8091: ###############################################
 8092: sub show_course {
 8093:     my $course = !$env{'user.adv'};
 8094:     if (!$env{'user.adv'}) {
 8095:         foreach my $env (keys(%env)) {
 8096:             next if ($env !~ m/^user\.priv\./);
 8097:             if ($env !~ m/^user\.priv\.(?:st|cm)/) {
 8098:                 $course = 0;
 8099:                 last;
 8100:             }
 8101:         }
 8102:     }
 8103:     return $course;
 8104: }
 8105: 
 8106: ###############################################
 8107: 
 8108: =pod
 8109: 
 8110: =item * &check_user_status()
 8111: 
 8112: Determines current status of supplied role for a
 8113: specific user. Roles can be active, previous or future.
 8114: 
 8115: Inputs: 
 8116: user's domain, user's username, course's domain,
 8117: course's number, optional section ID.
 8118: 
 8119: Outputs:
 8120: role status: active, previous or future. 
 8121: 
 8122: =cut
 8123: 
 8124: sub check_user_status {
 8125:     my ($udom,$uname,$cdom,$crs,$role,$sec) = @_;
 8126:     my %userinfo = &Apache::lonnet::dump('roles',$udom,$uname);
 8127:     my @uroles = keys %userinfo;
 8128:     my $srchstr;
 8129:     my $active_chk = 'none';
 8130:     my $now = time;
 8131:     if (@uroles > 0) {
 8132:         if (($role eq 'cc') || ($role eq 'co') || ($sec eq '') || (!defined($sec))) {
 8133:             $srchstr = '/'.$cdom.'/'.$crs.'_'.$role;
 8134:         } else {
 8135:             $srchstr = '/'.$cdom.'/'.$crs.'/'.$sec.'_'.$role;
 8136:         }
 8137:         if (grep/^\Q$srchstr\E$/,@uroles) {
 8138:             my $role_end = 0;
 8139:             my $role_start = 0;
 8140:             $active_chk = 'active';
 8141:             if ($userinfo{$srchstr} =~ m/^\Q$role\E_(\d+)/) {
 8142:                 $role_end = $1;
 8143:                 if ($userinfo{$srchstr} =~ m/^\Q$role\E_\Q$role_end\E_(\d+)$/) {
 8144:                     $role_start = $1;
 8145:                 }
 8146:             }
 8147:             if ($role_start > 0) {
 8148:                 if ($now < $role_start) {
 8149:                     $active_chk = 'future';
 8150:                 }
 8151:             }
 8152:             if ($role_end > 0) {
 8153:                 if ($now > $role_end) {
 8154:                     $active_chk = 'previous';
 8155:                 }
 8156:             }
 8157:         }
 8158:     }
 8159:     return $active_chk;
 8160: }
 8161: 
 8162: ###############################################
 8163: 
 8164: =pod
 8165: 
 8166: =item * &get_sections()
 8167: 
 8168: Determines all the sections for a course including
 8169: sections with students and sections containing other roles.
 8170: Incoming parameters: 
 8171: 
 8172: 1. domain
 8173: 2. course number 
 8174: 3. reference to array containing roles for which sections should 
 8175: be gathered (optional).
 8176: 4. reference to array containing status types for which sections 
 8177: should be gathered (optional).
 8178: 
 8179: If the third argument is undefined, sections are gathered for any role. 
 8180: If the fourth argument is undefined, sections are gathered for any status.
 8181: Permissible values are 'active' or 'future' or 'previous'.
 8182:  
 8183: Returns section hash (keys are section IDs, values are
 8184: number of users in each section), subject to the
 8185: optional roles filter, optional status filter 
 8186: 
 8187: =cut
 8188: 
 8189: ###############################################
 8190: sub get_sections {
 8191:     my ($cdom,$cnum,$possible_roles,$possible_status) = @_;
 8192:     if (!defined($cdom) || !defined($cnum)) {
 8193:         my $cid =  $env{'request.course.id'};
 8194: 
 8195: 	return if (!defined($cid));
 8196: 
 8197:         $cdom = $env{'course.'.$cid.'.domain'};
 8198:         $cnum = $env{'course.'.$cid.'.num'};
 8199:     }
 8200: 
 8201:     my %sectioncount;
 8202:     my $now = time;
 8203: 
 8204:     if (!defined($possible_roles) || (grep(/^st$/,@$possible_roles))) {
 8205: 	my ($classlist) = &Apache::loncoursedata::get_classlist($cdom,$cnum);
 8206: 	my $sec_index = &Apache::loncoursedata::CL_SECTION();
 8207: 	my $status_index = &Apache::loncoursedata::CL_STATUS();
 8208:         my $start_index = &Apache::loncoursedata::CL_START();
 8209:         my $end_index = &Apache::loncoursedata::CL_END();
 8210:         my $status;
 8211: 	while (my ($student,$data) = each(%$classlist)) {
 8212: 	    my ($section,$stu_status,$start,$end) = ($data->[$sec_index],
 8213: 				                     $data->[$status_index],
 8214:                                                      $data->[$start_index],
 8215:                                                      $data->[$end_index]);
 8216:             if ($stu_status eq 'Active') {
 8217:                 $status = 'active';
 8218:             } elsif ($end < $now) {
 8219:                 $status = 'previous';
 8220:             } elsif ($start > $now) {
 8221:                 $status = 'future';
 8222:             } 
 8223: 	    if ($section ne '-1' && $section !~ /^\s*$/) {
 8224:                 if ((!defined($possible_status)) || (($status ne '') && 
 8225:                     (grep/^\Q$status\E$/,@{$possible_status}))) { 
 8226: 		    $sectioncount{$section}++;
 8227:                 }
 8228: 	    }
 8229: 	}
 8230:     }
 8231:     my %courseroles = &Apache::lonnet::dump('nohist_userroles',$cdom,$cnum);
 8232:     foreach my $user (sort(keys(%courseroles))) {
 8233: 	if ($user !~ /^(\w{2})/) { next; }
 8234: 	my ($role) = ($user =~ /^(\w{2})/);
 8235: 	if ($possible_roles && !(grep(/^$role$/,@$possible_roles))) { next; }
 8236: 	my ($section,$status);
 8237: 	if ($role eq 'cr' &&
 8238: 	    $user =~ m-^$role/[^/]*/[^/]*/[^/]*:[^:]*:[^:]*:(\w+)-) {
 8239: 	    $section=$1;
 8240: 	}
 8241: 	if ($user =~ /^$role:[^:]*:[^:]*:(\w+)/) { $section=$1; }
 8242: 	if (!defined($section) || $section eq '-1') { next; }
 8243:         my ($end,$start) = ($courseroles{$user} =~ /^([^:]*):([^:]*)$/);
 8244:         if ($end == -1 && $start == -1) {
 8245:             next; #deleted role
 8246:         }
 8247:         if (!defined($possible_status)) { 
 8248:             $sectioncount{$section}++;
 8249:         } else {
 8250:             if ((!$end || $end >= $now) && (!$start || $start <= $now)) {
 8251:                 $status = 'active';
 8252:             } elsif ($end < $now) {
 8253:                 $status = 'future';
 8254:             } elsif ($start > $now) {
 8255:                 $status = 'previous';
 8256:             }
 8257:             if (($status ne '') && (grep/^\Q$status\E$/,@{$possible_status})) {
 8258:                 $sectioncount{$section}++;
 8259:             }
 8260:         }
 8261:     }
 8262:     return %sectioncount;
 8263: }
 8264: 
 8265: ###############################################
 8266: 
 8267: =pod
 8268: 
 8269: =item * &get_course_users()
 8270: 
 8271: Retrieves usernames:domains for users in the specified course
 8272: with specific role(s), and access status. 
 8273: 
 8274: Incoming parameters:
 8275: 1. course domain
 8276: 2. course number
 8277: 3. access status: users must have - either active, 
 8278: previous, future, or all.
 8279: 4. reference to array of permissible roles
 8280: 5. reference to array of section restrictions (optional)
 8281: 6. reference to results object (hash of hashes).
 8282: 7. reference to optional userdata hash
 8283: 8. reference to optional statushash
 8284: 9. flag if privileged users (except those set to unhide in
 8285:    course settings) should be excluded    
 8286: Keys of top level results hash are roles.
 8287: Keys of inner hashes are username:domain, with 
 8288: values set to access type.
 8289: Optional userdata hash returns an array with arguments in the 
 8290: same order as loncoursedata::get_classlist() for student data.
 8291: 
 8292: Optional statushash returns
 8293: 
 8294: Entries for end, start, section and status are blank because
 8295: of the possibility of multiple values for non-student roles.
 8296: 
 8297: =cut
 8298: 
 8299: ###############################################
 8300: 
 8301: sub get_course_users {
 8302:     my ($cdom,$cnum,$types,$roles,$sections,$users,$userdata,$statushash,$hidepriv) = @_;
 8303:     my %idx = ();
 8304:     my %seclists;
 8305: 
 8306:     $idx{udom} = &Apache::loncoursedata::CL_SDOM();
 8307:     $idx{uname} =  &Apache::loncoursedata::CL_SNAME();
 8308:     $idx{end} = &Apache::loncoursedata::CL_END();
 8309:     $idx{start} = &Apache::loncoursedata::CL_START();
 8310:     $idx{id} = &Apache::loncoursedata::CL_ID();
 8311:     $idx{section} = &Apache::loncoursedata::CL_SECTION();
 8312:     $idx{fullname} = &Apache::loncoursedata::CL_FULLNAME();
 8313:     $idx{status} = &Apache::loncoursedata::CL_STATUS();
 8314: 
 8315:     if (grep(/^st$/,@{$roles})) {
 8316:         my ($classlist,$keylist)=&Apache::loncoursedata::get_classlist($cdom,$cnum);
 8317:         my $now = time;
 8318:         foreach my $student (keys(%{$classlist})) {
 8319:             my $match = 0;
 8320:             my $secmatch = 0;
 8321:             my $section = $$classlist{$student}[$idx{section}];
 8322:             my $status = $$classlist{$student}[$idx{status}];
 8323:             if ($section eq '') {
 8324:                 $section = 'none';
 8325:             }
 8326:             if ((ref($sections) eq 'ARRAY') && (@{$sections} > 0)) {
 8327:                 if (grep(/^all$/,@{$sections})) {
 8328:                     $secmatch = 1;
 8329:                 } elsif ($$classlist{$student}[$idx{section}] eq '') {
 8330:                     if (grep(/^none$/,@{$sections})) {
 8331:                         $secmatch = 1;
 8332:                     }
 8333:                 } else {  
 8334: 		    if (grep(/^\Q$section\E$/,@{$sections})) {
 8335: 		        $secmatch = 1;
 8336:                     }
 8337: 		}
 8338:                 if (!$secmatch) {
 8339:                     next;
 8340:                 }
 8341:             }
 8342:             if (defined($$types{'active'})) {
 8343:                 if ($$classlist{$student}[$idx{status}] eq 'Active') {
 8344:                     push(@{$$users{st}{$student}},'active');
 8345:                     $match = 1;
 8346:                 }
 8347:             }
 8348:             if (defined($$types{'previous'})) {
 8349:                 if ($$classlist{$student}[$idx{status}] eq 'Expired') {
 8350:                     push(@{$$users{st}{$student}},'previous');
 8351:                     $match = 1;
 8352:                 }
 8353:             }
 8354:             if (defined($$types{'future'})) {
 8355:                 if ($$classlist{$student}[$idx{status}] eq 'Future') {
 8356:                     push(@{$$users{st}{$student}},'future');
 8357:                     $match = 1;
 8358:                 }
 8359:             }
 8360:             if ($match) {
 8361:                 push(@{$seclists{$student}},$section);
 8362:                 if (ref($userdata) eq 'HASH') {
 8363:                     $$userdata{$student} = $$classlist{$student};
 8364:                 }
 8365:                 if (ref($statushash) eq 'HASH') {
 8366:                     $statushash->{$student}{'st'}{$section} = $status;
 8367:                 }
 8368:             }
 8369:         }
 8370:     }
 8371:     if ((@{$roles} > 1) || ((@{$roles} == 1) && ($$roles[0] ne "st"))) {
 8372:         my %coursepersonnel = &Apache::lonnet::dump('nohist_userroles',$cdom,$cnum);
 8373:         my $now = time;
 8374:         my %displaystatus = ( previous => 'Expired',
 8375:                               active   => 'Active',
 8376:                               future   => 'Future',
 8377:                             );
 8378:         my %nothide;
 8379:         if ($hidepriv) {
 8380:             my %coursehash=&Apache::lonnet::coursedescription($cdom.'_'.$cnum);
 8381:             foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
 8382:                 if ($user !~ /:/) {
 8383:                     $nothide{join(':',split(/[\@]/,$user))}=1;
 8384:                 } else {
 8385:                     $nothide{$user} = 1;
 8386:                 }
 8387:             }
 8388:         }
 8389:         foreach my $person (sort(keys(%coursepersonnel))) {
 8390:             my $match = 0;
 8391:             my $secmatch = 0;
 8392:             my $status;
 8393:             my ($role,$user,$usec) = ($person =~ /^([^:]*):([^:]+:[^:]+):([^:]*)/);
 8394:             $user =~ s/:$//;
 8395:             my ($end,$start) = split(/:/,$coursepersonnel{$person});
 8396:             if ($end == -1 || $start == -1) {
 8397:                 next;
 8398:             }
 8399:             if (($role) && ((grep(/^\Q$role\E$/,@{$roles})) ||
 8400:                 (grep(/^cr$/,@{$roles}) && $role =~ /^cr\//))) {
 8401:                 my ($uname,$udom) = split(/:/,$user);
 8402:                 if ((ref($sections) eq 'ARRAY') && (@{$sections} > 0)) {
 8403:                     if (grep(/^all$/,@{$sections})) {
 8404:                         $secmatch = 1;
 8405:                     } elsif ($usec eq '') {
 8406:                         if (grep(/^none$/,@{$sections})) {
 8407:                             $secmatch = 1;
 8408:                         }
 8409:                     } else {
 8410:                         if (grep(/^\Q$usec\E$/,@{$sections})) {
 8411:                             $secmatch = 1;
 8412:                         }
 8413:                     }
 8414:                     if (!$secmatch) {
 8415:                         next;
 8416:                     }
 8417:                 }
 8418:                 if ($usec eq '') {
 8419:                     $usec = 'none';
 8420:                 }
 8421:                 if ($uname ne '' && $udom ne '') {
 8422:                     if ($hidepriv) {
 8423:                         if ((&Apache::lonnet::privileged($uname,$udom)) &&
 8424:                             (!$nothide{$uname.':'.$udom})) {
 8425:                             next;
 8426:                         }
 8427:                     }
 8428:                     if ($end > 0 && $end < $now) {
 8429:                         $status = 'previous';
 8430:                     } elsif ($start > $now) {
 8431:                         $status = 'future';
 8432:                     } else {
 8433:                         $status = 'active';
 8434:                     }
 8435:                     foreach my $type (keys(%{$types})) { 
 8436:                         if ($status eq $type) {
 8437:                             if (!grep(/^\Q$type\E$/,@{$$users{$role}{$user}})) {
 8438:                                 push(@{$$users{$role}{$user}},$type);
 8439:                             }
 8440:                             $match = 1;
 8441:                         }
 8442:                     }
 8443:                     if (($match) && (ref($userdata) eq 'HASH')) {
 8444:                         if (!exists($$userdata{$uname.':'.$udom})) {
 8445: 			    &get_user_info($udom,$uname,\%idx,$userdata);
 8446:                         }
 8447:                         if (!grep(/^\Q$usec\E$/,@{$seclists{$uname.':'.$udom}})) {
 8448:                             push(@{$seclists{$uname.':'.$udom}},$usec);
 8449:                         }
 8450:                         if (ref($statushash) eq 'HASH') {
 8451:                             $statushash->{$uname.':'.$udom}{$role}{$usec} = $displaystatus{$status};
 8452:                         }
 8453:                     }
 8454:                 }
 8455:             }
 8456:         }
 8457:         if (grep(/^ow$/,@{$roles})) {
 8458:             if ((defined($cdom)) && (defined($cnum))) {
 8459:                 my %csettings = &Apache::lonnet::get('environment',['internal.courseowner'],$cdom,$cnum);
 8460:                 if ( defined($csettings{'internal.courseowner'}) ) {
 8461:                     my $owner = $csettings{'internal.courseowner'};
 8462:                     next if ($owner eq '');
 8463:                     my ($ownername,$ownerdom);
 8464:                     if ($owner =~ /^([^:]+):([^:]+)$/) {
 8465:                         $ownername = $1;
 8466:                         $ownerdom = $2;
 8467:                     } else {
 8468:                         $ownername = $owner;
 8469:                         $ownerdom = $cdom;
 8470:                         $owner = $ownername.':'.$ownerdom;
 8471:                     }
 8472:                     @{$$users{'ow'}{$owner}} = 'any';
 8473:                     if (defined($userdata) && 
 8474: 			!exists($$userdata{$owner})) {
 8475: 			&get_user_info($ownerdom,$ownername,\%idx,$userdata);
 8476:                         if (!grep(/^none$/,@{$seclists{$owner}})) {
 8477:                             push(@{$seclists{$owner}},'none');
 8478:                         }
 8479:                         if (ref($statushash) eq 'HASH') {
 8480:                             $statushash->{$owner}{'ow'}{'none'} = 'Any';
 8481:                         }
 8482: 		    }
 8483:                 }
 8484:             }
 8485:         }
 8486:         foreach my $user (keys(%seclists)) {
 8487:             @{$seclists{$user}} = (sort {$a <=> $b} @{$seclists{$user}});
 8488:             $$userdata{$user}[$idx{section}] = join(',',@{$seclists{$user}});
 8489:         }
 8490:     }
 8491:     return;
 8492: }
 8493: 
 8494: sub get_user_info {
 8495:     my ($udom,$uname,$idx,$userdata) = @_;
 8496:     $$userdata{$uname.':'.$udom}[$$idx{fullname}] = 
 8497: 	&plainname($uname,$udom,'lastname');
 8498:     $$userdata{$uname.':'.$udom}[$$idx{uname}] = $uname;
 8499:     $$userdata{$uname.':'.$udom}[$$idx{udom}] = $udom;
 8500:     my %idhash =  &Apache::lonnet::idrget($udom,($uname));
 8501:     $$userdata{$uname.':'.$udom}[$$idx{id}] = $idhash{$uname}; 
 8502:     return;
 8503: }
 8504: 
 8505: ###############################################
 8506: 
 8507: =pod
 8508: 
 8509: =item * &get_user_quota()
 8510: 
 8511: Retrieves quota assigned for storage of portfolio files for a user  
 8512: 
 8513: Incoming parameters:
 8514: 1. user's username
 8515: 2. user's domain
 8516: 
 8517: Returns:
 8518: 1. Disk quota (in Mb) assigned to student.
 8519: 2. (Optional) Type of setting: custom or default
 8520:    (individually assigned or default for user's 
 8521:    institutional status).
 8522: 3. (Optional) - User's institutional status (e.g., faculty, staff
 8523:    or student - types as defined in localenroll::inst_usertypes 
 8524:    for user's domain, which determines default quota for user.
 8525: 4. (Optional) - Default quota which would apply to the user.
 8526: 
 8527: If a value has been stored in the user's environment, 
 8528: it will return that, otherwise it returns the maximal default
 8529: defined for the user's instituional status(es) in the domain.
 8530: 
 8531: =cut
 8532: 
 8533: ###############################################
 8534: 
 8535: 
 8536: sub get_user_quota {
 8537:     my ($uname,$udom) = @_;
 8538:     my ($quota,$quotatype,$settingstatus,$defquota);
 8539:     if (!defined($udom)) {
 8540:         $udom = $env{'user.domain'};
 8541:     }
 8542:     if (!defined($uname)) {
 8543:         $uname = $env{'user.name'};
 8544:     }
 8545:     if (($udom eq '' || $uname eq '') ||
 8546:         ($udom eq 'public') && ($uname eq 'public')) {
 8547:         $quota = 0;
 8548:         $quotatype = 'default';
 8549:         $defquota = 0; 
 8550:     } else {
 8551:         my $inststatus;
 8552:         if ($udom eq $env{'user.domain'} && $uname eq $env{'user.name'}) {
 8553:             $quota = $env{'environment.portfolioquota'};
 8554:             $inststatus = $env{'environment.inststatus'};
 8555:         } else {
 8556:             my %userenv = 
 8557:                 &Apache::lonnet::get('environment',['portfolioquota',
 8558:                                      'inststatus'],$udom,$uname);
 8559:             my ($tmp) = keys(%userenv);
 8560:             if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
 8561:                 $quota = $userenv{'portfolioquota'};
 8562:                 $inststatus = $userenv{'inststatus'};
 8563:             } else {
 8564:                 undef(%userenv);
 8565:             }
 8566:         }
 8567:         ($defquota,$settingstatus) = &default_quota($udom,$inststatus);
 8568:         if ($quota eq '') {
 8569:             $quota = $defquota;
 8570:             $quotatype = 'default';
 8571:         } else {
 8572:             $quotatype = 'custom';
 8573:         }
 8574:     }
 8575:     if (wantarray) {
 8576:         return ($quota,$quotatype,$settingstatus,$defquota);
 8577:     } else {
 8578:         return $quota;
 8579:     }
 8580: }
 8581: 
 8582: ###############################################
 8583: 
 8584: =pod
 8585: 
 8586: =item * &default_quota()
 8587: 
 8588: Retrieves default quota assigned for storage of user portfolio files,
 8589: given an (optional) user's institutional status.
 8590: 
 8591: Incoming parameters:
 8592: 1. domain
 8593: 2. (Optional) institutional status(es).  This is a : separated list of 
 8594:    status types (e.g., faculty, staff, student etc.)
 8595:    which apply to the user for whom the default is being retrieved.
 8596:    If the institutional status string in undefined, the domain
 8597:    default quota will be returned. 
 8598: 
 8599: Returns:
 8600: 1. Default disk quota (in Mb) for user portfolios in the domain.
 8601: 2. (Optional) institutional type which determined the value of the
 8602:    default quota.
 8603: 
 8604: If a value has been stored in the domain's configuration db,
 8605: it will return that, otherwise it returns 20 (for backwards 
 8606: compatibility with domains which have not set up a configuration
 8607: db file; the original statically defined portfolio quota was 20 Mb). 
 8608: 
 8609: If the user's status includes multiple types (e.g., staff and student),
 8610: the largest default quota which applies to the user determines the
 8611: default quota returned.
 8612: 
 8613: =back
 8614: 
 8615: =cut
 8616: 
 8617: ###############################################
 8618: 
 8619: 
 8620: sub default_quota {
 8621:     my ($udom,$inststatus) = @_;
 8622:     my ($defquota,$settingstatus);
 8623:     my %quotahash = &Apache::lonnet::get_dom('configuration',
 8624:                                             ['quotas'],$udom);
 8625:     if (ref($quotahash{'quotas'}) eq 'HASH') {
 8626:         if ($inststatus ne '') {
 8627:             my @statuses = map { &unescape($_); } split(/:/,$inststatus);
 8628:             foreach my $item (@statuses) {
 8629:                 if (ref($quotahash{'quotas'}{'defaultquota'}) eq 'HASH') {
 8630:                     if ($quotahash{'quotas'}{'defaultquota'}{$item} ne '') {
 8631:                         if ($defquota eq '') {
 8632:                             $defquota = $quotahash{'quotas'}{'defaultquota'}{$item};
 8633:                             $settingstatus = $item;
 8634:                         } elsif ($quotahash{'quotas'}{'defaultquota'}{$item} > $defquota) {
 8635:                             $defquota = $quotahash{'quotas'}{'defaultquota'}{$item};
 8636:                             $settingstatus = $item;
 8637:                         }
 8638:                     }
 8639:                 } else {
 8640:                     if ($quotahash{'quotas'}{$item} ne '') {
 8641:                         if ($defquota eq '') {
 8642:                             $defquota = $quotahash{'quotas'}{$item};
 8643:                             $settingstatus = $item;
 8644:                         } elsif ($quotahash{'quotas'}{$item} > $defquota) {
 8645:                             $defquota = $quotahash{'quotas'}{$item};
 8646:                             $settingstatus = $item;
 8647:                         }
 8648:                     }
 8649:                 }
 8650:             }
 8651:         }
 8652:         if ($defquota eq '') {
 8653:             if (ref($quotahash{'quotas'}{'defaultquota'}) eq 'HASH') {
 8654:                 $defquota = $quotahash{'quotas'}{'defaultquota'}{'default'};
 8655:             } else {
 8656:                 $defquota = $quotahash{'quotas'}{'default'};
 8657:             }
 8658:             $settingstatus = 'default';
 8659:         }
 8660:     } else {
 8661:         $settingstatus = 'default';
 8662:         $defquota = 20;
 8663:     }
 8664:     if (wantarray) {
 8665:         return ($defquota,$settingstatus);
 8666:     } else {
 8667:         return $defquota;
 8668:     }
 8669: }
 8670: 
 8671: sub get_secgrprole_info {
 8672:     my ($cdom,$cnum,$needroles,$type)  = @_;
 8673:     my %sections_count = &get_sections($cdom,$cnum);
 8674:     my @sections =  (sort {$a <=> $b} keys(%sections_count));
 8675:     my %curr_groups = &Apache::longroup::coursegroups($cdom,$cnum);
 8676:     my @groups = sort(keys(%curr_groups));
 8677:     my $allroles = [];
 8678:     my $rolehash;
 8679:     my $accesshash = {
 8680:                      active => 'Currently has access',
 8681:                      future => 'Will have future access',
 8682:                      previous => 'Previously had access',
 8683:                   };
 8684:     if ($needroles) {
 8685:         $rolehash = {'all' => 'all'};
 8686:         my %user_roles = &Apache::lonnet::dump('nohist_userroles',$cdom,$cnum);
 8687: 	if (&Apache::lonnet::error(%user_roles)) {
 8688: 	    undef(%user_roles);
 8689: 	}
 8690:         foreach my $item (keys(%user_roles)) {
 8691:             my ($role)=split(/\:/,$item,2);
 8692:             if ($role eq 'cr') { next; }
 8693:             if ($role =~ /^cr/) {
 8694:                 $$rolehash{$role} = (split('/',$role))[3];
 8695:             } else {
 8696:                 $$rolehash{$role} = &Apache::lonnet::plaintext($role,$type);
 8697:             }
 8698:         }
 8699:         foreach my $key (sort(keys(%{$rolehash}))) {
 8700:             push(@{$allroles},$key);
 8701:         }
 8702:         push (@{$allroles},'st');
 8703:         $$rolehash{'st'} = &Apache::lonnet::plaintext('st',$type);
 8704:     }
 8705:     return (\@sections,\@groups,$allroles,$rolehash,$accesshash);
 8706: }
 8707: 
 8708: sub user_picker {
 8709:     my ($dom,$srch,$forcenewuser,$caller,$cancreate,$usertype,$context) = @_;
 8710:     my $currdom = $dom;
 8711:     my %curr_selected = (
 8712:                         srchin => 'dom',
 8713:                         srchby => 'lastname',
 8714:                       );
 8715:     my $srchterm;
 8716:     if ((ref($srch) eq 'HASH') && ($env{'form.origform'} ne 'crtusername')) {
 8717:         if ($srch->{'srchby'} ne '') {
 8718:             $curr_selected{'srchby'} = $srch->{'srchby'};
 8719:         }
 8720:         if ($srch->{'srchin'} ne '') {
 8721:             $curr_selected{'srchin'} = $srch->{'srchin'};
 8722:         }
 8723:         if ($srch->{'srchtype'} ne '') {
 8724:             $curr_selected{'srchtype'} = $srch->{'srchtype'};
 8725:         }
 8726:         if ($srch->{'srchdomain'} ne '') {
 8727:             $currdom = $srch->{'srchdomain'};
 8728:         }
 8729:         $srchterm = $srch->{'srchterm'};
 8730:     }
 8731:     my %lt=&Apache::lonlocal::texthash(
 8732:                     'usr'       => 'Search criteria',
 8733:                     'doma'      => 'Domain/institution to search',
 8734:                     'uname'     => 'username',
 8735:                     'lastname'  => 'last name',
 8736:                     'lastfirst' => 'last name, first name',
 8737:                     'crs'       => 'in this course',
 8738:                     'dom'       => 'in selected LON-CAPA domain', 
 8739:                     'alc'       => 'all LON-CAPA',
 8740:                     'instd'     => 'in institutional directory for selected domain',
 8741:                     'exact'     => 'is',
 8742:                     'contains'  => 'contains',
 8743:                     'begins'    => 'begins with',
 8744:                     'youm'      => "You must include some text to search for.",
 8745:                     'thte'      => "The text you are searching for must contain at least two characters when using a 'begins' type search.",
 8746:                     'thet'      => "The text you are searching for must contain at least three characters when using a 'contains' type search.",
 8747:                     'yomc'      => "You must choose a domain when using an institutional directory search.",
 8748:                     'ymcd'      => "You must choose a domain when using a domain search.",
 8749:                     'whus'      => "When using searching by last,first you must include a comma as separator between last name and first name.",
 8750:                     'whse'      => "When searching by last,first you must include at least one character in the first name.",
 8751:                      'thfo'     => "The following need to be corrected before the search can be run:",
 8752:                                        );
 8753:     my $domform = &select_dom_form($currdom,'srchdomain',1,1);
 8754:     my $srchinsel = ' <select name="srchin">';
 8755: 
 8756:     my @srchins = ('crs','dom','alc','instd');
 8757: 
 8758:     foreach my $option (@srchins) {
 8759:         # FIXME 'alc' option unavailable until 
 8760:         #       loncreateuser::print_user_query_page()
 8761:         #       has been completed.
 8762:         next if ($option eq 'alc');
 8763:         next if (($option eq 'crs') && ($env{'form.form'} eq 'requestcrs'));  
 8764:         next if ($option eq 'crs' && !$env{'request.course.id'});
 8765:         if ($curr_selected{'srchin'} eq $option) {
 8766:             $srchinsel .= ' 
 8767:    <option value="'.$option.'" selected="selected">'.$lt{$option}.'</option>';
 8768:         } else {
 8769:             $srchinsel .= '
 8770:    <option value="'.$option.'">'.$lt{$option}.'</option>';
 8771:         }
 8772:     }
 8773:     $srchinsel .= "\n  </select>\n";
 8774: 
 8775:     my $srchbysel =  ' <select name="srchby">';
 8776:     foreach my $option ('lastname','lastfirst','uname') {
 8777:         if ($curr_selected{'srchby'} eq $option) {
 8778:             $srchbysel .= '
 8779:    <option value="'.$option.'" selected="selected">'.$lt{$option}.'</option>';
 8780:         } else {
 8781:             $srchbysel .= '
 8782:    <option value="'.$option.'">'.$lt{$option}.'</option>';
 8783:          }
 8784:     }
 8785:     $srchbysel .= "\n  </select>\n";
 8786: 
 8787:     my $srchtypesel = ' <select name="srchtype">';
 8788:     foreach my $option ('begins','contains','exact') {
 8789:         if ($curr_selected{'srchtype'} eq $option) {
 8790:             $srchtypesel .= '
 8791:    <option value="'.$option.'" selected="selected">'.$lt{$option}.'</option>';
 8792:         } else {
 8793:             $srchtypesel .= '
 8794:    <option value="'.$option.'">'.$lt{$option}.'</option>';
 8795:         }
 8796:     }
 8797:     $srchtypesel .= "\n  </select>\n";
 8798: 
 8799:     my ($newuserscript,$new_user_create);
 8800:     my $context_dom = $env{'request.role.domain'};
 8801:     if ($context eq 'requestcrs') {
 8802:         if ($env{'form.coursedom'} ne '') { 
 8803:             $context_dom = $env{'form.coursedom'};
 8804:         }
 8805:     }
 8806:     if ($forcenewuser) {
 8807:         if (ref($srch) eq 'HASH') {
 8808:             if ($srch->{'srchby'} eq 'uname' && $srch->{'srchtype'} eq 'exact' && $srch->{'srchin'} eq 'dom' && $srch->{'srchdomain'} eq $context_dom) {
 8809:                 if ($cancreate) {
 8810:                     $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>';
 8811:                 } else {
 8812:                     my $helplink = 'javascript:helpMenu('."'display'".')';
 8813:                     my %usertypetext = (
 8814:                         official   => 'institutional',
 8815:                         unofficial => 'non-institutional',
 8816:                     );
 8817:                     $new_user_create = '<p class="LC_warning">'
 8818:                                       .&mt("You are not authorized to create new $usertypetext{$usertype} users in this domain.")
 8819:                                       .' '
 8820:                                       .&mt('Please contact the [_1]helpdesk[_2] for assistance.'
 8821:                                           ,'<a href="'.$helplink.'">','</a>')
 8822:                                       .'</p><br />';
 8823:                 }
 8824:             }
 8825:         }
 8826: 
 8827:         $newuserscript = <<"ENDSCRIPT";
 8828: 
 8829: function setSearch(createnew,callingForm) {
 8830:     if (createnew == 1) {
 8831:         for (var i=0; i<callingForm.srchby.length; i++) {
 8832:             if (callingForm.srchby.options[i].value == 'uname') {
 8833:                 callingForm.srchby.selectedIndex = i;
 8834:             }
 8835:         }
 8836:         for (var i=0; i<callingForm.srchin.length; i++) {
 8837:             if ( callingForm.srchin.options[i].value == 'dom') {
 8838: 		callingForm.srchin.selectedIndex = i;
 8839:             }
 8840:         }
 8841:         for (var i=0; i<callingForm.srchtype.length; i++) {
 8842:             if (callingForm.srchtype.options[i].value == 'exact') {
 8843:                 callingForm.srchtype.selectedIndex = i;
 8844:             }
 8845:         }
 8846:         for (var i=0; i<callingForm.srchdomain.length; i++) {
 8847:             if (callingForm.srchdomain.options[i].value == '$context_dom') {
 8848:                 callingForm.srchdomain.selectedIndex = i;
 8849:             }
 8850:         }
 8851:     }
 8852: }
 8853: ENDSCRIPT
 8854: 
 8855:     }
 8856: 
 8857:     my $output = <<"END_BLOCK";
 8858: <script type="text/javascript">
 8859: // <![CDATA[
 8860: function validateEntry(callingForm) {
 8861: 
 8862:     var checkok = 1;
 8863:     var srchin;
 8864:     for (var i=0; i<callingForm.srchin.length; i++) {
 8865: 	if ( callingForm.srchin[i].checked ) {
 8866: 	    srchin = callingForm.srchin[i].value;
 8867: 	}
 8868:     }
 8869: 
 8870:     var srchtype = callingForm.srchtype.options[callingForm.srchtype.selectedIndex].value;
 8871:     var srchby = callingForm.srchby.options[callingForm.srchby.selectedIndex].value;
 8872:     var srchdomain = callingForm.srchdomain.options[callingForm.srchdomain.selectedIndex].value;
 8873:     var srchterm =  callingForm.srchterm.value;
 8874:     var srchin = callingForm.srchin.options[callingForm.srchin.selectedIndex].value;
 8875:     var msg = "";
 8876: 
 8877:     if (srchterm == "") {
 8878:         checkok = 0;
 8879:         msg += "$lt{'youm'}\\n";
 8880:     }
 8881: 
 8882:     if (srchtype== 'begins') {
 8883:         if (srchterm.length < 2) {
 8884:             checkok = 0;
 8885:             msg += "$lt{'thte'}\\n";
 8886:         }
 8887:     }
 8888: 
 8889:     if (srchtype== 'contains') {
 8890:         if (srchterm.length < 3) {
 8891:             checkok = 0;
 8892:             msg += "$lt{'thet'}\\n";
 8893:         }
 8894:     }
 8895:     if (srchin == 'instd') {
 8896:         if (srchdomain == '') {
 8897:             checkok = 0;
 8898:             msg += "$lt{'yomc'}\\n";
 8899:         }
 8900:     }
 8901:     if (srchin == 'dom') {
 8902:         if (srchdomain == '') {
 8903:             checkok = 0;
 8904:             msg += "$lt{'ymcd'}\\n";
 8905:         }
 8906:     }
 8907:     if (srchby == 'lastfirst') {
 8908:         if (srchterm.indexOf(",") == -1) {
 8909:             checkok = 0;
 8910:             msg += "$lt{'whus'}\\n";
 8911:         }
 8912:         if (srchterm.indexOf(",") == srchterm.length -1) {
 8913:             checkok = 0;
 8914:             msg += "$lt{'whse'}\\n";
 8915:         }
 8916:     }
 8917:     if (checkok == 0) {
 8918:         alert("$lt{'thfo'}\\n"+msg);
 8919:         return;
 8920:     }
 8921:     if (checkok == 1) {
 8922:         callingForm.submit();
 8923:     }
 8924: }
 8925: 
 8926: $newuserscript
 8927: 
 8928: // ]]>
 8929: </script>
 8930: 
 8931: $new_user_create
 8932: 
 8933: END_BLOCK
 8934: 
 8935:     $output .= &Apache::lonhtmlcommon::start_pick_box().
 8936:                &Apache::lonhtmlcommon::row_title($lt{'doma'}).
 8937:                $domform.
 8938:                &Apache::lonhtmlcommon::row_closure().
 8939:                &Apache::lonhtmlcommon::row_title($lt{'usr'}).
 8940:                $srchbysel.
 8941:                $srchtypesel. 
 8942:                '<input type="text" size="15" name="srchterm" value="'.$srchterm.'" />'.
 8943:                $srchinsel.
 8944:                &Apache::lonhtmlcommon::row_closure(1). 
 8945:                &Apache::lonhtmlcommon::end_pick_box().
 8946:                '<br />';
 8947:     return $output;
 8948: }
 8949: 
 8950: sub user_rule_check {
 8951:     my ($usershash,$checks,$alerts,$rulematch,$inst_results,$curr_rules,$got_rules) = @_;
 8952:     my $response;
 8953:     if (ref($usershash) eq 'HASH') {
 8954:         foreach my $user (keys(%{$usershash})) {
 8955:             my ($uname,$udom) = split(/:/,$user);
 8956:             next if ($udom eq '' || $uname eq '');
 8957:             my ($id,$newuser);
 8958:             if (ref($usershash->{$user}) eq 'HASH') {
 8959:                 $newuser = $usershash->{$user}->{'newuser'};
 8960:                 $id = $usershash->{$user}->{'id'};
 8961:             }
 8962:             my $inst_response;
 8963:             if (ref($checks) eq 'HASH') {
 8964:                 if (defined($checks->{'username'})) {
 8965:                     ($inst_response,%{$inst_results->{$user}}) = 
 8966:                         &Apache::lonnet::get_instuser($udom,$uname);
 8967:                 } elsif (defined($checks->{'id'})) {
 8968:                     ($inst_response,%{$inst_results->{$user}}) =
 8969:                         &Apache::lonnet::get_instuser($udom,undef,$id);
 8970:                 }
 8971:             } else {
 8972:                 ($inst_response,%{$inst_results->{$user}}) =
 8973:                     &Apache::lonnet::get_instuser($udom,$uname);
 8974:                 return;
 8975:             }
 8976:             if (!$got_rules->{$udom}) {
 8977:                 my %domconfig = &Apache::lonnet::get_dom('configuration',
 8978:                                                   ['usercreation'],$udom);
 8979:                 if (ref($domconfig{'usercreation'}) eq 'HASH') {
 8980:                     foreach my $item ('username','id') {
 8981:                         if (ref($domconfig{'usercreation'}{$item.'_rule'}) eq 'ARRAY') {
 8982:                             $$curr_rules{$udom}{$item} = 
 8983:                                 $domconfig{'usercreation'}{$item.'_rule'};
 8984:                         }
 8985:                     }
 8986:                 }
 8987:                 $got_rules->{$udom} = 1;  
 8988:             }
 8989:             foreach my $item (keys(%{$checks})) {
 8990:                 if (ref($$curr_rules{$udom}) eq 'HASH') {
 8991:                     if (ref($$curr_rules{$udom}{$item}) eq 'ARRAY') {
 8992:                         if (@{$$curr_rules{$udom}{$item}} > 0) {
 8993:                             my %rule_check = &Apache::lonnet::inst_rulecheck($udom,$uname,$id,$item,$$curr_rules{$udom}{$item});
 8994:                             foreach my $rule (@{$$curr_rules{$udom}{$item}}) {
 8995:                                 if ($rule_check{$rule}) {
 8996:                                     $$rulematch{$user}{$item} = $rule;
 8997:                                     if ($inst_response eq 'ok') {
 8998:                                         if (ref($inst_results) eq 'HASH') {
 8999:                                             if (ref($inst_results->{$user}) eq 'HASH') {
 9000:                                                 if (keys(%{$inst_results->{$user}}) == 0) {
 9001:                                                     $$alerts{$item}{$udom}{$uname} = 1;
 9002:                                                 }
 9003:                                             }
 9004:                                         }
 9005:                                     }
 9006:                                     last;
 9007:                                 }
 9008:                             }
 9009:                         }
 9010:                     }
 9011:                 }
 9012:             }
 9013:         }
 9014:     }
 9015:     return;
 9016: }
 9017: 
 9018: sub user_rule_formats {
 9019:     my ($domain,$domdesc,$curr_rules,$check) = @_;
 9020:     my %text = ( 
 9021:                  'username' => 'Usernames',
 9022:                  'id'       => 'IDs',
 9023:                );
 9024:     my $output;
 9025:     my ($rules,$ruleorder) = &Apache::lonnet::inst_userrules($domain,$check);
 9026:     if ((ref($rules) eq 'HASH') && (ref($ruleorder) eq 'ARRAY')) {
 9027:         if (@{$ruleorder} > 0) {
 9028:             $output = '<br />'.
 9029:                       &mt($text{$check}.' with the following format(s) may [_1]only[_2] be used for verified users at [_3]:',
 9030:                           '<span class="LC_cusr_emph">','</span>',$domdesc).
 9031:                       ' <ul>';
 9032:             foreach my $rule (@{$ruleorder}) {
 9033:                 if (ref($curr_rules) eq 'ARRAY') {
 9034:                     if (grep(/^\Q$rule\E$/,@{$curr_rules})) {
 9035:                         if (ref($rules->{$rule}) eq 'HASH') {
 9036:                             $output .= '<li>'.$rules->{$rule}{'name'}.': '.
 9037:                                         $rules->{$rule}{'desc'}.'</li>';
 9038:                         }
 9039:                     }
 9040:                 }
 9041:             }
 9042:             $output .= '</ul>';
 9043:         }
 9044:     }
 9045:     return $output;
 9046: }
 9047: 
 9048: sub instrule_disallow_msg {
 9049:     my ($checkitem,$domdesc,$count,$mode) = @_;
 9050:     my $response;
 9051:     my %text = (
 9052:                   item   => 'username',
 9053:                   items  => 'usernames',
 9054:                   match  => 'matches',
 9055:                   do     => 'does',
 9056:                   action => 'a username',
 9057:                   one    => 'one',
 9058:                );
 9059:     if ($count > 1) {
 9060:         $text{'item'} = 'usernames';
 9061:         $text{'match'} ='match';
 9062:         $text{'do'} = 'do';
 9063:         $text{'action'} = 'usernames',
 9064:         $text{'one'} = 'ones';
 9065:     }
 9066:     if ($checkitem eq 'id') {
 9067:         $text{'items'} = 'IDs';
 9068:         $text{'item'} = 'ID';
 9069:         $text{'action'} = 'an ID';
 9070:         if ($count > 1) {
 9071:             $text{'item'} = 'IDs';
 9072:             $text{'action'} = 'IDs';
 9073:         }
 9074:     }
 9075:     $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 />';
 9076:     if ($mode eq 'upload') {
 9077:         if ($checkitem eq 'username') {
 9078:             $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'}.");
 9079:         } elsif ($checkitem eq 'id') {
 9080:             $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.");
 9081:         }
 9082:     } elsif ($mode eq 'selfcreate') {
 9083:         if ($checkitem eq 'id') {
 9084:             $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.");
 9085:         }
 9086:     } else {
 9087:         if ($checkitem eq 'username') {
 9088:             $response .= &mt("You must choose $text{'action'} with a different format --  $text{'one'} that will not conflict with 'official' institutional $text{'items'}.");
 9089:         } elsif ($checkitem eq 'id') {
 9090:             $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.");
 9091:         }
 9092:     }
 9093:     return $response;
 9094: }
 9095: 
 9096: sub personal_data_fieldtitles {
 9097:     my %fieldtitles = &Apache::lonlocal::texthash (
 9098:                         id => 'Student/Employee ID',
 9099:                         permanentemail => 'E-mail address',
 9100:                         lastname => 'Last Name',
 9101:                         firstname => 'First Name',
 9102:                         middlename => 'Middle Name',
 9103:                         generation => 'Generation',
 9104:                         gen => 'Generation',
 9105:                         inststatus => 'Affiliation',
 9106:                    );
 9107:     return %fieldtitles;
 9108: }
 9109: 
 9110: sub sorted_inst_types {
 9111:     my ($dom) = @_;
 9112:     my ($usertypes,$order) = &Apache::lonnet::retrieve_inst_usertypes($dom);
 9113:     my $othertitle = &mt('All users');
 9114:     if ($env{'request.course.id'}) {
 9115:         $othertitle  = &mt('Any users');
 9116:     }
 9117:     my @types;
 9118:     if (ref($order) eq 'ARRAY') {
 9119:         @types = @{$order};
 9120:     }
 9121:     if (@types == 0) {
 9122:         if (ref($usertypes) eq 'HASH') {
 9123:             @types = sort(keys(%{$usertypes}));
 9124:         }
 9125:     }
 9126:     if (keys(%{$usertypes}) > 0) {
 9127:         $othertitle = &mt('Other users');
 9128:     }
 9129:     return ($othertitle,$usertypes,\@types);
 9130: }
 9131: 
 9132: sub get_institutional_codes {
 9133:     my ($settings,$allcourses,$LC_code) = @_;
 9134: # Get complete list of course sections to update
 9135:     my @currsections = ();
 9136:     my @currxlists = ();
 9137:     my $coursecode = $$settings{'internal.coursecode'};
 9138: 
 9139:     if ($$settings{'internal.sectionnums'} ne '') {
 9140:         @currsections = split(/,/,$$settings{'internal.sectionnums'});
 9141:     }
 9142: 
 9143:     if ($$settings{'internal.crosslistings'} ne '') {
 9144:         @currxlists = split(/,/,$$settings{'internal.crosslistings'});
 9145:     }
 9146: 
 9147:     if (@currxlists > 0) {
 9148:         foreach (@currxlists) {
 9149:             if (m/^([^:]+):(\w*)$/) {
 9150:                 unless (grep/^$1$/,@{$allcourses}) {
 9151:                     push @{$allcourses},$1;
 9152:                     $$LC_code{$1} = $2;
 9153:                 }
 9154:             }
 9155:         }
 9156:     }
 9157:  
 9158:     if (@currsections > 0) {
 9159:         foreach (@currsections) {
 9160:             if (m/^(\w+):(\w*)$/) {
 9161:                 my $sec = $coursecode.$1;
 9162:                 my $lc_sec = $2;
 9163:                 unless (grep/^$sec$/,@{$allcourses}) {
 9164:                     push @{$allcourses},$sec;
 9165:                     $$LC_code{$sec} = $lc_sec;
 9166:                 }
 9167:             }
 9168:         }
 9169:     }
 9170:     return;
 9171: }
 9172: 
 9173: sub get_standard_codeitems {
 9174:     return ('Year','Semester','Department','Number','Section');
 9175: }
 9176: 
 9177: =pod
 9178: 
 9179: =head1 Slot Helpers
 9180: 
 9181: =over 4
 9182: 
 9183: =item * sorted_slots()
 9184: 
 9185: Sorts an array of slot names in order of an optional sort key,
 9186: default sort is by slot start time (earliest first). 
 9187: 
 9188: Inputs:
 9189: 
 9190: =over 4
 9191: 
 9192: slotsarr  - Reference to array of unsorted slot names.
 9193: 
 9194: slots     - Reference to hash of hash, where outer hash keys are slot names.
 9195: 
 9196: sortkey   - Name of key in inner hash to be sorted on (e.g., starttime).
 9197: 
 9198: =back
 9199: 
 9200: Returns:
 9201: 
 9202: =over 4
 9203: 
 9204: sorted   - An array of slot names sorted by a specified sort key 
 9205:            (default sort key is start time of the slot).
 9206: 
 9207: =back
 9208: 
 9209: =cut
 9210: 
 9211: 
 9212: sub sorted_slots {
 9213:     my ($slotsarr,$slots,$sortkey) = @_;
 9214:     if ($sortkey eq '') {
 9215:         $sortkey = 'starttime';
 9216:     }
 9217:     my @sorted;
 9218:     if ((ref($slotsarr) eq 'ARRAY') && (ref($slots) eq 'HASH')) {
 9219:         @sorted =
 9220:             sort {
 9221:                      if (ref($slots->{$a}) && ref($slots->{$b})) {
 9222:                          return $slots->{$a}{$sortkey} <=> $slots->{$b}{$sortkey}
 9223:                      }
 9224:                      if (ref($slots->{$a})) { return -1;}
 9225:                      if (ref($slots->{$b})) { return 1;}
 9226:                      return 0;
 9227:                  } @{$slotsarr};
 9228:     }
 9229:     return @sorted;
 9230: }
 9231: 
 9232: =pod
 9233: 
 9234: =item * get_future_slots()
 9235: 
 9236: Inputs:
 9237: 
 9238: =over 4
 9239: 
 9240: cnum - course number
 9241: 
 9242: cdom - course domain
 9243: 
 9244: now - current UNIX time
 9245: 
 9246: symb - optional symb
 9247: 
 9248: =back
 9249: 
 9250: Returns:
 9251: 
 9252: =over 4
 9253: 
 9254: sorted_reservable - ref to array of student_schedulable slots currently 
 9255:                     reservable, ordered by end date of reservation period.
 9256: 
 9257: reservable_now - ref to hash of student_schedulable slots currently
 9258:                  reservable.
 9259: 
 9260:     Keys in inner hash are:
 9261:     (a) symb: either blank or symb to which slot use is restricted.
 9262:     (b) endreserve: end date of reservation period. 
 9263: 
 9264: sorted_future - ref to array of student_schedulable slots reservable in
 9265:                 the future, ordered by start date of reservation period.
 9266: 
 9267: future_reservable - ref to hash of student_schedulable slots reservable
 9268:                     in the future.
 9269: 
 9270:     Keys in inner hash are:
 9271:     (a) symb: either blank or symb to which slot use is restricted.
 9272:     (b) startreserve:  start date of reservation period.
 9273: 
 9274: =back
 9275: 
 9276: =cut
 9277: 
 9278: sub get_future_slots {
 9279:     my ($cnum,$cdom,$now,$symb) = @_;
 9280:     my (%reservable_now,%future_reservable,@sorted_reservable,@sorted_future);
 9281:     my %slots = &Apache::lonnet::get_course_slots($cnum,$cdom);
 9282:     foreach my $slot (keys(%slots)) {
 9283:         next unless($slots{$slot}->{'type'} eq 'schedulable_student');
 9284:         if ($symb) {
 9285:             next if (($slots{$slot}->{'symb'} ne '') && 
 9286:                      ($slots{$slot}->{'symb'} ne $symb));
 9287:         }
 9288:         if (($slots{$slot}->{'starttime'} > $now) &&
 9289:             ($slots{$slot}->{'endtime'} > $now)) {
 9290:             if (($slots{$slot}->{'allowedsections'}) || ($slots{$slot}->{'allowedusers'})) {
 9291:                 my $userallowed = 0;
 9292:                 if ($slots{$slot}->{'allowedsections'}) {
 9293:                     my @allowed_sec = split(',',$slots{$slot}->{'allowedsections'});
 9294:                     if (!defined($env{'request.role.sec'})
 9295:                         && grep(/^No section assigned$/,@allowed_sec)) {
 9296:                         $userallowed=1;
 9297:                     } else {
 9298:                         if (grep(/^\Q$env{'request.role.sec'}\E$/,@allowed_sec)) {
 9299:                             $userallowed=1;
 9300:                         }
 9301:                     }
 9302:                     unless ($userallowed) {
 9303:                         if (defined($env{'request.course.groups'})) {
 9304:                             my @groups = split(/:/,$env{'request.course.groups'});
 9305:                             foreach my $group (@groups) {
 9306:                                 if (grep(/^\Q$group\E$/,@allowed_sec)) {
 9307:                                     $userallowed=1;
 9308:                                     last;
 9309:                                 }
 9310:                             }
 9311:                         }
 9312:                     }
 9313:                 }
 9314:                 if ($slots{$slot}->{'allowedusers'}) {
 9315:                     my @allowed_users = split(',',$slots{$slot}->{'allowedusers'});
 9316:                     my $user = $env{'user.name'}.':'.$env{'user.domain'};
 9317:                     if (grep(/^\Q$user\E$/,@allowed_users)) {
 9318:                         $userallowed = 1;
 9319:                     }
 9320:                 }
 9321:                 next unless($userallowed);
 9322:             }
 9323:             my $startreserve = $slots{$slot}->{'startreserve'};
 9324:             my $endreserve = $slots{$slot}->{'endreserve'};
 9325:             my $symb = $slots{$slot}->{'symb'};
 9326:             if (($startreserve < $now) &&
 9327:                 (!$endreserve || $endreserve > $now)) {
 9328:                 my $lastres = $endreserve;
 9329:                 if (!$lastres) {
 9330:                     $lastres = $slots{$slot}->{'starttime'};
 9331:                 }
 9332:                 $reservable_now{$slot} = {
 9333:                                            symb       => $symb,
 9334:                                            endreserve => $lastres
 9335:                                          };
 9336:             } elsif (($startreserve > $now) &&
 9337:                      (!$endreserve || $endreserve > $startreserve)) {
 9338:                 $future_reservable{$slot} = {
 9339:                                               symb         => $symb,
 9340:                                               startreserve => $startreserve
 9341:                                             };
 9342:             }
 9343:         }
 9344:     }
 9345:     my @unsorted_reservable = keys(%reservable_now);
 9346:     if (@unsorted_reservable > 0) {
 9347:         @sorted_reservable = 
 9348:             &sorted_slots(\@unsorted_reservable,\%reservable_now,'endreserve');
 9349:     }
 9350:     my @unsorted_future = keys(%future_reservable);
 9351:     if (@unsorted_future > 0) {
 9352:         @sorted_future =
 9353:             &sorted_slots(\@unsorted_future,\%future_reservable,'startreserve');
 9354:     }
 9355:     return (\@sorted_reservable,\%reservable_now,\@sorted_future,\%future_reservable);
 9356: }
 9357: 
 9358: =pod
 9359: 
 9360: =back
 9361: 
 9362: =head1 HTTP Helpers
 9363: 
 9364: =over 4
 9365: 
 9366: =item * &get_unprocessed_cgi($query,$possible_names)
 9367: 
 9368: Modify the %env hash to contain unprocessed CGI form parameters held in
 9369: $query.  The parameters listed in $possible_names (an array reference),
 9370: will be set in $env{'form.name'} if they do not already exist.
 9371: 
 9372: Typically called with $ENV{'QUERY_STRING'} as the first parameter.  
 9373: $possible_names is an ref to an array of form element names.  As an example:
 9374: get_unprocessed_cgi($ENV{'QUERY_STRING'},['uname','udom']);
 9375: will result in $env{'form.uname'} and $env{'form.udom'} being set.
 9376: 
 9377: =cut
 9378: 
 9379: sub get_unprocessed_cgi {
 9380:   my ($query,$possible_names)= @_;
 9381:   # $Apache::lonxml::debug=1;
 9382:   foreach my $pair (split(/&/,$query)) {
 9383:     my ($name, $value) = split(/=/,$pair);
 9384:     $name = &unescape($name);
 9385:     if (!defined($possible_names) || (grep {$_ eq $name} @$possible_names)) {
 9386:       $value =~ tr/+/ /;
 9387:       $value =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack("C",hex($1))/eg;
 9388:       unless (defined($env{'form.'.$name})) { &add_to_env('form.'.$name,$value) };
 9389:     }
 9390:   }
 9391: }
 9392: 
 9393: =pod
 9394: 
 9395: =item * &cacheheader() 
 9396: 
 9397: returns cache-controlling header code
 9398: 
 9399: =cut
 9400: 
 9401: sub cacheheader {
 9402:     unless ($env{'request.method'} eq 'GET') { return ''; }
 9403:     my $date=strftime("%a, %d %b %Y %H:%M:%S GMT",gmtime);
 9404:     my $output .='<meta HTTP-EQUIV="Expires" CONTENT="'.$date.'" />
 9405:                 <meta HTTP-EQUIV="Cache-control" CONTENT="no-cache" />
 9406:                 <meta HTTP-EQUIV="Pragma" CONTENT="no-cache" />';
 9407:     return $output;
 9408: }
 9409: 
 9410: =pod
 9411: 
 9412: =item * &no_cache($r) 
 9413: 
 9414: specifies header code to not have cache
 9415: 
 9416: =cut
 9417: 
 9418: sub no_cache {
 9419:     my ($r) = @_;
 9420:     if ($ENV{'REQUEST_METHOD'} ne 'GET' &&
 9421: 	$env{'request.method'} ne 'GET') { return ''; }
 9422:     my $date=strftime("%a, %d %b %Y %H:%M:%S GMT",gmtime(time));
 9423:     $r->no_cache(1);
 9424:     $r->header_out("Expires" => $date);
 9425:     $r->header_out("Pragma" => "no-cache");
 9426: }
 9427: 
 9428: sub content_type {
 9429:     my ($r,$type,$charset) = @_;
 9430:     if ($r) {
 9431: 	#  Note that printout.pl calls this with undef for $r.
 9432: 	&no_cache($r);
 9433:     }
 9434:     if ($env{'browser.mathml'} && $type eq 'text/html') { $type='text/xml'; }
 9435:     unless ($charset) {
 9436: 	$charset=&Apache::lonlocal::current_encoding;
 9437:     }
 9438:     if ($charset) { $type.='; charset='.$charset; }
 9439:     if ($r) {
 9440: 	$r->content_type($type);
 9441:     } else {
 9442: 	print("Content-type: $type\n\n");
 9443:     }
 9444: }
 9445: 
 9446: =pod
 9447: 
 9448: =item * &add_to_env($name,$value) 
 9449: 
 9450: adds $name to the %env hash with value
 9451: $value, if $name already exists, the entry is converted to an array
 9452: reference and $value is added to the array.
 9453: 
 9454: =cut
 9455: 
 9456: sub add_to_env {
 9457:   my ($name,$value)=@_;
 9458:   if (defined($env{$name})) {
 9459:     if (ref($env{$name})) {
 9460:       #already have multiple values
 9461:       push(@{ $env{$name} },$value);
 9462:     } else {
 9463:       #first time seeing multiple values, convert hash entry to an arrayref
 9464:       my $first=$env{$name};
 9465:       undef($env{$name});
 9466:       push(@{ $env{$name} },$first,$value);
 9467:     }
 9468:   } else {
 9469:     $env{$name}=$value;
 9470:   }
 9471: }
 9472: 
 9473: =pod
 9474: 
 9475: =item * &get_env_multiple($name) 
 9476: 
 9477: gets $name from the %env hash, it seemlessly handles the cases where multiple
 9478: values may be defined and end up as an array ref.
 9479: 
 9480: returns an array of values
 9481: 
 9482: =cut
 9483: 
 9484: sub get_env_multiple {
 9485:     my ($name) = @_;
 9486:     my @values;
 9487:     if (defined($env{$name})) {
 9488:         # exists is it an array
 9489:         if (ref($env{$name})) {
 9490:             @values=@{ $env{$name} };
 9491:         } else {
 9492:             $values[0]=$env{$name};
 9493:         }
 9494:     }
 9495:     return(@values);
 9496: }
 9497: 
 9498: sub ask_for_embedded_content {
 9499:     my ($actionurl,$state,$allfiles,$codebase,$args)=@_;
 9500:     my (%subdependencies,%dependencies,%mapping,%existing,%newfiles,%pathchanges,
 9501:         %currsubfile,%unused,$rem);
 9502:     my $counter = 0;
 9503:     my $numnew = 0;
 9504:     my $numremref = 0;
 9505:     my $numinvalid = 0;
 9506:     my $numpathchg = 0;
 9507:     my $numexisting = 0;
 9508:     my $numunused = 0;
 9509:     my ($output,$upload_output,$toplevel,$url,$udom,$uname,$getpropath,$cdom,$cnum,
 9510:         $fileloc,$filename,$delete_output,$modify_output,$title,$symb,$path);
 9511:     my $heading = &mt('Upload embedded files');
 9512:     my $buttontext = &mt('Upload');
 9513: 
 9514:     my $navmap;
 9515:     if ($env{'request.course.id'}) {
 9516:         $navmap = Apache::lonnavmaps::navmap->new();
 9517:     }
 9518:     if (($actionurl eq '/adm/portfolio') || ($actionurl eq '/adm/coursegrp_portfolio')) {
 9519:         my $current_path='/';
 9520:         if ($env{'form.currentpath'}) {
 9521:             $current_path = $env{'form.currentpath'};
 9522:         }
 9523:         if ($actionurl eq '/adm/coursegrp_portfolio') {
 9524:             $udom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 9525:             $uname = $env{'course.'.$env{'request.course.id'}.'.num'};
 9526:             $url = '/userfiles/groups/'.$env{'form.group'}.'/portfolio';
 9527:         } else {
 9528:             $udom = $env{'user.domain'};
 9529:             $uname = $env{'user.name'};
 9530:             $url = '/userfiles/portfolio';
 9531:         }
 9532:         $toplevel = $url.'/';
 9533:         $url .= $current_path;
 9534:         $getpropath = 1;
 9535:     } elsif (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank') ||
 9536:              ($actionurl eq '/adm/imsimport')) { 
 9537:         my ($udom,$uname,$rest) = ($args->{'current_path'} =~ m{/priv/($match_domain)/($match_username)/?(.*)$});
 9538:         $url = $Apache::lonnet::perlvar{'lonDocRoot'}."/priv/$udom/$uname/";
 9539:         $toplevel = $url;
 9540:         if ($rest ne '') {
 9541:             $url .= $rest;
 9542:         }
 9543:     } elsif ($actionurl eq '/adm/coursedocs') {
 9544:         if (ref($args) eq 'HASH') {
 9545:             $url = $args->{'docs_url'};
 9546:             $toplevel = $url;
 9547:             if ($args->{'context'} eq 'paste') {
 9548:                 ($cdom,$cnum) = ($url =~ m{^\Q/uploaded/\E($match_domain)/($match_courseid)/});
 9549:                 ($path) = 
 9550:                     ($toplevel =~ m{^(\Q/uploaded/$cdom/$cnum/\E(?:docs|supplemental)/(?:default|\d+)/\d+)/});
 9551:                 $fileloc = &Apache::lonnet::filelocation('',$toplevel);
 9552:                 $fileloc =~ s{^/}{};
 9553:             }
 9554:         }
 9555:     } elsif ($actionurl eq '/adm/dependencies')  {
 9556:         if ($env{'request.course.id'} ne '') {
 9557:             $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 9558:             $cnum =  $env{'course.'.$env{'request.course.id'}.'.num'};
 9559:             if (ref($args) eq 'HASH') {
 9560:                 $url = $args->{'docs_url'};
 9561:                 $title = $args->{'docs_title'};
 9562:                 $toplevel = "/$url";
 9563:                 ($rem) = ($toplevel =~ m{^(.+/)[^/]+$});
 9564:                 ($path) =  
 9565:                     ($toplevel =~ m{^(\Q/uploaded/$cdom/$cnum/\E(?:docs|supplemental)/(?:default|\d+)/\d+)/});
 9566:                 $fileloc = &Apache::lonnet::filelocation('',$toplevel);
 9567:                 $fileloc =~ s{^/}{};
 9568:                 ($filename) = ($fileloc =~ m{.+/([^/]+)$});
 9569:                 $heading = &mt('Status of dependencies in [_1]',"$title ($filename)");
 9570:             }
 9571:         }
 9572:     }
 9573:     my $now = time();
 9574:     foreach my $embed_file (keys(%{$allfiles})) {
 9575:         my $absolutepath;
 9576:         if ($embed_file =~ m{^\w+://}) {
 9577:             $newfiles{$embed_file} = 1;
 9578:             $mapping{$embed_file} = $embed_file;
 9579:         } else {
 9580:             if ($embed_file =~ m{^/}) {
 9581:                 $absolutepath = $embed_file;
 9582:                 $embed_file =~ s{^(/+)}{};
 9583:             }
 9584:             if ($embed_file =~ m{/}) {
 9585:                 my ($path,$fname) = ($embed_file =~ m{^(.+)/([^/]*)$});
 9586:                 $path = &check_for_traversal($path,$url,$toplevel);
 9587:                 my $item = $fname;
 9588:                 if ($path ne '') {
 9589:                     $item = $path.'/'.$fname;
 9590:                     $subdependencies{$path}{$fname} = 1;
 9591:                 } else {
 9592:                     $dependencies{$item} = 1;
 9593:                 }
 9594:                 if ($absolutepath) {
 9595:                     $mapping{$item} = $absolutepath;
 9596:                 } else {
 9597:                     $mapping{$item} = $embed_file;
 9598:                 }
 9599:             } else {
 9600:                 $dependencies{$embed_file} = 1;
 9601:                 if ($absolutepath) {
 9602:                     $mapping{$embed_file} = $absolutepath;
 9603:                 } else {
 9604:                     $mapping{$embed_file} = $embed_file;
 9605:                 }
 9606:             }
 9607:         }
 9608:     }
 9609:     my $dirptr = 16384;
 9610:     foreach my $path (keys(%subdependencies)) {
 9611:         $currsubfile{$path} = {};
 9612:         if (($actionurl eq '/adm/portfolio') || ($actionurl eq '/adm/coursegrp_portfolio')) { 
 9613:             my ($sublistref,$listerror) =
 9614:                 &Apache::lonnet::dirlist($url.$path,$udom,$uname,$getpropath);
 9615:             if (ref($sublistref) eq 'ARRAY') {
 9616:                 foreach my $line (@{$sublistref}) {
 9617:                     my ($file_name,$rest) = split(/\&/,$line,2);
 9618:                     $currsubfile{$path}{$file_name} = 1;
 9619:                 }
 9620:             }
 9621:         } elsif (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank')) {
 9622:             if (opendir(my $dir,$url.'/'.$path)) {
 9623:                 my @subdir_list = grep(!/^\./,readdir($dir));
 9624:                 map {$currsubfile{$path}{$_} = 1;} @subdir_list;
 9625:             }
 9626:         } elsif (($actionurl eq '/adm/dependencies') ||
 9627:                  (($actionurl eq '/adm/coursedocs') && (ref($args) eq 'HASH') &&
 9628:                   ($args->{'context'} eq 'paste'))) {
 9629:             if ($env{'request.course.id'} ne '') {
 9630:                 my ($dir) = ($fileloc =~ m{^(.+/)[^/]+$});
 9631:                 if ($dir ne '') {
 9632:                     my ($sublistref,$listerror) =
 9633:                         &Apache::lonnet::dirlist($dir.$path,$cdom,$cnum,$getpropath,undef,'/');
 9634:                     if (ref($sublistref) eq 'ARRAY') {
 9635:                         foreach my $line (@{$sublistref}) {
 9636:                             my ($file_name,$dom,undef,$testdir,undef,undef,undef,undef,$size,
 9637:                                 undef,$mtime)=split(/\&/,$line,12);
 9638:                             unless (($testdir&$dirptr) ||
 9639:                                     ($file_name =~ /^\.\.?$/)) {
 9640:                                 $currsubfile{$path}{$file_name} = [$size,$mtime];
 9641:                             }
 9642:                         }
 9643:                     }
 9644:                 }
 9645:             }
 9646:         }
 9647:         foreach my $file (keys(%{$subdependencies{$path}})) {
 9648:             if (exists($currsubfile{$path}{$file})) {
 9649:                 my $item = $path.'/'.$file;
 9650:                 unless ($mapping{$item} eq $item) {
 9651:                     $pathchanges{$item} = 1;
 9652:                 }
 9653:                 $existing{$item} = 1;
 9654:                 $numexisting ++;
 9655:             } else {
 9656:                 $newfiles{$path.'/'.$file} = 1;
 9657:             }
 9658:         }
 9659:         if ($actionurl eq '/adm/dependencies') {
 9660:             foreach my $path (keys(%currsubfile)) {
 9661:                 if (ref($currsubfile{$path}) eq 'HASH') {
 9662:                     foreach my $file (keys(%{$currsubfile{$path}})) {
 9663:                          unless ($subdependencies{$path}{$file}) {
 9664:                              next if (($rem ne '') &&
 9665:                                       (($env{"httpref.$rem"."$path/$file"} ne '') ||
 9666:                                        (ref($navmap) &&
 9667:                                        (($navmap->getResourceByUrl($rem."$path/$file") ne '') ||
 9668:                                         (($file =~ /^(.*\.s?html?)\.bak$/i) &&
 9669:                                          ($navmap->getResourceByUrl($rem."$path/$1")))))));
 9670:                              $unused{$path.'/'.$file} = 1; 
 9671:                          }
 9672:                     }
 9673:                 }
 9674:             }
 9675:         }
 9676:     }
 9677:     my %currfile;
 9678:     if (($actionurl eq '/adm/portfolio') || ($actionurl eq '/adm/coursegrp_portfolio')) {
 9679:         my ($dirlistref,$listerror) =
 9680:             &Apache::lonnet::dirlist($url,$udom,$uname,$getpropath);
 9681:         if (ref($dirlistref) eq 'ARRAY') {
 9682:             foreach my $line (@{$dirlistref}) {
 9683:                 my ($file_name,$rest) = split(/\&/,$line,2);
 9684:                 $currfile{$file_name} = 1;
 9685:             }
 9686:         }
 9687:     } elsif (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank')) {
 9688:         if (opendir(my $dir,$url)) {
 9689:             my @dir_list = grep(!/^\./,readdir($dir));
 9690:             map {$currfile{$_} = 1;} @dir_list;
 9691:         }
 9692:     } elsif (($actionurl eq '/adm/dependencies') ||
 9693:              (($actionurl eq '/adm/coursedocs') && (ref($args) eq 'HASH') &&
 9694:               ($args->{'context'} eq 'paste'))) {
 9695:         if ($env{'request.course.id'} ne '') {
 9696:             my ($dir) = ($fileloc =~ m{^(.+/)[^/]+$});
 9697:             if ($dir ne '') {
 9698:                 my ($dirlistref,$listerror) =
 9699:                     &Apache::lonnet::dirlist($dir,$cdom,$cnum,$getpropath,undef,'/');
 9700:                 if (ref($dirlistref) eq 'ARRAY') {
 9701:                     foreach my $line (@{$dirlistref}) {
 9702:                         my ($file_name,$dom,undef,$testdir,undef,undef,undef,undef,
 9703:                             $size,undef,$mtime)=split(/\&/,$line,12);
 9704:                         unless (($testdir&$dirptr) ||
 9705:                                 ($file_name =~ /^\.\.?$/)) {
 9706:                             $currfile{$file_name} = [$size,$mtime];
 9707:                         }
 9708:                     }
 9709:                 }
 9710:             }
 9711:         }
 9712:     }
 9713:     foreach my $file (keys(%dependencies)) {
 9714:         if (exists($currfile{$file})) {
 9715:             unless ($mapping{$file} eq $file) {
 9716:                 $pathchanges{$file} = 1;
 9717:             }
 9718:             $existing{$file} = 1;
 9719:             $numexisting ++;
 9720:         } else {
 9721:             $newfiles{$file} = 1;
 9722:         }
 9723:     }
 9724:     foreach my $file (keys(%currfile)) {
 9725:         unless (($file eq $filename) ||
 9726:                 ($file eq $filename.'.bak') ||
 9727:                 ($dependencies{$file})) {
 9728:             if ($actionurl eq '/adm/dependencies') {
 9729:                 next if (($rem ne '') &&
 9730:                          (($env{"httpref.$rem".$file} ne '') ||
 9731:                           (ref($navmap) &&
 9732:                           (($navmap->getResourceByUrl($rem.$file) ne '') ||
 9733:                            (($file =~ /^(.*\.s?html?)\.bak$/i) &&
 9734:                             ($navmap->getResourceByUrl($rem.$1)))))));
 9735:             }
 9736:             $unused{$file} = 1;
 9737:         }
 9738:     }
 9739:     if (($actionurl eq '/adm/coursedocs') && (ref($args) eq 'HASH') &&
 9740:         ($args->{'context'} eq 'paste')) {
 9741:         $counter = scalar(keys(%existing));
 9742:         $numpathchg = scalar(keys(%pathchanges));
 9743:         return ($output,$counter,$numpathchg,\%existing); 
 9744:     }
 9745:     foreach my $embed_file (sort {lc($a) cmp lc($b)} keys(%newfiles)) {
 9746:         if ($actionurl eq '/adm/dependencies') {
 9747:             next if ($embed_file =~ m{^\w+://});
 9748:         }
 9749:         $upload_output .= &start_data_table_row().
 9750:                           '<td><img src="'.&icon($embed_file).'" />&nbsp;'.
 9751:                           '<span class="LC_filename">'.$embed_file.'</span>';
 9752:         unless ($mapping{$embed_file} eq $embed_file) {
 9753:             $upload_output .= '<br /><span class="LC_info" style="font-size:smaller;">'.&mt('changed from: [_1]',$mapping{$embed_file}).'</span>';
 9754:         }
 9755:         $upload_output .= '</td><td>';
 9756:         if ($args->{'ignore_remote_references'} && $embed_file =~ m{^\w+://}) { 
 9757:             $upload_output.='<span class="LC_warning">'.&mt("URL points to other server.").'</span>';
 9758:             $numremref++;
 9759:         } elsif ($args->{'error_on_invalid_names'}
 9760:             && $embed_file ne &Apache::lonnet::clean_filename($embed_file,{'keep_path' => 1,})) {
 9761:             $upload_output.='<span class="LC_warning">'.&mt('Invalid characters').'</span>';
 9762:             $numinvalid++;
 9763:         } else {
 9764:             $upload_output .= &embedded_file_element('upload_embedded',$counter,
 9765:                                                      $embed_file,\%mapping,
 9766:                                                      $allfiles,$codebase,'upload');
 9767:             $counter ++;
 9768:             $numnew ++;
 9769:         }
 9770:         $upload_output .= '</td>'.&Apache::loncommon::end_data_table_row()."\n";
 9771:     }
 9772:     foreach my $embed_file (sort {lc($a) cmp lc($b)} keys(%existing)) {
 9773:         if ($actionurl eq '/adm/dependencies') {
 9774:             my ($size,$mtime) = &get_dependency_details(\%currfile,\%currsubfile,$embed_file);
 9775:             $modify_output .= &start_data_table_row().
 9776:                               '<td><a href="'.$path.'/'.$embed_file.'" style="text-decoration:none;">'.
 9777:                               '<img src="'.&icon($embed_file).'" border="0" />'.
 9778:                               '&nbsp;<span class="LC_filename">'.$embed_file.'</span></a></td>'.
 9779:                               '<td>'.$size.'</td>'.
 9780:                               '<td>'.$mtime.'</td>'.
 9781:                               '<td><label><input type="checkbox" name="mod_upload_dep" '.
 9782:                               'onclick="toggleBrowse('."'$counter'".')" id="mod_upload_dep_'.
 9783:                               $counter.'" value="'.$counter.'" />'.&mt('Yes').'</label>'.
 9784:                               '<div id="moduploaddep_'.$counter.'" style="display:none;">'.
 9785:                               &embedded_file_element('upload_embedded',$counter,
 9786:                                                      $embed_file,\%mapping,
 9787:                                                      $allfiles,$codebase,'modify').
 9788:                               '</div></td>'.
 9789:                               &end_data_table_row()."\n";
 9790:             $counter ++;
 9791:         } else {
 9792:             $upload_output .= &start_data_table_row().
 9793:                               '<td><span class="LC_filename">'.$embed_file.'</span></td>';
 9794:                               '<td><span class="LC_warning">'.&mt('Already exists').'</span></td>'.
 9795:                               &Apache::loncommon::end_data_table_row()."\n";
 9796:         }
 9797:     }
 9798:     my $delidx = $counter;
 9799:     foreach my $oldfile (sort {lc($a) cmp lc($b)} keys(%unused)) {
 9800:         my ($size,$mtime) = &get_dependency_details(\%currfile,\%currsubfile,$oldfile);
 9801:         $delete_output .= &start_data_table_row().
 9802:                           '<td><img src="'.&icon($oldfile).'" />'.
 9803:                           '&nbsp;<span class="LC_filename">'.$oldfile.'</span></td>'.
 9804:                           '<td>'.$size.'</td>'.
 9805:                           '<td>'.$mtime.'</td>'.
 9806:                           '<td><label><input type="checkbox" name="del_upload_dep" '.
 9807:                           ' value="'.$delidx.'" />'.&mt('Yes').'</label>'.
 9808:                           &embedded_file_element('upload_embedded',$delidx,
 9809:                                                  $oldfile,\%mapping,$allfiles,
 9810:                                                  $codebase,'delete').'</td>'.
 9811:                           &end_data_table_row()."\n"; 
 9812:         $numunused ++;
 9813:         $delidx ++;
 9814:     }
 9815:     if ($upload_output) {
 9816:         $upload_output = &start_data_table().
 9817:                          $upload_output.
 9818:                          &end_data_table()."\n";
 9819:     }
 9820:     if ($modify_output) {
 9821:         $modify_output = &start_data_table().
 9822:                          &start_data_table_header_row().
 9823:                          '<th>'.&mt('File').'</th>'.
 9824:                          '<th>'.&mt('Size (KB)').'</th>'.
 9825:                          '<th>'.&mt('Modified').'</th>'.
 9826:                          '<th>'.&mt('Upload replacement?').'</th>'.
 9827:                          &end_data_table_header_row().
 9828:                          $modify_output.
 9829:                          &end_data_table()."\n";
 9830:     }
 9831:     if ($delete_output) {
 9832:         $delete_output = &start_data_table().
 9833:                          &start_data_table_header_row().
 9834:                          '<th>'.&mt('File').'</th>'.
 9835:                          '<th>'.&mt('Size (KB)').'</th>'.
 9836:                          '<th>'.&mt('Modified').'</th>'.
 9837:                          '<th>'.&mt('Delete?').'</th>'.
 9838:                          &end_data_table_header_row().
 9839:                          $delete_output.
 9840:                          &end_data_table()."\n";
 9841:     }
 9842:     my $applies = 0;
 9843:     if ($numremref) {
 9844:         $applies ++;
 9845:     }
 9846:     if ($numinvalid) {
 9847:         $applies ++;
 9848:     }
 9849:     if ($numexisting) {
 9850:         $applies ++;
 9851:     }
 9852:     if ($counter || $numunused) {
 9853:         $output = '<form name="upload_embedded" action="'.$actionurl.'"'.
 9854:                   ' method="post" enctype="multipart/form-data">'."\n".
 9855:                   $state.'<h3>'.$heading.'</h3>'; 
 9856:         if ($actionurl eq '/adm/dependencies') {
 9857:             if ($numnew) {
 9858:                 $output .= '<h4>'.&mt('Missing dependencies').'</h4>'.
 9859:                            '<p>'.&mt('The following files need to be uploaded.').'</p>'."\n".
 9860:                            $upload_output.'<br />'."\n";
 9861:             }
 9862:             if ($numexisting) {
 9863:                 $output .= '<h4>'.&mt('Uploaded dependencies (in use)').'</h4>'.
 9864:                            '<p>'.&mt('Upload a new file to replace the one currently in use.').'</p>'."\n".
 9865:                            $modify_output.'<br />'."\n";
 9866:                            $buttontext = &mt('Save changes');
 9867:             }
 9868:             if ($numunused) {
 9869:                 $output .= '<h4>'.&mt('Unused files').'</h4>'.
 9870:                            '<p>'.&mt('The following uploaded files are no longer used.').'</p>'."\n".
 9871:                            $delete_output.'<br />'."\n";
 9872:                            $buttontext = &mt('Save changes');
 9873:             }
 9874:         } else {
 9875:             $output .= $upload_output.'<br />'."\n";
 9876:         }
 9877:         $output .= '<input type ="hidden" name="number_embedded_items" value="'.
 9878:                    $counter.'" />'."\n";
 9879:         if ($actionurl eq '/adm/dependencies') { 
 9880:             $output .= '<input type ="hidden" name="number_newemb_items" value="'.
 9881:                        $numnew.'" />'."\n";
 9882:         } elsif ($actionurl eq '') {
 9883:             $output .=  '<input type="hidden" name="phase" value="three" />';
 9884:         }
 9885:     } elsif ($applies) {
 9886:         $output = '<b>'.&mt('Referenced files').'</b>:<br />';
 9887:         if ($applies > 1) {
 9888:             $output .=  
 9889:                 &mt('No files need to be uploaded, as one of the following applies to each reference:').'<ul>';
 9890:             if ($numremref) {
 9891:                 $output .= '<li>'.&mt('reference is to a URL which points to another server').'</li>'."\n";
 9892:             }
 9893:             if ($numinvalid) {
 9894:                 $output .= '<li>'.&mt('reference is to file with a name containing invalid characters').'</li>'."\n";
 9895:             }
 9896:             if ($numexisting) {
 9897:                 $output .= '<li>'.&mt('reference is to an existing file at the specified location').'</li>'."\n";
 9898:             }
 9899:             $output .= '</ul><br />';
 9900:         } elsif ($numremref) {
 9901:             $output .= '<p>'.&mt('None to upload, as all references are to URLs pointing to another server.').'</p>';
 9902:         } elsif ($numinvalid) {
 9903:             $output .= '<p>'.&mt('None to upload, as all references are to files with names containing invalid characters.').'</p>';
 9904:         } elsif ($numexisting) {
 9905:             $output .= '<p>'.&mt('None to upload, as all references are to existing files.').'</p>';
 9906:         }
 9907:         $output .= $upload_output.'<br />';
 9908:     }
 9909:     my ($pathchange_output,$chgcount);
 9910:     $chgcount = $counter;
 9911:     if (keys(%pathchanges) > 0) {
 9912:         foreach my $embed_file (sort {lc($a) cmp lc($b)} keys(%pathchanges)) {
 9913:             if ($counter) {
 9914:                 $output .= &embedded_file_element('pathchange',$chgcount,
 9915:                                                   $embed_file,\%mapping,
 9916:                                                   $allfiles,$codebase,'change');
 9917:             } else {
 9918:                 $pathchange_output .= 
 9919:                     &start_data_table_row().
 9920:                     '<td><input type ="checkbox" name="namechange" value="'.
 9921:                     $chgcount.'" checked="checked" /></td>'.
 9922:                     '<td>'.$mapping{$embed_file}.'</td>'.
 9923:                     '<td>'.$embed_file.
 9924:                     &embedded_file_element('pathchange',$numpathchg,$embed_file,
 9925:                                            \%mapping,$allfiles,$codebase,'change').
 9926:                     '</td>'.&end_data_table_row();
 9927:             }
 9928:             $numpathchg ++;
 9929:             $chgcount ++;
 9930:         }
 9931:     }
 9932:     if ($counter) {
 9933:         if ($numpathchg) {
 9934:             $output .= '<input type ="hidden" name="number_pathchange_items" value="'.
 9935:                        $numpathchg.'" />'."\n";
 9936:         }
 9937:         if (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank') || 
 9938:             ($actionurl eq '/adm/imsimport')) {
 9939:             $output .= '<input type="hidden" name="phase" value="three" />'."\n";
 9940:         } elsif ($actionurl eq '/adm/portfolio' || $actionurl eq '/adm/coursegrp_portfolio') {
 9941:             $output .= '<input type="hidden" name="action" value="upload_embedded" />';
 9942:         } elsif ($actionurl eq '/adm/dependencies') {
 9943:             $output .= '<input type="hidden" name="action" value="process_changes" />';
 9944:         }
 9945:         $output .=  '<input type ="submit" value="'.$buttontext.'" />'."\n".'</form>'."\n";
 9946:     } elsif ($numpathchg) {
 9947:         my %pathchange = ();
 9948:         $output .= &modify_html_form('pathchange',$actionurl,$state,\%pathchange,$pathchange_output);
 9949:         if (($actionurl eq '/adm/portfolio') || ($actionurl eq '/adm/coursegrp_portfolio')) {
 9950:             $output .= '<p>'.&mt('or').'</p>'; 
 9951:         } 
 9952:     }
 9953:     return ($output,$counter,$numpathchg);
 9954: }
 9955: 
 9956: sub embedded_file_element {
 9957:     my ($context,$num,$embed_file,$mapping,$allfiles,$codebase,$type) = @_;
 9958:     return unless ((ref($mapping) eq 'HASH') && (ref($allfiles) eq 'HASH') &&
 9959:                    (ref($codebase) eq 'HASH'));
 9960:     my $output;
 9961:     if (($context eq 'upload_embedded') && ($type ne 'delete')) {
 9962:        $output = '<input name="embedded_item_'.$num.'" type="file" value="" />'."\n";
 9963:     }
 9964:     $output .= '<input name="embedded_orig_'.$num.'" type="hidden" value="'.
 9965:                &escape($embed_file).'" />';
 9966:     unless (($context eq 'upload_embedded') && 
 9967:             ($mapping->{$embed_file} eq $embed_file)) {
 9968:         $output .='
 9969:         <input name="embedded_ref_'.$num.'" type="hidden" value="'.&escape($mapping->{$embed_file}).'" />';
 9970:     }
 9971:     my $attrib;
 9972:     if (ref($allfiles->{$mapping->{$embed_file}}) eq 'ARRAY') {
 9973:         $attrib = &escape(join(':',@{$allfiles->{$mapping->{$embed_file}}}));
 9974:     }
 9975:     $output .=
 9976:         "\n\t\t".
 9977:         '<input name="embedded_attrib_'.$num.'" type="hidden" value="'.
 9978:         $attrib.'" />';
 9979:     if (exists($codebase->{$mapping->{$embed_file}})) {
 9980:         $output .=
 9981:             "\n\t\t".
 9982:             '<input name="codebase_'.$num.'" type="hidden" value="'.
 9983:             &escape($codebase->{$mapping->{$embed_file}}).'" />';
 9984:     }
 9985:     return $output;
 9986: }
 9987: 
 9988: sub get_dependency_details {
 9989:     my ($currfile,$currsubfile,$embed_file) = @_;
 9990:     my ($size,$mtime,$showsize,$showmtime);
 9991:     if ((ref($currfile) eq 'HASH') && (ref($currsubfile))) {
 9992:         if ($embed_file =~ m{/}) {
 9993:             my ($path,$fname) = split(/\//,$embed_file);
 9994:             if (ref($currsubfile->{$path}{$fname}) eq 'ARRAY') {
 9995:                 ($size,$mtime) = @{$currsubfile->{$path}{$fname}};
 9996:             }
 9997:         } else {
 9998:             if (ref($currfile->{$embed_file}) eq 'ARRAY') {
 9999:                 ($size,$mtime) = @{$currfile->{$embed_file}};
10000:             }
10001:         }
10002:         $showsize = $size/1024.0;
10003:         $showsize = sprintf("%.1f",$showsize);
10004:         if ($mtime > 0) {
10005:             $showmtime = &Apache::lonlocal::locallocaltime($mtime);
10006:         }
10007:     }
10008:     return ($showsize,$showmtime);
10009: }
10010: 
10011: sub ask_embedded_js {
10012:     return <<"END";
10013: <script type="text/javascript"">
10014: // <![CDATA[
10015: function toggleBrowse(counter) {
10016:     var chkboxid = document.getElementById('mod_upload_dep_'+counter);
10017:     var fileid = document.getElementById('embedded_item_'+counter);
10018:     var uploaddivid = document.getElementById('moduploaddep_'+counter);
10019:     if (chkboxid.checked == true) {
10020:         uploaddivid.style.display='block';
10021:     } else {
10022:         uploaddivid.style.display='none';
10023:         fileid.value = '';
10024:     }
10025: }
10026: // ]]>
10027: </script>
10028: 
10029: END
10030: }
10031: 
10032: sub upload_embedded {
10033:     my ($context,$dirpath,$uname,$udom,$dir_root,$url_root,$group,$disk_quota,
10034:         $current_disk_usage,$hiddenstate,$actionurl) = @_;
10035:     my (%pathchange,$output,$modifyform,$footer,$returnflag);
10036:     for (my $i=0; $i<$env{'form.number_embedded_items'}; $i++) {
10037:         next if (!exists($env{'form.embedded_item_'.$i.'.filename'}));
10038:         my $orig_uploaded_filename =
10039:             $env{'form.embedded_item_'.$i.'.filename'};
10040:         foreach my $type ('orig','ref','attrib','codebase') {
10041:             if ($env{'form.embedded_'.$type.'_'.$i} ne '') {
10042:                 $env{'form.embedded_'.$type.'_'.$i} =
10043:                     &unescape($env{'form.embedded_'.$type.'_'.$i});
10044:             }
10045:         }
10046:         my ($path,$fname) =
10047:             ($env{'form.embedded_orig_'.$i} =~ m{(.*/)([^/]*)});
10048:         # no path, whole string is fname
10049:         if (!$fname) { $fname = $env{'form.embedded_orig_'.$i} };
10050:         $fname = &Apache::lonnet::clean_filename($fname);
10051:         # See if there is anything left
10052:         next if ($fname eq '');
10053: 
10054:         # Check if file already exists as a file or directory.
10055:         my ($state,$msg);
10056:         if ($context eq 'portfolio') {
10057:             my $port_path = $dirpath;
10058:             if ($group ne '') {
10059:                 $port_path = "groups/$group/$port_path";
10060:             }
10061:             ($state,$msg) = &check_for_upload($env{'form.currentpath'}.$path,
10062:                                               $fname,$group,'embedded_item_'.$i,
10063:                                               $dir_root,$port_path,$disk_quota,
10064:                                               $current_disk_usage,$uname,$udom);
10065:             if ($state eq 'will_exceed_quota'
10066:                 || $state eq 'file_locked') {
10067:                 $output .= $msg;
10068:                 next;
10069:             }
10070:         } elsif (($context eq 'author') || ($context eq 'testbank')) {
10071:             ($state,$msg) = &check_for_existing($path,$fname,'embedded_item_'.$i);
10072:             if ($state eq 'exists') {
10073:                 $output .= $msg;
10074:                 next;
10075:             }
10076:         }
10077:         # Check if extension is valid
10078:         if (($fname =~ /\.(\w+)$/) &&
10079:             (&Apache::loncommon::fileembstyle($1) eq 'hdn')) {
10080:             $output .= &mt('Invalid file extension ([_1]) - reserved for LONCAPA use - rename the file with a different extension and re-upload. ',$1).'<br />';
10081:             next;
10082:         } elsif (($fname =~ /\.(\w+)$/) &&
10083:                  (!defined(&Apache::loncommon::fileembstyle($1)))) {
10084:             $output .= &mt('Unrecognized file extension ([_1]) - rename the file with a proper extension and re-upload.',$1).'<br />';
10085:             next;
10086:         } elsif ($fname=~/\.(\d+)\.(\w+)$/) {
10087:             $output .= &mt('File name not allowed - rename the file to remove the number immediately before the file extension([_1]) and re-upload.',$2).'<br />';
10088:             next;
10089:         }
10090:         $env{'form.embedded_item_'.$i.'.filename'}=$fname;
10091:         if ($context eq 'portfolio') {
10092:             my $result;
10093:             if ($state eq 'existingfile') {
10094:                 $result=
10095:                     &Apache::lonnet::userfileupload('embedded_item_'.$i,'existingfile',
10096:                                                     $dirpath.$env{'form.currentpath'}.$path);
10097:             } else {
10098:                 $result=
10099:                     &Apache::lonnet::userfileupload('embedded_item_'.$i,'',
10100:                                                     $dirpath.
10101:                                                     $env{'form.currentpath'}.$path);
10102:                 if ($result !~ m|^/uploaded/|) {
10103:                     $output .= '<span class="LC_error">'
10104:                                .&mt('An error occurred ([_1]) while trying to upload [_2] for embedded element [_3].'
10105:                                ,$result,$orig_uploaded_filename,$env{'form.embedded_orig_'.$i})
10106:                                .'</span><br />';
10107:                     next;
10108:                 } else {
10109:                     $output .= &mt('Uploaded [_1]','<span class="LC_filename">'.
10110:                                $path.$fname.'</span>').'<br />';     
10111:                 }
10112:             }
10113:         } elsif ($context eq 'coursedoc') {
10114:             my $result =
10115:                 &Apache::lonnet::userfileupload('embedded_item_'.$i,'coursedoc',
10116:                                                 $dirpath.'/'.$path);
10117:             if ($result !~ m|^/uploaded/|) {
10118:                 $output .= '<span class="LC_error">'
10119:                            .&mt('An error occurred ([_1]) while trying to upload [_2] for embedded element [_3].'
10120:                            ,$result,$orig_uploaded_filename,$env{'form.embedded_orig_'.$i})
10121:                            .'</span><br />';
10122:                     next;
10123:             } else {
10124:                 $output .= &mt('Uploaded [_1]','<span class="LC_filename">'.
10125:                            $path.$fname.'</span>').'<br />';
10126:             }
10127:         } else {
10128: # Save the file
10129:             my $target = $env{'form.embedded_item_'.$i};
10130:             my $fullpath = $dir_root.$dirpath.'/'.$path;
10131:             my $dest = $fullpath.$fname;
10132:             my $url = $url_root.$dirpath.'/'.$path.$fname;
10133:             my @parts=split(/\//,"$dirpath/$path");
10134:             my $count;
10135:             my $filepath = $dir_root;
10136:             foreach my $subdir (@parts) {
10137:                 $filepath .= "/$subdir";
10138:                 if (!-e $filepath) {
10139:                     mkdir($filepath,0770);
10140:                 }
10141:             }
10142:             my $fh;
10143:             if (!open($fh,'>'.$dest)) {
10144:                 &Apache::lonnet::logthis('Failed to create '.$dest);
10145:                 $output .= '<span class="LC_error">'.
10146:                            &mt('An error occurred while trying to upload [_1] for embedded element [_2].',
10147:                                $orig_uploaded_filename,$env{'form.embedded_orig_'.$i}).
10148:                            '</span><br />';
10149:             } else {
10150:                 if (!print $fh $env{'form.embedded_item_'.$i}) {
10151:                     &Apache::lonnet::logthis('Failed to write to '.$dest);
10152:                     $output .= '<span class="LC_error">'.
10153:                               &mt('An error occurred while writing the file [_1] for embedded element [_2].',
10154:                                   $orig_uploaded_filename,$env{'form.embedded_orig_'.$i}).
10155:                               '</span><br />';
10156:                 } else {
10157:                     $output .= &mt('Uploaded [_1]','<span class="LC_filename">'.
10158:                                $url.'</span>').'<br />';
10159:                     unless ($context eq 'testbank') {
10160:                         $footer .= &mt('View embedded file: [_1]',
10161:                                        '<a href="'.$url.'">'.$fname.'</a>').'<br />';
10162:                     }
10163:                 }
10164:                 close($fh);
10165:             }
10166:         }
10167:         if ($env{'form.embedded_ref_'.$i}) {
10168:             $pathchange{$i} = 1;
10169:         }
10170:     }
10171:     if ($output) {
10172:         $output = '<p>'.$output.'</p>';
10173:     }
10174:     $output .= &modify_html_form('upload_embedded',$actionurl,$hiddenstate,\%pathchange);
10175:     $returnflag = 'ok';
10176:     my $numpathchgs = scalar(keys(%pathchange));
10177:     if ($numpathchgs > 0) {
10178:         if ($context eq 'portfolio') {
10179:             $output .= '<p>'.&mt('or').'</p>';
10180:         } elsif ($context eq 'testbank') {
10181:             $output .=  '<p>'.&mt('Or [_1]continue[_2] the testbank import without modifying the reference(s).',
10182:                                   '<a href="javascript:document.testbankForm.submit();">','</a>').'</p>';
10183:             $returnflag = 'modify_orightml';
10184:         }
10185:     }
10186:     return ($output.$footer,$returnflag,$numpathchgs);
10187: }
10188: 
10189: sub modify_html_form {
10190:     my ($context,$actionurl,$hiddenstate,$pathchange,$pathchgtable) = @_;
10191:     my $end = 0;
10192:     my $modifyform;
10193:     if ($context eq 'upload_embedded') {
10194:         return unless (ref($pathchange) eq 'HASH');
10195:         if ($env{'form.number_embedded_items'}) {
10196:             $end += $env{'form.number_embedded_items'};
10197:         }
10198:         if ($env{'form.number_pathchange_items'}) {
10199:             $end += $env{'form.number_pathchange_items'};
10200:         }
10201:         if ($end) {
10202:             for (my $i=0; $i<$end; $i++) {
10203:                 if ($i < $env{'form.number_embedded_items'}) {
10204:                     next unless($pathchange->{$i});
10205:                 }
10206:                 $modifyform .=
10207:                     &start_data_table_row().
10208:                     '<td><input type ="checkbox" name="namechange" value="'.$i.'" '.
10209:                     'checked="checked" /></td>'.
10210:                     '<td>'.$env{'form.embedded_ref_'.$i}.
10211:                     '<input type="hidden" name="embedded_ref_'.$i.'" value="'.
10212:                     &escape($env{'form.embedded_ref_'.$i}).'" />'.
10213:                     '<input type="hidden" name="embedded_codebase_'.$i.'" value="'.
10214:                     &escape($env{'form.embedded_codebase_'.$i}).'" />'.
10215:                     '<input type="hidden" name="embedded_attrib_'.$i.'" value="'.
10216:                     &escape($env{'form.embedded_attrib_'.$i}).'" /></td>'.
10217:                     '<td>'.$env{'form.embedded_orig_'.$i}.
10218:                     '<input type="hidden" name="embedded_orig_'.$i.'" value="'.
10219:                     &escape($env{'form.embedded_orig_'.$i}).'" /></td>'.
10220:                     &end_data_table_row();
10221:             }
10222:         }
10223:     } else {
10224:         $modifyform = $pathchgtable;
10225:         if (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank')) {
10226:             $hiddenstate .= '<input type="hidden" name="phase" value="four" />';
10227:         } elsif (($actionurl eq '/adm/portfolio') || ($actionurl eq '/adm/coursegrp_portfolio')) {
10228:             $hiddenstate .= '<input type="hidden" name="action" value="modify_orightml" />';
10229:         }
10230:     }
10231:     if ($modifyform) {
10232:         if ($actionurl eq '/adm/dependencies') {
10233:             $hiddenstate .= '<input type="hidden" name="action" value="modifyhrefs" />';
10234:         }
10235:         return '<h3>'.&mt('Changes in content of HTML file required').'</h3>'."\n".
10236:                '<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".
10237:                '<li>'.&mt('For consistency between the reference(s) and the location of the corresponding stored file within LON-CAPA.').'</li>'."\n".
10238:                '<li>'.&mt('To change absolute paths to relative paths, or replace directory traversal via "../" within the original reference.').'</li>'."\n".
10239:                '</ol></p>'."\n".'<p>'.
10240:                &mt('LON-CAPA can make the required changes to your HTML file.').'</p>'."\n".
10241:                '<form method="post" name="refchanger" action="'.$actionurl.'">'.
10242:                &start_data_table()."\n".
10243:                &start_data_table_header_row().
10244:                '<th>'.&mt('Change?').'</th>'.
10245:                '<th>'.&mt('Current reference').'</th>'.
10246:                '<th>'.&mt('Required reference').'</th>'.
10247:                &end_data_table_header_row()."\n".
10248:                $modifyform.
10249:                &end_data_table().'<br />'."\n".$hiddenstate.
10250:                '<input type="submit" name="pathchanges" value="'.&mt('Modify HTML file').'" />'.
10251:                '</form>'."\n";
10252:     }
10253:     return;
10254: }
10255: 
10256: sub modify_html_refs {
10257:     my ($context,$dirpath,$uname,$udom,$dir_root) = @_;
10258:     my $container;
10259:     if ($context eq 'portfolio') {
10260:         $container = $env{'form.container'};
10261:     } elsif ($context eq 'coursedoc') {
10262:         $container = $env{'form.primaryurl'};
10263:     } elsif ($context eq 'manage_dependencies') {
10264:         (undef,undef,$container) = &Apache::lonnet::decode_symb($env{'form.symb'});
10265:         $container = "/$container";
10266:     } else {
10267:         $container = $Apache::lonnet::perlvar{'lonDocRoot'}.$env{'form.filename'};
10268:     }
10269:     my (%allfiles,%codebase,$output,$content);
10270:     my @changes = &get_env_multiple('form.namechange');
10271:     unless (@changes > 0) {
10272:         if (wantarray) {
10273:             return ('',0,0); 
10274:         } else {
10275:             return;
10276:         }
10277:     }
10278:     if (($context eq 'portfolio') || ($context eq 'coursedoc') || 
10279:         ($context eq 'manage_dependencies')) {
10280:         unless ($container =~ m{^/uploaded/\Q$udom\E/\Q$uname\E/}) {
10281:             if (wantarray) {
10282:                 return ('',0,0);
10283:             } else {
10284:                 return;
10285:             }
10286:         } 
10287:         $content = &Apache::lonnet::getfile($container);
10288:         if ($content eq '-1') {
10289:             if (wantarray) {
10290:                 return ('',0,0);
10291:             } else {
10292:                 return;
10293:             }
10294:         }
10295:     } else {
10296:         unless ($container =~ /^\Q$dir_root\E/) {
10297:             if (wantarray) {
10298:                 return ('',0,0);
10299:             } else {
10300:                 return;
10301:             }
10302:         } 
10303:         if (open(my $fh,"<$container")) {
10304:             $content = join('', <$fh>);
10305:             close($fh);
10306:         } else {
10307:             if (wantarray) {
10308:                 return ('',0,0);
10309:             } else {
10310:                 return;
10311:             }
10312:         }
10313:     }
10314:     my ($count,$codebasecount) = (0,0);
10315:     my $mm = new File::MMagic;
10316:     my $mime_type = $mm->checktype_contents($content);
10317:     if ($mime_type eq 'text/html') {
10318:         my $parse_result = 
10319:             &Apache::lonnet::extract_embedded_items($container,\%allfiles,
10320:                                                     \%codebase,\$content);
10321:         if ($parse_result eq 'ok') {
10322:             foreach my $i (@changes) {
10323:                 my $orig = &unescape($env{'form.embedded_orig_'.$i});
10324:                 my $ref = &unescape($env{'form.embedded_ref_'.$i});
10325:                 if ($allfiles{$ref}) {
10326:                     my $newname =  $orig;
10327:                     my ($attrib_regexp,$codebase);
10328:                     $attrib_regexp = &unescape($env{'form.embedded_attrib_'.$i});
10329:                     if ($attrib_regexp =~ /:/) {
10330:                         $attrib_regexp =~ s/\:/|/g;
10331:                     }
10332:                     if ($content =~ m{($attrib_regexp\s*=\s*['"]?)\Q$ref\E(['"]?)}) {
10333:                         my $numchg = ($content =~ s{($attrib_regexp\s*=\s*['"]?)\Q$ref\E(['"]?)}{$1$newname$2}gi);
10334:                         $count += $numchg;
10335:                     }
10336:                     if ($env{'form.embedded_codebase_'.$i} ne '') {
10337:                         $codebase = &unescape($env{'form.embedded_codebase_'.$i});
10338:                         my $numchg = ($content =~ s/(codebase\s*=\s*["']?)\Q$codebase\E(["']?)/$1.$2/i); #' stupid emacs
10339:                         $codebasecount ++;
10340:                     }
10341:                 }
10342:             }
10343:             if ($count || $codebasecount) {
10344:                 my $saveresult;
10345:                 if (($context eq 'portfolio') || ($context eq 'coursedoc') || 
10346:                     ($context eq 'manage_dependencies')) {
10347:                     my $url = &Apache::lonnet::store_edited_file($container,$content,$udom,$uname,\$saveresult);
10348:                     if ($url eq $container) {
10349:                         my ($fname) = ($container =~ m{/([^/]+)$});
10350:                         $output = '<p>'.&mt('Updated [quant,_1,reference] in [_2].',
10351:                                             $count,'<span class="LC_filename">'.
10352:                                             $fname.'</span>').'</p>';
10353:                     } else {
10354:                          $output = '<p class="LC_error">'.
10355:                                    &mt('Error: update failed for: [_1].',
10356:                                    '<span class="LC_filename">'.
10357:                                    $container.'</span>').'</p>';
10358:                     }
10359:                 } else {
10360:                     if (open(my $fh,">$container")) {
10361:                         print $fh $content;
10362:                         close($fh);
10363:                         $output = '<p>'.&mt('Updated [quant,_1,reference] in [_2].',
10364:                                   $count,'<span class="LC_filename">'.
10365:                                   $container.'</span>').'</p>';
10366:                     } else {
10367:                          $output = '<p class="LC_error">'.
10368:                                    &mt('Error: could not update [_1].',
10369:                                    '<span class="LC_filename">'.
10370:                                    $container.'</span>').'</p>';
10371:                     }
10372:                 }
10373:             }
10374:         } else {
10375:             &logthis('Failed to parse '.$container.
10376:                      ' to modify references: '.$parse_result);
10377:         }
10378:     }
10379:     if (wantarray) {
10380:         return ($output,$count,$codebasecount);
10381:     } else {
10382:         return $output;
10383:     }
10384: }
10385: 
10386: sub check_for_existing {
10387:     my ($path,$fname,$element) = @_;
10388:     my ($state,$msg);
10389:     if (-d $path.'/'.$fname) {
10390:         $state = 'exists';
10391:         $msg = &mt('Unable to upload [_1]. A directory by that name was found in [_2].','<span class="LC_filename">'.$fname.'</span>',$path);
10392:     } elsif (-e $path.'/'.$fname) {
10393:         $state = 'exists';
10394:         $msg = &mt('Unable to upload [_1]. A file by that name was found in [_2].','<span class="LC_filename">'.$fname.'</span>',$path);
10395:     }
10396:     if ($state eq 'exists') {
10397:         $msg = '<span class="LC_error">'.$msg.'</span><br />';
10398:     }
10399:     return ($state,$msg);
10400: }
10401: 
10402: sub check_for_upload {
10403:     my ($path,$fname,$group,$element,$portfolio_root,$port_path,
10404:         $disk_quota,$current_disk_usage,$uname,$udom) = @_;
10405:     my $filesize = length($env{'form.'.$element});
10406:     if (!$filesize) {
10407:         my $msg = '<span class="LC_error">'.
10408:                   &mt('Unable to upload [_1]. (size = [_2] bytes)', 
10409:                       '<span class="LC_filename">'.$fname.'</span>',
10410:                       $filesize).'<br />'.
10411:                   &mt('Either the file you attempted to upload was empty, or your web browser was unable to read its contents.').'<br />'.
10412:                   '</span>';
10413:         return ('zero_bytes',$msg);
10414:     }
10415:     $filesize =  $filesize/1000; #express in k (1024?)
10416:     my $getpropath = 1;
10417:     my ($dirlistref,$listerror) =
10418:          &Apache::lonnet::dirlist($portfolio_root.$path,$udom,$uname,$getpropath);
10419:     my $found_file = 0;
10420:     my $locked_file = 0;
10421:     my @lockers;
10422:     my $navmap;
10423:     if ($env{'request.course.id'}) {
10424:         $navmap = Apache::lonnavmaps::navmap->new();
10425:     }
10426:     if (ref($dirlistref) eq 'ARRAY') {
10427:         foreach my $line (@{$dirlistref}) {
10428:             my ($file_name,$rest)=split(/\&/,$line,2);
10429:             if ($file_name eq $fname){
10430:                 $file_name = $path.$file_name;
10431:                 if ($group ne '') {
10432:                     $file_name = $group.$file_name;
10433:                 }
10434:                 $found_file = 1;
10435:                 if (&Apache::lonnet::is_locked($file_name,$udom,$uname,\@lockers) eq 'true') {
10436:                     foreach my $lock (@lockers) {
10437:                         if (ref($lock) eq 'ARRAY') {
10438:                             my ($symb,$crsid) = @{$lock};
10439:                             if ($crsid eq $env{'request.course.id'}) {
10440:                                 if (ref($navmap)) {
10441:                                     my $res = $navmap->getBySymb($symb);
10442:                                     foreach my $part (@{$res->parts()}) { 
10443:                                         my ($slot_status,$slot_time,$slot_name)=$res->check_for_slot($part);
10444:                                         unless (($slot_status == $res->RESERVED) ||
10445:                                                 ($slot_status == $res->RESERVED_LOCATION)) {
10446:                                             $locked_file = 1;
10447:                                         }
10448:                                     }
10449:                                 } else {
10450:                                     $locked_file = 1;
10451:                                 }
10452:                             } else {
10453:                                 $locked_file = 1;
10454:                             }
10455:                         }
10456:                    }
10457:                 } else {
10458:                     my @info = split(/\&/,$rest);
10459:                     my $currsize = $info[6]/1000;
10460:                     if ($currsize < $filesize) {
10461:                         my $extra = $filesize - $currsize;
10462:                         if (($current_disk_usage + $extra) > $disk_quota) {
10463:                             my $msg = '<span class="LC_error">'.
10464:                                       &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.',
10465:                                           '<span class="LC_filename">'.$fname.'</span>',$filesize,$currsize).'</span>'.
10466:                                       '<br />'.&mt('Disk quota is [_1] kilobytes. Your current disk usage is [_2] kilobytes.',
10467:                                                    $disk_quota,$current_disk_usage);
10468:                             return ('will_exceed_quota',$msg);
10469:                         }
10470:                     }
10471:                 }
10472:             }
10473:         }
10474:     }
10475:     if (($current_disk_usage + $filesize) > $disk_quota){
10476:         my $msg = '<span class="LC_error">'.
10477:                 &mt('Unable to upload [_1]. (size = [_2] kilobytes). Disk quota will be exceeded.','<span class="LC_filename">'.$fname.'</span>',$filesize).'</span>'.
10478:                   '<br />'.&mt('Disk quota is [_1] kilobytes. Your current disk usage is [_2] kilobytes.',$disk_quota,$current_disk_usage);
10479:         return ('will_exceed_quota',$msg);
10480:     } elsif ($found_file) {
10481:         if ($locked_file) {
10482:             my $msg = '<span class="LC_error">';
10483:             $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>');
10484:             $msg .= '</span><br />';
10485:             $msg .= &mt('You will be able to rename or delete existing [_1] after a grade has been assigned.','<span class="LC_filename">'.$fname.'</span>');
10486:             return ('file_locked',$msg);
10487:         } else {
10488:             my $msg = '<span class="LC_error">';
10489:             $msg .= &mt(' A file by that name: [_1] was found in [_2].','<span class="LC_filename">'.$fname.'</span>',$port_path.$env{'form.currentpath'});
10490:             $msg .= '</span>';
10491:             return ('existingfile',$msg);
10492:         }
10493:     }
10494: }
10495: 
10496: sub check_for_traversal {
10497:     my ($path,$url,$toplevel) = @_;
10498:     my @parts=split(/\//,$path);
10499:     my $cleanpath;
10500:     my $fullpath = $url;
10501:     for (my $i=0;$i<@parts;$i++) {
10502:         next if ($parts[$i] eq '.');
10503:         if ($parts[$i] eq '..') {
10504:             $fullpath =~ s{([^/]+/)$}{};
10505:         } else {
10506:             $fullpath .= $parts[$i].'/';
10507:         }
10508:     }
10509:     if ($fullpath =~ /^\Q$url\E(.*)$/) {
10510:         $cleanpath = $1;
10511:     } elsif ($fullpath =~ /^\Q$toplevel\E(.*)$/) {
10512:         my $curr_toprel = $1;
10513:         my @parts = split(/\//,$curr_toprel);
10514:         my ($url_toprel) = ($url =~ /^\Q$toplevel\E(.*)$/);
10515:         my @urlparts = split(/\//,$url_toprel);
10516:         my $doubledots;
10517:         my $startdiff = -1;
10518:         for (my $i=0; $i<@urlparts; $i++) {
10519:             if ($startdiff == -1) {
10520:                 unless ($urlparts[$i] eq $parts[$i]) {
10521:                     $startdiff = $i;
10522:                     $doubledots .= '../';
10523:                 }
10524:             } else {
10525:                 $doubledots .= '../';
10526:             }
10527:         }
10528:         if ($startdiff > -1) {
10529:             $cleanpath = $doubledots;
10530:             for (my $i=$startdiff; $i<@parts; $i++) {
10531:                 $cleanpath .= $parts[$i].'/';
10532:             }
10533:         }
10534:     }
10535:     $cleanpath =~ s{(/)$}{};
10536:     return $cleanpath;
10537: }
10538: 
10539: sub is_archive_file {
10540:     my ($mimetype) = @_;
10541:     if (($mimetype eq 'application/octet-stream') ||
10542:         ($mimetype eq 'application/x-stuffit') ||
10543:         ($mimetype =~ m{^application/(x\-)?(compressed|tar|zip|tgz|gz|gtar|gzip|gunzip|bz|bz2|bzip2)})) {
10544:         return 1;
10545:     }
10546:     return;
10547: }
10548: 
10549: sub decompress_form {
10550:     my ($mimetype,$archiveurl,$action,$noextract,$hiddenelements,$dirlist) = @_;
10551:     my %lt = &Apache::lonlocal::texthash (
10552:         this => 'This file is an archive file.',
10553:         camt => 'This file is a Camtasia archive file.',
10554:         itsc => 'Its contents are as follows:',
10555:         youm => 'You may wish to extract its contents.',
10556:         extr => 'Extract contents',
10557:         auto => 'LON-CAPA can process the files automatically, or you can decide how each should be handled.',
10558:         proa => 'Process automatically?',
10559:         yes  => 'Yes',
10560:         no   => 'No',
10561:         fold => 'Title for folder containing movie',
10562:         movi => 'Title for page containing embedded movie', 
10563:     );
10564:     my $fileloc = &Apache::lonnet::filelocation(undef,$archiveurl);
10565:     my ($is_camtasia,$topdir,%toplevel,@paths);
10566:     my $info = &list_archive_contents($fileloc,\@paths);
10567:     if (@paths) {
10568:         foreach my $path (@paths) {
10569:             $path =~ s{^/}{};
10570:             if ($path =~ m{^([^/]+)/$}) {
10571:                 $topdir = $1;
10572:             }
10573:             if ($path =~ m{^([^/]+)/}) {
10574:                 $toplevel{$1} = $path;
10575:             } else {
10576:                 $toplevel{$path} = $path;
10577:             }
10578:         }
10579:     }
10580:     if ($mimetype =~ m{^application/(x\-)?(compressed|zip)}) {
10581:         my @camtasia = ("$topdir/","$topdir/index.html",
10582:                         "$topdir/media/",
10583:                         "$topdir/media/$topdir.mp4",
10584:                         "$topdir/media/FirstFrame.png",
10585:                         "$topdir/media/player.swf",
10586:                         "$topdir/media/swfobject.js",
10587:                         "$topdir/media/expressInstall.swf");
10588:         my @diffs = &compare_arrays(\@paths,\@camtasia);
10589:         if (@diffs == 0) {
10590:             $is_camtasia = 1;
10591:         }
10592:     }
10593:     my $output;
10594:     if ($is_camtasia) {
10595:         $output = <<"ENDCAM";
10596: <script type="text/javascript" language="Javascript">
10597: // <![CDATA[
10598: 
10599: function camtasiaToggle() {
10600:     for (var i=0; i<document.uploaded_decompress.autoextract_camtasia.length; i++) {
10601:         if (document.uploaded_decompress.autoextract_camtasia[i].checked) {
10602:             if (document.uploaded_decompress.autoextract_camtasia[i].value == 1) {
10603: 
10604:                 document.getElementById('camtasia_titles').style.display='block';
10605:             } else {
10606:                 document.getElementById('camtasia_titles').style.display='none';
10607:             }
10608:         }
10609:     }
10610:     return;
10611: }
10612: 
10613: // ]]>
10614: </script>
10615: <p>$lt{'camt'}</p>
10616: ENDCAM
10617:     } else {
10618:         $output = '<p>'.$lt{'this'};
10619:         if ($info eq '') {
10620:             $output .= ' '.$lt{'youm'}.'</p>'."\n";
10621:         } else {
10622:             $output .= ' '.$lt{'itsc'}.'</p>'."\n".
10623:                        '<div><pre>'.$info.'</pre></div>';
10624:         }
10625:     }
10626:     $output .= '<form name="uploaded_decompress" action="'.$action.'" method="post">'."\n";
10627:     my $duplicates;
10628:     my $num = 0;
10629:     if (ref($dirlist) eq 'ARRAY') {
10630:         foreach my $item (@{$dirlist}) {
10631:             if (ref($item) eq 'ARRAY') {
10632:                 if (exists($toplevel{$item->[0]})) {
10633:                     $duplicates .= 
10634:                         &start_data_table_row().
10635:                         '<td><label><input type="radio" name="archive_overwrite_'.$num.'" '.
10636:                         'value="0" checked="checked" />'.&mt('No').'</label>'.
10637:                         '&nbsp;<label><input type="radio" name="archive_overwrite_'.$num.'" '.
10638:                         'value="1" />'.&mt('Yes').'</label>'.
10639:                         '<input type="hidden" name="archive_overwrite_name_'.$num.'" value="'.$item->[0].'" /></td>'."\n".
10640:                         '<td>'.$item->[0].'</td>';
10641:                     if ($item->[2]) {
10642:                         $duplicates .= '<td>'.&mt('Directory').'</td>';
10643:                     } else {
10644:                         $duplicates .= '<td>'.&mt('File').'</td>';
10645:                     }
10646:                     $duplicates .= '<td>'.$item->[3].'</td>'.
10647:                                    '<td>'.
10648:                                    &Apache::lonlocal::locallocaltime($item->[4]).
10649:                                    '</td>'.
10650:                                    &end_data_table_row();
10651:                     $num ++;
10652:                 }
10653:             }
10654:         }
10655:     }
10656:     my $itemcount;
10657:     if (@paths > 0) {
10658:         $itemcount = scalar(@paths);
10659:     } else {
10660:         $itemcount = 1;
10661:     }
10662:     if ($is_camtasia) {
10663:         $output .= $lt{'auto'}.'<br />'.
10664:                    '<span class="LC_nobreak">'.$lt{'proa'}.'<label>'.
10665:                    '<input type="radio" name="autoextract_camtasia" value="1" onclick="javascript:camtasiaToggle();" checked="checked" />'.
10666:                    $lt{'yes'}.'</label>&nbsp;<label>'.
10667:                    '<input type="radio" name="autoextract_camtasia" value="0" onclick="javascript:camtasiaToggle();" />'.
10668:                    $lt{'no'}.'</label></span><br />'.
10669:                    '<div id="camtasia_titles" style="display:block">'.
10670:                    &Apache::lonhtmlcommon::start_pick_box().
10671:                    &Apache::lonhtmlcommon::row_title($lt{'fold'}).
10672:                    '<input type="textbox" name="camtasia_foldername" value="'.$env{'form.comment'}.'" />'."\n".
10673:                    &Apache::lonhtmlcommon::row_closure().
10674:                    &Apache::lonhtmlcommon::row_title($lt{'movi'}).
10675:                    '<input type="textbox" name="camtasia_moviename" value="" />'."\n".
10676:                    &Apache::lonhtmlcommon::row_closure(1).
10677:                    &Apache::lonhtmlcommon::end_pick_box().
10678:                    '</div>';
10679:     }
10680:     $output .= 
10681:         '<input type="hidden" name="archive_overwrite_total" value="'.$num.'" />'.
10682:         '<input type="hidden" name="archive_itemcount" value="'.$itemcount.'" />'.
10683:         "\n";
10684:     if ($duplicates ne '') {
10685:         $output .= '<p><span class="LC_warning">'.
10686:                    &mt('Warning: decompression of the archive will overwrite the following items which already exist:').'</span><br />'.  
10687:                    &start_data_table().
10688:                    &start_data_table_header_row().
10689:                    '<th>'.&mt('Overwrite?').'</th>'.
10690:                    '<th>'.&mt('Name').'</th>'.
10691:                    '<th>'.&mt('Type').'</th>'.
10692:                    '<th>'.&mt('Size').'</th>'.
10693:                    '<th>'.&mt('Last modified').'</th>'.
10694:                    &end_data_table_header_row().
10695:                    $duplicates.
10696:                    &end_data_table().
10697:                    '</p>';
10698:     }
10699:     $output .= '<input type="hidden" name="archiveurl" value="'.$archiveurl.'" />'."\n";
10700:     if (ref($hiddenelements) eq 'HASH') {
10701:         foreach my $hidden (sort(keys(%{$hiddenelements}))) {
10702:             $output .= '<input type="hidden" name="'.$hidden.'" value="'.$hiddenelements->{$hidden}.'" />'."\n";
10703:         }
10704:     }
10705:     $output .= <<"END";
10706: <br />
10707: <input type="submit" name="decompress" value="$lt{'extr'}" />
10708: </form>
10709: $noextract
10710: END
10711:     return $output;
10712: }
10713: 
10714: sub decompression_utility {
10715:     my ($program) = @_;
10716:     my @utilities = ('tar','gunzip','bunzip2','unzip'); 
10717:     my $location;
10718:     if (grep(/^\Q$program\E$/,@utilities)) { 
10719:         foreach my $dir ('/bin/','/usr/bin/','/usr/local/bin/','/sbin/',
10720:                          '/usr/sbin/') {
10721:             if (-x $dir.$program) {
10722:                 $location = $dir.$program;
10723:                 last;
10724:             }
10725:         }
10726:     }
10727:     return $location;
10728: }
10729: 
10730: sub list_archive_contents {
10731:     my ($file,$pathsref) = @_;
10732:     my (@cmd,$output);
10733:     my $needsregexp;
10734:     if ($file =~ /\.zip$/) {
10735:         @cmd = (&decompression_utility('unzip'),"-l");
10736:         $needsregexp = 1;
10737:     } elsif (($file =~ m/\.tar\.gz$/) ||
10738:              ($file =~ /\.tgz$/)) {
10739:         @cmd = (&decompression_utility('tar'),"-ztf");
10740:     } elsif ($file =~ /\.tar\.bz2$/) {
10741:         @cmd = (&decompression_utility('tar'),"-jtf");
10742:     } elsif ($file =~ m|\.tar$|) {
10743:         @cmd = (&decompression_utility('tar'),"-tf");
10744:     }
10745:     if (@cmd) {
10746:         undef($!);
10747:         undef($@);
10748:         if (open(my $fh,"-|", @cmd, $file)) {
10749:             while (my $line = <$fh>) {
10750:                 $output .= $line;
10751:                 chomp($line);
10752:                 my $item;
10753:                 if ($needsregexp) {
10754:                     ($item) = ($line =~ /^\s*\d+\s+[\d\-]+\s+[\d:]+\s*(.+)$/); 
10755:                 } else {
10756:                     $item = $line;
10757:                 }
10758:                 if ($item ne '') {
10759:                     unless (grep(/^\Q$item\E$/,@{$pathsref})) {
10760:                         push(@{$pathsref},$item);
10761:                     } 
10762:                 }
10763:             }
10764:             close($fh);
10765:         }
10766:     }
10767:     return $output;
10768: }
10769: 
10770: sub decompress_uploaded_file {
10771:     my ($file,$dir) = @_;
10772:     &Apache::lonnet::appenv({'cgi.file' => $file});
10773:     &Apache::lonnet::appenv({'cgi.dir' => $dir});
10774:     my $result = &Apache::lonnet::ssi_body('/cgi-bin/decompress.pl');
10775:     my ($handle) = ($env{'user.environment'} =~m{/([^/]+)\.id$});
10776:     my $lonidsdir = $Apache::lonnet::perlvar{'lonIDsDir'};
10777:     &Apache::lonnet::transfer_profile_to_env($lonidsdir,$handle,1);
10778:     my $decompressed = $env{'cgi.decompressed'};
10779:     &Apache::lonnet::delenv('cgi.file');
10780:     &Apache::lonnet::delenv('cgi.dir');
10781:     &Apache::lonnet::delenv('cgi.decompressed');
10782:     return ($decompressed,$result);
10783: }
10784: 
10785: sub process_decompression {
10786:     my ($docudom,$docuname,$file,$destination,$dir_root,$hiddenelem) = @_;
10787:     my ($dir,$error,$warning,$output);
10788:     if ($file !~ /\.(zip|tar|bz2|gz|tar.gz|tar.bz2|tgz)$/) {
10789:         $error = &mt('File name not a supported archive file type.').
10790:                  '<br />'.&mt('File name should end with one of: [_1].',
10791:                               '.zip, .tar, .bz2, .gz, .tar.gz, .tar.bz2, .tgz');
10792:     } else {
10793:         my $docuhome = &Apache::lonnet::homeserver($docuname,$docudom);
10794:         if ($docuhome eq 'no_host') {
10795:             $error = &mt('Could not determine home server for course.');
10796:         } else {
10797:             my @ids=&Apache::lonnet::current_machine_ids();
10798:             my $currdir = "$dir_root/$destination";
10799:             if (grep(/^\Q$docuhome\E$/,@ids)) {
10800:                 $dir = &LONCAPA::propath($docudom,$docuname).
10801:                        "$dir_root/$destination";
10802:             } else {
10803:                 $dir = $Apache::lonnet::perlvar{'lonDocRoot'}.
10804:                        "$dir_root/$docudom/$docuname/$destination";
10805:                 unless (&Apache::lonnet::repcopy_userfile("$dir/$file") eq 'ok') {
10806:                     $error = &mt('Archive file not found.');
10807:                 }
10808:             }
10809:             my (@to_overwrite,@to_skip);
10810:             if ($env{'form.archive_overwrite_total'} > 0) {
10811:                 my $total = $env{'form.archive_overwrite_total'};
10812:                 for (my $i=0; $i<$total; $i++) {
10813:                     if ($env{'form.archive_overwrite_'.$i} == 1) {
10814:                         push(@to_overwrite,$env{'form.archive_overwrite_name_'.$i});
10815:                     } elsif ($env{'form.archive_overwrite_'.$i} == 0) {
10816:                         push(@to_skip,$env{'form.archive_overwrite_name_'.$i});
10817:                     }
10818:                 }
10819:             }
10820:             my $numskip = scalar(@to_skip);
10821:             if (($numskip > 0) && 
10822:                 ($numskip == $env{'form.archive_itemcount'})) {
10823:                 $warning = &mt('All items in the archive file already exist, and no overwriting of existing files has been requested.');         
10824:             } elsif ($dir eq '') {
10825:                 $error = &mt('Directory containing archive file unavailable.');
10826:             } elsif (!$error) {
10827:                 my ($decompressed,$display);
10828:                 if ($numskip > 0) {
10829:                     my $tempdir = time.'_'.$$.int(rand(10000));
10830:                     mkdir("$dir/$tempdir",0755);
10831:                     system("mv $dir/$file $dir/$tempdir/$file");
10832:                     ($decompressed,$display) = 
10833:                         &decompress_uploaded_file($file,"$dir/$tempdir");
10834:                     foreach my $item (@to_skip) {
10835:                         if (($item ne '') && ($item !~ /\.\./)) {
10836:                             if (-f "$dir/$tempdir/$item") { 
10837:                                 unlink("$dir/$tempdir/$item");
10838:                             } elsif (-d "$dir/$tempdir/$item") {
10839:                                 system("rm -rf $dir/$tempdir/$item");
10840:                             }
10841:                         }
10842:                     }
10843:                     system("mv $dir/$tempdir/* $dir");
10844:                     rmdir("$dir/$tempdir");   
10845:                 } else {
10846:                     ($decompressed,$display) = 
10847:                         &decompress_uploaded_file($file,$dir);
10848:                 }
10849:                 if ($decompressed eq 'ok') {
10850:                     $output = '<p class="LC_info">'.
10851:                               &mt('Files extracted successfully from archive.').
10852:                               '</p>'."\n";
10853:                     my ($warning,$result,@contents);
10854:                     my ($newdirlistref,$newlisterror) =
10855:                         &Apache::lonnet::dirlist($currdir,$docudom,
10856:                                                  $docuname,1);
10857:                     my (%is_dir,%changes,@newitems);
10858:                     my $dirptr = 16384;
10859:                     if (ref($newdirlistref) eq 'ARRAY') {
10860:                         foreach my $dir_line (@{$newdirlistref}) {
10861:                             my ($item,undef,undef,$testdir)=split(/\&/,$dir_line,5);
10862:                             unless (($item =~ /^\.+$/) || ($item eq $file) || 
10863:                                     ((@to_skip > 0) && (grep(/^\Q$item\E$/,@to_skip)))) {
10864:                                 push(@newitems,$item);
10865:                                 if ($dirptr&$testdir) {
10866:                                     $is_dir{$item} = 1;
10867:                                 }
10868:                                 $changes{$item} = 1;
10869:                             }
10870:                         }
10871:                     }
10872:                     if (keys(%changes) > 0) {
10873:                         foreach my $item (sort(@newitems)) {
10874:                             if ($changes{$item}) {
10875:                                 push(@contents,$item);
10876:                             }
10877:                         }
10878:                     }
10879:                     if (@contents > 0) {
10880:                         my $wantform;
10881:                         unless ($env{'form.autoextract_camtasia'}) {
10882:                             $wantform = 1;
10883:                         }
10884:                         my (%children,%parent,%dirorder,%titles);
10885:                         my ($count,$datatable) = &get_extracted($docudom,$docuname,
10886:                                                                 $currdir,\%is_dir,
10887:                                                                 \%children,\%parent,
10888:                                                                 \@contents,\%dirorder,
10889:                                                                 \%titles,$wantform);
10890:                         if ($datatable ne '') {
10891:                             $output .= &archive_options_form('decompressed',$datatable,
10892:                                                              $count,$hiddenelem);
10893:                             my $startcount = 6;
10894:                             $output .= &archive_javascript($startcount,$count,
10895:                                                            \%titles,\%children);
10896:                         }
10897:                         if ($env{'form.autoextract_camtasia'}) {
10898:                             my %displayed;
10899:                             my $total = 1;
10900:                             $env{'form.archive_directory'} = [];
10901:                             foreach my $i (sort { $a <=> $b } keys(%dirorder)) {
10902:                                 my $path = join('/',map { $titles{$_}; } @{$dirorder{$i}});
10903:                                 $path =~ s{/$}{};
10904:                                 my $item;
10905:                                 if ($path ne '') {
10906:                                     $item = "$path/$titles{$i}";
10907:                                 } else {
10908:                                     $item = $titles{$i};
10909:                                 }
10910:                                 $env{'form.archive_content_'.$i} = "$dir_root/$destination/$item";
10911:                                 if ($item eq $contents[0]) {
10912:                                     push(@{$env{'form.archive_directory'}},$i);
10913:                                     $env{'form.archive_'.$i} = 'display';
10914:                                     $env{'form.archive_title_'.$i} = $env{'form.camtasia_foldername'};
10915:                                     $displayed{'folder'} = $i;
10916:                                 } elsif ($item eq "$contents[0]/index.html") {
10917:                                     $env{'form.archive_'.$i} = 'display';
10918:                                     $env{'form.archive_title_'.$i} = $env{'form.camtasia_moviename'};
10919:                                     $displayed{'web'} = $i;
10920:                                 } else {
10921:                                     if ($item eq "$contents[0]/media") {
10922:                                         push(@{$env{'form.archive_directory'}},$i);
10923:                                     }
10924:                                     $env{'form.archive_'.$i} = 'dependency';
10925:                                 }
10926:                                 $total ++;
10927:                             }
10928:                             for (my $i=1; $i<$total; $i++) {
10929:                                 next if ($i == $displayed{'web'});
10930:                                 next if ($i == $displayed{'folder'});
10931:                                 $env{'form.archive_dependent_on_'.$i} = $displayed{'web'};
10932:                             }
10933:                             $env{'form.phase'} = 'decompress_cleanup';
10934:                             $env{'form.archivedelete'} = 1;
10935:                             $env{'form.archive_count'} = $total-1;
10936:                             $output .=
10937:                                 &process_extracted_files('coursedocs',$docudom,
10938:                                                          $docuname,$destination,
10939:                                                          $dir_root,$hiddenelem);
10940:                         }
10941:                     } else {
10942:                         $warning = &mt('No new items extracted from archive file.');
10943:                     }
10944:                 } else {
10945:                     $output = $display;
10946:                     $error = &mt('An error occurred during extraction from the archive file.');
10947:                 }
10948:             }
10949:         }
10950:     }
10951:     if ($error) {
10952:         $output .= '<p class="LC_error">'.&mt('Not extracted.').'<br />'.
10953:                    $error.'</p>'."\n";
10954:     }
10955:     if ($warning) {
10956:         $output .= '<p class="LC_warning">'.$warning.'</p>'."\n";
10957:     }
10958:     return $output;
10959: }
10960: 
10961: sub get_extracted {
10962:     my ($docudom,$docuname,$currdir,$is_dir,$children,$parent,$contents,$dirorder,
10963:         $titles,$wantform) = @_;
10964:     my $count = 0;
10965:     my $depth = 0;
10966:     my $datatable;
10967:     my @hierarchy;
10968:     return unless ((ref($is_dir) eq 'HASH') && (ref($children) eq 'HASH') &&
10969:                    (ref($parent) eq 'HASH') && (ref($contents) eq 'ARRAY') &&
10970:                    (ref($dirorder) eq 'HASH') && (ref($titles) eq 'HASH'));
10971:     foreach my $item (@{$contents}) {
10972:         $count ++;
10973:         @{$dirorder->{$count}} = @hierarchy;
10974:         $titles->{$count} = $item;
10975:         &archive_hierarchy($depth,$count,$parent,$children);
10976:         if ($wantform) {
10977:             $datatable .= &archive_row($is_dir->{$item},$item,
10978:                                        $currdir,$depth,$count);
10979:         }
10980:         if ($is_dir->{$item}) {
10981:             $depth ++;
10982:             push(@hierarchy,$count);
10983:             $parent->{$depth} = $count;
10984:             $datatable .=
10985:                 &recurse_extracted_archive("$currdir/$item",$docudom,$docuname,
10986:                                            \$depth,\$count,\@hierarchy,$dirorder,
10987:                                            $children,$parent,$titles,$wantform);
10988:             $depth --;
10989:             pop(@hierarchy);
10990:         }
10991:     }
10992:     return ($count,$datatable);
10993: }
10994: 
10995: sub recurse_extracted_archive {
10996:     my ($currdir,$docudom,$docuname,$depth,$count,$hierarchy,$dirorder,
10997:         $children,$parent,$titles,$wantform) = @_;
10998:     my $result='';
10999:     unless ((ref($depth)) && (ref($count)) && (ref($hierarchy) eq 'ARRAY') &&
11000:             (ref($children) eq 'HASH') && (ref($parent) eq 'HASH') &&
11001:             (ref($dirorder) eq 'HASH')) {
11002:         return $result;
11003:     }
11004:     my $dirptr = 16384;
11005:     my ($newdirlistref,$newlisterror) =
11006:         &Apache::lonnet::dirlist($currdir,$docudom,$docuname,1);
11007:     if (ref($newdirlistref) eq 'ARRAY') {
11008:         foreach my $dir_line (@{$newdirlistref}) {
11009:             my ($item,undef,undef,$testdir)=split(/\&/,$dir_line,5);
11010:             unless ($item =~ /^\.+$/) {
11011:                 $$count ++;
11012:                 @{$dirorder->{$$count}} = @{$hierarchy};
11013:                 $titles->{$$count} = $item;
11014:                 &archive_hierarchy($$depth,$$count,$parent,$children);
11015: 
11016:                 my $is_dir;
11017:                 if ($dirptr&$testdir) {
11018:                     $is_dir = 1;
11019:                 }
11020:                 if ($wantform) {
11021:                     $result .= &archive_row($is_dir,$item,$currdir,$$depth,$$count);
11022:                 }
11023:                 if ($is_dir) {
11024:                     $$depth ++;
11025:                     push(@{$hierarchy},$$count);
11026:                     $parent->{$$depth} = $$count;
11027:                     $result .=
11028:                         &recurse_extracted_archive("$currdir/$item",$docudom,
11029:                                                    $docuname,$depth,$count,
11030:                                                    $hierarchy,$dirorder,$children,
11031:                                                    $parent,$titles,$wantform);
11032:                     $$depth --;
11033:                     pop(@{$hierarchy});
11034:                 }
11035:             }
11036:         }
11037:     }
11038:     return $result;
11039: }
11040: 
11041: sub archive_hierarchy {
11042:     my ($depth,$count,$parent,$children) =@_;
11043:     if ((ref($parent) eq 'HASH') && (ref($children) eq 'HASH')) {
11044:         if (exists($parent->{$depth})) {
11045:              $children->{$parent->{$depth}} .= $count.':';
11046:         }
11047:     }
11048:     return;
11049: }
11050: 
11051: sub archive_row {
11052:     my ($is_dir,$item,$currdir,$depth,$count) = @_;
11053:     my ($name) = ($item =~ m{([^/]+)$});
11054:     my %choices = &Apache::lonlocal::texthash (
11055:                                        'display'    => 'Add as file',
11056:                                        'dependency' => 'Include as dependency',
11057:                                        'discard'    => 'Discard',
11058:                                       );
11059:     if ($is_dir) {
11060:         $choices{'display'} = &mt('Add as folder'); 
11061:     }
11062:     my $output = &start_data_table_row().'<td align="right">'.$count.'</td>'."\n";
11063:     my $offset = 0;
11064:     foreach my $action ('display','dependency','discard') {
11065:         $offset ++;
11066:         if ($action ne 'display') {
11067:             $offset ++;
11068:         }  
11069:         $output .= '<td><span class="LC_nobreak">'.
11070:                    '<label><input type="radio" name="archive_'.$count.
11071:                    '" id="archive_'.$action.'_'.$count.'" value="'.$action.'"';
11072:         my $text = $choices{$action};
11073:         if ($is_dir) {
11074:             $output .= ' onclick="javascript:propagateCheck(this.form,'."'$count'".');"';
11075:             if ($action eq 'display') {
11076:                 $text = &mt('Add as folder');
11077:             }
11078:         } else {
11079:             $output .= ' onclick="javascript:dependencyCheck(this.form,'."$count,$offset".');"';
11080: 
11081:         }
11082:         $output .= ' />&nbsp;'.$choices{$action}.'</label></span>';
11083:         if ($action eq 'dependency') {
11084:             $output .= '<div id="arc_depon_'.$count.'" style="display:none;">'."\n".
11085:                        &mt('Used by:').'&nbsp;<select name="archive_dependent_on_'.$count.'" '.
11086:                        'onchange="propagateSelect(this.form,'."$count,$offset".')">'."\n".
11087:                        '<option value=""></option>'."\n".
11088:                        '</select>'."\n".
11089:                        '</div>';
11090:         } elsif ($action eq 'display') {
11091:             $output .= '<div id="arc_title_'.$count.'" style="display:none;">'."\n".
11092:                        &mt('Title:').'&nbsp;<input type="text" name="archive_title_'.$count.'" id="archive_title_'.$count.'" />'."\n".
11093:                        '</div>';
11094:         }
11095:         $output .= '</td>';
11096:     }
11097:     $output .= '<td><input type="hidden" name="archive_content_'.$count.'" value="'.
11098:                &HTML::Entities::encode("$currdir/$item",'"<>&').'" />'.('&nbsp;' x 2);
11099:     for (my $i=0; $i<$depth; $i++) {
11100:         $output .= ('<img src="/adm/lonIcons/whitespace1.gif" class="LC_docs_spacer" alt="" />' x2)."\n";
11101:     }
11102:     if ($is_dir) {
11103:         $output .= '<img src="/adm/lonIcons/navmap.folder.open.gif" alt="" />&nbsp;'."\n".
11104:                    '<input type="hidden" name="archive_directory" value="'.$count.'" />'."\n";
11105:     } else {
11106:         $output .= '<input type="hidden" name="archive_file" value="'.$count.'" />'."\n";
11107:     }
11108:     $output .= '&nbsp;'.$name.'</td>'."\n".
11109:                &end_data_table_row();
11110:     return $output;
11111: }
11112: 
11113: sub archive_options_form {
11114:     my ($form,$display,$count,$hiddenelem) = @_;
11115:     my %lt = &Apache::lonlocal::texthash(
11116:                perm => 'Permanently remove archive file?',
11117:                hows => 'How should each extracted item be incorporated in the course?',
11118:                cont => 'Content actions for all',
11119:                addf => 'Add as folder/file',
11120:                incd => 'Include as dependency for a displayed file',
11121:                disc => 'Discard',
11122:                no   => 'No',
11123:                yes  => 'Yes',
11124:                save => 'Save',
11125:     );
11126:     my $output = <<"END";
11127: <form name="$form" method="post" action="">
11128: <p><span class="LC_nobreak">$lt{'perm'}&nbsp;
11129: <label>
11130:   <input type="radio" name="archivedelete" value="0" checked="checked" />$lt{'no'}
11131: </label>
11132: &nbsp;
11133: <label>
11134:   <input type="radio" name="archivedelete" value="1" />$lt{'yes'}</label>
11135: </span>
11136: </p>
11137: <input type="hidden" name="phase" value="decompress_cleanup" />
11138: <br />$lt{'hows'}
11139: <div class="LC_columnSection">
11140:   <fieldset>
11141:     <legend>$lt{'cont'}</legend>
11142:     <input type="button" value="$lt{'addf'}" onclick="javascript:checkAll(document.$form,'display');" /> 
11143:     &nbsp;&nbsp;<input type="button" value="$lt{'incd'}" onclick="javascript:checkAll(document.$form,'dependency');" />
11144:     &nbsp;&nbsp;<input type="button" value="$lt{'disc'}" onclick="javascript:checkAll(document.$form,'discard');" />
11145:   </fieldset>
11146: </div>
11147: END
11148:     return $output.
11149:            &start_data_table()."\n".
11150:            $display."\n".
11151:            &end_data_table()."\n".
11152:            '<input type="hidden" name="archive_count" value="'.$count.'" />'.
11153:            $hiddenelem.
11154:            '<br /><input type="submit" name="archive_submit" value="'.$lt{'save'}.'" />'.
11155:            '</form>';
11156: }
11157: 
11158: sub archive_javascript {
11159:     my ($startcount,$numitems,$titles,$children) = @_;
11160:     return unless ((ref($titles) eq 'HASH') && (ref($children) eq 'HASH'));
11161:     my $maintitle = $env{'form.comment'};
11162:     my $scripttag = <<START;
11163: <script type="text/javascript">
11164: // <![CDATA[
11165: 
11166: function checkAll(form,prefix) {
11167:     var idstr =  new RegExp("^archive_"+prefix+"_\\\\d+\$");
11168:     for (var i=0; i < form.elements.length; i++) {
11169:         var id = form.elements[i].id;
11170:         if ((id != '') && (id != undefined)) {
11171:             if (idstr.test(id)) {
11172:                 if (form.elements[i].type == 'radio') {
11173:                     form.elements[i].checked = true;
11174:                     var nostart = i-$startcount;
11175:                     var offset = nostart%7;
11176:                     var count = (nostart-offset)/7;    
11177:                     dependencyCheck(form,count,offset);
11178:                 }
11179:             }
11180:         }
11181:     }
11182: }
11183: 
11184: function propagateCheck(form,count) {
11185:     if (count > 0) {
11186:         var startelement = $startcount + ((count-1) * 7);
11187:         for (var j=1; j<6; j++) {
11188:             if ((j != 2) && (j != 4)) {
11189:                 var item = startelement + j; 
11190:                 if (form.elements[item].type == 'radio') {
11191:                     if (form.elements[item].checked) {
11192:                         containerCheck(form,count,j);
11193:                         break;
11194:                     }
11195:                 }
11196:             }
11197:         }
11198:     }
11199: }
11200: 
11201: numitems = $numitems
11202: var titles = new Array(numitems);
11203: var parents = new Array(numitems);
11204: for (var i=0; i<numitems; i++) {
11205:     parents[i] = new Array;
11206: }
11207: var maintitle = '$maintitle';
11208: 
11209: START
11210: 
11211:     foreach my $container (sort { $a <=> $b } (keys(%{$children}))) {
11212:         my @contents = split(/:/,$children->{$container});
11213:         for (my $i=0; $i<@contents; $i ++) {
11214:             $scripttag .= 'parents['.$container.']['.$i.'] = '.$contents[$i]."\n";
11215:         }
11216:     }
11217: 
11218:     foreach my $key (sort { $a <=> $b } (keys(%{$titles}))) {
11219:         $scripttag .= "titles[$key] = '".$titles->{$key}."';\n";
11220:     }
11221: 
11222:     $scripttag .= <<END;
11223: 
11224: function containerCheck(form,count,offset) {
11225:     if (count > 0) {
11226:         dependencyCheck(form,count,offset);
11227:         var item = (offset+$startcount)+7*(count-1);
11228:         form.elements[item].checked = true;
11229:         if(Object.prototype.toString.call(parents[count]) === '[object Array]') {
11230:             if (parents[count].length > 0) {
11231:                 for (var j=0; j<parents[count].length; j++) {
11232:                     containerCheck(form,parents[count][j],offset);
11233:                 }
11234:             }
11235:         }
11236:     }
11237: }
11238: 
11239: function dependencyCheck(form,count,offset) {
11240:     if (count > 0) {
11241:         var chosen = (offset+$startcount)+7*(count-1);
11242:         var depitem = $startcount + ((count-1) * 7) + 4;
11243:         var currtype = form.elements[depitem].type;
11244:         if (form.elements[chosen].value == 'dependency') {
11245:             document.getElementById('arc_depon_'+count).style.display='block'; 
11246:             form.elements[depitem].options.length = 0;
11247:             form.elements[depitem].options[0] = new Option('Select','',true,true);
11248:             for (var i=1; i<=numitems; i++) {
11249:                 if (i == count) {
11250:                     continue;
11251:                 }
11252:                 var startelement = $startcount + (i-1) * 7;
11253:                 for (var j=1; j<6; j++) {
11254:                     if ((j != 2) && (j!= 4)) {
11255:                         var item = startelement + j;
11256:                         if (form.elements[item].type == 'radio') {
11257:                             if (form.elements[item].checked) {
11258:                                 if (form.elements[item].value == 'display') {
11259:                                     var n = form.elements[depitem].options.length;
11260:                                     form.elements[depitem].options[n] = new Option(titles[i],i,false,false);
11261:                                 }
11262:                             }
11263:                         }
11264:                     }
11265:                 }
11266:             }
11267:         } else {
11268:             document.getElementById('arc_depon_'+count).style.display='none';
11269:             form.elements[depitem].options.length = 0;
11270:             form.elements[depitem].options[0] = new Option('Select','',true,true);
11271:         }
11272:         titleCheck(form,count,offset);
11273:     }
11274: }
11275: 
11276: function propagateSelect(form,count,offset) {
11277:     if (count > 0) {
11278:         var item = (1+offset+$startcount)+7*(count-1);
11279:         var picked = form.elements[item].options[form.elements[item].selectedIndex].value; 
11280:         if (Object.prototype.toString.call(parents[count]) === '[object Array]') {
11281:             if (parents[count].length > 0) {
11282:                 for (var j=0; j<parents[count].length; j++) {
11283:                     containerSelect(form,parents[count][j],offset,picked);
11284:                 }
11285:             }
11286:         }
11287:     }
11288: }
11289: 
11290: function containerSelect(form,count,offset,picked) {
11291:     if (count > 0) {
11292:         var item = (offset+$startcount)+7*(count-1);
11293:         if (form.elements[item].type == 'radio') {
11294:             if (form.elements[item].value == 'dependency') {
11295:                 if (form.elements[item+1].type == 'select-one') {
11296:                     for (var i=0; i<form.elements[item+1].options.length; i++) {
11297:                         if (form.elements[item+1].options[i].value == picked) {
11298:                             form.elements[item+1].selectedIndex = i;
11299:                             break;
11300:                         }
11301:                     }
11302:                 }
11303:                 if (Object.prototype.toString.call(parents[count]) === '[object Array]') {
11304:                     if (parents[count].length > 0) {
11305:                         for (var j=0; j<parents[count].length; j++) {
11306:                             containerSelect(form,parents[count][j],offset,picked);
11307:                         }
11308:                     }
11309:                 }
11310:             }
11311:         }
11312:     }
11313: }
11314: 
11315: function titleCheck(form,count,offset) {
11316:     if (count > 0) {
11317:         var chosen = (offset+$startcount)+7*(count-1);
11318:         var depitem = $startcount + ((count-1) * 7) + 2;
11319:         var currtype = form.elements[depitem].type;
11320:         if (form.elements[chosen].value == 'display') {
11321:             document.getElementById('arc_title_'+count).style.display='block';
11322:             if ((count==1) && ((parents[count].length > 0) || (numitems == 1))) {
11323:                 document.getElementById('archive_title_'+count).value=maintitle;
11324:             }
11325:         } else {
11326:             document.getElementById('arc_title_'+count).style.display='none';
11327:             if (currtype == 'text') { 
11328:                 document.getElementById('archive_title_'+count).value='';
11329:             }
11330:         }
11331:     }
11332:     return;
11333: }
11334: 
11335: // ]]>
11336: </script>
11337: END
11338:     return $scripttag;
11339: }
11340: 
11341: sub process_extracted_files {
11342:     my ($context,$docudom,$docuname,$destination,$dir_root,$hiddenelem) = @_;
11343:     my $numitems = $env{'form.archive_count'};
11344:     return unless ($numitems);
11345:     my @ids=&Apache::lonnet::current_machine_ids();
11346:     my ($prefix,$pathtocheck,$dir,$ishome,$error,$warning,%toplevelitems,%is_dir,
11347:         %folders,%containers,%mapinner,%prompttofetch);
11348:     my $docuhome = &Apache::lonnet::homeserver($docuname,$docudom);
11349:     if (grep(/^\Q$docuhome\E$/,@ids)) {
11350:         $prefix = &LONCAPA::propath($docudom,$docuname);
11351:         $pathtocheck = "$dir_root/$destination";
11352:         $dir = $dir_root;
11353:         $ishome = 1;
11354:     } else {
11355:         $prefix = $Apache::lonnet::perlvar{'lonDocRoot'};
11356:         $pathtocheck = "$dir_root/$docudom/$docuname/$destination";
11357:         $dir = "$dir_root/$docudom/$docuname";    
11358:     }
11359:     my $currdir = "$dir_root/$destination";
11360:     (my $docstype,$mapinner{'0'}) = ($destination =~ m{^(docs|supplemental)/(\w+)/});
11361:     if ($env{'form.folderpath'}) {
11362:         my @items = split('&',$env{'form.folderpath'});
11363:         $folders{'0'} = $items[-2];
11364:         if ($env{'form.folderpath'} =~ /\:1$/) {
11365:             $containers{'0'}='page';
11366:         } else {  
11367:             $containers{'0'}='sequence';
11368:         }
11369:     }
11370:     my @archdirs = &get_env_multiple('form.archive_directory');
11371:     if ($numitems) {
11372:         for (my $i=1; $i<=$numitems; $i++) {
11373:             my $path = $env{'form.archive_content_'.$i};
11374:             if ($path =~ m{^\Q$pathtocheck\E/([^/]+)$}) {
11375:                 my $item = $1;
11376:                 $toplevelitems{$item} = $i;
11377:                 if (grep(/^\Q$i\E$/,@archdirs)) {
11378:                     $is_dir{$item} = 1;
11379:                 }
11380:             }
11381:         }
11382:     }
11383:     my ($output,%children,%parent,%titles,%dirorder,$result);
11384:     if (keys(%toplevelitems) > 0) {
11385:         my @contents = sort(keys(%toplevelitems));
11386:         (my $count,undef) = &get_extracted($docudom,$docuname,$currdir,\%is_dir,\%children,
11387:                                            \%parent,\@contents,\%dirorder,\%titles);
11388:     }
11389:     my (%referrer,%orphaned,%todelete,%todeletedir,%newdest,%newseqid);
11390:     if ($numitems) {
11391:         for (my $i=1; $i<=$numitems; $i++) {
11392:             next if ($env{'form.archive_'.$i} eq 'dependency');
11393:             my $path = $env{'form.archive_content_'.$i};
11394:             if ($path =~ /^\Q$pathtocheck\E/) {
11395:                 if ($env{'form.archive_'.$i} eq 'discard') {
11396:                     if ($prefix ne '' && $path ne '') {
11397:                         if (-e $prefix.$path) {
11398:                             if ((@archdirs > 0) && 
11399:                                 (grep(/^\Q$i\E$/,@archdirs))) {
11400:                                 $todeletedir{$prefix.$path} = 1;
11401:                             } else {
11402:                                 $todelete{$prefix.$path} = 1;
11403:                             }
11404:                         }
11405:                     }
11406:                 } elsif ($env{'form.archive_'.$i} eq 'display') {
11407:                     my ($docstitle,$title,$url,$outer);
11408:                     ($title) = ($path =~ m{/([^/]+)$});
11409:                     $docstitle = $env{'form.archive_title_'.$i};
11410:                     if ($docstitle eq '') {
11411:                         $docstitle = $title;
11412:                     }
11413:                     $outer = 0;
11414:                     if (ref($dirorder{$i}) eq 'ARRAY') {
11415:                         if (@{$dirorder{$i}} > 0) {
11416:                             foreach my $item (reverse(@{$dirorder{$i}})) {
11417:                                 if ($env{'form.archive_'.$item} eq 'display') {
11418:                                     $outer = $item;
11419:                                     last;
11420:                                 }
11421:                             }
11422:                         }
11423:                     }
11424:                     my ($errtext,$fatal) = 
11425:                         &LONCAPA::map::mapread('/uploaded/'.$docudom.'/'.$docuname.
11426:                                                '/'.$folders{$outer}.'.'.
11427:                                                $containers{$outer});
11428:                     next if ($fatal);
11429:                     if ((@archdirs > 0) && (grep(/^\Q$i\E$/,@archdirs))) {
11430:                         if ($context eq 'coursedocs') {
11431:                             $mapinner{$i} = time;
11432:                             $folders{$i} = 'default_'.$mapinner{$i};
11433:                             $containers{$i} = 'sequence';
11434:                             my $url = '/uploaded/'.$docudom.'/'.$docuname.'/'.
11435:                                       $folders{$i}.'.'.$containers{$i};
11436:                             my $newidx = &LONCAPA::map::getresidx();
11437:                             $LONCAPA::map::resources[$newidx]=
11438:                                 $docstitle.':'.$url.':false:normal:res';
11439:                             push(@LONCAPA::map::order,$newidx);
11440:                             my ($outtext,$errtext) =
11441:                                 &LONCAPA::map::storemap('/uploaded/'.$docudom.'/'.
11442:                                                         $docuname.'/'.$folders{$outer}.
11443:                                                         '.'.$containers{$outer},1,1);
11444:                             $newseqid{$i} = $newidx;
11445:                             unless ($errtext) {
11446:                                 $result .=  '<li>'.&mt('Folder: [_1] added to course',$docstitle).'</li>'."\n";
11447:                             }
11448:                         }
11449:                     } else {
11450:                         if ($context eq 'coursedocs') {
11451:                             my $newidx=&LONCAPA::map::getresidx();
11452:                             my $url = '/uploaded/'.$docudom.'/'.$docuname.'/'.
11453:                                       $docstype.'/'.$mapinner{$outer}.'/'.$newidx.'/'.
11454:                                       $title;
11455:                             if (!-e "$prefix$dir/$docstype/$mapinner{$outer}") {
11456:                                 mkdir("$prefix$dir/$docstype/$mapinner{$outer}",0755);
11457:                             }
11458:                             if (!-e "$prefix$dir/$docstype/$mapinner{$outer}/$newidx") {
11459:                                 mkdir("$prefix$dir/$docstype/$mapinner{$outer}/$newidx");
11460:                             }
11461:                             if (-e "$prefix$dir/$docstype/$mapinner{$outer}/$newidx") {
11462:                                 system("mv $prefix$path $prefix$dir/$docstype/$mapinner{$outer}/$newidx/$title");
11463:                                 $newdest{$i} = "$prefix$dir/$docstype/$mapinner{$outer}/$newidx";
11464:                                 unless ($ishome) {
11465:                                     my $fetch = "$newdest{$i}/$title";
11466:                                     $fetch =~ s/^\Q$prefix$dir\E//;
11467:                                     $prompttofetch{$fetch} = 1;
11468:                                 }
11469:                             }
11470:                             $LONCAPA::map::resources[$newidx]=
11471:                                 $docstitle.':'.$url.':false:normal:res';
11472:                             push(@LONCAPA::map::order, $newidx);
11473:                             my ($outtext,$errtext)=
11474:                                 &LONCAPA::map::storemap('/uploaded/'.$docudom.'/'.
11475:                                                         $docuname.'/'.$folders{$outer}.
11476:                                                         '.'.$containers{$outer},1,1);
11477:                             unless ($errtext) {
11478:                                 if (-e "$prefix$dir/$docstype/$mapinner{$outer}/$newidx/$title") {
11479:                                     $result .= '<li>'.&mt('File: [_1] added to course',$docstitle).'</li>'."\n";
11480:                                 }
11481:                             }
11482:                         }
11483:                     }
11484:                 }
11485:             } else {
11486:                 $warning .= &mt('Item extracted from archive: [_1] has unexpected path.',$path).'<br />'; 
11487:             }
11488:         }
11489:         for (my $i=1; $i<=$numitems; $i++) {
11490:             next unless ($env{'form.archive_'.$i} eq 'dependency');
11491:             my $path = $env{'form.archive_content_'.$i};
11492:             if ($path =~ /^\Q$pathtocheck\E/) {
11493:                 my ($title) = ($path =~ m{/([^/]+)$});
11494:                 $referrer{$i} = $env{'form.archive_dependent_on_'.$i};
11495:                 if ($env{'form.archive_'.$referrer{$i}} eq 'display') {
11496:                     if (ref($dirorder{$i}) eq 'ARRAY') {
11497:                         my ($itemidx,$fullpath,$relpath);
11498:                         if (ref($dirorder{$referrer{$i}}) eq 'ARRAY') {
11499:                             my $container = $dirorder{$referrer{$i}}->[-1];
11500:                             for (my $j=0; $j<@{$dirorder{$i}}; $j++) {
11501:                                 if ($dirorder{$i}->[$j] eq $container) {
11502:                                     $itemidx = $j;
11503:                                 }
11504:                             }
11505:                         }
11506:                         if ($itemidx eq '') {
11507:                             $itemidx =  0;
11508:                         } 
11509:                         if (grep(/^\Q$referrer{$i}\E$/,@archdirs)) {
11510:                             if ($mapinner{$referrer{$i}}) {
11511:                                 $fullpath = "$prefix$dir/$docstype/$mapinner{$referrer{$i}}";
11512:                                 for (my $j=$itemidx; $j<@{$dirorder{$i}}; $j++) {
11513:                                     if (grep(/^\Q$dirorder{$i}->[$j]\E$/,@archdirs)) {
11514:                                         unless (defined($newseqid{$dirorder{$i}->[$j]})) {
11515:                                             $fullpath .= '/'.$titles{$dirorder{$i}->[$j]};
11516:                                             $relpath .= '/'.$titles{$dirorder{$i}->[$j]};
11517:                                             if (!-e $fullpath) {
11518:                                                 mkdir($fullpath,0755);
11519:                                             }
11520:                                         }
11521:                                     } else {
11522:                                         last;
11523:                                     }
11524:                                 }
11525:                             }
11526:                         } elsif ($newdest{$referrer{$i}}) {
11527:                             $fullpath = $newdest{$referrer{$i}};
11528:                             for (my $j=$itemidx; $j<@{$dirorder{$i}}; $j++) {
11529:                                 if ($env{'form.archive_'.$dirorder{$i}->[$j]} eq 'discard') {
11530:                                     $orphaned{$i} = $env{'form.archive_'.$dirorder{$i}->[$j]};
11531:                                     last;
11532:                                 } elsif (grep(/^\Q$dirorder{$i}->[$j]\E$/,@archdirs)) {
11533:                                     unless (defined($newseqid{$dirorder{$i}->[$j]})) {
11534:                                         $fullpath .= '/'.$titles{$dirorder{$i}->[$j]};
11535:                                         $relpath .= '/'.$titles{$dirorder{$i}->[$j]};
11536:                                         if (!-e $fullpath) {
11537:                                             mkdir($fullpath,0755);
11538:                                         }
11539:                                     }
11540:                                 } else {
11541:                                     last;
11542:                                 }
11543:                             }
11544:                         }
11545:                         if ($fullpath ne '') {
11546:                             if (-e "$prefix$path") {
11547:                                 system("mv $prefix$path $fullpath/$title");
11548:                             }
11549:                             if (-e "$fullpath/$title") {
11550:                                 my $showpath;
11551:                                 if ($relpath ne '') {
11552:                                     $showpath = "$relpath/$title";
11553:                                 } else {
11554:                                     $showpath = "/$title";
11555:                                 } 
11556:                                 $result .= '<li>'.&mt('[_1] included as a dependency',$showpath).'</li>'."\n";
11557:                             } 
11558:                             unless ($ishome) {
11559:                                 my $fetch = "$fullpath/$title";
11560:                                 $fetch =~ s/^\Q$prefix$dir\E//; 
11561:                                 $prompttofetch{$fetch} = 1;
11562:                             }
11563:                         }
11564:                     }
11565:                 } elsif ($env{'form.archive_'.$referrer{$i}} eq 'discard') {
11566:                     $warning .= &mt('[_1] is a dependency of [_2], which was discarded.',
11567:                                     $path,$env{'form.archive_content_'.$referrer{$i}}).'<br />';
11568:                 }
11569:             } else {
11570:                 $warning .= &mt('Item extracted from archive: [_1] has unexpected path.',$path).'<br />'; 
11571:             }
11572:         }
11573:         if (keys(%todelete)) {
11574:             foreach my $key (keys(%todelete)) {
11575:                 unlink($key);
11576:             }
11577:         }
11578:         if (keys(%todeletedir)) {
11579:             foreach my $key (keys(%todeletedir)) {
11580:                 rmdir($key);
11581:             }
11582:         }
11583:         foreach my $dir (sort(keys(%is_dir))) {
11584:             if (($pathtocheck ne '') && ($dir ne ''))  {
11585:                 &cleanup_empty_dirs($prefix."$pathtocheck/$dir");
11586:             }
11587:         }
11588:         if ($result ne '') {
11589:             $output .= '<ul>'."\n".
11590:                        $result."\n".
11591:                        '</ul>';
11592:         }
11593:         unless ($ishome) {
11594:             my $replicationfail;
11595:             foreach my $item (keys(%prompttofetch)) {
11596:                 my $fetchresult= &Apache::lonnet::reply('fetchuserfile:'.$item,$docuhome);
11597:                 unless ($fetchresult eq 'ok') {
11598:                     $replicationfail .= '<li>'.$item.'</li>'."\n";
11599:                 }
11600:             }
11601:             if ($replicationfail) {
11602:                 $output .= '<p class="LC_error">'.
11603:                            &mt('Course home server failed to retrieve:').'<ul>'.
11604:                            $replicationfail.
11605:                            '</ul></p>';
11606:             }
11607:         }
11608:     } else {
11609:         $warning = &mt('No items found in archive.');
11610:     }
11611:     if ($error) {
11612:         $output .= '<p class="LC_error">'.&mt('Not extracted.').'<br />'.
11613:                    $error.'</p>'."\n";
11614:     }
11615:     if ($warning) {
11616:         $output .= '<p class="LC_warning">'.$warning.'</p>'."\n";
11617:     }
11618:     return $output;
11619: }
11620: 
11621: sub cleanup_empty_dirs {
11622:     my ($path) = @_;
11623:     if (($path ne '') && (-d $path)) {
11624:         if (opendir(my $dirh,$path)) {
11625:             my @dircontents = grep(!/^\./,readdir($dirh));
11626:             my $numitems = 0;
11627:             foreach my $item (@dircontents) {
11628:                 if (-d "$path/$item") {
11629:                     &recurse_dirs("$path/$item");
11630:                     if (-e "$path/$item") {
11631:                         $numitems ++;
11632:                     }
11633:                 } else {
11634:                     $numitems ++;
11635:                 }
11636:             }
11637:             if ($numitems == 0) {
11638:                 rmdir($path);
11639:             }
11640:             closedir($dirh);
11641:         }
11642:     }
11643:     return;
11644: }
11645: 
11646: =pod
11647: 
11648: =item &get_folder_hierarchy()
11649: 
11650: Provides hierarchy of names of folders/sub-folders containing the current
11651: item,
11652: 
11653: Inputs: 3
11654:      - $navmap - navmaps object
11655: 
11656:      - $map - url for map (either the trigger itself, or map containing
11657:                            the resource, which is the trigger).
11658: 
11659:      - $showitem - 1 => show title for map itself; 0 => do not show.
11660: 
11661: Outputs: 1 @pathitems - array of folder/subfolder names.
11662: 
11663: =cut
11664: 
11665: sub get_folder_hierarchy {
11666:     my ($navmap,$map,$showitem) = @_;
11667:     my @pathitems;
11668:     if (ref($navmap)) {
11669:         my $mapres = $navmap->getResourceByUrl($map);
11670:         if (ref($mapres)) {
11671:             my $pcslist = $mapres->map_hierarchy();
11672:             if ($pcslist ne '') {
11673:                 my @pcs = split(/,/,$pcslist);
11674:                 foreach my $pc (@pcs) {
11675:                     if ($pc == 1) {
11676:                         push(@pathitems,&mt('Main Course Documents'));
11677:                     } else {
11678:                         my $res = $navmap->getByMapPc($pc);
11679:                         if (ref($res)) {
11680:                             my $title = $res->compTitle();
11681:                             $title =~ s/\W+/_/g;
11682:                             if ($title ne '') {
11683:                                 push(@pathitems,$title);
11684:                             }
11685:                         }
11686:                     }
11687:                 }
11688:             }
11689:             if ($showitem) {
11690:                 if ($mapres->{ID} eq '0.0') {
11691:                     push(@pathitems,&mt('Main Course Documents'));
11692:                 } else {
11693:                     my $maptitle = $mapres->compTitle();
11694:                     $maptitle =~ s/\W+/_/g;
11695:                     if ($maptitle ne '') {
11696:                         push(@pathitems,$maptitle);
11697:                     }
11698:                 }
11699:             }
11700:         }
11701:     }
11702:     return @pathitems;
11703: }
11704: 
11705: =pod
11706: 
11707: =item * &get_turnedin_filepath()
11708: 
11709: Determines path in a user's portfolio file for storage of files uploaded
11710: to a specific essayresponse or dropbox item.
11711: 
11712: Inputs: 3 required + 1 optional.
11713: $symb is symb for resource, $uname and $udom are for current user (required).
11714: $caller is optional (can be "submission", if routine is called when storing
11715: an upoaded file when "Submit Answer" button was pressed).
11716: 
11717: Returns array containing $path and $multiresp. 
11718: $path is path in portfolio.  $multiresp is 1 if this resource contains more
11719: than one file upload item.  Callers of routine should append partid as a 
11720: subdirectory to $path in cases where $multiresp is 1.
11721: 
11722: Called by: homework/essayresponse.pm and homework/structuretags.pm
11723: 
11724: =cut
11725: 
11726: sub get_turnedin_filepath {
11727:     my ($symb,$uname,$udom,$caller) = @_;
11728:     my ($map,$resid,$resurl)=&Apache::lonnet::decode_symb($symb);
11729:     my $turnindir;
11730:     my %userhash = &Apache::lonnet::userenvironment($udom,$uname,'turnindir');
11731:     $turnindir = $userhash{'turnindir'};
11732:     my ($path,$multiresp);
11733:     if ($turnindir eq '') {
11734:         if ($caller eq 'submission') {
11735:             $turnindir = &mt('turned in');
11736:             $turnindir =~ s/\W+/_/g;
11737:             my %newhash = (
11738:                             'turnindir' => $turnindir,
11739:                           );
11740:             &Apache::lonnet::put('environment',\%newhash,$udom,$uname);
11741:         }
11742:     }
11743:     if ($turnindir ne '') {
11744:         $path = '/'.$turnindir.'/';
11745:         my ($multipart,$turnin,@pathitems);
11746:         my $navmap = Apache::lonnavmaps::navmap->new();
11747:         if (defined($navmap)) {
11748:             my $mapres = $navmap->getResourceByUrl($map);
11749:             if (ref($mapres)) {
11750:                 my $pcslist = $mapres->map_hierarchy();
11751:                 if ($pcslist ne '') {
11752:                     foreach my $pc (split(/,/,$pcslist)) {
11753:                         my $res = $navmap->getByMapPc($pc);
11754:                         if (ref($res)) {
11755:                             my $title = $res->compTitle();
11756:                             $title =~ s/\W+/_/g;
11757:                             if ($title ne '') {
11758:                                 push(@pathitems,$title);
11759:                             }
11760:                         }
11761:                     }
11762:                 }
11763:                 my $maptitle = $mapres->compTitle();
11764:                 $maptitle =~ s/\W+/_/g;
11765:                 if ($maptitle ne '') {
11766:                     push(@pathitems,$maptitle);
11767:                 }
11768:                 unless ($env{'request.state'} eq 'construct') {
11769:                     my $res = $navmap->getBySymb($symb);
11770:                     if (ref($res)) {
11771:                         my $partlist = $res->parts();
11772:                         my $totaluploads = 0;
11773:                         if (ref($partlist) eq 'ARRAY') {
11774:                             foreach my $part (@{$partlist}) {
11775:                                 my @types = $res->responseType($part);
11776:                                 my @ids = $res->responseIds($part);
11777:                                 for (my $i=0; $i < scalar(@ids); $i++) {
11778:                                     if ($types[$i] eq 'essay') {
11779:                                         my $partid = $part.'_'.$ids[$i];
11780:                                         if (&Apache::lonnet::EXT("resource.$partid.uploadedfiletypes") ne '') {
11781:                                             $totaluploads ++;
11782:                                         }
11783:                                     }
11784:                                 }
11785:                             }
11786:                             if ($totaluploads > 1) {
11787:                                 $multiresp = 1;
11788:                             }
11789:                         }
11790:                     }
11791:                 }
11792:             } else {
11793:                 return;
11794:             }
11795:         } else {
11796:             return;
11797:         }
11798:         my $restitle=&Apache::lonnet::gettitle($symb);
11799:         $restitle =~ s/\W+/_/g;
11800:         if ($restitle eq '') {
11801:             $restitle = ($resurl =~ m{/[^/]+$});
11802:             if ($restitle eq '') {
11803:                 $restitle = time;
11804:             }
11805:         }
11806:         push(@pathitems,$restitle);
11807:         $path .= join('/',@pathitems);
11808:     }
11809:     return ($path,$multiresp);
11810: }
11811: 
11812: =pod
11813: 
11814: =back
11815: 
11816: =head1 CSV Upload/Handling functions
11817: 
11818: =over 4
11819: 
11820: =item * &upfile_store($r)
11821: 
11822: Store uploaded file, $r should be the HTTP Request object,
11823: needs $env{'form.upfile'}
11824: returns $datatoken to be put into hidden field
11825: 
11826: =cut
11827: 
11828: sub upfile_store {
11829:     my $r=shift;
11830:     $env{'form.upfile'}=~s/\r/\n/gs;
11831:     $env{'form.upfile'}=~s/\f/\n/gs;
11832:     $env{'form.upfile'}=~s/\n+/\n/gs;
11833:     $env{'form.upfile'}=~s/\n+$//gs;
11834: 
11835:     my $datatoken=$env{'user.name'}.'_'.$env{'user.domain'}.
11836: 	'_enroll_'.$env{'request.course.id'}.'_'.time.'_'.$$;
11837:     {
11838:         my $datafile = $r->dir_config('lonDaemons').
11839:                            '/tmp/'.$datatoken.'.tmp';
11840:         if ( open(my $fh,">$datafile") ) {
11841:             print $fh $env{'form.upfile'};
11842:             close($fh);
11843:         }
11844:     }
11845:     return $datatoken;
11846: }
11847: 
11848: =pod
11849: 
11850: =item * &load_tmp_file($r)
11851: 
11852: Load uploaded file from tmp, $r should be the HTTP Request object,
11853: needs $env{'form.datatoken'},
11854: sets $env{'form.upfile'} to the contents of the file
11855: 
11856: =cut
11857: 
11858: sub load_tmp_file {
11859:     my $r=shift;
11860:     my @studentdata=();
11861:     {
11862:         my $studentfile = $r->dir_config('lonDaemons').
11863:                               '/tmp/'.$env{'form.datatoken'}.'.tmp';
11864:         if ( open(my $fh,"<$studentfile") ) {
11865:             @studentdata=<$fh>;
11866:             close($fh);
11867:         }
11868:     }
11869:     $env{'form.upfile'}=join('',@studentdata);
11870: }
11871: 
11872: =pod
11873: 
11874: =item * &upfile_record_sep()
11875: 
11876: Separate uploaded file into records
11877: returns array of records,
11878: needs $env{'form.upfile'} and $env{'form.upfiletype'}
11879: 
11880: =cut
11881: 
11882: sub upfile_record_sep {
11883:     if ($env{'form.upfiletype'} eq 'xml') {
11884:     } else {
11885: 	my @records;
11886: 	foreach my $line (split(/\n/,$env{'form.upfile'})) {
11887: 	    if ($line=~/^\s*$/) { next; }
11888: 	    push(@records,$line);
11889: 	}
11890: 	return @records;
11891:     }
11892: }
11893: 
11894: =pod
11895: 
11896: =item * &record_sep($record)
11897: 
11898: Separate a record into fields $record should be an item from the upfile_record_sep(), needs $env{'form.upfiletype'}
11899: 
11900: =cut
11901: 
11902: sub takeleft {
11903:     my $index=shift;
11904:     return substr('0000'.$index,-4,4);
11905: }
11906: 
11907: sub record_sep {
11908:     my $record=shift;
11909:     my %components=();
11910:     if ($env{'form.upfiletype'} eq 'xml') {
11911:     } elsif ($env{'form.upfiletype'} eq 'space') {
11912:         my $i=0;
11913:         foreach my $field (split(/\s+/,$record)) {
11914:             $field=~s/^(\"|\')//;
11915:             $field=~s/(\"|\')$//;
11916:             $components{&takeleft($i)}=$field;
11917:             $i++;
11918:         }
11919:     } elsif ($env{'form.upfiletype'} eq 'tab') {
11920:         my $i=0;
11921:         foreach my $field (split(/\t/,$record)) {
11922:             $field=~s/^(\"|\')//;
11923:             $field=~s/(\"|\')$//;
11924:             $components{&takeleft($i)}=$field;
11925:             $i++;
11926:         }
11927:     } else {
11928:         my $separator=',';
11929:         if ($env{'form.upfiletype'} eq 'semisv') {
11930:             $separator=';';
11931:         }
11932:         my $i=0;
11933: # the character we are looking for to indicate the end of a quote or a record 
11934:         my $looking_for=$separator;
11935: # do not add the characters to the fields
11936:         my $ignore=0;
11937: # we just encountered a separator (or the beginning of the record)
11938:         my $just_found_separator=1;
11939: # store the field we are working on here
11940:         my $field='';
11941: # work our way through all characters in record
11942:         foreach my $character ($record=~/(.)/g) {
11943:             if ($character eq $looking_for) {
11944:                if ($character ne $separator) {
11945: # Found the end of a quote, again looking for separator
11946:                   $looking_for=$separator;
11947:                   $ignore=1;
11948:                } else {
11949: # Found a separator, store away what we got
11950:                   $components{&takeleft($i)}=$field;
11951: 	          $i++;
11952:                   $just_found_separator=1;
11953:                   $ignore=0;
11954:                   $field='';
11955:                }
11956:                next;
11957:             }
11958: # single or double quotation marks after a separator indicate beginning of a quote
11959: # we are now looking for the end of the quote and need to ignore separators
11960:             if ((($character eq '"') || ($character eq "'")) && ($just_found_separator))  {
11961:                $looking_for=$character;
11962:                next;
11963:             }
11964: # ignore would be true after we reached the end of a quote
11965:             if ($ignore) { next; }
11966:             if (($just_found_separator) && ($character=~/\s/)) { next; }
11967:             $field.=$character;
11968:             $just_found_separator=0; 
11969:         }
11970: # catch the very last entry, since we never encountered the separator
11971:         $components{&takeleft($i)}=$field;
11972:     }
11973:     return %components;
11974: }
11975: 
11976: ######################################################
11977: ######################################################
11978: 
11979: =pod
11980: 
11981: =item * &upfile_select_html()
11982: 
11983: Return HTML code to select a file from the users machine and specify 
11984: the file type.
11985: 
11986: =cut
11987: 
11988: ######################################################
11989: ######################################################
11990: sub upfile_select_html {
11991:     my %Types = (
11992:                  csv   => &mt('CSV (comma separated values, spreadsheet)'),
11993:                  semisv => &mt('Semicolon separated values'),
11994:                  space => &mt('Space separated'),
11995:                  tab   => &mt('Tabulator separated'),
11996: #                 xml   => &mt('HTML/XML'),
11997:                  );
11998:     my $Str = '<input type="file" name="upfile" size="50" />'.
11999:         '<br />'.&mt('Type').': <select name="upfiletype">';
12000:     foreach my $type (sort(keys(%Types))) {
12001:         $Str .= '<option value="'.$type.'" >'.$Types{$type}."</option>\n";
12002:     }
12003:     $Str .= "</select>\n";
12004:     return $Str;
12005: }
12006: 
12007: sub get_samples {
12008:     my ($records,$toget) = @_;
12009:     my @samples=({});
12010:     my $got=0;
12011:     foreach my $rec (@$records) {
12012: 	my %temp = &record_sep($rec);
12013: 	if (! grep(/\S/, values(%temp))) { next; }
12014: 	if (%temp) {
12015: 	    $samples[$got]=\%temp;
12016: 	    $got++;
12017: 	    if ($got == $toget) { last; }
12018: 	}
12019:     }
12020:     return \@samples;
12021: }
12022: 
12023: ######################################################
12024: ######################################################
12025: 
12026: =pod
12027: 
12028: =item * &csv_print_samples($r,$records)
12029: 
12030: Prints a table of sample values from each column uploaded $r is an
12031: Apache Request ref, $records is an arrayref from
12032: &Apache::loncommon::upfile_record_sep
12033: 
12034: =cut
12035: 
12036: ######################################################
12037: ######################################################
12038: sub csv_print_samples {
12039:     my ($r,$records) = @_;
12040:     my $samples = &get_samples($records,5);
12041: 
12042:     $r->print(&mt('Samples').'<br />'.&start_data_table().
12043:               &start_data_table_header_row());
12044:     foreach my $sample (sort({$a <=> $b} keys(%{ $samples->[0] }))) { 
12045:         $r->print('<th>'.&mt('Column [_1]',($sample+1)).'</th>'); }
12046:     $r->print(&end_data_table_header_row());
12047:     foreach my $hash (@$samples) {
12048: 	$r->print(&start_data_table_row());
12049: 	foreach my $sample (sort({$a <=> $b} keys(%{ $samples->[0] }))) {
12050: 	    $r->print('<td>');
12051: 	    if (defined($$hash{$sample})) { $r->print($$hash{$sample}); }
12052: 	    $r->print('</td>');
12053: 	}
12054: 	$r->print(&end_data_table_row());
12055:     }
12056:     $r->print(&end_data_table().'<br />'."\n");
12057: }
12058: 
12059: ######################################################
12060: ######################################################
12061: 
12062: =pod
12063: 
12064: =item * &csv_print_select_table($r,$records,$d)
12065: 
12066: Prints a table to create associations between values and table columns.
12067: 
12068: $r is an Apache Request ref,
12069: $records is an arrayref from &Apache::loncommon::upfile_record_sep,
12070: $d is an array of 2 element arrays (internal name, displayed name,defaultcol)
12071: 
12072: =cut
12073: 
12074: ######################################################
12075: ######################################################
12076: sub csv_print_select_table {
12077:     my ($r,$records,$d) = @_;
12078:     my $i=0;
12079:     my $samples = &get_samples($records,1);
12080:     $r->print(&mt('Associate columns with student attributes.')."\n".
12081: 	      &start_data_table().&start_data_table_header_row().
12082:               '<th>'.&mt('Attribute').'</th>'.
12083:               '<th>'.&mt('Column').'</th>'.
12084:               &end_data_table_header_row()."\n");
12085:     foreach my $array_ref (@$d) {
12086: 	my ($value,$display,$defaultcol)=@{ $array_ref };
12087: 	$r->print(&start_data_table_row().'<td>'.$display.'</td>');
12088: 
12089: 	$r->print('<td><select name="f'.$i.'"'.
12090: 		  ' onchange="javascript:flip(this.form,'.$i.');">');
12091: 	$r->print('<option value="none"></option>');
12092: 	foreach my $sample (sort({$a <=> $b} keys(%{ $samples->[0] }))) {
12093: 	    $r->print('<option value="'.$sample.'"'.
12094:                       ($sample eq $defaultcol ? ' selected="selected" ' : '').
12095:                       '>'.&mt('Column [_1]',($sample+1)).'</option>');
12096: 	}
12097: 	$r->print('</select></td>'.&end_data_table_row()."\n");
12098: 	$i++;
12099:     }
12100:     $r->print(&end_data_table());
12101:     $i--;
12102:     return $i;
12103: }
12104: 
12105: ######################################################
12106: ######################################################
12107: 
12108: =pod
12109: 
12110: =item * &csv_samples_select_table($r,$records,$d)
12111: 
12112: Prints a table of sample values from the upload and can make associate samples to internal names.
12113: 
12114: $r is an Apache Request ref,
12115: $records is an arrayref from &Apache::loncommon::upfile_record_sep,
12116: $d is an array of 2 element arrays (internal name, displayed name)
12117: 
12118: =cut
12119: 
12120: ######################################################
12121: ######################################################
12122: sub csv_samples_select_table {
12123:     my ($r,$records,$d) = @_;
12124:     my $i=0;
12125:     #
12126:     my $max_samples = 5;
12127:     my $samples = &get_samples($records,$max_samples);
12128:     $r->print(&start_data_table().
12129:               &start_data_table_header_row().'<th>'.
12130:               &mt('Field').'</th><th>'.&mt('Samples').'</th>'.
12131:               &end_data_table_header_row());
12132: 
12133:     foreach my $key (sort(keys(%{ $samples->[0] }))) {
12134: 	$r->print(&start_data_table_row().'<td><select name="f'.$i.'"'.
12135: 		  ' onchange="javascript:flip(this.form,'.$i.');">');
12136: 	foreach my $option (@$d) {
12137: 	    my ($value,$display,$defaultcol)=@{ $option };
12138: 	    $r->print('<option value="'.$value.'"'.
12139:                       ($i eq $defaultcol ? ' selected="selected" ':'').'>'.
12140:                       $display.'</option>');
12141: 	}
12142: 	$r->print('</select></td><td>');
12143: 	foreach my $line (0..($max_samples-1)) {
12144: 	    if (defined($samples->[$line]{$key})) { 
12145: 		$r->print($samples->[$line]{$key}."<br />\n"); 
12146: 	    }
12147: 	}
12148: 	$r->print('</td>'.&end_data_table_row());
12149: 	$i++;
12150:     }
12151:     $r->print(&end_data_table());
12152:     $i--;
12153:     return($i);
12154: }
12155: 
12156: ######################################################
12157: ######################################################
12158: 
12159: =pod
12160: 
12161: =item * &clean_excel_name($name)
12162: 
12163: Returns a replacement for $name which does not contain any illegal characters.
12164: 
12165: =cut
12166: 
12167: ######################################################
12168: ######################################################
12169: sub clean_excel_name {
12170:     my ($name) = @_;
12171:     $name =~ s/[:\*\?\/\\]//g;
12172:     if (length($name) > 31) {
12173:         $name = substr($name,0,31);
12174:     }
12175:     return $name;
12176: }
12177: 
12178: =pod
12179: 
12180: =item * &check_if_partid_hidden($id,$symb,$udom,$uname)
12181: 
12182: Returns either 1 or undef
12183: 
12184: 1 if the part is to be hidden, undef if it is to be shown
12185: 
12186: Arguments are:
12187: 
12188: $id the id of the part to be checked
12189: $symb, optional the symb of the resource to check
12190: $udom, optional the domain of the user to check for
12191: $uname, optional the username of the user to check for
12192: 
12193: =cut
12194: 
12195: sub check_if_partid_hidden {
12196:     my ($id,$symb,$udom,$uname) = @_;
12197:     my $hiddenparts=&Apache::lonnet::EXT('resource.0.hiddenparts',
12198: 					 $symb,$udom,$uname);
12199:     my $truth=1;
12200:     #if the string starts with !, then the list is the list to show not hide
12201:     if ($hiddenparts=~s/^\s*!//) { $truth=undef; }
12202:     my @hiddenlist=split(/,/,$hiddenparts);
12203:     foreach my $checkid (@hiddenlist) {
12204: 	if ($checkid =~ /^\s*\Q$id\E\s*$/) { return $truth; }
12205:     }
12206:     return !$truth;
12207: }
12208: 
12209: 
12210: ############################################################
12211: ############################################################
12212: 
12213: =pod
12214: 
12215: =back 
12216: 
12217: =head1 cgi-bin script and graphing routines
12218: 
12219: =over 4
12220: 
12221: =item * &get_cgi_id()
12222: 
12223: Inputs: none
12224: 
12225: Returns an id which can be used to pass environment variables
12226: to various cgi-bin scripts.  These environment variables will
12227: be removed from the users environment after a given time by
12228: the routine &Apache::lonnet::transfer_profile_to_env.
12229: 
12230: =cut
12231: 
12232: ############################################################
12233: ############################################################
12234: my $uniq=0;
12235: sub get_cgi_id {
12236:     $uniq=($uniq+1)%100000;
12237:     return (time.'_'.$$.'_'.$uniq);
12238: }
12239: 
12240: ############################################################
12241: ############################################################
12242: 
12243: =pod
12244: 
12245: =item * &DrawBarGraph()
12246: 
12247: Facilitates the plotting of data in a (stacked) bar graph.
12248: Puts plot definition data into the users environment in order for 
12249: graph.png to plot it.  Returns an <img> tag for the plot.
12250: The bars on the plot are labeled '1','2',...,'n'.
12251: 
12252: Inputs:
12253: 
12254: =over 4
12255: 
12256: =item $Title: string, the title of the plot
12257: 
12258: =item $xlabel: string, text describing the X-axis of the plot
12259: 
12260: =item $ylabel: string, text describing the Y-axis of the plot
12261: 
12262: =item $Max: scalar, the maximum Y value to use in the plot
12263: If $Max is < any data point, the graph will not be rendered.
12264: 
12265: =item $colors: array ref holding the colors to be used for the data sets when
12266: they are plotted.  If undefined, default values will be used.
12267: 
12268: =item $labels: array ref holding the labels to use on the x-axis for the bars.
12269: 
12270: =item @Values: An array of array references.  Each array reference holds data
12271: to be plotted in a stacked bar chart.
12272: 
12273: =item If the final element of @Values is a hash reference the key/value
12274: pairs will be added to the graph definition.
12275: 
12276: =back
12277: 
12278: Returns:
12279: 
12280: An <img> tag which references graph.png and the appropriate identifying
12281: information for the plot.
12282: 
12283: =cut
12284: 
12285: ############################################################
12286: ############################################################
12287: sub DrawBarGraph {
12288:     my ($Title,$xlabel,$ylabel,$Max,$colors,$labels,@Values)=@_;
12289:     #
12290:     if (! defined($colors)) {
12291:         $colors = ['#33ff00', 
12292:                   '#0033cc', '#990000', '#aaaa66', '#663399', '#ff9933',
12293:                   '#66ccff', '#ff9999', '#cccc33', '#660000', '#33cc66',
12294:                   ]; 
12295:     }
12296:     my $extra_settings = {};
12297:     if (ref($Values[-1]) eq 'HASH') {
12298:         $extra_settings = pop(@Values);
12299:     }
12300:     #
12301:     my $identifier = &get_cgi_id();
12302:     my $id = 'cgi.'.$identifier;        
12303:     if (! @Values || ref($Values[0]) ne 'ARRAY') {
12304:         return '';
12305:     }
12306:     #
12307:     my @Labels;
12308:     if (defined($labels)) {
12309:         @Labels = @$labels;
12310:     } else {
12311:         for (my $i=0;$i<@{$Values[0]};$i++) {
12312:             push (@Labels,$i+1);
12313:         }
12314:     }
12315:     #
12316:     my $NumBars = scalar(@{$Values[0]});
12317:     if ($NumBars < scalar(@Labels)) { $NumBars = scalar(@Labels); }
12318:     my %ValuesHash;
12319:     my $NumSets=1;
12320:     foreach my $array (@Values) {
12321:         next if (! ref($array));
12322:         $ValuesHash{$id.'.data.'.$NumSets++} = 
12323:             join(',',@$array);
12324:     }
12325:     #
12326:     my ($height,$width,$xskip,$bar_width) = (200,120,1,15);
12327:     if ($NumBars < 3) {
12328:         $width = 120+$NumBars*32;
12329:         $xskip = 1;
12330:         $bar_width = 30;
12331:     } elsif ($NumBars < 5) {
12332:         $width = 120+$NumBars*20;
12333:         $xskip = 1;
12334:         $bar_width = 20;
12335:     } elsif ($NumBars < 10) {
12336:         $width = 120+$NumBars*15;
12337:         $xskip = 1;
12338:         $bar_width = 15;
12339:     } elsif ($NumBars <= 25) {
12340:         $width = 120+$NumBars*11;
12341:         $xskip = 5;
12342:         $bar_width = 8;
12343:     } elsif ($NumBars <= 50) {
12344:         $width = 120+$NumBars*8;
12345:         $xskip = 5;
12346:         $bar_width = 4;
12347:     } else {
12348:         $width = 120+$NumBars*8;
12349:         $xskip = 5;
12350:         $bar_width = 4;
12351:     }
12352:     #
12353:     $Max = 1 if ($Max < 1);
12354:     if ( int($Max) < $Max ) {
12355:         $Max++;
12356:         $Max = int($Max);
12357:     }
12358:     $Title  = '' if (! defined($Title));
12359:     $xlabel = '' if (! defined($xlabel));
12360:     $ylabel = '' if (! defined($ylabel));
12361:     $ValuesHash{$id.'.title'}    = &escape($Title);
12362:     $ValuesHash{$id.'.xlabel'}   = &escape($xlabel);
12363:     $ValuesHash{$id.'.ylabel'}   = &escape($ylabel);
12364:     $ValuesHash{$id.'.y_max_value'} = $Max;
12365:     $ValuesHash{$id.'.NumBars'}  = $NumBars;
12366:     $ValuesHash{$id.'.NumSets'}  = $NumSets;
12367:     $ValuesHash{$id.'.PlotType'} = 'bar';
12368:     $ValuesHash{$id.'.Colors'}   = join(',',@{$colors});
12369:     $ValuesHash{$id.'.height'}   = $height;
12370:     $ValuesHash{$id.'.width'}    = $width;
12371:     $ValuesHash{$id.'.xskip'}    = $xskip;
12372:     $ValuesHash{$id.'.bar_width'} = $bar_width;
12373:     $ValuesHash{$id.'.labels'} = join(',',@Labels);
12374:     #
12375:     # Deal with other parameters
12376:     while (my ($key,$value) = each(%$extra_settings)) {
12377:         $ValuesHash{$id.'.'.$key} = $value;
12378:     }
12379:     #
12380:     &Apache::lonnet::appenv(\%ValuesHash);
12381:     return '<img src="/cgi-bin/graph.png?'.$identifier.'" border="1" />';
12382: }
12383: 
12384: ############################################################
12385: ############################################################
12386: 
12387: =pod
12388: 
12389: =item * &DrawXYGraph()
12390: 
12391: Facilitates the plotting of data in an XY graph.
12392: Puts plot definition data into the users environment in order for 
12393: graph.png to plot it.  Returns an <img> tag for the plot.
12394: 
12395: Inputs:
12396: 
12397: =over 4
12398: 
12399: =item $Title: string, the title of the plot
12400: 
12401: =item $xlabel: string, text describing the X-axis of the plot
12402: 
12403: =item $ylabel: string, text describing the Y-axis of the plot
12404: 
12405: =item $Max: scalar, the maximum Y value to use in the plot
12406: If $Max is < any data point, the graph will not be rendered.
12407: 
12408: =item $colors: Array ref containing the hex color codes for the data to be 
12409: plotted in.  If undefined, default values will be used.
12410: 
12411: =item $Xlabels: Array ref containing the labels to be used for the X-axis.
12412: 
12413: =item $Ydata: Array ref containing Array refs.  
12414: Each of the contained arrays will be plotted as a separate curve.
12415: 
12416: =item %Values: hash indicating or overriding any default values which are 
12417: passed to graph.png.  
12418: Possible values are: width, xskip, x_ticks, x_tick_offset, among others.
12419: 
12420: =back
12421: 
12422: Returns:
12423: 
12424: An <img> tag which references graph.png and the appropriate identifying
12425: information for the plot.
12426: 
12427: =cut
12428: 
12429: ############################################################
12430: ############################################################
12431: sub DrawXYGraph {
12432:     my ($Title,$xlabel,$ylabel,$Max,$colors,$Xlabels,$Ydata,%Values)=@_;
12433:     #
12434:     # Create the identifier for the graph
12435:     my $identifier = &get_cgi_id();
12436:     my $id = 'cgi.'.$identifier;
12437:     #
12438:     $Title  = '' if (! defined($Title));
12439:     $xlabel = '' if (! defined($xlabel));
12440:     $ylabel = '' if (! defined($ylabel));
12441:     my %ValuesHash = 
12442:         (
12443:          $id.'.title'  => &escape($Title),
12444:          $id.'.xlabel' => &escape($xlabel),
12445:          $id.'.ylabel' => &escape($ylabel),
12446:          $id.'.y_max_value'=> $Max,
12447:          $id.'.labels'     => join(',',@$Xlabels),
12448:          $id.'.PlotType'   => 'XY',
12449:          );
12450:     #
12451:     if (defined($colors) && ref($colors) eq 'ARRAY') {
12452:         $ValuesHash{$id.'.Colors'}   = join(',',@{$colors});
12453:     }
12454:     #
12455:     if (! ref($Ydata) || ref($Ydata) ne 'ARRAY') {
12456:         return '';
12457:     }
12458:     my $NumSets=1;
12459:     foreach my $array (@{$Ydata}){
12460:         next if (! ref($array));
12461:         $ValuesHash{$id.'.data.'.$NumSets++} = join(',',@$array);
12462:     }
12463:     $ValuesHash{$id.'.NumSets'} = $NumSets-1;
12464:     #
12465:     # Deal with other parameters
12466:     while (my ($key,$value) = each(%Values)) {
12467:         $ValuesHash{$id.'.'.$key} = $value;
12468:     }
12469:     #
12470:     &Apache::lonnet::appenv(\%ValuesHash);
12471:     return '<img src="/cgi-bin/graph.png?'.$identifier.'" border="1" />';
12472: }
12473: 
12474: ############################################################
12475: ############################################################
12476: 
12477: =pod
12478: 
12479: =item * &DrawXYYGraph()
12480: 
12481: Facilitates the plotting of data in an XY graph with two Y axes.
12482: Puts plot definition data into the users environment in order for 
12483: graph.png to plot it.  Returns an <img> tag for the plot.
12484: 
12485: Inputs:
12486: 
12487: =over 4
12488: 
12489: =item $Title: string, the title of the plot
12490: 
12491: =item $xlabel: string, text describing the X-axis of the plot
12492: 
12493: =item $ylabel: string, text describing the Y-axis of the plot
12494: 
12495: =item $colors: Array ref containing the hex color codes for the data to be 
12496: plotted in.  If undefined, default values will be used.
12497: 
12498: =item $Xlabels: Array ref containing the labels to be used for the X-axis.
12499: 
12500: =item $Ydata1: The first data set
12501: 
12502: =item $Min1: The minimum value of the left Y-axis
12503: 
12504: =item $Max1: The maximum value of the left Y-axis
12505: 
12506: =item $Ydata2: The second data set
12507: 
12508: =item $Min2: The minimum value of the right Y-axis
12509: 
12510: =item $Max2: The maximum value of the left Y-axis
12511: 
12512: =item %Values: hash indicating or overriding any default values which are 
12513: passed to graph.png.  
12514: Possible values are: width, xskip, x_ticks, x_tick_offset, among others.
12515: 
12516: =back
12517: 
12518: Returns:
12519: 
12520: An <img> tag which references graph.png and the appropriate identifying
12521: information for the plot.
12522: 
12523: =cut
12524: 
12525: ############################################################
12526: ############################################################
12527: sub DrawXYYGraph {
12528:     my ($Title,$xlabel,$ylabel,$colors,$Xlabels,$Ydata1,$Min1,$Max1,
12529:                                         $Ydata2,$Min2,$Max2,%Values)=@_;
12530:     #
12531:     # Create the identifier for the graph
12532:     my $identifier = &get_cgi_id();
12533:     my $id = 'cgi.'.$identifier;
12534:     #
12535:     $Title  = '' if (! defined($Title));
12536:     $xlabel = '' if (! defined($xlabel));
12537:     $ylabel = '' if (! defined($ylabel));
12538:     my %ValuesHash = 
12539:         (
12540:          $id.'.title'  => &escape($Title),
12541:          $id.'.xlabel' => &escape($xlabel),
12542:          $id.'.ylabel' => &escape($ylabel),
12543:          $id.'.labels' => join(',',@$Xlabels),
12544:          $id.'.PlotType' => 'XY',
12545:          $id.'.NumSets' => 2,
12546:          $id.'.two_axes' => 1,
12547:          $id.'.y1_max_value' => $Max1,
12548:          $id.'.y1_min_value' => $Min1,
12549:          $id.'.y2_max_value' => $Max2,
12550:          $id.'.y2_min_value' => $Min2,
12551:          );
12552:     #
12553:     if (defined($colors) && ref($colors) eq 'ARRAY') {
12554:         $ValuesHash{$id.'.Colors'}   = join(',',@{$colors});
12555:     }
12556:     #
12557:     if (! ref($Ydata1) || ref($Ydata1) ne 'ARRAY' ||
12558:         ! ref($Ydata2) || ref($Ydata2) ne 'ARRAY'){
12559:         return '';
12560:     }
12561:     my $NumSets=1;
12562:     foreach my $array ($Ydata1,$Ydata2){
12563:         next if (! ref($array));
12564:         $ValuesHash{$id.'.data.'.$NumSets++} = join(',',@$array);
12565:     }
12566:     #
12567:     # Deal with other parameters
12568:     while (my ($key,$value) = each(%Values)) {
12569:         $ValuesHash{$id.'.'.$key} = $value;
12570:     }
12571:     #
12572:     &Apache::lonnet::appenv(\%ValuesHash);
12573:     return '<img src="/cgi-bin/graph.png?'.$identifier.'" border="1" />';
12574: }
12575: 
12576: ############################################################
12577: ############################################################
12578: 
12579: =pod
12580: 
12581: =back 
12582: 
12583: =head1 Statistics helper routines?  
12584: 
12585: Bad place for them but what the hell.
12586: 
12587: =over 4
12588: 
12589: =item * &chartlink()
12590: 
12591: Returns a link to the chart for a specific student.  
12592: 
12593: Inputs:
12594: 
12595: =over 4
12596: 
12597: =item $linktext: The text of the link
12598: 
12599: =item $sname: The students username
12600: 
12601: =item $sdomain: The students domain
12602: 
12603: =back
12604: 
12605: =back
12606: 
12607: =cut
12608: 
12609: ############################################################
12610: ############################################################
12611: sub chartlink {
12612:     my ($linktext, $sname, $sdomain) = @_;
12613:     my $link = '<a href="/adm/statistics?reportSelected=student_assessment'.
12614:         '&amp;SelectedStudent='.&escape($sname.':'.$sdomain).
12615:         '&amp;chartoutputmode='.HTML::Entities::encode('html, with all links').
12616:        '">'.$linktext.'</a>';
12617: }
12618: 
12619: #######################################################
12620: #######################################################
12621: 
12622: =pod
12623: 
12624: =head1 Course Environment Routines
12625: 
12626: =over 4
12627: 
12628: =item * &restore_course_settings()
12629: 
12630: =item * &store_course_settings()
12631: 
12632: Restores/Store indicated form parameters from the course environment.
12633: Will not overwrite existing values of the form parameters.
12634: 
12635: Inputs: 
12636: a scalar describing the data (e.g. 'chart', 'problem_analysis')
12637: 
12638: a hash ref describing the data to be stored.  For example:
12639:    
12640: %Save_Parameters = ('Status' => 'scalar',
12641:     'chartoutputmode' => 'scalar',
12642:     'chartoutputdata' => 'scalar',
12643:     'Section' => 'array',
12644:     'Group' => 'array',
12645:     'StudentData' => 'array',
12646:     'Maps' => 'array');
12647: 
12648: Returns: both routines return nothing
12649: 
12650: =back
12651: 
12652: =cut
12653: 
12654: #######################################################
12655: #######################################################
12656: sub store_course_settings {
12657:     return &store_settings($env{'request.course.id'},@_);
12658: }
12659: 
12660: sub store_settings {
12661:     # save to the environment
12662:     # appenv the same items, just to be safe
12663:     my $udom  = $env{'user.domain'};
12664:     my $uname = $env{'user.name'};
12665:     my ($context,$prefix,$Settings) = @_;
12666:     my %SaveHash;
12667:     my %AppHash;
12668:     while (my ($setting,$type) = each(%$Settings)) {
12669:         my $basename = join('.','internal',$context,$prefix,$setting);
12670:         my $envname = 'environment.'.$basename;
12671:         if (exists($env{'form.'.$setting})) {
12672:             # Save this value away
12673:             if ($type eq 'scalar' &&
12674:                 (! exists($env{$envname}) || 
12675:                  $env{$envname} ne $env{'form.'.$setting})) {
12676:                 $SaveHash{$basename} = $env{'form.'.$setting};
12677:                 $AppHash{$envname}   = $env{'form.'.$setting};
12678:             } elsif ($type eq 'array') {
12679:                 my $stored_form;
12680:                 if (ref($env{'form.'.$setting})) {
12681:                     $stored_form = join(',',
12682:                                         map {
12683:                                             &escape($_);
12684:                                         } sort(@{$env{'form.'.$setting}}));
12685:                 } else {
12686:                     $stored_form = 
12687:                         &escape($env{'form.'.$setting});
12688:                 }
12689:                 # Determine if the array contents are the same.
12690:                 if ($stored_form ne $env{$envname}) {
12691:                     $SaveHash{$basename} = $stored_form;
12692:                     $AppHash{$envname}   = $stored_form;
12693:                 }
12694:             }
12695:         }
12696:     }
12697:     my $put_result = &Apache::lonnet::put('environment',\%SaveHash,
12698:                                           $udom,$uname);
12699:     if ($put_result !~ /^(ok|delayed)/) {
12700:         &Apache::lonnet::logthis('unable to save form parameters, '.
12701:                                  'got error:'.$put_result);
12702:     }
12703:     # Make sure these settings stick around in this session, too
12704:     &Apache::lonnet::appenv(\%AppHash);
12705:     return;
12706: }
12707: 
12708: sub restore_course_settings {
12709:     return &restore_settings($env{'request.course.id'},@_);
12710: }
12711: 
12712: sub restore_settings {
12713:     my ($context,$prefix,$Settings) = @_;
12714:     while (my ($setting,$type) = each(%$Settings)) {
12715:         next if (exists($env{'form.'.$setting}));
12716:         my $envname = 'environment.internal.'.$context.'.'.$prefix.
12717:             '.'.$setting;
12718:         if (exists($env{$envname})) {
12719:             if ($type eq 'scalar') {
12720:                 $env{'form.'.$setting} = $env{$envname};
12721:             } elsif ($type eq 'array') {
12722:                 $env{'form.'.$setting} = [ 
12723:                                            map { 
12724:                                                &unescape($_); 
12725:                                            } split(',',$env{$envname})
12726:                                            ];
12727:             }
12728:         }
12729:     }
12730: }
12731: 
12732: #######################################################
12733: #######################################################
12734: 
12735: =pod
12736: 
12737: =head1 Domain E-mail Routines  
12738: 
12739: =over 4
12740: 
12741: =item * &build_recipient_list()
12742: 
12743: Build recipient lists for five types of e-mail:
12744: (a) Error Reports, (b) Package Updates, (c) lonstatus warnings/errors
12745: (d) Help requests, (e) Course requests needing approval,  generated by
12746: lonerrorhandler.pm, CHECKRPMS, loncron, lonsupportreq.pm and
12747: loncoursequeueadmin.pm respectively.
12748: 
12749: Inputs:
12750: defmail (scalar - email address of default recipient), 
12751: mailing type (scalar - errormail, packagesmail, or helpdeskmail), 
12752: defdom (domain for which to retrieve configuration settings),
12753: origmail (scalar - email address of recipient from loncapa.conf, 
12754: i.e., predates configuration by DC via domainprefs.pm 
12755: 
12756: Returns: comma separated list of addresses to which to send e-mail.
12757: 
12758: =back
12759: 
12760: =cut
12761: 
12762: ############################################################
12763: ############################################################
12764: sub build_recipient_list {
12765:     my ($defmail,$mailing,$defdom,$origmail) = @_;
12766:     my @recipients;
12767:     my $otheremails;
12768:     my %domconfig =
12769:          &Apache::lonnet::get_dom('configuration',['contacts'],$defdom);
12770:     if (ref($domconfig{'contacts'}) eq 'HASH') {
12771:         if (exists($domconfig{'contacts'}{$mailing})) {
12772:             if (ref($domconfig{'contacts'}{$mailing}) eq 'HASH') {
12773:                 my @contacts = ('adminemail','supportemail');
12774:                 foreach my $item (@contacts) {
12775:                     if ($domconfig{'contacts'}{$mailing}{$item}) {
12776:                         my $addr = $domconfig{'contacts'}{$item}; 
12777:                         if (!grep(/^\Q$addr\E$/,@recipients)) {
12778:                             push(@recipients,$addr);
12779:                         }
12780:                     }
12781:                     $otheremails = $domconfig{'contacts'}{$mailing}{'others'};
12782:                 }
12783:             }
12784:         } elsif ($origmail ne '') {
12785:             push(@recipients,$origmail);
12786:         }
12787:     } elsif ($origmail ne '') {
12788:         push(@recipients,$origmail);
12789:     }
12790:     if (defined($defmail)) {
12791:         if ($defmail ne '') {
12792:             push(@recipients,$defmail);
12793:         }
12794:     }
12795:     if ($otheremails) {
12796:         my @others;
12797:         if ($otheremails =~ /,/) {
12798:             @others = split(/,/,$otheremails);
12799:         } else {
12800:             push(@others,$otheremails);
12801:         }
12802:         foreach my $addr (@others) {
12803:             if (!grep(/^\Q$addr\E$/,@recipients)) {
12804:                 push(@recipients,$addr);
12805:             }
12806:         }
12807:     }
12808:     my $recipientlist = join(',',@recipients); 
12809:     return $recipientlist;
12810: }
12811: 
12812: ############################################################
12813: ############################################################
12814: 
12815: =pod
12816: 
12817: =head1 Course Catalog Routines
12818: 
12819: =over 4
12820: 
12821: =item * &gather_categories()
12822: 
12823: Converts category definitions - keys of categories hash stored in  
12824: coursecategories in configuration.db on the primary library server in a 
12825: domain - to an array.  Also generates javascript and idx hash used to 
12826: generate Domain Coordinator interface for editing Course Categories.
12827: 
12828: Inputs:
12829: 
12830: categories (reference to hash of category definitions).
12831: 
12832: cats (reference to array of arrays/hashes which encapsulates hierarchy of
12833:       categories and subcategories).
12834: 
12835: idx (reference to hash of counters used in Domain Coordinator interface for 
12836:       editing Course Categories).
12837: 
12838: jsarray (reference to array of categories used to create Javascript arrays for
12839:          Domain Coordinator interface for editing Course Categories).
12840: 
12841: Returns: nothing
12842: 
12843: Side effects: populates cats, idx and jsarray. 
12844: 
12845: =cut
12846: 
12847: sub gather_categories {
12848:     my ($categories,$cats,$idx,$jsarray) = @_;
12849:     my %counters;
12850:     my $num = 0;
12851:     foreach my $item (keys(%{$categories})) {
12852:         my ($cat,$container,$depth) = map { &unescape($_); } split(/:/,$item);
12853:         if ($container eq '' && $depth == 0) {
12854:             $cats->[$depth][$categories->{$item}] = $cat;
12855:         } else {
12856:             $cats->[$depth]{$container}[$categories->{$item}] = $cat;
12857:         }
12858:         my ($escitem,$tail) = split(/:/,$item,2);
12859:         if ($counters{$tail} eq '') {
12860:             $counters{$tail} = $num;
12861:             $num ++;
12862:         }
12863:         if (ref($idx) eq 'HASH') {
12864:             $idx->{$item} = $counters{$tail};
12865:         }
12866:         if (ref($jsarray) eq 'ARRAY') {
12867:             push(@{$jsarray->[$counters{$tail}]},$item);
12868:         }
12869:     }
12870:     return;
12871: }
12872: 
12873: =pod
12874: 
12875: =item * &extract_categories()
12876: 
12877: Used to generate breadcrumb trails for course categories.
12878: 
12879: Inputs:
12880: 
12881: categories (reference to hash of category definitions).
12882: 
12883: cats (reference to array of arrays/hashes which encapsulates hierarchy of
12884:       categories and subcategories).
12885: 
12886: trails (reference to array of breacrumb trails for each category).
12887: 
12888: allitems (reference to hash - key is category key 
12889:          (format: escaped(name):escaped(parent category):depth in hierarchy).
12890: 
12891: idx (reference to hash of counters used in Domain Coordinator interface for
12892:       editing Course Categories).
12893: 
12894: jsarray (reference to array of categories used to create Javascript arrays for
12895:          Domain Coordinator interface for editing Course Categories).
12896: 
12897: subcats (reference to hash of arrays containing all subcategories within each 
12898:          category, -recursive)
12899: 
12900: Returns: nothing
12901: 
12902: Side effects: populates trails and allitems hash references.
12903: 
12904: =cut
12905: 
12906: sub extract_categories {
12907:     my ($categories,$cats,$trails,$allitems,$idx,$jsarray,$subcats) = @_;
12908:     if (ref($categories) eq 'HASH') {
12909:         &gather_categories($categories,$cats,$idx,$jsarray);
12910:         if (ref($cats->[0]) eq 'ARRAY') {
12911:             for (my $i=0; $i<@{$cats->[0]}; $i++) {
12912:                 my $name = $cats->[0][$i];
12913:                 my $item = &escape($name).'::0';
12914:                 my $trailstr;
12915:                 if ($name eq 'instcode') {
12916:                     $trailstr = &mt('Official courses (with institutional codes)');
12917:                 } elsif ($name eq 'communities') {
12918:                     $trailstr = &mt('Communities');
12919:                 } else {
12920:                     $trailstr = $name;
12921:                 }
12922:                 if ($allitems->{$item} eq '') {
12923:                     push(@{$trails},$trailstr);
12924:                     $allitems->{$item} = scalar(@{$trails})-1;
12925:                 }
12926:                 my @parents = ($name);
12927:                 if (ref($cats->[1]{$name}) eq 'ARRAY') {
12928:                     for (my $j=0; $j<@{$cats->[1]{$name}}; $j++) {
12929:                         my $category = $cats->[1]{$name}[$j];
12930:                         if (ref($subcats) eq 'HASH') {
12931:                             push(@{$subcats->{$item}},&escape($category).':'.&escape($name).':1');
12932:                         }
12933:                         &recurse_categories($cats,2,$category,$trails,$allitems,\@parents,$subcats);
12934:                     }
12935:                 } else {
12936:                     if (ref($subcats) eq 'HASH') {
12937:                         $subcats->{$item} = [];
12938:                     }
12939:                 }
12940:             }
12941:         }
12942:     }
12943:     return;
12944: }
12945: 
12946: =pod
12947: 
12948: =item *&recurse_categories()
12949: 
12950: Recursively used to generate breadcrumb trails for course categories.
12951: 
12952: Inputs:
12953: 
12954: cats (reference to array of arrays/hashes which encapsulates hierarchy of
12955:       categories and subcategories).
12956: 
12957: depth (current depth in hierarchy of categories and sub-categories - 0 indexed).
12958: 
12959: category (current course category, for which breadcrumb trail is being generated).
12960: 
12961: trails (reference to array of breadcrumb trails for each category).
12962: 
12963: allitems (reference to hash - key is category key
12964:          (format: escaped(name):escaped(parent category):depth in hierarchy).
12965: 
12966: parents (array containing containers directories for current category, 
12967:          back to top level). 
12968: 
12969: Returns: nothing
12970: 
12971: Side effects: populates trails and allitems hash references
12972: 
12973: =cut
12974: 
12975: sub recurse_categories {
12976:     my ($cats,$depth,$category,$trails,$allitems,$parents,$subcats) = @_;
12977:     my $shallower = $depth - 1;
12978:     if (ref($cats->[$depth]{$category}) eq 'ARRAY') {
12979:         for (my $k=0; $k<@{$cats->[$depth]{$category}}; $k++) {
12980:             my $name = $cats->[$depth]{$category}[$k];
12981:             my $item = &escape($category).':'.&escape($parents->[-1]).':'.$shallower;
12982:             my $trailstr = join(' -&gt; ',(@{$parents},$category));
12983:             if ($allitems->{$item} eq '') {
12984:                 push(@{$trails},$trailstr);
12985:                 $allitems->{$item} = scalar(@{$trails})-1;
12986:             }
12987:             my $deeper = $depth+1;
12988:             push(@{$parents},$category);
12989:             if (ref($subcats) eq 'HASH') {
12990:                 my $subcat = &escape($name).':'.$category.':'.$depth;
12991:                 for (my $j=@{$parents}; $j>=0; $j--) {
12992:                     my $higher;
12993:                     if ($j > 0) {
12994:                         $higher = &escape($parents->[$j]).':'.
12995:                                   &escape($parents->[$j-1]).':'.$j;
12996:                     } else {
12997:                         $higher = &escape($parents->[$j]).'::'.$j;
12998:                     }
12999:                     push(@{$subcats->{$higher}},$subcat);
13000:                 }
13001:             }
13002:             &recurse_categories($cats,$deeper,$name,$trails,$allitems,$parents,
13003:                                 $subcats);
13004:             pop(@{$parents});
13005:         }
13006:     } else {
13007:         my $item = &escape($category).':'.&escape($parents->[-1]).':'.$shallower;
13008:         my $trailstr = join(' -&gt; ',(@{$parents},$category));
13009:         if ($allitems->{$item} eq '') {
13010:             push(@{$trails},$trailstr);
13011:             $allitems->{$item} = scalar(@{$trails})-1;
13012:         }
13013:     }
13014:     return;
13015: }
13016: 
13017: =pod
13018: 
13019: =item *&assign_categories_table()
13020: 
13021: Create a datatable for display of hierarchical categories in a domain,
13022: with checkboxes to allow a course to be categorized. 
13023: 
13024: Inputs:
13025: 
13026: cathash - reference to hash of categories defined for the domain (from
13027:           configuration.db)
13028: 
13029: currcat - scalar with an & separated list of categories assigned to a course. 
13030: 
13031: type    - scalar contains course type (Course or Community).
13032: 
13033: Returns: $output (markup to be displayed) 
13034: 
13035: =cut
13036: 
13037: sub assign_categories_table {
13038:     my ($cathash,$currcat,$type) = @_;
13039:     my $output;
13040:     if (ref($cathash) eq 'HASH') {
13041:         my (@cats,@trails,%allitems,%idx,@jsarray,@path,$maxdepth);
13042:         &extract_categories($cathash,\@cats,\@trails,\%allitems,\%idx,\@jsarray);
13043:         $maxdepth = scalar(@cats);
13044:         if (@cats > 0) {
13045:             my $itemcount = 0;
13046:             if (ref($cats[0]) eq 'ARRAY') {
13047:                 my @currcategories;
13048:                 if ($currcat ne '') {
13049:                     @currcategories = split('&',$currcat);
13050:                 }
13051:                 my $table;
13052:                 for (my $i=0; $i<@{$cats[0]}; $i++) {
13053:                     my $parent = $cats[0][$i];
13054:                     next if ($parent eq 'instcode');
13055:                     if ($type eq 'Community') {
13056:                         next unless ($parent eq 'communities');
13057:                     } else {
13058:                         next if ($parent eq 'communities');
13059:                     }
13060:                     my $css_class = $itemcount%2?' class="LC_odd_row"':'';
13061:                     my $item = &escape($parent).'::0';
13062:                     my $checked = '';
13063:                     if (@currcategories > 0) {
13064:                         if (grep(/^\Q$item\E$/,@currcategories)) {
13065:                             $checked = ' checked="checked"';
13066:                         }
13067:                     }
13068:                     my $parent_title = $parent;
13069:                     if ($parent eq 'communities') {
13070:                         $parent_title = &mt('Communities');
13071:                     }
13072:                     $table .= '<tr '.$css_class.'><td><span class="LC_nobreak">'.
13073:                               '<input type="checkbox" name="usecategory" value="'.
13074:                               $item.'"'.$checked.' />'.$parent_title.'</span>'.
13075:                               '<input type="hidden" name="catname" value="'.$parent.'" /></td>';
13076:                     my $depth = 1;
13077:                     push(@path,$parent);
13078:                     $table .= &assign_category_rows($itemcount,\@cats,$depth,$parent,\@path,\@currcategories);
13079:                     pop(@path);
13080:                     $table .= '</tr><tr><td colspan="'.$maxdepth.'" class="LC_row_separator"></td></tr>';
13081:                     $itemcount ++;
13082:                 }
13083:                 if ($itemcount) {
13084:                     $output = &Apache::loncommon::start_data_table().
13085:                               $table.
13086:                               &Apache::loncommon::end_data_table();
13087:                 }
13088:             }
13089:         }
13090:     }
13091:     return $output;
13092: }
13093: 
13094: =pod
13095: 
13096: =item *&assign_category_rows()
13097: 
13098: Create a datatable row for display of nested categories in a domain,
13099: with checkboxes to allow a course to be categorized,called recursively.
13100: 
13101: Inputs:
13102: 
13103: itemcount - track row number for alternating colors
13104: 
13105: cats - reference to array of arrays/hashes which encapsulates hierarchy of
13106:       categories and subcategories.
13107: 
13108: depth - current depth in hierarchy of categories and sub-categories - 0 indexed.
13109: 
13110: parent - parent of current category item
13111: 
13112: path - Array containing all categories back up through the hierarchy from the
13113:        current category to the top level.
13114: 
13115: currcategories - reference to array of current categories assigned to the course
13116: 
13117: Returns: $output (markup to be displayed).
13118: 
13119: =cut
13120: 
13121: sub assign_category_rows {
13122:     my ($itemcount,$cats,$depth,$parent,$path,$currcategories) = @_;
13123:     my ($text,$name,$item,$chgstr);
13124:     if (ref($cats) eq 'ARRAY') {
13125:         my $maxdepth = scalar(@{$cats});
13126:         if (ref($cats->[$depth]) eq 'HASH') {
13127:             if (ref($cats->[$depth]{$parent}) eq 'ARRAY') {
13128:                 my $numchildren = @{$cats->[$depth]{$parent}};
13129:                 my $css_class = $itemcount%2?' class="LC_odd_row"':'';
13130:                 $text .= '<td><table class="LC_datatable">';
13131:                 for (my $j=0; $j<$numchildren; $j++) {
13132:                     $name = $cats->[$depth]{$parent}[$j];
13133:                     $item = &escape($name).':'.&escape($parent).':'.$depth;
13134:                     my $deeper = $depth+1;
13135:                     my $checked = '';
13136:                     if (ref($currcategories) eq 'ARRAY') {
13137:                         if (@{$currcategories} > 0) {
13138:                             if (grep(/^\Q$item\E$/,@{$currcategories})) {
13139:                                 $checked = ' checked="checked"';
13140:                             }
13141:                         }
13142:                     }
13143:                     $text .= '<tr><td><span class="LC_nobreak"><label>'.
13144:                              '<input type="checkbox" name="usecategory" value="'.
13145:                              $item.'"'.$checked.' />'.$name.'</label></span>'.
13146:                              '<input type="hidden" name="catname" value="'.$name.'" />'.
13147:                              '</td><td>';
13148:                     if (ref($path) eq 'ARRAY') {
13149:                         push(@{$path},$name);
13150:                         $text .= &assign_category_rows($itemcount,$cats,$deeper,$name,$path,$currcategories);
13151:                         pop(@{$path});
13152:                     }
13153:                     $text .= '</td></tr>';
13154:                 }
13155:                 $text .= '</table></td>';
13156:             }
13157:         }
13158:     }
13159:     return $text;
13160: }
13161: 
13162: ############################################################
13163: ############################################################
13164: 
13165: 
13166: sub commit_customrole {
13167:     my ($udom,$uname,$url,$three,$four,$five,$start,$end,$context) = @_;
13168:     my $output = &mt('Assigning custom role').' "'.$five.'" by '.$four.':'.$three.' in '.$url.
13169:                          ($start?', '.&mt('starting').' '.localtime($start):'').
13170:                          ($end?', ending '.localtime($end):'').': <b>'.
13171:               &Apache::lonnet::assigncustomrole(
13172:                  $udom,$uname,$url,$three,$four,$five,$end,$start,undef,undef,$context).
13173:                  '</b><br />';
13174:     return $output;
13175: }
13176: 
13177: sub commit_standardrole {
13178:     my ($udom,$uname,$url,$three,$start,$end,$one,$two,$sec,$context) = @_;
13179:     my ($output,$logmsg,$linefeed);
13180:     if ($context eq 'auto') {
13181:         $linefeed = "\n";
13182:     } else {
13183:         $linefeed = "<br />\n";
13184:     }  
13185:     if ($three eq 'st') {
13186:         my $result = &commit_studentrole(\$logmsg,$udom,$uname,$url,$three,$start,$end,
13187:                                          $one,$two,$sec,$context);
13188:         if (($result =~ /^error/) || ($result eq 'not_in_class') || 
13189:             ($result eq 'unknown_course') || ($result eq 'refused')) {
13190:             $output = $logmsg.' '.&mt('Error: ').$result."\n"; 
13191:         } else {
13192:             $output = $logmsg.$linefeed.&mt('Assigning').' '.$three.' in '.$url.
13193:                ($start?', '.&mt('starting').' '.localtime($start):'').
13194:                ($end?', '.&mt('ending').' '.localtime($end):'').': ';
13195:             if ($context eq 'auto') {
13196:                 $output .= $result.$linefeed.&mt('Add to classlist').': ok';
13197:             } else {
13198:                $output .= '<b>'.$result.'</b>'.$linefeed.
13199:                &mt('Add to classlist').': <b>ok</b>';
13200:             }
13201:             $output .= $linefeed;
13202:         }
13203:     } else {
13204:         $output = &mt('Assigning').' '.$three.' in '.$url.
13205:                ($start?', '.&mt('starting').' '.localtime($start):'').
13206:                ($end?', '.&mt('ending').' '.localtime($end):'').': ';
13207:         my $result = &Apache::lonnet::assignrole($udom,$uname,$url,$three,$end,$start,'','',$context);
13208:         if ($context eq 'auto') {
13209:             $output .= $result.$linefeed;
13210:         } else {
13211:             $output .= '<b>'.$result.'</b>'.$linefeed;
13212:         }
13213:     }
13214:     return $output;
13215: }
13216: 
13217: sub commit_studentrole {
13218:     my ($logmsg,$udom,$uname,$url,$three,$start,$end,$one,$two,$sec,$context) = @_;
13219:     my ($result,$linefeed,$oldsecurl,$newsecurl);
13220:     if ($context eq 'auto') {
13221:         $linefeed = "\n";
13222:     } else {
13223:         $linefeed = '<br />'."\n";
13224:     }
13225:     if (defined($one) && defined($two)) {
13226:         my $cid=$one.'_'.$two;
13227:         my $oldsec=&Apache::lonnet::getsection($udom,$uname,$cid);
13228:         my $secchange = 0;
13229:         my $expire_role_result;
13230:         my $modify_section_result;
13231:         if ($oldsec ne '-1') { 
13232:             if ($oldsec ne $sec) {
13233:                 $secchange = 1;
13234:                 my $now = time;
13235:                 my $uurl='/'.$cid;
13236:                 $uurl=~s/\_/\//g;
13237:                 if ($oldsec) {
13238:                     $uurl.='/'.$oldsec;
13239:                 }
13240:                 $oldsecurl = $uurl;
13241:                 $expire_role_result = 
13242:                     &Apache::lonnet::assignrole($udom,$uname,$uurl,'st',$now,'','',$context);
13243:                 if ($env{'request.course.sec'} ne '') { 
13244:                     if ($expire_role_result eq 'refused') {
13245:                         my @roles = ('st');
13246:                         my @statuses = ('previous');
13247:                         my @roledoms = ($one);
13248:                         my $withsec = 1;
13249:                         my %roleshash = 
13250:                             &Apache::lonnet::get_my_roles($uname,$udom,'userroles',
13251:                                               \@statuses,\@roles,\@roledoms,$withsec);
13252:                         if (defined ($roleshash{$two.':'.$one.':st:'.$oldsec})) {
13253:                             my ($oldstart,$oldend) = 
13254:                                 split(':',$roleshash{$two.':'.$one.':st:'.$oldsec});
13255:                             if ($oldend > 0 && $oldend <= $now) {
13256:                                 $expire_role_result = 'ok';
13257:                             }
13258:                         }
13259:                     }
13260:                 }
13261:                 $result = $expire_role_result;
13262:             }
13263:         }
13264:         if (($expire_role_result eq 'ok') || ($secchange == 0)) {
13265:             $modify_section_result = &Apache::lonnet::modify_student_enrollment($udom,$uname,undef,undef,undef,undef,undef,$sec,$end,$start,'','',$cid,'',$context);
13266:             if ($modify_section_result =~ /^ok/) {
13267:                 if ($secchange == 1) {
13268:                     if ($sec eq '') {
13269:                         $$logmsg .= &mt('Section for [_1] switched from (possibly expired) old section: [_2] to student role without a section.',$uname,$oldsec).$linefeed;
13270:                     } else {
13271:                         $$logmsg .= &mt('Section for [_1] switched from (possibly expired) old section: [_2] to new section: [_3].',$uname,$oldsec,$sec).$linefeed;
13272:                     }
13273:                 } elsif ($oldsec eq '-1') {
13274:                     if ($sec eq '') {
13275:                         $$logmsg .= &mt('New student role without a section for [_1] in course [_2].',$uname,$cid).$linefeed;
13276:                     } else {
13277:                         $$logmsg .= &mt('New student role for [_1] in section [_2] in course [_3].',$uname,$sec,$cid).$linefeed;
13278:                     }
13279:                 } else {
13280:                     if ($sec eq '') {
13281:                         $$logmsg .= &mt('Student [_1] assigned to course [_2] without a section.',$uname,$cid).$linefeed;
13282:                     } else {
13283:                         $$logmsg .= &mt('Student [_1] assigned to section [_2] in course [_3].',$uname,$sec,$cid).$linefeed;
13284:                     }
13285:                 }
13286:             } else {
13287:                 if ($secchange) {       
13288:                     $$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;
13289:                 } else {
13290:                     $$logmsg .= &mt('Error when attempting to modify role for [_1] for section: "[_2]" in course [_3] -error:',$uname,$sec,$cid).' '.$modify_section_result.$linefeed;
13291:                 }
13292:             }
13293:             $result = $modify_section_result;
13294:         } elsif ($secchange == 1) {
13295:             if ($oldsec eq '') {
13296:                 $$logmsg .= &mt('Error when attempting to expire existing role without a section for [_1] in course [_2] -error: ',$uname,$cid).' '.$expire_role_result.$linefeed;
13297:             } else {
13298:                 $$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;
13299:             }
13300:             if ($expire_role_result eq 'refused') {
13301:                 my $newsecurl = '/'.$cid;
13302:                 $newsecurl =~ s/\_/\//g;
13303:                 if ($sec ne '') {
13304:                     $newsecurl.='/'.$sec;
13305:                 }
13306:                 if (&Apache::lonnet::allowed('cst',$newsecurl) && !(&Apache::lonnet::allowed('cst',$oldsecurl))) {
13307:                     if ($sec eq '') {
13308:                         $$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;
13309:                     } else {
13310:                         $$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;
13311:                     }
13312:                 }
13313:             }
13314:         }
13315:     } else {
13316:         $$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;
13317:         $result = "error: incomplete course id\n";
13318:     }
13319:     return $result;
13320: }
13321: 
13322: sub show_role_extent {
13323:     my ($scope,$context,$role) = @_;
13324:     $scope =~ s{^/}{};
13325:     my @courseroles = &Apache::lonuserutils::roles_by_context('course',1);
13326:     push(@courseroles,'co');
13327:     my @authorroles = &Apache::lonuserutils::roles_by_context('author');
13328:     if (($context eq 'course') || (grep(/^\Q$role\E/,@courseroles))) {
13329:         $scope =~ s{/}{_};
13330:         return '<span class="LC_cusr_emph">'.$env{'course.'.$scope.'.description'}.'</span>';
13331:     } elsif (($context eq 'author') || (grep(/^\Q$role\E/,@authorroles))) {
13332:         my ($audom,$auname) = split(/\//,$scope);
13333:         return &mt('[_1] Author Space','<span class="LC_cusr_emph">'.
13334:                    &Apache::loncommon::plainname($auname,$audom).'</span>');
13335:     } else {
13336:         $scope =~ s{/$}{};
13337:         return &mt('Domain: [_1]','<span class="LC_cusr_emph">'.
13338:                    &Apache::lonnet::domain($scope,'description').'</span>');
13339:     }
13340: }
13341: 
13342: ############################################################
13343: ############################################################
13344: 
13345: sub check_clone {
13346:     my ($args,$linefeed) = @_;
13347:     my $cloneid='/'.$args->{'clonedomain'}.'/'.$args->{'clonecourse'};
13348:     my ($clonecrsudom,$clonecrsunum)= &LONCAPA::split_courseid($cloneid);
13349:     my $clonehome=&Apache::lonnet::homeserver($clonecrsunum,$clonecrsudom);
13350:     my $clonemsg;
13351:     my $can_clone = 0;
13352:     my $lctype = lc($args->{'crstype'});
13353:     if ($lctype ne 'community') {
13354:         $lctype = 'course';
13355:     }
13356:     if ($clonehome eq 'no_host') {
13357:         if ($args->{'crstype'} eq 'Community') {
13358:             $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'});
13359:         } else {
13360:             $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'});
13361:         }     
13362:     } else {
13363: 	my %clonedesc = &Apache::lonnet::coursedescription($cloneid,{'one_time' => 1});
13364:         if ($args->{'crstype'} eq 'Community') {
13365:             if ($clonedesc{'type'} ne 'Community') {
13366:                  $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'});
13367:                 return ($can_clone, $clonemsg, $cloneid, $clonehome);
13368:             }
13369:         }
13370: 	if (($env{'request.role.domain'} eq $args->{'clonedomain'}) && 
13371:             (&Apache::lonnet::allowed('ccc',$env{'request.role.domain'}))) {
13372: 	    $can_clone = 1;
13373: 	} else {
13374: 	    my %clonehash = &Apache::lonnet::get('environment',['cloners'],
13375: 						 $args->{'clonedomain'},$args->{'clonecourse'});
13376: 	    my @cloners = split(/,/,$clonehash{'cloners'});
13377:             if (grep(/^\*$/,@cloners)) {
13378:                 $can_clone = 1;
13379:             } elsif (grep(/^\*\:\Q$args->{'ccdomain'}\E$/,@cloners)) {
13380:                 $can_clone = 1;
13381:             } else {
13382:                 my $ccrole = 'cc';
13383:                 if ($args->{'crstype'} eq 'Community') {
13384:                     $ccrole = 'co';
13385:                 }
13386: 	        my %roleshash =
13387: 		    &Apache::lonnet::get_my_roles($args->{'ccuname'},
13388: 					 $args->{'ccdomain'},
13389:                                          'userroles',['active'],[$ccrole],
13390: 					 [$args->{'clonedomain'}]);
13391: 	        if (($roleshash{$args->{'clonecourse'}.':'.$args->{'clonedomain'}.':'.$ccrole}) || (grep(/^\Q$args->{'ccuname'}\E:\Q$args->{'ccdomain'}\E$/,@cloners))) {
13392:                     $can_clone = 1;
13393:                 } elsif (&Apache::lonnet::is_course_owner($args->{'clonedomain'},$args->{'clonecourse'},$args->{'ccuname'},$args->{'ccdomain'})) {
13394:                     $can_clone = 1;
13395:                 } else {
13396:                     if ($args->{'crstype'} eq 'Community') {
13397:                         $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'});
13398:                     } else {
13399:                         $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'});
13400:                     }
13401: 	        }
13402: 	    }
13403:         }
13404:     }
13405:     return ($can_clone, $clonemsg, $cloneid, $clonehome);
13406: }
13407: 
13408: sub construct_course {
13409:     my ($args,$logmsg,$courseid,$crsudom,$crsunum,$udom,$uname,$context,$cnum,$category) = @_;
13410:     my $outcome;
13411:     my $linefeed =  '<br />'."\n";
13412:     if ($context eq 'auto') {
13413:         $linefeed = "\n";
13414:     }
13415: 
13416: #
13417: # Are we cloning?
13418: #
13419:     my ($can_clone, $clonemsg, $cloneid, $clonehome);
13420:     if (($args->{'clonecourse'}) && ($args->{'clonedomain'})) {
13421: 	($can_clone, $clonemsg, $cloneid, $clonehome) = &check_clone($args,$linefeed);
13422: 	if ($context ne 'auto') {
13423:             if ($clonemsg ne '') {
13424: 	        $clonemsg = '<span class="LC_error">'.$clonemsg.'</span>';
13425:             }
13426: 	}
13427: 	$outcome .= $clonemsg.$linefeed;
13428: 
13429:         if (!$can_clone) {
13430: 	    return (0,$outcome);
13431: 	}
13432:     }
13433: 
13434: #
13435: # Open course
13436: #
13437:     my $crstype = lc($args->{'crstype'});
13438:     my %cenv=();
13439:     $$courseid=&Apache::lonnet::createcourse($args->{'course_domain'},
13440:                                              $args->{'cdescr'},
13441:                                              $args->{'curl'},
13442:                                              $args->{'course_home'},
13443:                                              $args->{'nonstandard'},
13444:                                              $args->{'crscode'},
13445:                                              $args->{'ccuname'}.':'.
13446:                                              $args->{'ccdomain'},
13447:                                              $args->{'crstype'},
13448:                                              $cnum,$context,$category);
13449: 
13450:     # Note: The testing routines depend on this being output; see 
13451:     # Utils::Course. This needs to at least be output as a comment
13452:     # if anyone ever decides to not show this, and Utils::Course::new
13453:     # will need to be suitably modified.
13454:     $outcome .= &mt('New LON-CAPA [_1] ID: [_2]',$crstype,$$courseid).$linefeed;
13455:     if ($$courseid =~ /^error:/) {
13456:         return (0,$outcome);
13457:     }
13458: 
13459: #
13460: # Check if created correctly
13461: #
13462:     ($$crsudom,$$crsunum)= &LONCAPA::split_courseid($$courseid);
13463:     my $crsuhome=&Apache::lonnet::homeserver($$crsunum,$$crsudom);
13464:     if ($crsuhome eq 'no_host') {
13465:         $outcome .= &mt('Course creation failed, unrecognized course home server.').$linefeed;
13466:         return (0,$outcome);
13467:     }
13468:     $outcome .= &mt('Created on').': '.$crsuhome.$linefeed;
13469: 
13470: #
13471: # Do the cloning
13472: #   
13473:     if ($can_clone && $cloneid) {
13474: 	$clonemsg = &mt('Cloning [_1] from [_2]',$crstype,$clonehome);
13475: 	if ($context ne 'auto') {
13476: 	    $clonemsg = '<span class="LC_success">'.$clonemsg.'</span>';
13477: 	}
13478: 	$outcome .= $clonemsg.$linefeed;
13479: 	my %oldcenv=&Apache::lonnet::dump('environment',$$crsudom,$$crsunum);
13480: # Copy all files
13481: 	&Apache::lonclonecourse::copycoursefiles($cloneid,$$courseid,$args->{'datemode'},$args->{'dateshift'});
13482: # Restore URL
13483: 	$cenv{'url'}=$oldcenv{'url'};
13484: # Restore title
13485: 	$cenv{'description'}=$oldcenv{'description'};
13486: # Restore creation date, creator and creation context.
13487:         $cenv{'internal.created'}=$oldcenv{'internal.created'};
13488:         $cenv{'internal.creator'}=$oldcenv{'internal.creator'};
13489:         $cenv{'internal.creationcontext'}=$oldcenv{'internal.creationcontext'};
13490: # Mark as cloned
13491: 	$cenv{'clonedfrom'}=$cloneid;
13492: # Need to clone grading mode
13493:         my %newenv=&Apache::lonnet::get('environment',['grading'],$$crsudom,$$crsunum);
13494:         $cenv{'grading'}=$newenv{'grading'};
13495: # Do not clone these environment entries
13496:         &Apache::lonnet::del('environment',
13497:                   ['default_enrollment_start_date',
13498:                    'default_enrollment_end_date',
13499:                    'question.email',
13500:                    'policy.email',
13501:                    'comment.email',
13502:                    'pch.users.denied',
13503:                    'plc.users.denied',
13504:                    'hidefromcat',
13505:                    'categories'],
13506:                    $$crsudom,$$crsunum);
13507:     }
13508: 
13509: #
13510: # Set environment (will override cloned, if existing)
13511: #
13512:     my @sections = ();
13513:     my @xlists = ();
13514:     if ($args->{'crstype'}) {
13515:         $cenv{'type'}=$args->{'crstype'};
13516:     }
13517:     if ($args->{'crsid'}) {
13518:         $cenv{'courseid'}=$args->{'crsid'};
13519:     }
13520:     if ($args->{'crscode'}) {
13521:         $cenv{'internal.coursecode'}=$args->{'crscode'};
13522:     }
13523:     if ($args->{'crsquota'} ne '') {
13524:         $cenv{'internal.coursequota'}=$args->{'crsquota'};
13525:     } else {
13526:         $cenv{'internal.coursequota'}=$args->{'crsquota'} = 20;
13527:     }
13528:     if ($args->{'ccuname'}) {
13529:         $cenv{'internal.courseowner'} = $args->{'ccuname'}.
13530:                                         ':'.$args->{'ccdomain'};
13531:     } else {
13532:         $cenv{'internal.courseowner'} = $args->{'curruser'};
13533:     }
13534:     my @badclasses = (); # Used to accumulate sections/crosslistings that did not pass classlist access check for course owner.
13535:     if ($args->{'crssections'}) {
13536:         $cenv{'internal.sectionnums'} = '';
13537:         if ($args->{'crssections'} =~ m/,/) {
13538:             @sections = split/,/,$args->{'crssections'};
13539:         } else {
13540:             $sections[0] = $args->{'crssections'};
13541:         }
13542:         if (@sections > 0) {
13543:             foreach my $item (@sections) {
13544:                 my ($sec,$gp) = split/:/,$item;
13545:                 my $class = $args->{'crscode'}.$sec;
13546:                 my $addcheck = &Apache::lonnet::auto_new_course($$crsunum,$$crsudom,$class,$cenv{'internal.courseowner'});
13547:                 $cenv{'internal.sectionnums'} .= $item.',';
13548:                 unless ($addcheck eq 'ok') {
13549:                     push @badclasses, $class;
13550:                 }
13551:             }
13552:             $cenv{'internal.sectionnums'} =~ s/,$//;
13553:         }
13554:     }
13555: # do not hide course coordinator from staff listing, 
13556: # even if privileged
13557:     $cenv{'nothideprivileged'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
13558: # add crosslistings
13559:     if ($args->{'crsxlist'}) {
13560:         $cenv{'internal.crosslistings'}='';
13561:         if ($args->{'crsxlist'} =~ m/,/) {
13562:             @xlists = split/,/,$args->{'crsxlist'};
13563:         } else {
13564:             $xlists[0] = $args->{'crsxlist'};
13565:         }
13566:         if (@xlists > 0) {
13567:             foreach my $item (@xlists) {
13568:                 my ($xl,$gp) = split/:/,$item;
13569:                 my $addcheck =  &Apache::lonnet::auto_new_course($$crsunum,$$crsudom,$xl,$cenv{'internal.courseowner'});
13570:                 $cenv{'internal.crosslistings'} .= $item.',';
13571:                 unless ($addcheck eq 'ok') {
13572:                     push @badclasses, $xl;
13573:                 }
13574:             }
13575:             $cenv{'internal.crosslistings'} =~ s/,$//;
13576:         }
13577:     }
13578:     if ($args->{'autoadds'}) {
13579:         $cenv{'internal.autoadds'}=$args->{'autoadds'};
13580:     }
13581:     if ($args->{'autodrops'}) {
13582:         $cenv{'internal.autodrops'}=$args->{'autodrops'};
13583:     }
13584: # check for notification of enrollment changes
13585:     my @notified = ();
13586:     if ($args->{'notify_owner'}) {
13587:         if ($args->{'ccuname'} ne '') {
13588:             push(@notified,$args->{'ccuname'}.':'.$args->{'ccdomain'});
13589:         }
13590:     }
13591:     if ($args->{'notify_dc'}) {
13592:         if ($uname ne '') { 
13593:             push(@notified,$uname.':'.$udom);
13594:         }
13595:     }
13596:     if (@notified > 0) {
13597:         my $notifylist;
13598:         if (@notified > 1) {
13599:             $notifylist = join(',',@notified);
13600:         } else {
13601:             $notifylist = $notified[0];
13602:         }
13603:         $cenv{'internal.notifylist'} = $notifylist;
13604:     }
13605:     if (@badclasses > 0) {
13606:         my %lt=&Apache::lonlocal::texthash(
13607:                 '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',
13608:                 'dnhr' => 'does not have rights to access enrollment in these classes',
13609:                 'adby' => 'as determined by the policies of your institution on access to official classlists'
13610:         );
13611:         my $badclass_msg = $cenv{'internal.courseowner'}.') - '.$lt{'dnhr'}.
13612:                            ' ('.$lt{'adby'}.')';
13613:         if ($context eq 'auto') {
13614:             $outcome .= $badclass_msg.$linefeed;
13615:             $outcome .= '<div class="LC_warning">'.$badclass_msg.$linefeed.'<ul>'."\n";
13616:             foreach my $item (@badclasses) {
13617:                 if ($context eq 'auto') {
13618:                     $outcome .= " - $item\n";
13619:                 } else {
13620:                     $outcome .= "<li>$item</li>\n";
13621:                 }
13622:             }
13623:             if ($context eq 'auto') {
13624:                 $outcome .= $linefeed;
13625:             } else {
13626:                 $outcome .= "</ul><br /><br /></div>\n";
13627:             }
13628:         } 
13629:     }
13630:     if ($args->{'no_end_date'}) {
13631:         $args->{'endaccess'} = 0;
13632:     }
13633:     $cenv{'internal.autostart'}=$args->{'enrollstart'};
13634:     $cenv{'internal.autoend'}=$args->{'enrollend'};
13635:     $cenv{'default_enrollment_start_date'}=$args->{'startaccess'};
13636:     $cenv{'default_enrollment_end_date'}=$args->{'endaccess'};
13637:     if ($args->{'showphotos'}) {
13638:       $cenv{'internal.showphotos'}=$args->{'showphotos'};
13639:     }
13640:     $cenv{'internal.authtype'} = $args->{'authtype'};
13641:     $cenv{'internal.autharg'} = $args->{'autharg'}; 
13642:     if ( ($cenv{'internal.authtype'} =~ /^krb/) && ($cenv{'internal.autoadds'} == 1)) {
13643:         if (! defined($cenv{'internal.autharg'}) || $cenv{'internal.autharg'}  eq '') {
13644:             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'); 
13645:             if ($context eq 'auto') {
13646:                 $outcome .= $krb_msg;
13647:             } else {
13648:                 $outcome .= '<span class="LC_error">'.$krb_msg.'</span>';
13649:             }
13650:             $outcome .= $linefeed;
13651:         }
13652:     }
13653:     if (($args->{'ccdomain'}) && ($args->{'ccuname'})) {
13654:        if ($args->{'setpolicy'}) {
13655:            $cenv{'policy.email'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
13656:        }
13657:        if ($args->{'setcontent'}) {
13658:            $cenv{'question.email'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
13659:        }
13660:     }
13661:     if ($args->{'reshome'}) {
13662: 	$cenv{'reshome'}=$args->{'reshome'}.'/';
13663: 	$cenv{'reshome'}=~s/\/+$/\//;
13664:     }
13665: #
13666: # course has keyed access
13667: #
13668:     if ($args->{'setkeys'}) {
13669:        $cenv{'keyaccess'}='yes';
13670:     }
13671: # if specified, key authority is not course, but user
13672: # only active if keyaccess is yes
13673:     if ($args->{'keyauth'}) {
13674: 	my ($user,$domain) = split(':',$args->{'keyauth'});
13675: 	$user = &LONCAPA::clean_username($user);
13676: 	$domain = &LONCAPA::clean_username($domain);
13677: 	if ($user ne '' && $domain ne '') {
13678: 	    $cenv{'keyauth'}=$user.':'.$domain;
13679: 	}
13680:     }
13681: 
13682:     if ($args->{'disresdis'}) {
13683:         $cenv{'pch.roles.denied'}='st';
13684:     }
13685:     if ($args->{'disablechat'}) {
13686:         $cenv{'plc.roles.denied'}='st';
13687:     }
13688: 
13689:     # Record we've not yet viewed the Course Initialization Helper for this 
13690:     # course
13691:     $cenv{'course.helper.not.run'} = 1;
13692:     #
13693:     # Use new Randomseed
13694:     #
13695:     $cenv{'rndseed'}=&Apache::lonnet::latest_rnd_algorithm_id();;
13696:     $cenv{'receiptalg'}=&Apache::lonnet::latest_receipt_algorithm_id();;
13697:     #
13698:     # The encryption code and receipt prefix for this course
13699:     #
13700:     $cenv{'internal.encseed'}=$Apache::lonnet::perlvar{'lonReceipt'}.$$.time.int(rand(9999));
13701:     $cenv{'internal.encpref'}=100+int(9*rand(99));
13702:     #
13703:     # By default, use standard grading
13704:     if (!defined($cenv{'grading'})) { $cenv{'grading'} = 'standard'; }
13705: 
13706:     $outcome .= $linefeed.&mt('Setting environment').': '.                 
13707:           &Apache::lonnet::put('environment',\%cenv,$$crsudom,$$crsunum).$linefeed;
13708: #
13709: # Open all assignments
13710: #
13711:     if ($args->{'openall'}) {
13712:        my $storeunder=$$crsudom.'_'.$$crsunum.'.0.opendate';
13713:        my %storecontent = ($storeunder         => time,
13714:                            $storeunder.'.type' => 'date_start');
13715:        
13716:        $outcome .= &mt('Opening all assignments').': '.&Apache::lonnet::cput
13717:                  ('resourcedata',\%storecontent,$$crsudom,$$crsunum).$linefeed;
13718:    }
13719: #
13720: # Set first page
13721: #
13722:     unless (($args->{'nonstandard'}) || ($args->{'firstres'} eq 'blank')
13723: 	    || ($cloneid)) {
13724: 	use LONCAPA::map;
13725: 	$outcome .= &mt('Setting first resource').': ';
13726: 
13727: 	my $map = '/uploaded/'.$$crsudom.'/'.$$crsunum.'/default.sequence';
13728:         my ($errtext,$fatal)=&LONCAPA::map::mapread($map);
13729: 
13730:         $outcome .= ($fatal?$errtext:'read ok').' - ';
13731:         my $title; my $url;
13732:         if ($args->{'firstres'} eq 'syl') {
13733: 	    $title=&mt('Syllabus');
13734:             $url='/public/'.$$crsudom.'/'.$$crsunum.'/syllabus';
13735:         } else {
13736:             $title=&mt('Table of Contents');
13737:             $url='/adm/navmaps';
13738:         }
13739: 
13740:         $LONCAPA::map::resources[1]=$title.':'.$url.':false:start:res';
13741: 	(my $outtext,$errtext) = &LONCAPA::map::storemap($map,1);
13742: 
13743: 	if ($errtext) { $fatal=2; }
13744:         $outcome .= ($fatal?$errtext:'write ok').$linefeed;
13745:     }
13746: 
13747:     return (1,$outcome);
13748: }
13749: 
13750: ############################################################
13751: ############################################################
13752: 
13753: #SD
13754: # only Community and Course, or anything else?
13755: sub course_type {
13756:     my ($cid) = @_;
13757:     if (!defined($cid)) {
13758:         $cid = $env{'request.course.id'};
13759:     }
13760:     if (defined($env{'course.'.$cid.'.type'})) {
13761:         return $env{'course.'.$cid.'.type'};
13762:     } else {
13763:         return 'Course';
13764:     }
13765: }
13766: 
13767: sub group_term {
13768:     my $crstype = &course_type();
13769:     my %names = (
13770:                   'Course' => 'group',
13771:                   'Community' => 'group',
13772:                 );
13773:     return $names{$crstype};
13774: }
13775: 
13776: sub course_types {
13777:     my @types = ('official','unofficial','community');
13778:     my %typename = (
13779:                          official   => 'Official course',
13780:                          unofficial => 'Unofficial course',
13781:                          community  => 'Community',
13782:                    );
13783:     return (\@types,\%typename);
13784: }
13785: 
13786: sub icon {
13787:     my ($file)=@_;
13788:     my $curfext = lc((split(/\./,$file))[-1]);
13789:     my $iconname=$Apache::lonnet::perlvar{'lonIconsURL'}.'/unknown.gif';
13790:     my $embstyle = &Apache::loncommon::fileembstyle($curfext);
13791:     if (!(!defined($embstyle) || $embstyle eq 'unk' || $embstyle eq 'hdn')) {
13792: 	if (-e  $Apache::lonnet::perlvar{'lonDocRoot'}.'/'.
13793: 	          $Apache::lonnet::perlvar{'lonIconsURL'}.'/'.
13794: 	            $curfext.".gif") {
13795: 	    $iconname=$Apache::lonnet::perlvar{'lonIconsURL'}.'/'.
13796: 		$curfext.".gif";
13797: 	}
13798:     }
13799:     return &lonhttpdurl($iconname);
13800: } 
13801: 
13802: sub lonhttpdurl {
13803: #
13804: # Had been used for "small fry" static images on separate port 8080.
13805: # Modify here if lightweight http functionality desired again.
13806: # Currently eliminated due to increasing firewall issues.
13807: #
13808:     my ($url)=@_;
13809:     return $url;
13810: }
13811: 
13812: sub connection_aborted {
13813:     my ($r)=@_;
13814:     $r->print(" ");$r->rflush();
13815:     my $c = $r->connection;
13816:     return $c->aborted();
13817: }
13818: 
13819: #    Escapes strings that may have embedded 's that will be put into
13820: #    strings as 'strings'.
13821: sub escape_single {
13822:     my ($input) = @_;
13823:     $input =~ s/\\/\\\\/g;	# Escape the \'s..(must be first)>
13824:     $input =~ s/\'/\\\'/g;	# Esacpe the 's....
13825:     return $input;
13826: }
13827: 
13828: #  Same as escape_single, but escape's "'s  This 
13829: #  can be used for  "strings"
13830: sub escape_double {
13831:     my ($input) = @_;
13832:     $input =~ s/\\/\\\\/g;	# Escape the /'s..(must be first)>
13833:     $input =~ s/\"/\\\"/g;	# Esacpe the "s....
13834:     return $input;
13835: }
13836:  
13837: #   Escapes the last element of a full URL.
13838: sub escape_url {
13839:     my ($url)   = @_;
13840:     my @urlslices = split(/\//, $url,-1);
13841:     my $lastitem = &escape(pop(@urlslices));
13842:     return join('/',@urlslices).'/'.$lastitem;
13843: }
13844: 
13845: sub compare_arrays {
13846:     my ($arrayref1,$arrayref2) = @_;
13847:     my (@difference,%count);
13848:     @difference = ();
13849:     %count = ();
13850:     if ((ref($arrayref1) eq 'ARRAY') && (ref($arrayref2) eq 'ARRAY')) {
13851:         foreach my $element (@{$arrayref1}, @{$arrayref2}) { $count{$element}++; }
13852:         foreach my $element (keys(%count)) {
13853:             if ($count{$element} == 1) {
13854:                 push(@difference,$element);
13855:             }
13856:         }
13857:     }
13858:     return @difference;
13859: }
13860: 
13861: # -------------------------------------------------------- Initialize user login
13862: sub init_user_environment {
13863:     my ($r, $username, $domain, $authhost, $form, $args) = @_;
13864:     my $lonids=$Apache::lonnet::perlvar{'lonIDsDir'};
13865: 
13866:     my $public=($username eq 'public' && $domain eq 'public');
13867: 
13868: # See if old ID present, if so, remove
13869: 
13870:     my ($filename,$cookie,$userroles,$firstaccenv,$timerintenv);
13871:     my $now=time;
13872: 
13873:     if ($public) {
13874: 	my $max_public=100;
13875: 	my $oldest;
13876: 	my $oldest_time=0;
13877: 	for(my $next=1;$next<=$max_public;$next++) {
13878: 	    if (-e $lonids."/publicuser_$next.id") {
13879: 		my $mtime=(stat($lonids."/publicuser_$next.id"))[9];
13880: 		if ($mtime<$oldest_time || !$oldest_time) {
13881: 		    $oldest_time=$mtime;
13882: 		    $oldest=$next;
13883: 		}
13884: 	    } else {
13885: 		$cookie="publicuser_$next";
13886: 		last;
13887: 	    }
13888: 	}
13889: 	if (!$cookie) { $cookie="publicuser_$oldest"; }
13890:     } else {
13891: 	# if this isn't a robot, kill any existing non-robot sessions
13892: 	if (!$args->{'robot'}) {
13893: 	    opendir(DIR,$lonids);
13894: 	    while ($filename=readdir(DIR)) {
13895: 		if ($filename=~/^$username\_\d+\_$domain\_$authhost\.id$/) {
13896: 		    unlink($lonids.'/'.$filename);
13897: 		}
13898: 	    }
13899: 	    closedir(DIR);
13900: 	}
13901: # Give them a new cookie
13902: 	my $id = ($args->{'robot'} ? 'robot'.$args->{'robot'}
13903: 		                   : $now.$$.int(rand(10000)));
13904: 	$cookie="$username\_$id\_$domain\_$authhost";
13905:     
13906: # Initialize roles
13907: 
13908: 	($userroles,$firstaccenv,$timerintenv) = 
13909:             &Apache::lonnet::rolesinit($domain,$username,$authhost);
13910:     }
13911: # ------------------------------------ Check browser type and MathML capability
13912: 
13913:     my ($httpbrowser,$clientbrowser,$clientversion,$clientmathml,
13914:         $clientunicode,$clientos) = &decode_user_agent($r);
13915: 
13916: # ------------------------------------------------------------- Get environment
13917: 
13918:     my %userenv = &Apache::lonnet::dump('environment',$domain,$username);
13919:     my ($tmp) = keys(%userenv);
13920:     if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
13921:     } else {
13922: 	undef(%userenv);
13923:     }
13924:     if (($userenv{'interface'}) && (!$form->{'interface'})) {
13925: 	$form->{'interface'}=$userenv{'interface'};
13926:     }
13927:     if ($userenv{'texengine'} eq 'ttm') { $clientmathml=1; }
13928: 
13929: # --------------- Do not trust query string to be put directly into environment
13930:     foreach my $option ('interface','localpath','localres') {
13931:         $form->{$option}=~s/[\n\r\=]//gs;
13932:     }
13933: # --------------------------------------------------------- Write first profile
13934: 
13935:     {
13936: 	my %initial_env = 
13937: 	    ("user.name"          => $username,
13938: 	     "user.domain"        => $domain,
13939: 	     "user.home"          => $authhost,
13940: 	     "browser.type"       => $clientbrowser,
13941: 	     "browser.version"    => $clientversion,
13942: 	     "browser.mathml"     => $clientmathml,
13943: 	     "browser.unicode"    => $clientunicode,
13944: 	     "browser.os"         => $clientos,
13945: 	     "server.domain"      => $Apache::lonnet::perlvar{'lonDefDomain'},
13946: 	     "request.course.fn"  => '',
13947: 	     "request.course.uri" => '',
13948: 	     "request.course.sec" => '',
13949: 	     "request.role"       => 'cm',
13950: 	     "request.role.adv"   => $env{'user.adv'},
13951: 	     "request.host"       => $ENV{'REMOTE_ADDR'},);
13952: 
13953:         if ($form->{'localpath'}) {
13954: 	    $initial_env{"browser.localpath"}  = $form->{'localpath'};
13955: 	    $initial_env{"browser.localres"}   = $form->{'localres'};
13956:         }
13957: 	
13958: 	if ($form->{'interface'}) {
13959: 	    $form->{'interface'}=~s/\W//gs;
13960: 	    $initial_env{"browser.interface"} = $form->{'interface'};
13961: 	    $env{'browser.interface'}=$form->{'interface'};
13962: 	}
13963: 
13964:         my %is_adv = ( is_adv => $env{'user.adv'} );
13965:         my %domdef;
13966:         unless ($domain eq 'public') {
13967:             %domdef = &Apache::lonnet::get_domain_defaults($domain);
13968:         }
13969: 
13970:         foreach my $tool ('aboutme','blog','webdav','portfolio') {
13971:             $userenv{'availabletools.'.$tool} = 
13972:                 &Apache::lonnet::usertools_access($username,$domain,$tool,'reload',
13973:                                                   undef,\%userenv,\%domdef,\%is_adv);
13974:         }
13975: 
13976:         foreach my $crstype ('official','unofficial','community') {
13977:             $userenv{'canrequest.'.$crstype} =
13978:                 &Apache::lonnet::usertools_access($username,$domain,$crstype,
13979:                                                   'reload','requestcourses',
13980:                                                   \%userenv,\%domdef,\%is_adv);
13981:         }
13982: 
13983:         $userenv{'canrequest.author'} =
13984:             &Apache::lonnet::usertools_access($username,$domain,'requestauthor',
13985:                                         'reload','requestauthor',
13986:                                         \%userenv,\%domdef,\%is_adv);
13987:         my %reqauthor = &Apache::lonnet::get('requestauthor',['author_status','author'],
13988:                                              $domain,$username);
13989:         my $reqstatus = $reqauthor{'author_status'};
13990:         if ($reqstatus eq 'approval' || $reqstatus eq 'approved') { 
13991:             if (ref($reqauthor{'author'}) eq 'HASH') {
13992:                 $userenv{'requestauthorqueued'} = $reqstatus.':'.
13993:                                                   $reqauthor{'author'}{'timestamp'};
13994:             }
13995:         }
13996: 
13997: 	$env{'user.environment'} = "$lonids/$cookie.id";
13998: 
13999: 	if (tie(my %disk_env,'GDBM_File',"$lonids/$cookie.id",
14000: 		 &GDBM_WRCREAT(),0640)) {
14001: 	    &_add_to_env(\%disk_env,\%initial_env);
14002: 	    &_add_to_env(\%disk_env,\%userenv,'environment.');
14003: 	    &_add_to_env(\%disk_env,$userroles);
14004:             if (ref($firstaccenv) eq 'HASH') {
14005:                 &_add_to_env(\%disk_env,$firstaccenv);
14006:             }
14007:             if (ref($timerintenv) eq 'HASH') {
14008:                 &_add_to_env(\%disk_env,$timerintenv);
14009:             }
14010: 	    if (ref($args->{'extra_env'})) {
14011: 		&_add_to_env(\%disk_env,$args->{'extra_env'});
14012: 	    }
14013: 	    untie(%disk_env);
14014: 	} else {
14015: 	    &Apache::lonnet::logthis("<span style=\"color:blue;\">WARNING: ".
14016: 			   'Could not create environment storage in lonauth: '.$!.'</span>');
14017: 	    return 'error: '.$!;
14018: 	}
14019:     }
14020:     $env{'request.role'}='cm';
14021:     $env{'request.role.adv'}=$env{'user.adv'};
14022:     $env{'browser.type'}=$clientbrowser;
14023: 
14024:     return $cookie;
14025: 
14026: }
14027: 
14028: sub _add_to_env {
14029:     my ($idf,$env_data,$prefix) = @_;
14030:     if (ref($env_data) eq 'HASH') {
14031:         while (my ($key,$value) = each(%$env_data)) {
14032: 	    $idf->{$prefix.$key} = $value;
14033: 	    $env{$prefix.$key}   = $value;
14034:         }
14035:     }
14036: }
14037: 
14038: # --- Get the symbolic name of a problem and the url
14039: sub get_symb {
14040:     my ($request,$silent) = @_;
14041:     (my $url=$env{'form.url'}) =~ s-^https?\://($ENV{'SERVER_NAME'}|$ENV{'HTTP_HOST'})--;
14042:     my $symb=($env{'form.symb'} ne '' ? $env{'form.symb'} : (&Apache::lonnet::symbread($url)));
14043:     if ($symb eq '') {
14044:         if (!$silent) {
14045:             if (ref($request)) { 
14046:                 $request->print("Unable to handle ambiguous references:$url:.");
14047:             }
14048:             return ();
14049:         }
14050:     }
14051:     &Apache::lonenc::check_decrypt(\$symb);
14052:     return ($symb);
14053: }
14054: 
14055: # --------------------------------------------------------------Get annotation
14056: 
14057: sub get_annotation {
14058:     my ($symb,$enc) = @_;
14059: 
14060:     my $key = $symb;
14061:     if (!$enc) {
14062:         $key =
14063:             &Apache::lonnet::clutter((&Apache::lonnet::decode_symb($symb))[2]);
14064:     }
14065:     my %annotation=&Apache::lonnet::get('nohist_annotations',[$key]);
14066:     return $annotation{$key};
14067: }
14068: 
14069: sub clean_symb {
14070:     my ($symb,$delete_enc) = @_;
14071: 
14072:     &Apache::lonenc::check_decrypt(\$symb);
14073:     my $enc = $env{'request.enc'};
14074:     if ($delete_enc) {
14075:         delete($env{'request.enc'});
14076:     }
14077: 
14078:     return ($symb,$enc);
14079: }
14080: 
14081: sub build_release_hashes {
14082:     my ($checkparms,$checkresponsetypes,$checkcrstypes,$anonsurvey,$randomizetry) = @_;
14083:     return unless((ref($checkparms) eq 'HASH') && (ref($checkresponsetypes) eq 'HASH') &&
14084:                   (ref($checkcrstypes) eq 'HASH') && (ref($anonsurvey) eq 'HASH') &&
14085:                   (ref($randomizetry) eq 'HASH'));
14086:     foreach my $key (keys(%Apache::lonnet::needsrelease)) {
14087:         my ($item,$name,$value) = split(/:/,$key);
14088:         if ($item eq 'parameter') {
14089:             if (ref($checkparms->{$name}) eq 'ARRAY') {
14090:                 unless(grep(/^\Q$name\E$/,@{$checkparms->{$name}})) {
14091:                     push(@{$checkparms->{$name}},$value);
14092:                 }
14093:             } else {
14094:                 push(@{$checkparms->{$name}},$value);
14095:             }
14096:         } elsif ($item eq 'resourcetag') {
14097:             if ($name eq 'responsetype') {
14098:                 $checkresponsetypes->{$value} = $Apache::lonnet::needsrelease{$key}
14099:             }
14100:         } elsif ($item eq 'course') {
14101:             if ($name eq 'crstype') {
14102:                 $checkcrstypes->{$value} = $Apache::lonnet::needsrelease{$key};
14103:             }
14104:         }
14105:     }
14106:     ($anonsurvey->{major},$anonsurvey->{minor}) = split(/\./,$Apache::lonnet::needsrelease{'parameter:type:anonsurvey'});
14107:     ($randomizetry->{major},$randomizetry->{minor}) = split(/\./,$Apache::lonnet::needsrelease{'parameter:type:randomizetry'});
14108:     return;
14109: }
14110: 
14111: sub update_content_constraints {
14112:     my ($cdom,$cnum,$chome,$cid) = @_;
14113:     my %curr_reqd_hash = &Apache::lonnet::userenvironment($cdom,$cnum,'internal.releaserequired');
14114:     my ($reqdmajor,$reqdminor) = split(/\./,$curr_reqd_hash{'internal.releaserequired'});
14115:     my %checkresponsetypes;
14116:     foreach my $key (keys(%Apache::lonnet::needsrelease)) {
14117:         my ($item,$name,$value) = split(/:/,$key);
14118:         if ($item eq 'resourcetag') {
14119:             if ($name eq 'responsetype') {
14120:                 $checkresponsetypes{$value} = $Apache::lonnet::needsrelease{$key}
14121:             }
14122:         }
14123:     }
14124:     my $navmap = Apache::lonnavmaps::navmap->new();
14125:     if (defined($navmap)) {
14126:         my %allresponses;
14127:         foreach my $res ($navmap->retrieveResources(undef,sub { $_[0]->is_problem() },1,0)) {
14128:             my %responses = $res->responseTypes();
14129:             foreach my $key (keys(%responses)) {
14130:                 next unless(exists($checkresponsetypes{$key}));
14131:                 $allresponses{$key} += $responses{$key};
14132:             }
14133:         }
14134:         foreach my $key (keys(%allresponses)) {
14135:             my ($major,$minor) = split(/\./,$checkresponsetypes{$key});
14136:             if (($major > $reqdmajor) || ($major == $reqdmajor && $minor > $reqdminor)) {
14137:                 ($reqdmajor,$reqdminor) = ($major,$minor);
14138:             }
14139:         }
14140:         undef($navmap);
14141:     }
14142:     unless (($reqdmajor eq '') && ($reqdminor eq '')) {
14143:         &Apache::lonnet::update_released_required($reqdmajor.'.'.$reqdminor,$cdom,$cnum,$chome,$cid);
14144:     }
14145:     return;
14146: }
14147: 
14148: sub allmaps_incourse {
14149:     my ($cdom,$cnum,$chome,$cid) = @_;
14150:     if ($cdom eq '' || $cnum eq '' || $chome eq '' || $cid eq '') {
14151:         $cid = $env{'request.course.id'};
14152:         $cdom = $env{'course.'.$cid.'.domain'};
14153:         $cnum = $env{'course.'.$cid.'.num'};
14154:         $chome = $env{'course.'.$cid.'.home'};
14155:     }
14156:     my %allmaps = ();
14157:     my $lastchange =
14158:         &Apache::lonnet::get_coursechange($cdom,$cnum);
14159:     if ($lastchange > $env{'request.course.tied'}) {
14160:         my ($furl,$ferr) = &Apache::lonuserstate::readmap("$cdom/$cnum");
14161:         unless ($ferr) {
14162:             &update_content_constraints($cdom,$cnum,$chome,$cid);
14163:         }
14164:     }
14165:     my $navmap = Apache::lonnavmaps::navmap->new();
14166:     if (defined($navmap)) {
14167:         foreach my $res ($navmap->retrieveResources(undef,sub { $_[0]->is_map() },1,0,1)) {
14168:             $allmaps{$res->src()} = 1;
14169:         }
14170:     }
14171:     return \%allmaps;
14172: }
14173: 
14174: sub parse_supplemental_title {
14175:     my ($title) = @_;
14176: 
14177:     my ($foldertitle,$renametitle);
14178:     if ($title =~ /&amp;&amp;&amp;/) {
14179:         $title = &HTML::Entites::decode($title);
14180:     }
14181:     if ($title =~ m/^(\d+)___&&&___($match_username)___&&&___($match_domain)___&&&___(.*)$/) {
14182:         $renametitle=$4;
14183:         my ($time,$uname,$udom) = ($1,$2,$3);
14184:         $foldertitle=&Apache::lontexconvert::msgtexconverted($4);
14185:         my $name =  &plainname($uname,$udom);
14186:         $name = &HTML::Entities::encode($name,'"<>&\'');
14187:         $renametitle = &HTML::Entities::encode($renametitle,'"<>&\'');
14188:         $title='<i>'.&Apache::lonlocal::locallocaltime($time).'</i> '.
14189:             $name.': <br />'.$foldertitle;
14190:     }
14191:     if (wantarray) {
14192:         return ($title,$foldertitle,$renametitle);
14193:     }
14194:     return $title;
14195: }
14196: 
14197: sub symb_to_docspath {
14198:     my ($symb) = @_;
14199:     return unless ($symb);
14200:     my ($mapurl,$id,$resurl) = &Apache::lonnet::decode_symb($symb);
14201:     if ($resurl=~/\.(sequence|page)$/) {
14202:         $mapurl=$resurl;
14203:     } elsif ($resurl eq 'adm/navmaps') {
14204:         $mapurl=$env{'course.'.$env{'request.course.id'}.'.url'};
14205:     }
14206:     my $mapresobj;
14207:     my $navmap = Apache::lonnavmaps::navmap->new();
14208:     if (ref($navmap)) {
14209:         $mapresobj = $navmap->getResourceByUrl($mapurl);
14210:     }
14211:     $mapurl=~s{^.*/([^/]+)\.(\w+)$}{$1};
14212:     my $type=$2;
14213:     my $path;
14214:     if (ref($mapresobj)) {
14215:         my $pcslist = $mapresobj->map_hierarchy();
14216:         if ($pcslist ne '') {
14217:             foreach my $pc (split(/,/,$pcslist)) {
14218:                 next if ($pc <= 1);
14219:                 my $res = $navmap->getByMapPc($pc);
14220:                 if (ref($res)) {
14221:                     my $thisurl = $res->src();
14222:                     $thisurl=~s{^.*/([^/]+)\.\w+$}{$1};
14223:                     my $thistitle = $res->title();
14224:                     $path .= '&'.
14225:                              &Apache::lonhtmlcommon::entity_encode($thisurl).'&'.
14226:                              &Apache::lonhtmlcommon::entity_encode($thistitle).
14227:                              ':'.$res->randompick().
14228:                              ':'.$res->randomout().
14229:                              ':'.$res->encrypted().
14230:                              ':'.$res->randomorder().
14231:                              ':'.$res->is_page();
14232:                 }
14233:             }
14234:         }
14235:         $path =~ s/^\&//;
14236:         my $maptitle = $mapresobj->title();
14237:         if ($mapurl eq 'default') {
14238:             $maptitle = 'Main Course Documents';
14239:         }
14240:         $path .= (($path ne '')? '&' : '').
14241:                  &Apache::lonhtmlcommon::entity_encode($mapurl).'&'.
14242:                  &Apache::lonhtmlcommon::entity_encode($maptitle).
14243:                  ':'.$mapresobj->randompick().
14244:                  ':'.$mapresobj->randomout().
14245:                  ':'.$mapresobj->encrypted().
14246:                  ':'.$mapresobj->randomorder().
14247:                  ':'.$mapresobj->is_page();
14248:     } else {
14249:         my $maptitle = &Apache::lonnet::gettitle($mapurl);
14250:         my $ispage = (($type eq 'page')? 1 : '');
14251:         if ($mapurl eq 'default') {
14252:             $maptitle = 'Main Course Documents';
14253:         }
14254:         $path = &Apache::lonhtmlcommon::entity_encode($mapurl).'&'.
14255:                 &Apache::lonhtmlcommon::entity_encode($maptitle).':::::'.$ispage;
14256:     }
14257:     unless ($mapurl eq 'default') {
14258:         $path = 'default&'.
14259:                 &Apache::lonhtmlcommon::entity_encode('Main Course Documents').
14260:                 ':::::&'.$path;
14261:     }
14262:     return $path;
14263: }
14264: 
14265: sub captcha_display {
14266:     my ($context,$lonhost) = @_;
14267:     my ($output,$error);
14268:     my ($captcha,$pubkey,$privkey) = &get_captcha_config($context,$lonhost);
14269:     if ($captcha eq 'original') {
14270:         $output = &create_captcha();
14271:         unless ($output) {
14272:             $error = 'captcha'; 
14273:         }
14274:     } elsif ($captcha eq 'recaptcha') {
14275:         $output = &create_recaptcha($pubkey);
14276:         unless ($output) {
14277:             $error = 'recaptcha'; 
14278:         }
14279:     }
14280:     return ($output,$error);
14281: }
14282: 
14283: sub captcha_response {
14284:     my ($context,$lonhost) = @_;
14285:     my ($captcha_chk,$captcha_error);
14286:     my ($captcha,$pubkey,$privkey) = &get_captcha_config($context,$lonhost);
14287:     if ($captcha eq 'original') {
14288:         ($captcha_chk,$captcha_error) = &check_captcha();
14289:     } elsif ($captcha eq 'recaptcha') {
14290:         $captcha_chk = &check_recaptcha($privkey);
14291:     } else {
14292:         $captcha_chk = 1;
14293:     }
14294:     return ($captcha_chk,$captcha_error);
14295: }
14296: 
14297: sub get_captcha_config {
14298:     my ($context,$lonhost) = @_;
14299:     my ($captcha,$pubkey,$privkey,$hashtocheck);
14300:     my $hostname = &Apache::lonnet::hostname($lonhost);
14301:     my $serverhomeID = &Apache::lonnet::get_server_homeID($hostname);
14302:     my $serverhomedom = &Apache::lonnet::host_domain($serverhomeID);
14303:     if ($context eq 'usercreation') {
14304:         my %domconfig = &Apache::lonnet::get_dom('configuration',[$context],$serverhomedom);
14305:         if (ref($domconfig{$context}) eq 'HASH') {
14306:             $hashtocheck = $domconfig{$context}{'cancreate'};
14307:             if (ref($hashtocheck) eq 'HASH') {
14308:                 if ($hashtocheck->{'captcha'} eq 'recaptcha') {
14309:                     if (ref($hashtocheck->{'recaptchakeys'}) eq 'HASH') {
14310:                         $pubkey = $hashtocheck->{'recaptchakeys'}{'public'};
14311:                         $privkey = $hashtocheck->{'recaptchakeys'}{'private'};
14312:                     }
14313:                     if ($privkey && $pubkey) {
14314:                         $captcha = 'recaptcha';
14315:                     } else {
14316:                         $captcha = 'original';
14317:                     }
14318:                 } elsif ($hashtocheck->{'captcha'} ne 'notused') {
14319:                     $captcha = 'original';
14320:                 }
14321:             }
14322:         } else {
14323:             $captcha = 'captcha';
14324:         }
14325:     } elsif ($context eq 'login') {
14326:         my %domconfhash = &Apache::loncommon::get_domainconf($serverhomedom);
14327:         if ($domconfhash{$serverhomedom.'.login.captcha'} eq 'recaptcha') {
14328:             $pubkey = $domconfhash{$serverhomedom.'.login.recaptchakeys_public'};
14329:             $privkey = $domconfhash{$serverhomedom.'.login.recaptchakeys_private'};
14330:             if ($privkey && $pubkey) {
14331:                 $captcha = 'recaptcha';
14332:             } else {
14333:                 $captcha = 'original';
14334:             }
14335:         } elsif ($domconfhash{$serverhomedom.'.login.captcha'} eq 'original') {
14336:             $captcha = 'original';
14337:         }
14338:     }
14339:     return ($captcha,$pubkey,$privkey);
14340: }
14341: 
14342: sub create_captcha {
14343:     my %captcha_params = &captcha_settings();
14344:     my ($output,$maxtries,$tries) = ('',10,0);
14345:     while ($tries < $maxtries) {
14346:         $tries ++;
14347:         my $captcha = Authen::Captcha->new (
14348:                                            output_folder => $captcha_params{'output_dir'},
14349:                                            data_folder   => $captcha_params{'db_dir'},
14350:                                           );
14351:         my $md5sum = $captcha->generate_code($captcha_params{'numchars'});
14352: 
14353:         if (-e $Apache::lonnet::perlvar{'lonCaptchaDir'}.'/'.$md5sum.'.png') {
14354:             $output = '<input type="hidden" name="crypt" value="'.$md5sum.'" />'."\n".
14355:                       &mt('Type in the letters/numbers shown below').'&nbsp;'.
14356:                      '<input type="text" size="5" name="code" value="" /><br />'.
14357:                      '<img src="'.$captcha_params{'www_output_dir'}.'/'.$md5sum.'.png" />';
14358:             last;
14359:         }
14360:     }
14361:     return $output;
14362: }
14363: 
14364: sub captcha_settings {
14365:     my %captcha_params = (
14366:                            output_dir     => $Apache::lonnet::perlvar{'lonCaptchaDir'},
14367:                            www_output_dir => "/captchaspool",
14368:                            db_dir         => $Apache::lonnet::perlvar{'lonCaptchaDb'},
14369:                            numchars       => '5',
14370:                          );
14371:     return %captcha_params;
14372: }
14373: 
14374: sub check_captcha {
14375:     my ($captcha_chk,$captcha_error);
14376:     my $code = $env{'form.code'};
14377:     my $md5sum = $env{'form.crypt'};
14378:     my %captcha_params = &captcha_settings();
14379:     my $captcha = Authen::Captcha->new(
14380:                       output_folder => $captcha_params{'output_dir'},
14381:                       data_folder   => $captcha_params{'db_dir'},
14382:                   );
14383:     $captcha_chk = $captcha->check_code($code,$md5sum);
14384:     my %captcha_hash = (
14385:                         0       => 'Code not checked (file error)',
14386:                        -1      => 'Failed: code expired',
14387:                        -2      => 'Failed: invalid code (not in database)',
14388:                        -3      => 'Failed: invalid code (code does not match crypt)',
14389:     );
14390:     if ($captcha_chk != 1) {
14391:         $captcha_error = $captcha_hash{$captcha_chk}
14392:     }
14393:     return ($captcha_chk,$captcha_error);
14394: }
14395: 
14396: sub create_recaptcha {
14397:     my ($pubkey) = @_;
14398:     my $captcha = Captcha::reCAPTCHA->new;
14399:     return $captcha->get_options_setter({theme => 'white'})."\n".
14400:            $captcha->get_html($pubkey).
14401:            &mt('If either word is hard to read, [_1] will replace them.',
14402:                '<image src="/res/adm/pages/refresh.gif" alt="reCAPTCHA refresh" />').
14403:            '<br /><br />';
14404: }
14405: 
14406: sub check_recaptcha {
14407:     my ($privkey) = @_;
14408:     my $captcha_chk;
14409:     my $captcha = Captcha::reCAPTCHA->new;
14410:     my $captcha_result =
14411:         $captcha->check_answer(
14412:                                 $privkey,
14413:                                 $ENV{'REMOTE_ADDR'},
14414:                                 $env{'form.recaptcha_challenge_field'},
14415:                                 $env{'form.recaptcha_response_field'},
14416:                               );
14417:     if ($captcha_result->{is_valid}) {
14418:         $captcha_chk = 1;
14419:     }
14420:     return $captcha_chk;
14421: }
14422: 
14423: =pod
14424: 
14425: =back
14426: 
14427: =cut
14428: 
14429: 1;
14430: __END__;
14431: 

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