File:  [LON-CAPA] / loncom / interface / loncommon.pm
Revision 1.1075.2.91: download - view: text, annotated - select for diffs
Mon Apr 6 19:06:45 2015 UTC (9 years, 2 months ago) by raeburn
Branches: version_2_11_X
- For 2.11
  Backport 1.1212

    1: # The LearningOnline Network with CAPA
    2: # a pile of common routines
    3: #
    4: # $Id: loncommon.pm,v 1.1075.2.91 2015/04/06 19:06:45 raeburn Exp $
    5: #
    6: # Copyright Michigan State University Board of Trustees
    7: #
    8: # This file is part of the LearningOnline Network with CAPA (LON-CAPA).
    9: #
   10: # LON-CAPA is free software; you can redistribute it and/or modify
   11: # it under the terms of the GNU General Public License as published by
   12: # the Free Software Foundation; either version 2 of the License, or
   13: # (at your option) any later version.
   14: #
   15: # LON-CAPA is distributed in the hope that it will be useful,
   16: # but WITHOUT ANY WARRANTY; without even the implied warranty of
   17: # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   18: # GNU General Public License for more details.
   19: #
   20: # You should have received a copy of the GNU General Public License
   21: # along with LON-CAPA; if not, write to the Free Software
   22: # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
   23: #
   24: # /home/httpd/html/adm/gpl.txt
   25: #
   26: # http://www.lon-capa.org/
   27: #
   28: 
   29: # Makes a table out of the previous attempts
   30: # Inputs result_from_symbread, user, domain, course_id
   31: # Reads in non-network-related .tab files
   32: 
   33: # POD header:
   34: 
   35: =pod
   36: 
   37: =head1 NAME
   38: 
   39: Apache::loncommon - pile of common routines
   40: 
   41: =head1 SYNOPSIS
   42: 
   43: Common routines for manipulating connections, student answers,
   44:     domains, common Javascript fragments, etc.
   45: 
   46: =head1 OVERVIEW
   47: 
   48: A collection of commonly used subroutines that don't have a natural
   49: home anywhere else. This collection helps remove
   50: redundancy from other modules and increase efficiency of memory usage.
   51: 
   52: =cut 
   53: 
   54: # End of POD header
   55: package Apache::loncommon;
   56: 
   57: use strict;
   58: use Apache::lonnet;
   59: use GDBM_File;
   60: use POSIX qw(strftime mktime);
   61: use Apache::lonmenu();
   62: use Apache::lonenc();
   63: use Apache::lonlocal;
   64: use Apache::lonnet();
   65: use HTML::Entities;
   66: use Apache::lonhtmlcommon();
   67: use Apache::loncoursedata();
   68: use Apache::lontexconvert();
   69: use Apache::lonclonecourse();
   70: use Apache::lonuserutils();
   71: use Apache::lonuserstate();
   72: use Apache::courseclassifier();
   73: use LONCAPA qw(:DEFAULT :match);
   74: use DateTime::TimeZone;
   75: use DateTime::Locale::Catalog;
   76: use Authen::Captcha;
   77: use Captcha::reCAPTCHA;
   78: use Crypt::DES;
   79: use DynaLoader; # for Crypt::DES version
   80: 
   81: # ---------------------------------------------- Designs
   82: use vars qw(%defaultdesign);
   83: 
   84: my $readit;
   85: 
   86: 
   87: ##
   88: ## Global Variables
   89: ##
   90: 
   91: 
   92: # ----------------------------------------------- SSI with retries:
   93: #
   94: 
   95: =pod
   96: 
   97: =head1 Server Side include with retries:
   98: 
   99: =over 4
  100: 
  101: =item * &ssi_with_retries(resource,retries form)
  102: 
  103: Performs an ssi with some number of retries.  Retries continue either
  104: until the result is ok or until the retry count supplied by the
  105: caller is exhausted.  
  106: 
  107: Inputs:
  108: 
  109: =over 4
  110: 
  111: resource   - Identifies the resource to insert.
  112: 
  113: retries    - Count of the number of retries allowed.
  114: 
  115: form       - Hash that identifies the rendering options.
  116: 
  117: =back
  118: 
  119: Returns:
  120: 
  121: =over 4
  122: 
  123: content    - The content of the response.  If retries were exhausted this is empty.
  124: 
  125: response   - The response from the last attempt (which may or may not have been successful.
  126: 
  127: =back
  128: 
  129: =back
  130: 
  131: =cut
  132: 
  133: sub ssi_with_retries {
  134:     my ($resource, $retries, %form) = @_;
  135: 
  136: 
  137:     my $ok = 0;			# True if we got a good response.
  138:     my $content;
  139:     my $response;
  140: 
  141:     # Try to get the ssi done. within the retries count:
  142: 
  143:     do {
  144: 	($content, $response) = &Apache::lonnet::ssi($resource, %form);
  145: 	$ok      = $response->is_success;
  146:         if (!$ok) {
  147:             &Apache::lonnet::logthis("Failed ssi_with_retries on $resource: ".$response->is_success.', '.$response->code.', '.$response->message);
  148:         }
  149: 	$retries--;
  150:     } while (!$ok && ($retries > 0));
  151: 
  152:     if (!$ok) {
  153: 	$content = '';		# On error return an empty content.
  154:     }
  155:     return ($content, $response);
  156: 
  157: }
  158: 
  159: 
  160: 
  161: # ----------------------------------------------- Filetypes/Languages/Copyright
  162: my %language;
  163: my %supported_language;
  164: my %latex_language;		# For choosing hyphenation in <transl..>
  165: my %latex_language_bykey;	# for choosing hyphenation from metadata
  166: my %cprtag;
  167: my %scprtag;
  168: my %fe; my %fd; my %fm;
  169: my %category_extensions;
  170: 
  171: # ---------------------------------------------- Thesaurus variables
  172: #
  173: # %Keywords:
  174: #      A hash used by &keyword to determine if a word is considered a keyword.
  175: # $thesaurus_db_file 
  176: #      Scalar containing the full path to the thesaurus database.
  177: 
  178: my %Keywords;
  179: my $thesaurus_db_file;
  180: 
  181: #
  182: # Initialize values from language.tab, copyright.tab, filetypes.tab,
  183: # thesaurus.tab, and filecategories.tab.
  184: #
  185: BEGIN {
  186:     # Variable initialization
  187:     $thesaurus_db_file = $Apache::lonnet::perlvar{'lonTabDir'}."/thesaurus.db";
  188:     #
  189:     unless ($readit) {
  190: # ------------------------------------------------------------------- languages
  191:     {
  192:         my $langtabfile = $Apache::lonnet::perlvar{'lonTabDir'}.
  193:                                    '/language.tab';
  194:         if ( open(my $fh,"<$langtabfile") ) {
  195:             while (my $line = <$fh>) {
  196:                 next if ($line=~/^\#/);
  197:                 chomp($line);
  198:                 my ($key,$two,$country,$three,$enc,$val,$sup,$latex)=(split(/\t/,$line));
  199:                 $language{$key}=$val.' - '.$enc;
  200:                 if ($sup) {
  201:                     $supported_language{$key}=$sup;
  202:                 }
  203: 		if ($latex) {
  204: 		    $latex_language_bykey{$key} = $latex;
  205: 		    $latex_language{$two} = $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:         $credits_element) = @_;
  536:     my $wintitle = 'Course_Browser';
  537:     if ($crstype eq 'Community') {
  538:         $wintitle = 'Community_Browser';
  539:     }
  540:     my $id_functions = &javascript_index_functions();
  541:     my $output = '
  542: <script type="text/javascript" language="JavaScript">
  543: // <![CDATA[
  544:     var stdeditbrowser;'."\n";
  545: 
  546:     $output .= <<"ENDSTDBRW";
  547:     function opencrsbrowser(formname,uname,udom,desc,extra_element,multflag,type,type_elem) {
  548:         var url = '/adm/pickcourse?';
  549:         var formid = getFormIdByName(formname);
  550:         var domainfilter = getDomainFromSelectbox(formname,udom);
  551:         if (domainfilter != null) {
  552:            if (domainfilter != '') {
  553:                url += 'domainfilter='+domainfilter+'&';
  554: 	   }
  555:         }
  556:         url += 'form=' + formname + '&cnumelement='+uname+
  557: 	                            '&cdomelement='+udom+
  558:                                     '&cnameelement='+desc;
  559:         if (extra_element !=null && extra_element != '') {
  560:             if (formname == 'rolechoice' || formname == 'studentform') {
  561:                 url += '&roleelement='+extra_element;
  562:                 if (domainfilter == null || domainfilter == '') {
  563:                     url += '&domainfilter='+extra_element;
  564:                 }
  565:             }
  566:             else {
  567:                 if (formname == 'portform') {
  568:                     url += '&setroles='+extra_element;
  569:                 } else {
  570:                     if (formname == 'rules') {
  571:                         url += '&fixeddom='+extra_element; 
  572:                     }
  573:                 }
  574:             }     
  575:         }
  576:         if (type != null && type != '') {
  577:             url += '&type='+type;
  578:         }
  579:         if (type_elem != null && type_elem != '') {
  580:             url += '&typeelement='+type_elem;
  581:         }
  582:         if (formname == 'ccrs') {
  583:             var ownername = document.forms[formid].ccuname.value;
  584:             var ownerdom =  document.forms[formid].ccdomain.options[document.forms[formid].ccdomain.selectedIndex].value;
  585:             url += '&cloner='+ownername+':'+ownerdom;
  586:         }
  587:         if (multflag !=null && multflag != '') {
  588:             url += '&multiple='+multflag;
  589:         }
  590:         var title = '$wintitle';
  591:         var options = 'scrollbars=1,resizable=1,menubar=0';
  592:         options += ',width=700,height=600';
  593:         stdeditbrowser = open(url,title,options,'1');
  594:         stdeditbrowser.focus();
  595:     }
  596: $id_functions
  597: ENDSTDBRW
  598:     if (($sec_element ne '') || ($role_element ne '') || ($credits_element ne '')) {
  599:         $output .= &setsec_javascript($sec_element,$formname,$role_element,
  600:                                       $credits_element);
  601:     }
  602:     $output .= '
  603: // ]]>
  604: </script>';
  605:     return $output;
  606: }
  607: 
  608: sub javascript_index_functions {
  609:     return <<"ENDJS";
  610: 
  611: function getFormIdByName(formname) {
  612:     for (var i=0;i<document.forms.length;i++) {
  613:         if (document.forms[i].name == formname) {
  614:             return i;
  615:         }
  616:     }
  617:     return -1;
  618: }
  619: 
  620: function getIndexByName(formid,item) {
  621:     for (var i=0;i<document.forms[formid].elements.length;i++) {
  622:         if (document.forms[formid].elements[i].name == item) {
  623:             return i;
  624:         }
  625:     }
  626:     return -1;
  627: }
  628: 
  629: function getDomainFromSelectbox(formname,udom) {
  630:     var userdom;
  631:     var formid = getFormIdByName(formname);
  632:     if (formid > -1) {
  633:         var domid = getIndexByName(formid,udom);
  634:         if (domid > -1) {
  635:             if (document.forms[formid].elements[domid].type == 'select-one') {
  636:                 userdom=document.forms[formid].elements[domid].options[document.forms[formid].elements[domid].selectedIndex].value;
  637:             }
  638:             if (document.forms[formid].elements[domid].type == 'hidden') {
  639:                 userdom=document.forms[formid].elements[domid].value;
  640:             }
  641:         }
  642:     }
  643:     return userdom;
  644: }
  645: 
  646: ENDJS
  647: 
  648: }
  649: 
  650: sub javascript_array_indexof {
  651:     return <<ENDJS;
  652: <script type="text/javascript" language="JavaScript">
  653: // <![CDATA[
  654: 
  655: if (!Array.prototype.indexOf) {
  656:     Array.prototype.indexOf = function (searchElement /*, fromIndex */ ) {
  657:         "use strict";
  658:         if (this === void 0 || this === null) {
  659:             throw new TypeError();
  660:         }
  661:         var t = Object(this);
  662:         var len = t.length >>> 0;
  663:         if (len === 0) {
  664:             return -1;
  665:         }
  666:         var n = 0;
  667:         if (arguments.length > 0) {
  668:             n = Number(arguments[1]);
  669:             if (n !== n) { // shortcut for verifying if it's NaN
  670:                 n = 0;
  671:             } else if (n !== 0 && n !== (1 / 0) && n !== -(1 / 0)) {
  672:                 n = (n > 0 || -1) * Math.floor(Math.abs(n));
  673:             }
  674:         }
  675:         if (n >= len) {
  676:             return -1;
  677:         }
  678:         var k = n >= 0 ? n : Math.max(len - Math.abs(n), 0);
  679:         for (; k < len; k++) {
  680:             if (k in t && t[k] === searchElement) {
  681:                 return k;
  682:             }
  683:         }
  684:         return -1;
  685:     }
  686: }
  687: 
  688: // ]]>
  689: </script>
  690: 
  691: ENDJS
  692: 
  693: }
  694: 
  695: sub userbrowser_javascript {
  696:     my $id_functions = &javascript_index_functions();
  697:     return <<"ENDUSERBRW";
  698: 
  699: function openuserbrowser(formname,uname,udom,ulast,ufirst,uemail,hideudom,crsdom,caller) {
  700:     var url = '/adm/pickuser?';
  701:     var userdom = getDomainFromSelectbox(formname,udom);
  702:     if (userdom != null) {
  703:        if (userdom != '') {
  704:            url += 'srchdom='+userdom+'&';
  705:        }
  706:     }
  707:     url += 'form=' + formname + '&unameelement='+uname+
  708:                                 '&udomelement='+udom+
  709:                                 '&ulastelement='+ulast+
  710:                                 '&ufirstelement='+ufirst+
  711:                                 '&uemailelement='+uemail+
  712:                                 '&hideudomelement='+hideudom+
  713:                                 '&coursedom='+crsdom;
  714:     if ((caller != null) && (caller != undefined)) {
  715:         url += '&caller='+caller;
  716:     }
  717:     var title = 'User_Browser';
  718:     var options = 'scrollbars=1,resizable=1,menubar=0';
  719:     options += ',width=700,height=600';
  720:     var stdeditbrowser = open(url,title,options,'1');
  721:     stdeditbrowser.focus();
  722: }
  723: 
  724: function fix_domain (formname,udom,origdom,uname) {
  725:     var formid = getFormIdByName(formname);
  726:     if (formid > -1) {
  727:         var unameid = getIndexByName(formid,uname);
  728:         var domid = getIndexByName(formid,udom);
  729:         var hidedomid = getIndexByName(formid,origdom);
  730:         if (hidedomid > -1) {
  731:             var fixeddom = document.forms[formid].elements[hidedomid].value;
  732:             var unameval = document.forms[formid].elements[unameid].value;
  733:             if ((fixeddom != '') && (fixeddom != undefined) && (fixeddom != null) && (unameval != '') && (unameval != undefined) && (unameval != null)) {
  734:                 if (domid > -1) {
  735:                     var slct = document.forms[formid].elements[domid];
  736:                     if (slct.type == 'select-one') {
  737:                         var i;
  738:                         for (i=0;i<slct.length;i++) {
  739:                             if (slct.options[i].value==fixeddom) { slct.selectedIndex=i; }
  740:                         }
  741:                     }
  742:                     if (slct.type == 'hidden') {
  743:                         slct.value = fixeddom;
  744:                     }
  745:                 }
  746:             }
  747:         }
  748:     }
  749:     return;
  750: }
  751: 
  752: $id_functions
  753: ENDUSERBRW
  754: }
  755: 
  756: sub setsec_javascript {
  757:     my ($sec_element,$formname,$role_element,$credits_element) = @_;
  758:     my (@courserolenames,@communityrolenames,$rolestr,$courserolestr,
  759:         $communityrolestr);
  760:     if ($role_element ne '') {
  761:         my @allroles = ('st','ta','ep','in','ad');
  762:         foreach my $crstype ('Course','Community') {
  763:             if ($crstype eq 'Community') {
  764:                 foreach my $role (@allroles) {
  765:                     push(@communityrolenames,&Apache::lonnet::plaintext($role,$crstype));
  766:                 }
  767:                 push(@communityrolenames,&Apache::lonnet::plaintext('co'));
  768:             } else {
  769:                 foreach my $role (@allroles) {
  770:                     push(@courserolenames,&Apache::lonnet::plaintext($role,$crstype));
  771:                 }
  772:                 push(@courserolenames,&Apache::lonnet::plaintext('cc'));
  773:             }
  774:         }
  775:         $rolestr = '"'.join('","',@allroles).'"';
  776:         $courserolestr = '"'.join('","',@courserolenames).'"';
  777:         $communityrolestr = '"'.join('","',@communityrolenames).'"';
  778:     }
  779:     my $setsections = qq|
  780: function setSect(sectionlist) {
  781:     var sectionsArray = new Array();
  782:     if ((sectionlist != '') && (typeof sectionlist != "undefined")) {
  783:         sectionsArray = sectionlist.split(",");
  784:     }
  785:     var numSections = sectionsArray.length;
  786:     document.$formname.$sec_element.length = 0;
  787:     if (numSections == 0) {
  788:         document.$formname.$sec_element.multiple=false;
  789:         document.$formname.$sec_element.size=1;
  790:         document.$formname.$sec_element.options[0] = new Option('No existing sections','',false,false)
  791:     } else {
  792:         if (numSections == 1) {
  793:             document.$formname.$sec_element.multiple=false;
  794:             document.$formname.$sec_element.size=1;
  795:             document.$formname.$sec_element.options[0] = new Option('Select','',true,true);
  796:             document.$formname.$sec_element.options[1] = new Option('No section','',false,false)
  797:             document.$formname.$sec_element.options[2] = new Option(sectionsArray[0],sectionsArray[0],false,false);
  798:         } else {
  799:             for (var i=0; i<numSections; i++) {
  800:                 document.$formname.$sec_element.options[i] = new Option(sectionsArray[i],sectionsArray[i],false,false)
  801:             }
  802:             document.$formname.$sec_element.multiple=true
  803:             if (numSections < 3) {
  804:                 document.$formname.$sec_element.size=numSections;
  805:             } else {
  806:                 document.$formname.$sec_element.size=3;
  807:             }
  808:             document.$formname.$sec_element.options[0].selected = false
  809:         }
  810:     }
  811: }
  812: 
  813: function setRole(crstype) {
  814: |;
  815:     if ($role_element eq '') {
  816:         $setsections .= '    return;
  817: }
  818: ';
  819:     } else {
  820:         $setsections .= qq|
  821:     var elementLength = document.$formname.$role_element.length;
  822:     var allroles = Array($rolestr);
  823:     var courserolenames = Array($courserolestr);
  824:     var communityrolenames = Array($communityrolestr);
  825:     if (elementLength != undefined) {
  826:         if (document.$formname.$role_element.options[5].value == 'cc') {
  827:             if (crstype == 'Course') {
  828:                 return;
  829:             } else {
  830:                 allroles[5] = 'co';
  831:                 for (var i=0; i<6; i++) {
  832:                     document.$formname.$role_element.options[i].value = allroles[i];
  833:                     document.$formname.$role_element.options[i].text = communityrolenames[i];
  834:                 }
  835:             }
  836:         } else {
  837:             if (crstype == 'Community') {
  838:                 return;
  839:             } else {
  840:                 allroles[5] = 'cc';
  841:                 for (var i=0; i<6; i++) {
  842:                     document.$formname.$role_element.options[i].value = allroles[i];
  843:                     document.$formname.$role_element.options[i].text = courserolenames[i];
  844:                 }
  845:             }
  846:         }
  847:     }
  848:     return;
  849: }
  850: |;
  851:     }
  852:     if ($credits_element) {
  853:         $setsections .= qq|
  854: function setCredits(defaultcredits) {
  855:     document.$formname.$credits_element.value = defaultcredits;
  856:     return;
  857: }
  858: |;
  859:     }
  860:     return $setsections;
  861: }
  862: 
  863: sub selectcourse_link {
  864:    my ($form,$unameele,$udomele,$desc,$extra_element,$multflag,$selecttype,
  865:        $typeelement) = @_;
  866:    my $type = $selecttype;
  867:    my $linktext = &mt('Select Course');
  868:    if ($selecttype eq 'Community') {
  869:        $linktext = &mt('Select Community');
  870:    } elsif ($selecttype eq 'Course/Community') {
  871:        $linktext = &mt('Select Course/Community');
  872:        $type = '';
  873:    } elsif ($selecttype eq 'Select') {
  874:        $linktext = &mt('Select');
  875:        $type = '';
  876:    }
  877:    return '<span class="LC_nobreak">'
  878:          ."<a href='"
  879:          .'javascript:opencrsbrowser("'.$form.'","'.$unameele
  880:          .'","'.$udomele.'","'.$desc.'","'.$extra_element
  881:          .'","'.$multflag.'","'.$type.'","'.$typeelement.'");'
  882:          ."'>".$linktext.'</a>'
  883:          .'</span>';
  884: }
  885: 
  886: sub selectauthor_link {
  887:    my ($form,$udom)=@_;
  888:    return '<a href="javascript:openauthorbrowser('."'$form','$udom'".');">'.
  889:           &mt('Select Author').'</a>';
  890: }
  891: 
  892: sub selectuser_link {
  893:     my ($form,$unameelem,$domelem,$lastelem,$firstelem,$emailelem,$hdomelem,
  894:         $coursedom,$linktext,$caller) = @_;
  895:     return '<a href="javascript:openuserbrowser('."'$form','$unameelem','$domelem',".
  896:            "'$lastelem','$firstelem','$emailelem','$hdomelem','$coursedom','$caller'".
  897:            ');">'.$linktext.'</a>';
  898: }
  899: 
  900: sub check_uncheck_jscript {
  901:     my $jscript = <<"ENDSCRT";
  902: function checkAll(field) {
  903:     if (field.length > 0) {
  904:         for (i = 0; i < field.length; i++) {
  905:             if (!field[i].disabled) {
  906:                 field[i].checked = true;
  907:             }
  908:         }
  909:     } else {
  910:         if (!field.disabled) {
  911:             field.checked = true;
  912:         }
  913:     }
  914: }
  915:  
  916: function uncheckAll(field) {
  917:     if (field.length > 0) {
  918:         for (i = 0; i < field.length; i++) {
  919:             field[i].checked = false ;
  920:         }
  921:     } else {
  922:         field.checked = false ;
  923:     }
  924: }
  925: ENDSCRT
  926:     return $jscript;
  927: }
  928: 
  929: sub select_timezone {
  930:    my ($name,$selected,$onchange,$includeempty)=@_;
  931:    my $output='<select name="'.$name.'" '.$onchange.'>'."\n";
  932:    if ($includeempty) {
  933:        $output .= '<option value=""';
  934:        if (($selected eq '') || ($selected eq 'local')) {
  935:            $output .= ' selected="selected" ';
  936:        }
  937:        $output .= '> </option>';
  938:    }
  939:    my @timezones = DateTime::TimeZone->all_names;
  940:    foreach my $tzone (@timezones) {
  941:        $output.= '<option value="'.$tzone.'"';
  942:        if ($tzone eq $selected) {
  943:            $output.=' selected="selected"';
  944:        }
  945:        $output.=">$tzone</option>\n";
  946:    }
  947:    $output.="</select>";
  948:    return $output;
  949: }
  950: 
  951: sub select_datelocale {
  952:     my ($name,$selected,$onchange,$includeempty)=@_;
  953:     my $output='<select name="'.$name.'" '.$onchange.'>'."\n";
  954:     if ($includeempty) {
  955:         $output .= '<option value=""';
  956:         if ($selected eq '') {
  957:             $output .= ' selected="selected" ';
  958:         }
  959:         $output .= '> </option>';
  960:     }
  961:     my (@possibles,%locale_names);
  962:     my @locales = DateTime::Locale::Catalog::Locales;
  963:     foreach my $locale (@locales) {
  964:         if (ref($locale) eq 'HASH') {
  965:             my $id = $locale->{'id'};
  966:             if ($id ne '') {
  967:                 my $en_terr = $locale->{'en_territory'};
  968:                 my $native_terr = $locale->{'native_territory'};
  969:                 my @languages = &Apache::lonlocal::preferred_languages();
  970:                 if (grep(/^en$/,@languages) || !@languages) {
  971:                     if ($en_terr ne '') {
  972:                         $locale_names{$id} = '('.$en_terr.')';
  973:                     } elsif ($native_terr ne '') {
  974:                         $locale_names{$id} = $native_terr;
  975:                     }
  976:                 } else {
  977:                     if ($native_terr ne '') {
  978:                         $locale_names{$id} = $native_terr.' ';
  979:                     } elsif ($en_terr ne '') {
  980:                         $locale_names{$id} = '('.$en_terr.')';
  981:                     }
  982:                 }
  983:                 push (@possibles,$id);
  984:             }
  985:         }
  986:     }
  987:     foreach my $item (sort(@possibles)) {
  988:         $output.= '<option value="'.$item.'"';
  989:         if ($item eq $selected) {
  990:             $output.=' selected="selected"';
  991:         }
  992:         $output.=">$item";
  993:         if ($locale_names{$item} ne '') {
  994:             $output.="  $locale_names{$item}</option>\n";
  995:         }
  996:         $output.="</option>\n";
  997:     }
  998:     $output.="</select>";
  999:     return $output;
 1000: }
 1001: 
 1002: sub select_language {
 1003:     my ($name,$selected,$includeempty) = @_;
 1004:     my %langchoices;
 1005:     if ($includeempty) {
 1006:         %langchoices = ('' => 'No language preference');
 1007:     }
 1008:     foreach my $id (&languageids()) {
 1009:         my $code = &supportedlanguagecode($id);
 1010:         if ($code) {
 1011:             $langchoices{$code} = &plainlanguagedescription($id);
 1012:         }
 1013:     }
 1014:     %langchoices = &Apache::lonlocal::texthash(%langchoices);
 1015:     return &select_form($selected,$name,\%langchoices);
 1016: }
 1017: 
 1018: =pod
 1019: 
 1020: =item * &linked_select_forms(...)
 1021: 
 1022: linked_select_forms returns a string containing a <script></script> block
 1023: and html for two <select> menus.  The select menus will be linked in that
 1024: changing the value of the first menu will result in new values being placed
 1025: in the second menu.  The values in the select menu will appear in alphabetical
 1026: order unless a defined order is provided.
 1027: 
 1028: linked_select_forms takes the following ordered inputs:
 1029: 
 1030: =over 4
 1031: 
 1032: =item * $formname, the name of the <form> tag
 1033: 
 1034: =item * $middletext, the text which appears between the <select> tags
 1035: 
 1036: =item * $firstdefault, the default value for the first menu
 1037: 
 1038: =item * $firstselectname, the name of the first <select> tag
 1039: 
 1040: =item * $secondselectname, the name of the second <select> tag
 1041: 
 1042: =item * $hashref, a reference to a hash containing the data for the menus.
 1043: 
 1044: =item * $menuorder, the order of values in the first menu
 1045: 
 1046: =item * $onchangefirst, additional javascript call to execute for an onchange
 1047:         event for the first <select> tag
 1048: 
 1049: =item * $onchangesecond, additional javascript call to execute for an onchange
 1050:         event for the second <select> tag
 1051: 
 1052: =back 
 1053: 
 1054: Below is an example of such a hash.  Only the 'text', 'default', and 
 1055: 'select2' keys must appear as stated.  keys(%menu) are the possible 
 1056: values for the first select menu.  The text that coincides with the 
 1057: first menu value is given in $menu{$choice1}->{'text'}.  The values 
 1058: and text for the second menu are given in the hash pointed to by 
 1059: $menu{$choice1}->{'select2'}.  
 1060: 
 1061:  my %menu = ( A1 => { text =>"Choice A1" ,
 1062:                        default => "B3",
 1063:                        select2 => { 
 1064:                            B1 => "Choice B1",
 1065:                            B2 => "Choice B2",
 1066:                            B3 => "Choice B3",
 1067:                            B4 => "Choice B4"
 1068:                            },
 1069:                        order => ['B4','B3','B1','B2'],
 1070:                    },
 1071:                A2 => { text =>"Choice A2" ,
 1072:                        default => "C2",
 1073:                        select2 => { 
 1074:                            C1 => "Choice C1",
 1075:                            C2 => "Choice C2",
 1076:                            C3 => "Choice C3"
 1077:                            },
 1078:                        order => ['C2','C1','C3'],
 1079:                    },
 1080:                A3 => { text =>"Choice A3" ,
 1081:                        default => "D6",
 1082:                        select2 => { 
 1083:                            D1 => "Choice D1",
 1084:                            D2 => "Choice D2",
 1085:                            D3 => "Choice D3",
 1086:                            D4 => "Choice D4",
 1087:                            D5 => "Choice D5",
 1088:                            D6 => "Choice D6",
 1089:                            D7 => "Choice D7"
 1090:                            },
 1091:                        order => ['D4','D3','D2','D1','D7','D6','D5'],
 1092:                    }
 1093:                );
 1094: 
 1095: =cut
 1096: 
 1097: sub linked_select_forms {
 1098:     my ($formname,
 1099:         $middletext,
 1100:         $firstdefault,
 1101:         $firstselectname,
 1102:         $secondselectname, 
 1103:         $hashref,
 1104:         $menuorder,
 1105:         $onchangefirst,
 1106:         $onchangesecond
 1107:         ) = @_;
 1108:     my $second = "document.$formname.$secondselectname";
 1109:     my $first = "document.$formname.$firstselectname";
 1110:     # output the javascript to do the changing
 1111:     my $result = '';
 1112:     $result.='<script type="text/javascript" language="JavaScript">'."\n";
 1113:     $result.="// <![CDATA[\n";
 1114:     $result.="var select2data = new Object();\n";
 1115:     $" = '","';
 1116:     my $debug = '';
 1117:     foreach my $s1 (sort(keys(%$hashref))) {
 1118:         $result.="select2data.d_$s1 = new Object();\n";        
 1119:         $result.="select2data.d_$s1.def = new String('".
 1120:             $hashref->{$s1}->{'default'}."');\n";
 1121:         $result.="select2data.d_$s1.values = new Array(";
 1122:         my @s2values = sort(keys( %{ $hashref->{$s1}->{'select2'} } ));
 1123:         if (ref($hashref->{$s1}->{'order'}) eq 'ARRAY') {
 1124:             @s2values = @{$hashref->{$s1}->{'order'}};
 1125:         }
 1126:         $result.="\"@s2values\");\n";
 1127:         $result.="select2data.d_$s1.texts = new Array(";        
 1128:         my @s2texts;
 1129:         foreach my $value (@s2values) {
 1130:             push @s2texts, $hashref->{$s1}->{'select2'}->{$value};
 1131:         }
 1132:         $result.="\"@s2texts\");\n";
 1133:     }
 1134:     $"=' ';
 1135:     $result.= <<"END";
 1136: 
 1137: function select1_changed() {
 1138:     // Determine new choice
 1139:     var newvalue = "d_" + $first.value;
 1140:     // update select2
 1141:     var values     = select2data[newvalue].values;
 1142:     var texts      = select2data[newvalue].texts;
 1143:     var select2def = select2data[newvalue].def;
 1144:     var i;
 1145:     // out with the old
 1146:     for (i = 0; i < $second.options.length; i++) {
 1147:         $second.options[i] = null;
 1148:     }
 1149:     // in with the nuclear
 1150:     for (i=0;i<values.length; i++) {
 1151:         $second.options[i] = new Option(values[i]);
 1152:         $second.options[i].value = values[i];
 1153:         $second.options[i].text = texts[i];
 1154:         if (values[i] == select2def) {
 1155:             $second.options[i].selected = true;
 1156:         }
 1157:     }
 1158: }
 1159: // ]]>
 1160: </script>
 1161: END
 1162:     # output the initial values for the selection lists
 1163:     $result .= "<select size=\"1\" name=\"$firstselectname\" onchange=\"select1_changed();$onchangefirst\">\n";
 1164:     my @order = sort(keys(%{$hashref}));
 1165:     if (ref($menuorder) eq 'ARRAY') {
 1166:         @order = @{$menuorder};
 1167:     }
 1168:     foreach my $value (@order) {
 1169:         $result.="    <option value=\"$value\" ";
 1170:         $result.=" selected=\"selected\" " if ($value eq $firstdefault);
 1171:         $result.=">".&mt($hashref->{$value}->{'text'})."</option>\n";
 1172:     }
 1173:     $result .= "</select>\n";
 1174:     my %select2 = %{$hashref->{$firstdefault}->{'select2'}};
 1175:     $result .= $middletext;
 1176:     $result .= "<select size=\"1\" name=\"$secondselectname\"";
 1177:     if ($onchangesecond) {
 1178:         $result .= ' onchange="'.$onchangesecond.'"';
 1179:     }
 1180:     $result .= ">\n";
 1181:     my $seconddefault = $hashref->{$firstdefault}->{'default'};
 1182:     
 1183:     my @secondorder = sort(keys(%select2));
 1184:     if (ref($hashref->{$firstdefault}->{'order'}) eq 'ARRAY') {
 1185:         @secondorder = @{$hashref->{$firstdefault}->{'order'}};
 1186:     }
 1187:     foreach my $value (@secondorder) {
 1188:         $result.="    <option value=\"$value\" ";        
 1189:         $result.=" selected=\"selected\" " if ($value eq $seconddefault);
 1190:         $result.=">".&mt($select2{$value})."</option>\n";
 1191:     }
 1192:     $result .= "</select>\n";
 1193:     #    return $debug;
 1194:     return $result;
 1195: }   #  end of sub linked_select_forms {
 1196: 
 1197: =pod
 1198: 
 1199: =item * &help_open_topic($topic,$text,$stayOnPage,$width,$height,$imgid)
 1200: 
 1201: Returns a string corresponding to an HTML link to the given help
 1202: $topic, where $topic corresponds to the name of a .tex file in
 1203: /home/httpd/html/adm/help/tex, with underscores replaced by
 1204: spaces. 
 1205: 
 1206: $text will optionally be linked to the same topic, allowing you to
 1207: link text in addition to the graphic. If you do not want to link
 1208: text, but wish to specify one of the later parameters, pass an
 1209: empty string. 
 1210: 
 1211: $stayOnPage is a value that will be interpreted as a boolean. If true,
 1212: the link will not open a new window. If false, the link will open
 1213: a new window using Javascript. (Default is false.) 
 1214: 
 1215: $width and $height are optional numerical parameters that will
 1216: override the width and height of the popped up window, which may
 1217: be useful for certain help topics with big pictures included.
 1218: 
 1219: $imgid is the id of the img tag used for the help icon. This may be
 1220: used in a javascript call to switch the image src.  See 
 1221: lonhtmlcommon::htmlareaselectactive() for an example.
 1222: 
 1223: =cut
 1224: 
 1225: sub help_open_topic {
 1226:     my ($topic, $text, $stayOnPage, $width, $height, $imgid) = @_;
 1227:     $text = "" if (not defined $text);
 1228:     $stayOnPage = 0 if (not defined $stayOnPage);
 1229:     $width = 500 if (not defined $width);
 1230:     $height = 400 if (not defined $height);
 1231:     my $filename = $topic;
 1232:     $filename =~ s/ /_/g;
 1233: 
 1234:     my $template = "";
 1235:     my $link;
 1236:     
 1237:     $topic=~s/\W/\_/g;
 1238: 
 1239:     if (!$stayOnPage) {
 1240:         if ($env{'browser.mobile'}) {
 1241: 	    $link = "javascript:openMyModal('/adm/help/${filename}.hlp',$width,$height,'yes');";
 1242:         } else {
 1243:             $link = "javascript:void(open('/adm/help/${filename}.hlp', 'Help_for_$topic', 'menubar=0,toolbar=1,scrollbars=1,width=$width,height=$height,resizable=yes'))";
 1244:         }
 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> <span>'
 1296:                .&help_open_topic('Authoring_Multilingual_Problems',&mt('Languages'),$stayOnPage,undef,600)
 1297:                .'</span>';
 1298:     }
 1299:     $out .= '</span>'; # End cheatsheet
 1300:     return $out;
 1301: }
 1302: 
 1303: sub general_help {
 1304:     my $helptopic='Student_Intro';
 1305:     if ($env{'request.role'}=~/^(ca|au)/) {
 1306: 	$helptopic='Authoring_Intro';
 1307:     } elsif ($env{'request.role'}=~/^(cc|co)/) {
 1308: 	$helptopic='Course_Coordination_Intro';
 1309:     } elsif ($env{'request.role'}=~/^dc/) {
 1310:         $helptopic='Domain_Coordination_Intro';
 1311:     }
 1312:     return $helptopic;
 1313: }
 1314: 
 1315: sub update_help_link {
 1316:     my ($topic,$component_help,$faq,$bug,$stayOnPage) = @_;
 1317:     my $origurl = $ENV{'REQUEST_URI'};
 1318:     $origurl=~s|^/~|/priv/|;
 1319:     my $timestamp = time;
 1320:     foreach my $datum (\$topic,\$component_help,\$faq,\$bug,\$origurl) {
 1321:         $$datum = &escape($$datum);
 1322:     }
 1323: 
 1324:     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";
 1325:     my $output .= <<"ENDOUTPUT";
 1326: <script type="text/javascript">
 1327: // <![CDATA[
 1328: banner_link = '$banner_link';
 1329: // ]]>
 1330: </script>
 1331: ENDOUTPUT
 1332:     return $output;
 1333: }
 1334: 
 1335: # now just updates the help link and generates a blue icon
 1336: sub help_open_menu {
 1337:     my ($topic,$component_help,$faq,$bug,$stayOnPage,$width,$height,$text) 
 1338: 	= @_;    
 1339:     $stayOnPage = 1;
 1340:     my $output;
 1341:     if ($component_help) {
 1342: 	if (!$text) {
 1343: 	    $output=&help_open_topic($component_help,undef,$stayOnPage,
 1344: 				       $width,$height);
 1345: 	} else {
 1346: 	    my $help_text;
 1347: 	    $help_text=&unescape($topic);
 1348: 	    $output='<table><tr><td>'.
 1349: 		&help_open_topic($component_help,$help_text,$stayOnPage,
 1350: 				 $width,$height).'</td></tr></table>';
 1351: 	}
 1352:     }
 1353:     my $banner_link = &update_help_link($topic,$component_help,$faq,$bug,$stayOnPage);
 1354:     return $output.$banner_link;
 1355: }
 1356: 
 1357: sub top_nav_help {
 1358:     my ($text) = @_;
 1359:     $text = &mt($text);
 1360:     my $stay_on_page;
 1361:     unless ($env{'environment.remote'} eq 'on') {
 1362:         $stay_on_page = 1;
 1363:     }
 1364:     my ($link,$banner_link);
 1365:     unless ($env{'request.noversionuri'} =~ m{^/adm/helpmenu}) {
 1366:         $link = ($stay_on_page) ? "javascript:helpMenu('display')"
 1367: 	                         : "javascript:helpMenu('open')";
 1368:         $banner_link = &update_help_link(undef,undef,undef,undef,$stay_on_page);
 1369:     }
 1370:     my $title = &mt('Get help');
 1371:     if ($link) {
 1372:         return <<"END";
 1373: $banner_link
 1374: <a href="$link" title="$title">$text</a>
 1375: END
 1376:     } else {
 1377:         return '&nbsp;'.$text.'&nbsp;';
 1378:     }
 1379: }
 1380: 
 1381: sub help_menu_js {
 1382:     my ($httphost) = @_;
 1383:     my $stayOnPage = 1;
 1384:     my $width = 620;
 1385:     my $height = 600;
 1386:     my $helptopic=&general_help();
 1387:     my $details_link = $httphost.'/adm/help/'.$helptopic.'.hlp';
 1388:     my $nothing=&Apache::lonhtmlcommon::javascript_nothing();
 1389:     my $start_page =
 1390:         &Apache::loncommon::start_page('Help Menu', undef,
 1391: 				       {'frameset'    => 1,
 1392: 					'js_ready'    => 1,
 1393:                                         'use_absolute' => $httphost, 
 1394: 					'add_entries' => {
 1395: 					    'border' => '0',
 1396: 					    'rows'   => "110,*",},});
 1397:     my $end_page =
 1398:         &Apache::loncommon::end_page({'frameset' => 1,
 1399: 				      'js_ready' => 1,});
 1400: 
 1401:     my $template .= <<"ENDTEMPLATE";
 1402: <script type="text/javascript">
 1403: // <![CDATA[
 1404: // <!-- BEGIN LON-CAPA Internal
 1405: var banner_link = '';
 1406: function helpMenu(target) {
 1407:     var caller = this;
 1408:     if (target == 'open') {
 1409:         var newWindow = null;
 1410:         try {
 1411:             newWindow =  window.open($nothing,"helpmenu","HEIGHT=$height,WIDTH=$width,resizable=yes,scrollbars=yes" )
 1412:         }
 1413:         catch(error) {
 1414:             writeHelp(caller);
 1415:             return;
 1416:         }
 1417:         if (newWindow) {
 1418:             caller = newWindow;
 1419:         }
 1420:     }
 1421:     writeHelp(caller);
 1422:     return;
 1423: }
 1424: function writeHelp(caller) {
 1425:     caller.document.writeln('$start_page\\n<frame name="bannerframe" src="'+banner_link+'" marginwidth="0" marginheight="0" frameborder="0">\\n');
 1426:     caller.document.writeln('<frame name="bodyframe" src="$details_link" marginwidth="0" marginheight="0" frameborder="0">\\n$end_page');
 1427:     caller.document.close();
 1428:     caller.focus();
 1429: }
 1430: // END LON-CAPA Internal -->
 1431: // ]]>
 1432: </script>
 1433: ENDTEMPLATE
 1434:     return $template;
 1435: }
 1436: 
 1437: sub help_open_bug {
 1438:     my ($topic, $text, $stayOnPage, $width, $height) = @_;
 1439:     unless ($env{'user.adv'}) { return ''; }
 1440:     unless ($Apache::lonnet::perlvar{'BugzillaHost'}) { return ''; }
 1441:     $text = "" if (not defined $text);
 1442: 	$stayOnPage=1;
 1443:     $width = 600 if (not defined $width);
 1444:     $height = 600 if (not defined $height);
 1445: 
 1446:     $topic=~s/\W+/\+/g;
 1447:     my $link='';
 1448:     my $template='';
 1449:     my $url=$Apache::lonnet::perlvar{'BugzillaHost'}.'enter_bug.cgi?product=LON-CAPA&amp;bug_file_loc='.
 1450: 	&escape($ENV{'REQUEST_URI'}).'&amp;component='.$topic;
 1451:     if (!$stayOnPage)
 1452:     {
 1453: 	$link = "javascript:void(open('$url', 'Bugzilla', 'menubar=0,toolbar=1,scrollbars=1,width=$width,height=$height,resizable=yes'))";
 1454:     }
 1455:     else
 1456:     {
 1457: 	$link = $url;
 1458:     }
 1459:     # Add the text
 1460:     if ($text ne "")
 1461:     {
 1462: 	$template .= 
 1463:   "<table bgcolor='#AA3333' cellspacing='1' cellpadding='1' border='0'><tr>".
 1464:   "<td bgcolor='#FF5555'><a target=\"_top\" href=\"$link\"><span style=\"color:#FFFFFF;font-size:10pt;\">$text</span></a>";
 1465:     }
 1466: 
 1467:     # Add the graphic
 1468:     my $title = &mt('Report a Bug');
 1469:     my $bugicon=&lonhttpdurl("/adm/lonMisc/smallBug.gif");
 1470:     $template .= <<"ENDTEMPLATE";
 1471:  <a target="_top" href="$link" title="$title"><img src="$bugicon" border="0" alt="(Bug: $topic)" /></a>
 1472: ENDTEMPLATE
 1473:     if ($text ne '') { $template.='</td></tr></table>' };
 1474:     return $template;
 1475: 
 1476: }
 1477: 
 1478: sub help_open_faq {
 1479:     my ($topic, $text, $stayOnPage, $width, $height) = @_;
 1480:     unless ($env{'user.adv'}) { return ''; }
 1481:     unless ($Apache::lonnet::perlvar{'FAQHost'}) { return ''; }
 1482:     $text = "" if (not defined $text);
 1483: 	$stayOnPage=1;
 1484:     $width = 350 if (not defined $width);
 1485:     $height = 400 if (not defined $height);
 1486: 
 1487:     $topic=~s/\W+/\+/g;
 1488:     my $link='';
 1489:     my $template='';
 1490:     my $url=$Apache::lonnet::perlvar{'FAQHost'}.'/fom/cache/'.$topic.'.html';
 1491:     if (!$stayOnPage)
 1492:     {
 1493: 	$link = "javascript:void(open('$url', 'FAQ-O-Matic', 'menubar=0,toolbar=1,scrollbars=1,width=$width,height=$height,resizable=yes'))";
 1494:     }
 1495:     else
 1496:     {
 1497: 	$link = $url;
 1498:     }
 1499: 
 1500:     # Add the text
 1501:     if ($text ne "")
 1502:     {
 1503: 	$template .= 
 1504:   "<table bgcolor='#337733' cellspacing='1' cellpadding='1' border='0'><tr>".
 1505:   "<td bgcolor='#448844'><a target=\"_top\" href=\"$link\"><span style=\"color:#FFFFFF; font-size:10pt;\">$text</span></a>";
 1506:     }
 1507: 
 1508:     # Add the graphic
 1509:     my $title = &mt('View the FAQ');
 1510:     my $faqicon=&lonhttpdurl("/adm/lonMisc/smallFAQ.gif");
 1511:     $template .= <<"ENDTEMPLATE";
 1512:  <a target="_top" href="$link" title="$title"><img src="$faqicon" border="0" alt="(FAQ: $topic)" /></a>
 1513: ENDTEMPLATE
 1514:     if ($text ne '') { $template.='</td></tr></table>' };
 1515:     return $template;
 1516: 
 1517: }
 1518: 
 1519: ###############################################################
 1520: ###############################################################
 1521: 
 1522: =pod
 1523: 
 1524: =item * &change_content_javascript():
 1525: 
 1526: This and the next function allow you to create small sections of an
 1527: otherwise static HTML page that you can update on the fly with
 1528: Javascript, even in Netscape 4.
 1529: 
 1530: The Javascript fragment returned by this function (no E<lt>scriptE<gt> tag)
 1531: must be written to the HTML page once. It will prove the Javascript
 1532: function "change(name, content)". Calling the change function with the
 1533: name of the section 
 1534: you want to update, matching the name passed to C<changable_area>, and
 1535: the new content you want to put in there, will put the content into
 1536: that area.
 1537: 
 1538: B<Note>: Netscape 4 only reserves enough space for the changable area
 1539: to contain room for the original contents. You need to "make space"
 1540: for whatever changes you wish to make, and be B<sure> to check your
 1541: code in Netscape 4. This feature in Netscape 4 is B<not> powerful;
 1542: it's adequate for updating a one-line status display, but little more.
 1543: This script will set the space to 100% width, so you only need to
 1544: worry about height in Netscape 4.
 1545: 
 1546: Modern browsers are much less limiting, and if you can commit to the
 1547: user not using Netscape 4, this feature may be used freely with
 1548: pretty much any HTML.
 1549: 
 1550: =cut
 1551: 
 1552: sub change_content_javascript {
 1553:     # If we're on Netscape 4, we need to use Layer-based code
 1554:     if ($env{'browser.type'} eq 'netscape' &&
 1555: 	$env{'browser.version'} =~ /^4\./) {
 1556: 	return (<<NETSCAPE4);
 1557: 	function change(name, content) {
 1558: 	    doc = document.layers[name+"___escape"].layers[0].document;
 1559: 	    doc.open();
 1560: 	    doc.write(content);
 1561: 	    doc.close();
 1562: 	}
 1563: NETSCAPE4
 1564:     } else {
 1565: 	# Otherwise, we need to use semi-standards-compliant code
 1566: 	# (technically, "innerHTML" isn't standard but the equivalent
 1567: 	# is really scary, and every useful browser supports it
 1568: 	return (<<DOMBASED);
 1569: 	function change(name, content) {
 1570: 	    element = document.getElementById(name);
 1571: 	    element.innerHTML = content;
 1572: 	}
 1573: DOMBASED
 1574:     }
 1575: }
 1576: 
 1577: =pod
 1578: 
 1579: =item * &changable_area($name,$origContent):
 1580: 
 1581: This provides a "changable area" that can be modified on the fly via
 1582: the Javascript code provided in C<change_content_javascript>. $name is
 1583: the name you will use to reference the area later; do not repeat the
 1584: same name on a given HTML page more then once. $origContent is what
 1585: the area will originally contain, which can be left blank.
 1586: 
 1587: =cut
 1588: 
 1589: sub changable_area {
 1590:     my ($name, $origContent) = @_;
 1591: 
 1592:     if ($env{'browser.type'} eq 'netscape' &&
 1593: 	$env{'browser.version'} =~ /^4\./) {
 1594: 	# If this is netscape 4, we need to use the Layer tag
 1595: 	return "<ilayer width='100%' id='${name}___escape' overflow='none'><layer width='100%' id='$name' overflow='none'>$origContent</layer></ilayer>";
 1596:     } else {
 1597: 	return "<span id='$name'>$origContent</span>";
 1598:     }
 1599: }
 1600: 
 1601: =pod
 1602: 
 1603: =item * &viewport_geometry_js 
 1604: 
 1605: Provides javascript object (Geometry) which can provide information about the viewport geometry for the client browser.
 1606: 
 1607: =cut
 1608: 
 1609: 
 1610: sub viewport_geometry_js { 
 1611:     return <<"GEOMETRY";
 1612: var Geometry = {};
 1613: function init_geometry() {
 1614:     if (Geometry.init) { return };
 1615:     Geometry.init=1;
 1616:     if (window.innerHeight) {
 1617:         Geometry.getViewportHeight   = function() { return window.innerHeight; };
 1618:         Geometry.getViewportWidth   = function() { return window.innerWidth; };
 1619:         Geometry.getHorizontalScroll = function() { return window.pageXOffset; };
 1620:         Geometry.getVerticalScroll   = function() { return window.pageYOffset; };
 1621:     }
 1622:     else if (document.documentElement && document.documentElement.clientHeight) {
 1623:         Geometry.getViewportHeight =
 1624:             function() { return document.documentElement.clientHeight; };
 1625:         Geometry.getViewportWidth =
 1626:             function() { return document.documentElement.clientWidth; };
 1627: 
 1628:         Geometry.getHorizontalScroll =
 1629:             function() { return document.documentElement.scrollLeft; };
 1630:         Geometry.getVerticalScroll =
 1631:             function() { return document.documentElement.scrollTop; };
 1632:     }
 1633:     else if (document.body.clientHeight) {
 1634:         Geometry.getViewportHeight =
 1635:             function() { return document.body.clientHeight; };
 1636:         Geometry.getViewportWidth =
 1637:             function() { return document.body.clientWidth; };
 1638:         Geometry.getHorizontalScroll =
 1639:             function() { return document.body.scrollLeft; };
 1640:         Geometry.getVerticalScroll =
 1641:             function() { return document.body.scrollTop; };
 1642:     }
 1643: }
 1644: 
 1645: GEOMETRY
 1646: }
 1647: 
 1648: =pod
 1649: 
 1650: =item * &viewport_size_js()
 1651: 
 1652: 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. 
 1653: 
 1654: =cut
 1655: 
 1656: sub viewport_size_js {
 1657:     my $geometry = &viewport_geometry_js();
 1658:     return <<"DIMS";
 1659: 
 1660: $geometry
 1661: 
 1662: function getViewportDims(width,height) {
 1663:     init_geometry();
 1664:     width.value = Geometry.getViewportWidth();
 1665:     height.value = Geometry.getViewportHeight();
 1666:     return;
 1667: }
 1668: 
 1669: DIMS
 1670: }
 1671: 
 1672: =pod
 1673: 
 1674: =item * &resize_textarea_js()
 1675: 
 1676: emits the needed javascript to resize a textarea to be as big as possible
 1677: 
 1678: creates a function resize_textrea that takes two IDs first should be
 1679: the id of the element to resize, second should be the id of a div that
 1680: surrounds everything that comes after the textarea, this routine needs
 1681: to be attached to the <body> for the onload and onresize events.
 1682: 
 1683: =back
 1684: 
 1685: =cut
 1686: 
 1687: sub resize_textarea_js {
 1688:     my $geometry = &viewport_geometry_js();
 1689:     return <<"RESIZE";
 1690:     <script type="text/javascript">
 1691: // <![CDATA[
 1692: $geometry
 1693: 
 1694: function getX(element) {
 1695:     var x = 0;
 1696:     while (element) {
 1697: 	x += element.offsetLeft;
 1698: 	element = element.offsetParent;
 1699:     }
 1700:     return x;
 1701: }
 1702: function getY(element) {
 1703:     var y = 0;
 1704:     while (element) {
 1705: 	y += element.offsetTop;
 1706: 	element = element.offsetParent;
 1707:     }
 1708:     return y;
 1709: }
 1710: 
 1711: 
 1712: function resize_textarea(textarea_id,bottom_id) {
 1713:     init_geometry();
 1714:     var textarea        = document.getElementById(textarea_id);
 1715:     //alert(textarea);
 1716: 
 1717:     var textarea_top    = getY(textarea);
 1718:     var textarea_height = textarea.offsetHeight;
 1719:     var bottom          = document.getElementById(bottom_id);
 1720:     var bottom_top      = getY(bottom);
 1721:     var bottom_height   = bottom.offsetHeight;
 1722:     var window_height   = Geometry.getViewportHeight();
 1723:     var fudge           = 23;
 1724:     var new_height      = window_height-fudge-textarea_top-bottom_height;
 1725:     if (new_height < 300) {
 1726: 	new_height = 300;
 1727:     }
 1728:     textarea.style.height=new_height+'px';
 1729: }
 1730: // ]]>
 1731: </script>
 1732: RESIZE
 1733: 
 1734: }
 1735: 
 1736: =pod
 1737: 
 1738: =head1 Excel and CSV file utility routines
 1739: 
 1740: =cut
 1741: 
 1742: ###############################################################
 1743: ###############################################################
 1744: 
 1745: =pod
 1746: 
 1747: =over 4
 1748: 
 1749: =item * &csv_translate($text) 
 1750: 
 1751: Translate $text to allow it to be output as a 'comma separated values' 
 1752: format.
 1753: 
 1754: =cut
 1755: 
 1756: ###############################################################
 1757: ###############################################################
 1758: sub csv_translate {
 1759:     my $text = shift;
 1760:     $text =~ s/\"/\"\"/g;
 1761:     $text =~ s/\n/ /g;
 1762:     return $text;
 1763: }
 1764: 
 1765: ###############################################################
 1766: ###############################################################
 1767: 
 1768: =pod
 1769: 
 1770: =item * &define_excel_formats()
 1771: 
 1772: Define some commonly used Excel cell formats.
 1773: 
 1774: Currently supported formats:
 1775: 
 1776: =over 4
 1777: 
 1778: =item header
 1779: 
 1780: =item bold
 1781: 
 1782: =item h1
 1783: 
 1784: =item h2
 1785: 
 1786: =item h3
 1787: 
 1788: =item h4
 1789: 
 1790: =item i
 1791: 
 1792: =item date
 1793: 
 1794: =back
 1795: 
 1796: Inputs: $workbook
 1797: 
 1798: Returns: $format, a hash reference.
 1799: 
 1800: 
 1801: =cut
 1802: 
 1803: ###############################################################
 1804: ###############################################################
 1805: sub define_excel_formats {
 1806:     my ($workbook) = @_;
 1807:     my $format;
 1808:     $format->{'header'} = $workbook->add_format(bold      => 1, 
 1809:                                                 bottom    => 1,
 1810:                                                 align     => 'center');
 1811:     $format->{'bold'} = $workbook->add_format(bold=>1);
 1812:     $format->{'h1'}   = $workbook->add_format(bold=>1, size=>18);
 1813:     $format->{'h2'}   = $workbook->add_format(bold=>1, size=>16);
 1814:     $format->{'h3'}   = $workbook->add_format(bold=>1, size=>14);
 1815:     $format->{'h4'}   = $workbook->add_format(bold=>1, size=>12);
 1816:     $format->{'i'}    = $workbook->add_format(italic=>1);
 1817:     $format->{'date'} = $workbook->add_format(num_format=>
 1818:                                             'mm/dd/yyyy hh:mm:ss');
 1819:     return $format;
 1820: }
 1821: 
 1822: ###############################################################
 1823: ###############################################################
 1824: 
 1825: =pod
 1826: 
 1827: =item * &create_workbook()
 1828: 
 1829: Create an Excel worksheet.  If it fails, output message on the
 1830: request object and return undefs.
 1831: 
 1832: Inputs: Apache request object
 1833: 
 1834: Returns (undef) on failure, 
 1835:     Excel worksheet object, scalar with filename, and formats 
 1836:     from &Apache::loncommon::define_excel_formats on success
 1837: 
 1838: =cut
 1839: 
 1840: ###############################################################
 1841: ###############################################################
 1842: sub create_workbook {
 1843:     my ($r) = @_;
 1844:         #
 1845:     # Create the excel spreadsheet
 1846:     my $filename = '/prtspool/'.
 1847:         $env{'user.name'}.'_'.$env{'user.domain'}.'_'.
 1848:         time.'_'.rand(1000000000).'.xls';
 1849:     my $workbook  = Spreadsheet::WriteExcel->new('/home/httpd'.$filename);
 1850:     if (! defined($workbook)) {
 1851:         $r->log_error("Error creating excel spreadsheet $filename: $!");
 1852:         $r->print(
 1853:             '<p class="LC_error">'
 1854:            .&mt('Problems occurred in creating the new Excel file.')
 1855:            .' '.&mt('This error has been logged.')
 1856:            .' '.&mt('Please alert your LON-CAPA administrator.')
 1857:            .'</p>'
 1858:         );
 1859:         return (undef);
 1860:     }
 1861:     #
 1862:     $workbook->set_tempdir(LONCAPA::tempdir());
 1863:     #
 1864:     my $format = &Apache::loncommon::define_excel_formats($workbook);
 1865:     return ($workbook,$filename,$format);
 1866: }
 1867: 
 1868: ###############################################################
 1869: ###############################################################
 1870: 
 1871: =pod
 1872: 
 1873: =item * &create_text_file()
 1874: 
 1875: Create a file to write to and eventually make available to the user.
 1876: If file creation fails, outputs an error message on the request object and 
 1877: return undefs.
 1878: 
 1879: Inputs: Apache request object, and file suffix
 1880: 
 1881: Returns (undef) on failure, 
 1882:     Filehandle and filename on success.
 1883: 
 1884: =cut
 1885: 
 1886: ###############################################################
 1887: ###############################################################
 1888: sub create_text_file {
 1889:     my ($r,$suffix) = @_;
 1890:     if (! defined($suffix)) { $suffix = 'txt'; };
 1891:     my $fh;
 1892:     my $filename = '/prtspool/'.
 1893:         $env{'user.name'}.'_'.$env{'user.domain'}.'_'.
 1894:         time.'_'.rand(1000000000).'.'.$suffix;
 1895:     $fh = Apache::File->new('>/home/httpd'.$filename);
 1896:     if (! defined($fh)) {
 1897:         $r->log_error("Couldn't open $filename for output $!");
 1898:         $r->print(
 1899:             '<p class="LC_error">'
 1900:            .&mt('Problems occurred in creating the output file.')
 1901:            .' '.&mt('This error has been logged.')
 1902:            .' '.&mt('Please alert your LON-CAPA administrator.')
 1903:            .'</p>'
 1904:         );
 1905:     }
 1906:     return ($fh,$filename)
 1907: }
 1908: 
 1909: 
 1910: =pod 
 1911: 
 1912: =back
 1913: 
 1914: =cut
 1915: 
 1916: ###############################################################
 1917: ##        Home server <option> list generating code          ##
 1918: ###############################################################
 1919: 
 1920: # ------------------------------------------
 1921: 
 1922: sub domain_select {
 1923:     my ($name,$value,$multiple)=@_;
 1924:     my %domains=map { 
 1925: 	$_ => $_.' '. &Apache::lonnet::domain($_,'description') 
 1926:     } &Apache::lonnet::all_domains();
 1927:     if ($multiple) {
 1928: 	$domains{''}=&mt('Any domain');
 1929: 	$domains{'select_form_order'} = [sort {lc($a) cmp lc($b) } (keys(%domains))];
 1930: 	return &multiple_select_form($name,$value,4,\%domains);
 1931:     } else {
 1932: 	$domains{'select_form_order'} = [sort {lc($a) cmp lc($b) } (keys(%domains))];
 1933: 	return &select_form($name,$value,\%domains);
 1934:     }
 1935: }
 1936: 
 1937: #-------------------------------------------
 1938: 
 1939: =pod
 1940: 
 1941: =head1 Routines for form select boxes
 1942: 
 1943: =over 4
 1944: 
 1945: =item * &multiple_select_form($name,$value,$size,$hash,$order)
 1946: 
 1947: Returns a string containing a <select> element int multiple mode
 1948: 
 1949: 
 1950: Args:
 1951:   $name - name of the <select> element
 1952:   $value - scalar or array ref of values that should already be selected
 1953:   $size - number of rows long the select element is
 1954:   $hash - the elements should be 'option' => 'shown text'
 1955:           (shown text should already have been &mt())
 1956:   $order - (optional) array ref of the order to show the elements in
 1957: 
 1958: =cut
 1959: 
 1960: #-------------------------------------------
 1961: sub multiple_select_form {
 1962:     my ($name,$value,$size,$hash,$order)=@_;
 1963:     my %selected = map { $_ => 1 } ref($value)?@{$value}:($value);
 1964:     my $output='';
 1965:     if (! defined($size)) {
 1966:         $size = 4;
 1967:         if (scalar(keys(%$hash))<4) {
 1968:             $size = scalar(keys(%$hash));
 1969:         }
 1970:     }
 1971:     $output.="\n".'<select name="'.$name.'" size="'.$size.'" multiple="multiple">';
 1972:     my @order;
 1973:     if (ref($order) eq 'ARRAY')  {
 1974:         @order = @{$order};
 1975:     } else {
 1976:         @order = sort(keys(%$hash));
 1977:     }
 1978:     if (exists($$hash{'select_form_order'})) {
 1979:         @order = @{$$hash{'select_form_order'}};
 1980:     }
 1981:         
 1982:     foreach my $key (@order) {
 1983:         $output.='<option value="'.&HTML::Entities::encode($key,'"<>&').'" ';
 1984:         $output.='selected="selected" ' if ($selected{$key});
 1985:         $output.='>'.$hash->{$key}."</option>\n";
 1986:     }
 1987:     $output.="</select>\n";
 1988:     return $output;
 1989: }
 1990: 
 1991: #-------------------------------------------
 1992: 
 1993: =pod
 1994: 
 1995: =item * &select_form($defdom,$name,$hashref,$onchange)
 1996: 
 1997: Returns a string containing a <select name='$name' size='1'> form to 
 1998: allow a user to select options from a ref to a hash containing:
 1999: option_name => displayed text. An optional $onchange can include
 2000: a javascript onchange item, e.g., onchange="this.form.submit();"  
 2001: 
 2002: See lonrights.pm for an example invocation and use.
 2003: 
 2004: =cut
 2005: 
 2006: #-------------------------------------------
 2007: sub select_form {
 2008:     my ($def,$name,$hashref,$onchange) = @_;
 2009:     return unless (ref($hashref) eq 'HASH');
 2010:     if ($onchange) {
 2011:         $onchange = ' onchange="'.$onchange.'"';
 2012:     }
 2013:     my $selectform = "<select name=\"$name\" size=\"1\"$onchange>\n";
 2014:     my @keys;
 2015:     if (exists($hashref->{'select_form_order'})) {
 2016: 	@keys=@{$hashref->{'select_form_order'}};
 2017:     } else {
 2018: 	@keys=sort(keys(%{$hashref}));
 2019:     }
 2020:     foreach my $key (@keys) {
 2021:         $selectform.=
 2022: 	    '<option value="'.&HTML::Entities::encode($key,'"<>&').'" '.
 2023:             ($key eq $def ? 'selected="selected" ' : '').
 2024:                 ">".$hashref->{$key}."</option>\n";
 2025:     }
 2026:     $selectform.="</select>";
 2027:     return $selectform;
 2028: }
 2029: 
 2030: # For display filters
 2031: 
 2032: sub display_filter {
 2033:     my ($context) = @_;
 2034:     if (!$env{'form.show'}) { $env{'form.show'}=10; }
 2035:     if (!$env{'form.displayfilter'}) { $env{'form.displayfilter'}='currentfolder'; }
 2036:     my $phraseinput = 'hidden';
 2037:     my $includeinput = 'hidden';
 2038:     my ($checked,$includetypestext);
 2039:     if ($env{'form.displayfilter'} eq 'containing') {
 2040:         $phraseinput = 'text'; 
 2041:         if ($context eq 'parmslog') {
 2042:             $includeinput = 'checkbox';
 2043:             if ($env{'form.includetypes'}) {
 2044:                 $checked = ' checked="checked"';
 2045:             }
 2046:             $includetypestext = &mt('Include parameter types');
 2047:         }
 2048:     } else {
 2049:         $includetypestext = '&nbsp;';
 2050:     }
 2051:     my ($additional,$secondid,$thirdid);
 2052:     if ($context eq 'parmslog') {
 2053:         $additional = 
 2054:             '<label><input type="'.$includeinput.'" name="includetypes"'. 
 2055:             $checked.' name="includetypes" value="1" id="includetypes" />'.
 2056:             '&nbsp;<span id="includetypestext">'.$includetypestext.'</span>'.
 2057:             '</label>';
 2058:         $secondid = 'includetypes';
 2059:         $thirdid = 'includetypestext';
 2060:     }
 2061:     my $onchange = "javascript:toggleHistoryOptions(this,'containingphrase','$context',
 2062:                                                     '$secondid','$thirdid')";
 2063:     return '<span class="LC_nobreak"><label>'.&mt('Records: [_1]',
 2064: 			       &Apache::lonmeta::selectbox('show',$env{'form.show'},undef,
 2065: 							   (&mt('all'),10,20,50,100,1000,10000))).
 2066: 	   '</label></span> <span class="LC_nobreak">'.
 2067:            &mt('Filter: [_1]',
 2068: 	   &select_form($env{'form.displayfilter'},
 2069: 			'displayfilter',
 2070: 			{'currentfolder' => 'Current folder/page',
 2071: 			 'containing' => 'Containing phrase',
 2072: 			 'none' => 'None'},$onchange)).'&nbsp;'.
 2073: 			 '<input type="'.$phraseinput.'" name="containingphrase" id="containingphrase" size="30" value="'.
 2074:                          &HTML::Entities::encode($env{'form.containingphrase'}).
 2075:                          '" />'.$additional;
 2076: }
 2077: 
 2078: sub display_filter_js {
 2079:     my $includetext = &mt('Include parameter types');
 2080:     return <<"ENDJS";
 2081:   
 2082: function toggleHistoryOptions(setter,firstid,context,secondid,thirdid) {
 2083:     var firstType = 'hidden';
 2084:     if (setter.options[setter.selectedIndex].value == 'containing') {
 2085:         firstType = 'text';
 2086:     }
 2087:     firstObject = document.getElementById(firstid);
 2088:     if (typeof(firstObject) == 'object') {
 2089:         if (firstObject.type != firstType) {
 2090:             changeInputType(firstObject,firstType);
 2091:         }
 2092:     }
 2093:     if (context == 'parmslog') {
 2094:         var secondType = 'hidden';
 2095:         if (firstType == 'text') {
 2096:             secondType = 'checkbox';
 2097:         }
 2098:         secondObject = document.getElementById(secondid);  
 2099:         if (typeof(secondObject) == 'object') {
 2100:             if (secondObject.type != secondType) {
 2101:                 changeInputType(secondObject,secondType);
 2102:             }
 2103:         }
 2104:         var textItem = document.getElementById(thirdid);
 2105:         var currtext = textItem.innerHTML;
 2106:         var newtext;
 2107:         if (firstType == 'text') {
 2108:             newtext = '$includetext';
 2109:         } else {
 2110:             newtext = '&nbsp;';
 2111:         }
 2112:         if (currtext != newtext) {
 2113:             textItem.innerHTML = newtext;
 2114:         }
 2115:     }
 2116:     return;
 2117: }
 2118: 
 2119: function changeInputType(oldObject,newType) {
 2120:     var newObject = document.createElement('input');
 2121:     newObject.type = newType;
 2122:     if (oldObject.size) {
 2123:         newObject.size = oldObject.size;
 2124:     }
 2125:     if (oldObject.value) {
 2126:         newObject.value = oldObject.value;
 2127:     }
 2128:     if (oldObject.name) {
 2129:         newObject.name = oldObject.name;
 2130:     }
 2131:     if (oldObject.id) {
 2132:         newObject.id = oldObject.id;
 2133:     }
 2134:     oldObject.parentNode.replaceChild(newObject,oldObject);
 2135:     return;
 2136: }
 2137: 
 2138: ENDJS
 2139: }
 2140: 
 2141: sub gradeleveldescription {
 2142:     my $gradelevel=shift;
 2143:     my %gradelevels=(0 => 'Not specified',
 2144: 		     1 => 'Grade 1',
 2145: 		     2 => 'Grade 2',
 2146: 		     3 => 'Grade 3',
 2147: 		     4 => 'Grade 4',
 2148: 		     5 => 'Grade 5',
 2149: 		     6 => 'Grade 6',
 2150: 		     7 => 'Grade 7',
 2151: 		     8 => 'Grade 8',
 2152: 		     9 => 'Grade 9',
 2153: 		     10 => 'Grade 10',
 2154: 		     11 => 'Grade 11',
 2155: 		     12 => 'Grade 12',
 2156: 		     13 => 'Grade 13',
 2157: 		     14 => '100 Level',
 2158: 		     15 => '200 Level',
 2159: 		     16 => '300 Level',
 2160: 		     17 => '400 Level',
 2161: 		     18 => 'Graduate Level');
 2162:     return &mt($gradelevels{$gradelevel});
 2163: }
 2164: 
 2165: sub select_level_form {
 2166:     my ($deflevel,$name)=@_;
 2167:     unless ($deflevel) { $deflevel=0; }
 2168:     my $selectform = "<select name=\"$name\" size=\"1\">\n";
 2169:     for (my $i=0; $i<=18; $i++) {
 2170:         $selectform.="<option value=\"$i\" ".
 2171:             ($i==$deflevel ? 'selected="selected" ' : '').
 2172:                 ">".&gradeleveldescription($i)."</option>\n";
 2173:     }
 2174:     $selectform.="</select>";
 2175:     return $selectform;
 2176: }
 2177: 
 2178: #-------------------------------------------
 2179: 
 2180: =pod
 2181: 
 2182: =item * &select_dom_form($defdom,$name,$includeempty,$showdomdesc,$onchange,$incdoms,$excdoms)
 2183: 
 2184: Returns a string containing a <select name='$name' size='1'> form to 
 2185: allow a user to select the domain to preform an operation in.  
 2186: See loncreateuser.pm for an example invocation and use.
 2187: 
 2188: If the $includeempty flag is set, it also includes an empty choice ("no domain
 2189: selected");
 2190: 
 2191: If the $showdomdesc flag is set, the domain name is followed by the domain description.
 2192: 
 2193: 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.
 2194: 
 2195: The optional $incdoms is a reference to an array of domains which will be the only available options.
 2196: 
 2197: The optional $excdoms is a reference to an array of domains which will be excluded from the available options. 
 2198: 
 2199: =cut
 2200: 
 2201: #-------------------------------------------
 2202: sub select_dom_form {
 2203:     my ($defdom,$name,$includeempty,$showdomdesc,$onchange,$incdoms,$excdoms) = @_;
 2204:     if ($onchange) {
 2205:         $onchange = ' onchange="'.$onchange.'"';
 2206:     }
 2207:     my (@domains,%exclude);
 2208:     if (ref($incdoms) eq 'ARRAY') {
 2209:         @domains = sort {lc($a) cmp lc($b)} (@{$incdoms});
 2210:     } else {
 2211:         @domains = sort {lc($a) cmp lc($b)} (&Apache::lonnet::all_domains());
 2212:     }
 2213:     if ($includeempty) { @domains=('',@domains); }
 2214:     if (ref($excdoms) eq 'ARRAY') {
 2215:         map { $exclude{$_} = 1; } @{$excdoms};
 2216:     }
 2217:     my $selectdomain = "<select name=\"$name\" size=\"1\"$onchange>\n";
 2218:     foreach my $dom (@domains) {
 2219:         next if ($exclude{$dom});
 2220:         $selectdomain.="<option value=\"$dom\" ".
 2221:             ($dom eq $defdom ? 'selected="selected" ' : '').'>'.$dom;
 2222:         if ($showdomdesc) {
 2223:             if ($dom ne '') {
 2224:                 my $domdesc = &Apache::lonnet::domain($dom,'description');
 2225:                 if ($domdesc ne '') {
 2226:                     $selectdomain .= ' ('.$domdesc.')';
 2227:                 }
 2228:             } 
 2229:         }
 2230:         $selectdomain .= "</option>\n";
 2231:     }
 2232:     $selectdomain.="</select>";
 2233:     return $selectdomain;
 2234: }
 2235: 
 2236: #-------------------------------------------
 2237: 
 2238: =pod
 2239: 
 2240: =item * &home_server_form_item($domain,$name,$defaultflag)
 2241: 
 2242: input: 4 arguments (two required, two optional) - 
 2243:     $domain - domain of new user
 2244:     $name - name of form element
 2245:     $default - Value of 'default' causes a default item to be first 
 2246:                             option, and selected by default. 
 2247:     $hide - Value of 'hide' causes hiding of the name of the server, 
 2248:                             if 1 server found, or default, if 0 found.
 2249: output: returns 2 items: 
 2250: (a) form element which contains either:
 2251:    (i) <select name="$name">
 2252:         <option value="$hostid1">$hostid $servers{$hostid}</option>
 2253:         <option value="$hostid2">$hostid $servers{$hostid}</option>       
 2254:        </select>
 2255:        form item if there are multiple library servers in $domain, or
 2256:    (ii) an <input type="hidden" name="$name" value="$hostid" /> form item 
 2257:        if there is only one library server in $domain.
 2258: 
 2259: (b) number of library servers found.
 2260: 
 2261: See loncreateuser.pm for example of use.
 2262: 
 2263: =cut
 2264: 
 2265: #-------------------------------------------
 2266: sub home_server_form_item {
 2267:     my ($domain,$name,$default,$hide) = @_;
 2268:     my %servers = &Apache::lonnet::get_servers($domain,'library');
 2269:     my $result;
 2270:     my $numlib = keys(%servers);
 2271:     if ($numlib > 1) {
 2272:         $result .= '<select name="'.$name.'" />'."\n";
 2273:         if ($default) {
 2274:             $result .= '<option value="default" selected="selected">'.&mt('default').
 2275:                        '</option>'."\n";
 2276:         }
 2277:         foreach my $hostid (sort(keys(%servers))) {
 2278:             $result.= '<option value="'.$hostid.'">'.
 2279: 	              $hostid.' '.$servers{$hostid}."</option>\n";
 2280:         }
 2281:         $result .= '</select>'."\n";
 2282:     } elsif ($numlib == 1) {
 2283:         my $hostid;
 2284:         foreach my $item (keys(%servers)) {
 2285:             $hostid = $item;
 2286:         }
 2287:         $result .= '<input type="hidden" name="'.$name.'" value="'.
 2288:                    $hostid.'" />';
 2289:                    if (!$hide) {
 2290:                        $result .= $hostid.' '.$servers{$hostid};
 2291:                    }
 2292:                    $result .= "\n";
 2293:     } elsif ($default) {
 2294:         $result .= '<input type="hidden" name="'.$name.
 2295:                    '" value="default" />';
 2296:                    if (!$hide) {
 2297:                        $result .= &mt('default');
 2298:                    }
 2299:                    $result .= "\n";
 2300:     }
 2301:     return ($result,$numlib);
 2302: }
 2303: 
 2304: =pod
 2305: 
 2306: =back 
 2307: 
 2308: =cut
 2309: 
 2310: ###############################################################
 2311: ##                  Decoding User Agent                      ##
 2312: ###############################################################
 2313: 
 2314: =pod
 2315: 
 2316: =head1 Decoding the User Agent
 2317: 
 2318: =over 4
 2319: 
 2320: =item * &decode_user_agent()
 2321: 
 2322: Inputs: $r
 2323: 
 2324: Outputs:
 2325: 
 2326: =over 4
 2327: 
 2328: =item * $httpbrowser
 2329: 
 2330: =item * $clientbrowser
 2331: 
 2332: =item * $clientversion
 2333: 
 2334: =item * $clientmathml
 2335: 
 2336: =item * $clientunicode
 2337: 
 2338: =item * $clientos
 2339: 
 2340: =item * $clientmobile
 2341: 
 2342: =item * $clientinfo
 2343: 
 2344: =item * $clientosversion
 2345: 
 2346: =back
 2347: 
 2348: =back 
 2349: 
 2350: =cut
 2351: 
 2352: ###############################################################
 2353: ###############################################################
 2354: sub decode_user_agent {
 2355:     my ($r)=@_;
 2356:     my @browsertype=split(/\&/,$Apache::lonnet::perlvar{"lonBrowsDet"});
 2357:     my %mathcap=split(/\&/,$$Apache::lonnet::perlvar{"lonMathML"});
 2358:     my $httpbrowser=$ENV{"HTTP_USER_AGENT"};
 2359:     if (!$httpbrowser && $r) { $httpbrowser=$r->header_in('User-Agent'); }
 2360:     my $clientbrowser='unknown';
 2361:     my $clientversion='0';
 2362:     my $clientmathml='';
 2363:     my $clientunicode='0';
 2364:     my $clientmobile=0;
 2365:     my $clientosversion='';
 2366:     for (my $i=0;$i<=$#browsertype;$i++) {
 2367:         my ($bname,$match,$notmatch,$vreg,$minv,$univ)=split(/\%/,$browsertype[$i]);
 2368: 	if (($httpbrowser=~/$match/i)  && ($httpbrowser!~/$notmatch/i)) {
 2369: 	    $clientbrowser=$bname;
 2370:             $httpbrowser=~/$vreg/i;
 2371: 	    $clientversion=$1;
 2372:             $clientmathml=($clientversion>=$minv);
 2373:             $clientunicode=($clientversion>=$univ);
 2374: 	}
 2375:     }
 2376:     my $clientos='unknown';
 2377:     my $clientinfo;
 2378:     if (($httpbrowser=~/linux/i) ||
 2379:         ($httpbrowser=~/unix/i) ||
 2380:         ($httpbrowser=~/ux/i) ||
 2381:         ($httpbrowser=~/solaris/i)) { $clientos='unix'; }
 2382:     if (($httpbrowser=~/vax/i) ||
 2383:         ($httpbrowser=~/vms/i)) { $clientos='vms'; }
 2384:     if ($httpbrowser=~/next/i) { $clientos='next'; }
 2385:     if (($httpbrowser=~/mac/i) ||
 2386:         ($httpbrowser=~/powerpc/i)) { $clientos='mac'; }
 2387:     if ($httpbrowser=~/win/i) {
 2388:         $clientos='win';
 2389:         if ($httpbrowser =~/Windows\s+NT\s+(\d+\.\d+)/i) {
 2390:             $clientosversion = $1;
 2391:         }
 2392:     }
 2393:     if ($httpbrowser=~/embed/i) { $clientos='pda'; }
 2394:     if ($httpbrowser=~/(Android|iPod|iPad|iPhone|webOS|Blackberry|Windows Phone|Opera m(?:ob|in)|Fennec)/i) {
 2395:         $clientmobile=lc($1);
 2396:     }
 2397:     if ($httpbrowser=~ m{Firefox/(\d+\.\d+)}) {
 2398:         $clientinfo = 'firefox-'.$1;
 2399:     } elsif ($httpbrowser=~ m{chromeframe/(\d+\.\d+)\.}) {
 2400:         $clientinfo = 'chromeframe-'.$1;
 2401:     }
 2402:     return ($httpbrowser,$clientbrowser,$clientversion,$clientmathml,
 2403:             $clientunicode,$clientos,$clientmobile,$clientinfo,
 2404:             $clientosversion);
 2405: }
 2406: 
 2407: ###############################################################
 2408: ##    Authentication changing form generation subroutines    ##
 2409: ###############################################################
 2410: ##
 2411: ## All of the authform_xxxxxxx subroutines take their inputs in a
 2412: ## hash, and have reasonable default values.
 2413: ##
 2414: ##    formname = the name given in the <form> tag.
 2415: #-------------------------------------------
 2416: 
 2417: =pod
 2418: 
 2419: =head1 Authentication Routines
 2420: 
 2421: =over 4
 2422: 
 2423: =item * &authform_xxxxxx()
 2424: 
 2425: The authform_xxxxxx subroutines provide javascript and html forms which 
 2426: handle some of the conveniences required for authentication forms.  
 2427: This is not an optimal method, but it works.  
 2428: 
 2429: =over 4
 2430: 
 2431: =item * authform_header
 2432: 
 2433: =item * authform_authorwarning
 2434: 
 2435: =item * authform_nochange
 2436: 
 2437: =item * authform_kerberos
 2438: 
 2439: =item * authform_internal
 2440: 
 2441: =item * authform_filesystem
 2442: 
 2443: =back
 2444: 
 2445: See loncreateuser.pm for invocation and use examples.
 2446: 
 2447: =cut
 2448: 
 2449: #-------------------------------------------
 2450: sub authform_header{  
 2451:     my %in = (
 2452:         formname => 'cu',
 2453:         kerb_def_dom => '',
 2454:         @_,
 2455:     );
 2456:     $in{'formname'} = 'document.' . $in{'formname'};
 2457:     my $result='';
 2458: 
 2459: #---------------------------------------------- Code for upper case translation
 2460:     my $Javascript_toUpperCase;
 2461:     unless ($in{kerb_def_dom}) {
 2462:         $Javascript_toUpperCase =<<"END";
 2463:         switch (choice) {
 2464:            case 'krb': currentform.elements[choicearg].value =
 2465:                currentform.elements[choicearg].value.toUpperCase();
 2466:                break;
 2467:            default:
 2468:         }
 2469: END
 2470:     } else {
 2471:         $Javascript_toUpperCase = "";
 2472:     }
 2473: 
 2474:     my $radioval = "'nochange'";
 2475:     if (defined($in{'curr_authtype'})) {
 2476:         if ($in{'curr_authtype'} ne '') {
 2477:             $radioval = "'".$in{'curr_authtype'}."arg'";
 2478:         }
 2479:     }
 2480:     my $argfield = 'null';
 2481:     if (defined($in{'mode'})) {
 2482:         if ($in{'mode'} eq 'modifycourse')  {
 2483:             if (defined($in{'curr_autharg'})) {
 2484:                 if ($in{'curr_autharg'} ne '') {
 2485:                     $argfield = "'$in{'curr_autharg'}'";
 2486:                 }
 2487:             }
 2488:         }
 2489:     }
 2490: 
 2491:     $result.=<<"END";
 2492: var current = new Object();
 2493: current.radiovalue = $radioval;
 2494: current.argfield = $argfield;
 2495: 
 2496: function changed_radio(choice,currentform) {
 2497:     var choicearg = choice + 'arg';
 2498:     // If a radio button in changed, we need to change the argfield
 2499:     if (current.radiovalue != choice) {
 2500:         current.radiovalue = choice;
 2501:         if (current.argfield != null) {
 2502:             currentform.elements[current.argfield].value = '';
 2503:         }
 2504:         if (choice == 'nochange') {
 2505:             current.argfield = null;
 2506:         } else {
 2507:             current.argfield = choicearg;
 2508:             switch(choice) {
 2509:                 case 'krb': 
 2510:                     currentform.elements[current.argfield].value = 
 2511:                         "$in{'kerb_def_dom'}";
 2512:                 break;
 2513:               default:
 2514:                 break;
 2515:             }
 2516:         }
 2517:     }
 2518:     return;
 2519: }
 2520: 
 2521: function changed_text(choice,currentform) {
 2522:     var choicearg = choice + 'arg';
 2523:     if (currentform.elements[choicearg].value !='') {
 2524:         $Javascript_toUpperCase
 2525:         // clear old field
 2526:         if ((current.argfield != choicearg) && (current.argfield != null)) {
 2527:             currentform.elements[current.argfield].value = '';
 2528:         }
 2529:         current.argfield = choicearg;
 2530:     }
 2531:     set_auth_radio_buttons(choice,currentform);
 2532:     return;
 2533: }
 2534: 
 2535: function set_auth_radio_buttons(newvalue,currentform) {
 2536:     var numauthchoices = currentform.login.length;
 2537:     if (typeof numauthchoices  == "undefined") {
 2538:         return;
 2539:     } 
 2540:     var i=0;
 2541:     while (i < numauthchoices) {
 2542:         if (currentform.login[i].value == newvalue) { break; }
 2543:         i++;
 2544:     }
 2545:     if (i == numauthchoices) {
 2546:         return;
 2547:     }
 2548:     current.radiovalue = newvalue;
 2549:     currentform.login[i].checked = true;
 2550:     return;
 2551: }
 2552: END
 2553:     return $result;
 2554: }
 2555: 
 2556: sub authform_authorwarning {
 2557:     my $result='';
 2558:     $result='<i>'.
 2559:         &mt('As a general rule, only authors or co-authors should be '.
 2560:             'filesystem authenticated '.
 2561:             '(which allows access to the server filesystem).')."</i>\n";
 2562:     return $result;
 2563: }
 2564: 
 2565: sub authform_nochange {
 2566:     my %in = (
 2567:               formname => 'document.cu',
 2568:               kerb_def_dom => 'MSU.EDU',
 2569:               @_,
 2570:           );
 2571:     my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'}); 
 2572:     my $result;
 2573:     if (!$authnum) {
 2574:         $result = &mt('Under your current role you are not permitted to change login settings for this user');
 2575:     } else {
 2576:         $result = '<label>'.&mt('[_1] Do not change login data',
 2577:                   '<input type="radio" name="login" value="nochange" '.
 2578:                   'checked="checked" onclick="'.
 2579:             "javascript:changed_radio('nochange',$in{'formname'});".'" />').
 2580: 	    '</label>';
 2581:     }
 2582:     return $result;
 2583: }
 2584: 
 2585: sub authform_kerberos {
 2586:     my %in = (
 2587:               formname => 'document.cu',
 2588:               kerb_def_dom => 'MSU.EDU',
 2589:               kerb_def_auth => 'krb4',
 2590:               @_,
 2591:               );
 2592:     my ($check4,$check5,$krbcheck,$krbarg,$krbver,$result,$authtype,
 2593:         $autharg,$jscall);
 2594:     my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
 2595:     if ($in{'kerb_def_auth'} eq 'krb5') {
 2596:        $check5 = ' checked="checked"';
 2597:     } else {
 2598:        $check4 = ' checked="checked"';
 2599:     }
 2600:     $krbarg = $in{'kerb_def_dom'};
 2601:     if (defined($in{'curr_authtype'})) {
 2602:         if ($in{'curr_authtype'} eq 'krb') {
 2603:             $krbcheck = ' checked="checked"';
 2604:             if (defined($in{'mode'})) {
 2605:                 if ($in{'mode'} eq 'modifyuser') {
 2606:                     $krbcheck = '';
 2607:                 }
 2608:             }
 2609:             if (defined($in{'curr_kerb_ver'})) {
 2610:                 if ($in{'curr_krb_ver'} eq '5') {
 2611:                     $check5 = ' checked="checked"';
 2612:                     $check4 = '';
 2613:                 } else {
 2614:                     $check4 = ' checked="checked"';
 2615:                     $check5 = '';
 2616:                 }
 2617:             }
 2618:             if (defined($in{'curr_autharg'})) {
 2619:                 $krbarg = $in{'curr_autharg'};
 2620:             }
 2621:             if (!$can_assign{'krb4'} && !$can_assign{'krb5'}) {
 2622:                 if (defined($in{'curr_autharg'})) {
 2623:                     $result = 
 2624:     &mt('Currently Kerberos authenticated with domain [_1] Version [_2].',
 2625:         $in{'curr_autharg'},$krbver);
 2626:                 } else {
 2627:                     $result =
 2628:     &mt('Currently Kerberos authenticated, Version [_1].',$krbver);
 2629:                 }
 2630:                 return $result; 
 2631:             }
 2632:         }
 2633:     } else {
 2634:         if ($authnum == 1) {
 2635:             $authtype = '<input type="hidden" name="login" value="krb" />';
 2636:         }
 2637:     }
 2638:     if (!$can_assign{'krb4'} && !$can_assign{'krb5'}) {
 2639:         return;
 2640:     } elsif ($authtype eq '') {
 2641:         if (defined($in{'mode'})) {
 2642:             if ($in{'mode'} eq 'modifycourse') {
 2643:                 if ($authnum == 1) {
 2644:                     $authtype = '<input type="radio" name="login" value="krb" />';
 2645:                 }
 2646:             }
 2647:         }
 2648:     }
 2649:     $jscall = "javascript:changed_radio('krb',$in{'formname'});";
 2650:     if ($authtype eq '') {
 2651:         $authtype = '<input type="radio" name="login" value="krb" '.
 2652:                     'onclick="'.$jscall.'" onchange="'.$jscall.'"'.
 2653:                     $krbcheck.' />';
 2654:     }
 2655:     if (($can_assign{'krb4'} && $can_assign{'krb5'}) ||
 2656:         ($can_assign{'krb4'} && !$can_assign{'krb5'} &&
 2657:          $in{'curr_authtype'} eq 'krb5') ||
 2658:         (!$can_assign{'krb4'} && $can_assign{'krb5'} &&
 2659:          $in{'curr_authtype'} eq 'krb4')) {
 2660:         $result .= &mt
 2661:         ('[_1] Kerberos authenticated with domain [_2] '.
 2662:          '[_3] Version 4 [_4] Version 5 [_5]',
 2663:          '<label>'.$authtype,
 2664:          '</label><input type="text" size="10" name="krbarg" '.
 2665:              'value="'.$krbarg.'" '.
 2666:              'onchange="'.$jscall.'" />',
 2667:          '<label><input type="radio" name="krbver" value="4" '.$check4.' />',
 2668:          '</label><label><input type="radio" name="krbver" value="5" '.$check5.' />',
 2669: 	 '</label>');
 2670:     } elsif ($can_assign{'krb4'}) {
 2671:         $result .= &mt
 2672:         ('[_1] Kerberos authenticated with domain [_2] '.
 2673:          '[_3] Version 4 [_4]',
 2674:          '<label>'.$authtype,
 2675:          '</label><input type="text" size="10" name="krbarg" '.
 2676:              'value="'.$krbarg.'" '.
 2677:              'onchange="'.$jscall.'" />',
 2678:          '<label><input type="hidden" name="krbver" value="4" />',
 2679:          '</label>');
 2680:     } elsif ($can_assign{'krb5'}) {
 2681:         $result .= &mt
 2682:         ('[_1] Kerberos authenticated with domain [_2] '.
 2683:          '[_3] Version 5 [_4]',
 2684:          '<label>'.$authtype,
 2685:          '</label><input type="text" size="10" name="krbarg" '.
 2686:              'value="'.$krbarg.'" '.
 2687:              'onchange="'.$jscall.'" />',
 2688:          '<label><input type="hidden" name="krbver" value="5" />',
 2689:          '</label>');
 2690:     }
 2691:     return $result;
 2692: }
 2693: 
 2694: sub authform_internal {
 2695:     my %in = (
 2696:                 formname => 'document.cu',
 2697:                 kerb_def_dom => 'MSU.EDU',
 2698:                 @_,
 2699:                 );
 2700:     my ($intcheck,$intarg,$result,$authtype,$autharg,$jscall);
 2701:     my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
 2702:     if (defined($in{'curr_authtype'})) {
 2703:         if ($in{'curr_authtype'} eq 'int') {
 2704:             if ($can_assign{'int'}) {
 2705:                 $intcheck = 'checked="checked" ';
 2706:                 if (defined($in{'mode'})) {
 2707:                     if ($in{'mode'} eq 'modifyuser') {
 2708:                         $intcheck = '';
 2709:                     }
 2710:                 }
 2711:                 if (defined($in{'curr_autharg'})) {
 2712:                     $intarg = $in{'curr_autharg'};
 2713:                 }
 2714:             } else {
 2715:                 $result = &mt('Currently internally authenticated.');
 2716:                 return $result;
 2717:             }
 2718:         }
 2719:     } else {
 2720:         if ($authnum == 1) {
 2721:             $authtype = '<input type="hidden" name="login" value="int" />';
 2722:         }
 2723:     }
 2724:     if (!$can_assign{'int'}) {
 2725:         return;
 2726:     } elsif ($authtype eq '') {
 2727:         if (defined($in{'mode'})) {
 2728:             if ($in{'mode'} eq 'modifycourse') {
 2729:                 if ($authnum == 1) {
 2730:                     $authtype = '<input type="radio" name="login" value="int" />';
 2731:                 }
 2732:             }
 2733:         }
 2734:     }
 2735:     $jscall = "javascript:changed_radio('int',$in{'formname'});";
 2736:     if ($authtype eq '') {
 2737:         $authtype = '<input type="radio" name="login" value="int" '.$intcheck.
 2738:                     ' onchange="'.$jscall.'" onclick="'.$jscall.'" />';
 2739:     }
 2740:     $autharg = '<input type="password" size="10" name="intarg" value="'.
 2741:                $intarg.'" onchange="'.$jscall.'" />';
 2742:     $result = &mt
 2743:         ('[_1] Internally authenticated (with initial password [_2])',
 2744:          '<label>'.$authtype,'</label>'.$autharg);
 2745:     $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>';
 2746:     return $result;
 2747: }
 2748: 
 2749: sub authform_local {
 2750:     my %in = (
 2751:               formname => 'document.cu',
 2752:               kerb_def_dom => 'MSU.EDU',
 2753:               @_,
 2754:               );
 2755:     my ($loccheck,$locarg,$result,$authtype,$autharg,$jscall);
 2756:     my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
 2757:     if (defined($in{'curr_authtype'})) {
 2758:         if ($in{'curr_authtype'} eq 'loc') {
 2759:             if ($can_assign{'loc'}) {
 2760:                 $loccheck = 'checked="checked" ';
 2761:                 if (defined($in{'mode'})) {
 2762:                     if ($in{'mode'} eq 'modifyuser') {
 2763:                         $loccheck = '';
 2764:                     }
 2765:                 }
 2766:                 if (defined($in{'curr_autharg'})) {
 2767:                     $locarg = $in{'curr_autharg'};
 2768:                 }
 2769:             } else {
 2770:                 $result = &mt('Currently using local (institutional) authentication.');
 2771:                 return $result;
 2772:             }
 2773:         }
 2774:     } else {
 2775:         if ($authnum == 1) {
 2776:             $authtype = '<input type="hidden" name="login" value="loc" />';
 2777:         }
 2778:     }
 2779:     if (!$can_assign{'loc'}) {
 2780:         return;
 2781:     } elsif ($authtype eq '') {
 2782:         if (defined($in{'mode'})) {
 2783:             if ($in{'mode'} eq 'modifycourse') {
 2784:                 if ($authnum == 1) {
 2785:                     $authtype = '<input type="radio" name="login" value="loc" />';
 2786:                 }
 2787:             }
 2788:         }
 2789:     }
 2790:     $jscall = "javascript:changed_radio('loc',$in{'formname'});";
 2791:     if ($authtype eq '') {
 2792:         $authtype = '<input type="radio" name="login" value="loc" '.
 2793:                     $loccheck.' onchange="'.$jscall.'" onclick="'.
 2794:                     $jscall.'" />';
 2795:     }
 2796:     $autharg = '<input type="text" size="10" name="locarg" value="'.
 2797:                $locarg.'" onchange="'.$jscall.'" />';
 2798:     $result = &mt('[_1] Local Authentication with argument [_2]',
 2799:                   '<label>'.$authtype,'</label>'.$autharg);
 2800:     return $result;
 2801: }
 2802: 
 2803: sub authform_filesystem {
 2804:     my %in = (
 2805:               formname => 'document.cu',
 2806:               kerb_def_dom => 'MSU.EDU',
 2807:               @_,
 2808:               );
 2809:     my ($fsyscheck,$result,$authtype,$autharg,$jscall);
 2810:     my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
 2811:     if (defined($in{'curr_authtype'})) {
 2812:         if ($in{'curr_authtype'} eq 'fsys') {
 2813:             if ($can_assign{'fsys'}) {
 2814:                 $fsyscheck = 'checked="checked" ';
 2815:                 if (defined($in{'mode'})) {
 2816:                     if ($in{'mode'} eq 'modifyuser') {
 2817:                         $fsyscheck = '';
 2818:                     }
 2819:                 }
 2820:             } else {
 2821:                 $result = &mt('Currently Filesystem Authenticated.');
 2822:                 return $result;
 2823:             }           
 2824:         }
 2825:     } else {
 2826:         if ($authnum == 1) {
 2827:             $authtype = '<input type="hidden" name="login" value="fsys" />';
 2828:         }
 2829:     }
 2830:     if (!$can_assign{'fsys'}) {
 2831:         return;
 2832:     } elsif ($authtype eq '') {
 2833:         if (defined($in{'mode'})) {
 2834:             if ($in{'mode'} eq 'modifycourse') {
 2835:                 if ($authnum == 1) {
 2836:                     $authtype = '<input type="radio" name="login" value="fsys" />';
 2837:                 }
 2838:             }
 2839:         }
 2840:     }
 2841:     $jscall = "javascript:changed_radio('fsys',$in{'formname'});";
 2842:     if ($authtype eq '') {
 2843:         $authtype = '<input type="radio" name="login" value="fsys" '.
 2844:                     $fsyscheck.' onchange="'.$jscall.'" onclick="'.
 2845:                     $jscall.'" />';
 2846:     }
 2847:     $autharg = '<input type="text" size="10" name="fsysarg" value=""'.
 2848:                ' onchange="'.$jscall.'" />';
 2849:     $result = &mt
 2850:         ('[_1] Filesystem Authenticated (with initial password [_2])',
 2851:          '<label><input type="radio" name="login" value="fsys" '.
 2852:          $fsyscheck.'onchange="'.$jscall.'" onclick="'.$jscall.'" />',
 2853:          '</label><input type="password" size="10" name="fsysarg" value="" '.
 2854:                   'onchange="'.$jscall.'" />');
 2855:     return $result;
 2856: }
 2857: 
 2858: sub get_assignable_auth {
 2859:     my ($dom) = @_;
 2860:     if ($dom eq '') {
 2861:         $dom = $env{'request.role.domain'};
 2862:     }
 2863:     my %can_assign = (
 2864:                           krb4 => 1,
 2865:                           krb5 => 1,
 2866:                           int  => 1,
 2867:                           loc  => 1,
 2868:                      );
 2869:     my %domconfig = &Apache::lonnet::get_dom('configuration',['usercreation'],$dom);
 2870:     if (ref($domconfig{'usercreation'}) eq 'HASH') {
 2871:         if (ref($domconfig{'usercreation'}{'authtypes'}) eq 'HASH') {
 2872:             my $authhash = $domconfig{'usercreation'}{'authtypes'};
 2873:             my $context;
 2874:             if ($env{'request.role'} =~ /^au/) {
 2875:                 $context = 'author';
 2876:             } elsif ($env{'request.role'} =~ /^dc/) {
 2877:                 $context = 'domain';
 2878:             } elsif ($env{'request.course.id'}) {
 2879:                 $context = 'course';
 2880:             }
 2881:             if ($context) {
 2882:                 if (ref($authhash->{$context}) eq 'HASH') {
 2883:                    %can_assign = %{$authhash->{$context}}; 
 2884:                 }
 2885:             }
 2886:         }
 2887:     }
 2888:     my $authnum = 0;
 2889:     foreach my $key (keys(%can_assign)) {
 2890:         if ($can_assign{$key}) {
 2891:             $authnum ++;
 2892:         }
 2893:     }
 2894:     if ($can_assign{'krb4'} && $can_assign{'krb5'}) {
 2895:         $authnum --;
 2896:     }
 2897:     return ($authnum,%can_assign);
 2898: }
 2899: 
 2900: ###############################################################
 2901: ##    Get Kerberos Defaults for Domain                 ##
 2902: ###############################################################
 2903: ##
 2904: ## Returns default kerberos version and an associated argument
 2905: ## as listed in file domain.tab. If not listed, provides
 2906: ## appropriate default domain and kerberos version.
 2907: ##
 2908: #-------------------------------------------
 2909: 
 2910: =pod
 2911: 
 2912: =item * &get_kerberos_defaults()
 2913: 
 2914: get_kerberos_defaults($target_domain) returns the default kerberos
 2915: version and domain. If not found, it defaults to version 4 and the 
 2916: domain of the server.
 2917: 
 2918: =over 4
 2919: 
 2920: ($def_version, $def_krb_domain) = &get_kerberos_defaults($target_domain);
 2921: 
 2922: =back
 2923: 
 2924: =back
 2925: 
 2926: =cut
 2927: 
 2928: #-------------------------------------------
 2929: sub get_kerberos_defaults {
 2930:     my $domain=shift;
 2931:     my ($krbdef,$krbdefdom);
 2932:     my %domdefaults = &Apache::lonnet::get_domain_defaults($domain);
 2933:     if (($domdefaults{'auth_def'} =~/^krb(4|5)$/) && ($domdefaults{'auth_arg_def'} ne '')) {
 2934:         $krbdef = $domdefaults{'auth_def'};
 2935:         $krbdefdom = $domdefaults{'auth_arg_def'};
 2936:     } else {
 2937:         $ENV{'SERVER_NAME'}=~/(\w+\.\w+)$/;
 2938:         my $krbdefdom=$1;
 2939:         $krbdefdom=~tr/a-z/A-Z/;
 2940:         $krbdef = "krb4";
 2941:     }
 2942:     return ($krbdef,$krbdefdom);
 2943: }
 2944: 
 2945: 
 2946: ###############################################################
 2947: ##                Thesaurus Functions                        ##
 2948: ###############################################################
 2949: 
 2950: =pod
 2951: 
 2952: =head1 Thesaurus Functions
 2953: 
 2954: =over 4
 2955: 
 2956: =item * &initialize_keywords()
 2957: 
 2958: Initializes the package variable %Keywords if it is empty.  Uses the
 2959: package variable $thesaurus_db_file.
 2960: 
 2961: =cut
 2962: 
 2963: ###################################################
 2964: 
 2965: sub initialize_keywords {
 2966:     return 1 if (scalar keys(%Keywords));
 2967:     # If we are here, %Keywords is empty, so fill it up
 2968:     #   Make sure the file we need exists...
 2969:     if (! -e $thesaurus_db_file) {
 2970:         &Apache::lonnet::logthis("Attempt to access $thesaurus_db_file".
 2971:                                  " failed because it does not exist");
 2972:         return 0;
 2973:     }
 2974:     #   Set up the hash as a database
 2975:     my %thesaurus_db;
 2976:     if (! tie(%thesaurus_db,'GDBM_File',
 2977:               $thesaurus_db_file,&GDBM_READER(),0640)){
 2978:         &Apache::lonnet::logthis("Could not tie \%thesaurus_db to ".
 2979:                                  $thesaurus_db_file);
 2980:         return 0;
 2981:     } 
 2982:     #  Get the average number of appearances of a word.
 2983:     my $avecount = $thesaurus_db{'average.count'};
 2984:     #  Put keywords (those that appear > average) into %Keywords
 2985:     while (my ($word,$data)=each (%thesaurus_db)) {
 2986:         my ($count,undef) = split /:/,$data;
 2987:         $Keywords{$word}++ if ($count > $avecount);
 2988:     }
 2989:     untie %thesaurus_db;
 2990:     # Remove special values from %Keywords.
 2991:     foreach my $value ('total.count','average.count') {
 2992:         delete($Keywords{$value}) if (exists($Keywords{$value}));
 2993:   }
 2994:     return 1;
 2995: }
 2996: 
 2997: ###################################################
 2998: 
 2999: =pod
 3000: 
 3001: =item * &keyword($word)
 3002: 
 3003: Returns true if $word is a keyword.  A keyword is a word that appears more 
 3004: than the average number of times in the thesaurus database.  Calls 
 3005: &initialize_keywords
 3006: 
 3007: =cut
 3008: 
 3009: ###################################################
 3010: 
 3011: sub keyword {
 3012:     return if (!&initialize_keywords());
 3013:     my $word=lc(shift());
 3014:     $word=~s/\W//g;
 3015:     return exists($Keywords{$word});
 3016: }
 3017: 
 3018: ###############################################################
 3019: 
 3020: =pod 
 3021: 
 3022: =item * &get_related_words()
 3023: 
 3024: Look up a word in the thesaurus.  Takes a scalar argument and returns
 3025: an array of words.  If the keyword is not in the thesaurus, an empty array
 3026: will be returned.  The order of the words returned is determined by the
 3027: database which holds them.
 3028: 
 3029: Uses global $thesaurus_db_file.
 3030: 
 3031: 
 3032: =cut
 3033: 
 3034: ###############################################################
 3035: sub get_related_words {
 3036:     my $keyword = shift;
 3037:     my %thesaurus_db;
 3038:     if (! -e $thesaurus_db_file) {
 3039:         &Apache::lonnet::logthis("Attempt to access $thesaurus_db_file ".
 3040:                                  "failed because the file does not exist");
 3041:         return ();
 3042:     }
 3043:     if (! tie(%thesaurus_db,'GDBM_File',
 3044:               $thesaurus_db_file,&GDBM_READER(),0640)){
 3045:         return ();
 3046:     } 
 3047:     my @Words=();
 3048:     my $count=0;
 3049:     if (exists($thesaurus_db{$keyword})) {
 3050: 	# The first element is the number of times
 3051: 	# the word appears.  We do not need it now.
 3052: 	my (undef,@RelatedWords) = (split(/:/,$thesaurus_db{$keyword}));
 3053: 	my (undef,$mostfrequentcount)=split(/\,/,$RelatedWords[0]);
 3054: 	my $threshold=$mostfrequentcount/10;
 3055:         foreach my $possibleword (@RelatedWords) {
 3056:             my ($word,$wordcount)=split(/\,/,$possibleword);
 3057:             if ($wordcount>$threshold) {
 3058: 		push(@Words,$word);
 3059:                 $count++;
 3060:                 if ($count>10) { last; }
 3061: 	    }
 3062:         }
 3063:     }
 3064:     untie %thesaurus_db;
 3065:     return @Words;
 3066: }
 3067: 
 3068: =pod
 3069: 
 3070: =back
 3071: 
 3072: =cut
 3073: 
 3074: # -------------------------------------------------------------- Plaintext name
 3075: =pod
 3076: 
 3077: =head1 User Name Functions
 3078: 
 3079: =over 4
 3080: 
 3081: =item * &plainname($uname,$udom,$first)
 3082: 
 3083: Takes a users logon name and returns it as a string in
 3084: "first middle last generation" form 
 3085: if $first is set to 'lastname' then it returns it as
 3086: 'lastname generation, firstname middlename' if their is a lastname
 3087: 
 3088: =cut
 3089: 
 3090: 
 3091: ###############################################################
 3092: sub plainname {
 3093:     my ($uname,$udom,$first)=@_;
 3094:     return if (!defined($uname) || !defined($udom));
 3095:     my %names=&getnames($uname,$udom);
 3096:     my $name=&Apache::lonnet::format_name($names{'firstname'},
 3097: 					  $names{'middlename'},
 3098: 					  $names{'lastname'},
 3099: 					  $names{'generation'},$first);
 3100:     $name=~s/^\s+//;
 3101:     $name=~s/\s+$//;
 3102:     $name=~s/\s+/ /g;
 3103:     if ($name !~ /\S/) { $name=$uname.':'.$udom; }
 3104:     return $name;
 3105: }
 3106: 
 3107: # -------------------------------------------------------------------- Nickname
 3108: =pod
 3109: 
 3110: =item * &nickname($uname,$udom)
 3111: 
 3112: Gets a users name and returns it as a string as
 3113: 
 3114: "&quot;nickname&quot;"
 3115: 
 3116: if the user has a nickname or
 3117: 
 3118: "first middle last generation"
 3119: 
 3120: if the user does not
 3121: 
 3122: =cut
 3123: 
 3124: sub nickname {
 3125:     my ($uname,$udom)=@_;
 3126:     return if (!defined($uname) || !defined($udom));
 3127:     my %names=&getnames($uname,$udom);
 3128:     my $name=$names{'nickname'};
 3129:     if ($name) {
 3130:        $name='&quot;'.$name.'&quot;'; 
 3131:     } else {
 3132:        $name=$names{'firstname'}.' '.$names{'middlename'}.' '.
 3133: 	     $names{'lastname'}.' '.$names{'generation'};
 3134:        $name=~s/\s+$//;
 3135:        $name=~s/\s+/ /g;
 3136:     }
 3137:     return $name;
 3138: }
 3139: 
 3140: sub getnames {
 3141:     my ($uname,$udom)=@_;
 3142:     return if (!defined($uname) || !defined($udom));
 3143:     if ($udom eq 'public' && $uname eq 'public') {
 3144: 	return ('lastname' => &mt('Public'));
 3145:     }
 3146:     my $id=$uname.':'.$udom;
 3147:     my ($names,$cached)=&Apache::lonnet::is_cached_new('namescache',$id);
 3148:     if ($cached) {
 3149: 	return %{$names};
 3150:     } else {
 3151: 	my %loadnames=&Apache::lonnet::get('environment',
 3152:                     ['firstname','middlename','lastname','generation','nickname'],
 3153: 					 $udom,$uname);
 3154: 	&Apache::lonnet::do_cache_new('namescache',$id,\%loadnames);
 3155: 	return %loadnames;
 3156:     }
 3157: }
 3158: 
 3159: # -------------------------------------------------------------------- getemails
 3160: 
 3161: =pod
 3162: 
 3163: =item * &getemails($uname,$udom)
 3164: 
 3165: Gets a user's email information and returns it as a hash with keys:
 3166: notification, critnotification, permanentemail
 3167: 
 3168: For notification and critnotification, values are comma-separated lists 
 3169: of e-mail addresses; for permanentemail, value is a single e-mail address.
 3170:  
 3171: 
 3172: =cut
 3173: 
 3174: 
 3175: sub getemails {
 3176:     my ($uname,$udom)=@_;
 3177:     if ($udom eq 'public' && $uname eq 'public') {
 3178: 	return;
 3179:     }
 3180:     if (!$udom) { $udom=$env{'user.domain'}; }
 3181:     if (!$uname) { $uname=$env{'user.name'}; }
 3182:     my $id=$uname.':'.$udom;
 3183:     my ($names,$cached)=&Apache::lonnet::is_cached_new('emailscache',$id);
 3184:     if ($cached) {
 3185: 	return %{$names};
 3186:     } else {
 3187: 	my %loadnames=&Apache::lonnet::get('environment',
 3188:                     			   ['notification','critnotification',
 3189: 					    'permanentemail'],
 3190: 					   $udom,$uname);
 3191: 	&Apache::lonnet::do_cache_new('emailscache',$id,\%loadnames);
 3192: 	return %loadnames;
 3193:     }
 3194: }
 3195: 
 3196: sub flush_email_cache {
 3197:     my ($uname,$udom)=@_;
 3198:     if (!$udom)  { $udom =$env{'user.domain'}; }
 3199:     if (!$uname) { $uname=$env{'user.name'};   }
 3200:     return if ($udom eq 'public' && $uname eq 'public');
 3201:     my $id=$uname.':'.$udom;
 3202:     &Apache::lonnet::devalidate_cache_new('emailscache',$id);
 3203: }
 3204: 
 3205: # -------------------------------------------------------------------- getlangs
 3206: 
 3207: =pod
 3208: 
 3209: =item * &getlangs($uname,$udom)
 3210: 
 3211: Gets a user's language preference and returns it as a hash with key:
 3212: language.
 3213: 
 3214: =cut
 3215: 
 3216: 
 3217: sub getlangs {
 3218:     my ($uname,$udom) = @_;
 3219:     if (!$udom)  { $udom =$env{'user.domain'}; }
 3220:     if (!$uname) { $uname=$env{'user.name'};   }
 3221:     my $id=$uname.':'.$udom;
 3222:     my ($langs,$cached)=&Apache::lonnet::is_cached_new('userlangs',$id);
 3223:     if ($cached) {
 3224:         return %{$langs};
 3225:     } else {
 3226:         my %loadlangs=&Apache::lonnet::get('environment',['languages'],
 3227:                                            $udom,$uname);
 3228:         &Apache::lonnet::do_cache_new('userlangs',$id,\%loadlangs);
 3229:         return %loadlangs;
 3230:     }
 3231: }
 3232: 
 3233: sub flush_langs_cache {
 3234:     my ($uname,$udom)=@_;
 3235:     if (!$udom)  { $udom =$env{'user.domain'}; }
 3236:     if (!$uname) { $uname=$env{'user.name'};   }
 3237:     return if ($udom eq 'public' && $uname eq 'public');
 3238:     my $id=$uname.':'.$udom;
 3239:     &Apache::lonnet::devalidate_cache_new('userlangs',$id);
 3240: }
 3241: 
 3242: # ------------------------------------------------------------------ Screenname
 3243: 
 3244: =pod
 3245: 
 3246: =item * &screenname($uname,$udom)
 3247: 
 3248: Gets a users screenname and returns it as a string
 3249: 
 3250: =cut
 3251: 
 3252: sub screenname {
 3253:     my ($uname,$udom)=@_;
 3254:     if ($uname eq $env{'user.name'} &&
 3255: 	$udom eq $env{'user.domain'}) {return $env{'environment.screenname'};}
 3256:     my %names=&Apache::lonnet::get('environment',['screenname'],$udom,$uname);
 3257:     return $names{'screenname'};
 3258: }
 3259: 
 3260: 
 3261: # ------------------------------------------------------------- Confirm Wrapper
 3262: =pod
 3263: 
 3264: =item * &confirmwrapper($message)
 3265: 
 3266: Wrap messages about completion of operation in box
 3267: 
 3268: =cut
 3269: 
 3270: sub confirmwrapper {
 3271:     my ($message)=@_;
 3272:     if ($message) {
 3273:         return "\n".'<div class="LC_confirm_box">'."\n"
 3274:                .$message."\n"
 3275:                .'</div>'."\n";
 3276:     } else {
 3277:         return $message;
 3278:     }
 3279: }
 3280: 
 3281: # ------------------------------------------------------------- Message Wrapper
 3282: 
 3283: sub messagewrapper {
 3284:     my ($link,$username,$domain,$subject,$text)=@_;
 3285:     return 
 3286:         '<a href="/adm/email?compose=individual&amp;'.
 3287:         'recname='.$username.'&amp;recdom='.$domain.
 3288: 	'&amp;subject='.&escape($subject).'&amp;text='.&escape($text).'" '.
 3289:         'title="'.&mt('Send message').'">'.$link.'</a>';
 3290: }
 3291: 
 3292: # --------------------------------------------------------------- Notes Wrapper
 3293: 
 3294: sub noteswrapper {
 3295:     my ($link,$un,$do)=@_;
 3296:     return 
 3297: "<a href='/adm/email?recordftf=retrieve&amp;recname=$un&amp;recdom=$do'>$link</a>";
 3298: }
 3299: 
 3300: # ------------------------------------------------------------- Aboutme Wrapper
 3301: 
 3302: sub aboutmewrapper {
 3303:     my ($link,$username,$domain,$target,$class)=@_;
 3304:     if (!defined($username)  && !defined($domain)) {
 3305:         return;
 3306:     }
 3307:     return '<a href="/adm/'.$domain.'/'.$username.'/aboutme"'.
 3308: 	($target?' target="'.$target.'"':'').($class?' class="'.$class.'"':'').' title="'.&mt("View this user's personal information page").'">'.$link.'</a>';
 3309: }
 3310: 
 3311: # ------------------------------------------------------------ Syllabus Wrapper
 3312: 
 3313: sub syllabuswrapper {
 3314:     my ($linktext,$coursedir,$domain)=@_;
 3315:     return qq{<a href="/public/$domain/$coursedir/syllabus">$linktext</a>};
 3316: }
 3317: 
 3318: # -----------------------------------------------------------------------------
 3319: 
 3320: sub track_student_link {
 3321:     my ($linktext,$sname,$sdom,$target,$start,$only_body) = @_;
 3322:     my $link ="/adm/trackstudent?";
 3323:     my $title = 'View recent activity';
 3324:     if (defined($sname) && $sname !~ /^\s*$/ &&
 3325:         defined($sdom)  && $sdom  !~ /^\s*$/) {
 3326:         $link .= "selected_student=$sname:$sdom";
 3327:         $title .= ' of this student';
 3328:     } 
 3329:     if (defined($target) && $target !~ /^\s*$/) {
 3330:         $target = qq{target="$target"};
 3331:     } else {
 3332:         $target = '';
 3333:     }
 3334:     if ($start) { $link.='&amp;start='.$start; }
 3335:     if ($only_body) { $link .= '&amp;only_body=1'; }
 3336:     $title = &mt($title);
 3337:     $linktext = &mt($linktext);
 3338:     return qq{<a href="$link" title="$title" $target>$linktext</a>}.
 3339: 	&help_open_topic('View_recent_activity');
 3340: }
 3341: 
 3342: sub slot_reservations_link {
 3343:     my ($linktext,$sname,$sdom,$target) = @_;
 3344:     my $link ="/adm/slotrequest?command=showresv&amp;origin=aboutme";
 3345:     my $title = 'View slot reservation history';
 3346:     if (defined($sname) && $sname !~ /^\s*$/ &&
 3347:         defined($sdom)  && $sdom  !~ /^\s*$/) {
 3348:         $link .= "&amp;uname=$sname&amp;udom=$sdom";
 3349:         $title .= ' of this student';
 3350:     }
 3351:     if (defined($target) && $target !~ /^\s*$/) {
 3352:         $target = qq{target="$target"};
 3353:     } else {
 3354:         $target = '';
 3355:     }
 3356:     $title = &mt($title);
 3357:     $linktext = &mt($linktext);
 3358:     return qq{<a href="$link" title="$title" $target>$linktext</a>};
 3359: # FIXME uncomment when help item created: &help_open_topic('Slot_Reservation_History');
 3360: 
 3361: }
 3362: 
 3363: # ===================================================== Display a student photo
 3364: 
 3365: 
 3366: sub student_image_tag {
 3367:     my ($domain,$user)=@_;
 3368:     my $imgsrc=&Apache::lonnet::studentphoto($domain,$user,'jpg');
 3369:     if (($imgsrc) && ($imgsrc ne '/adm/lonKaputt/lonlogo_broken.gif')) {
 3370: 	return '<img src="'.$imgsrc.'" align="right" />';
 3371:     } else {
 3372: 	return '';
 3373:     }
 3374: }
 3375: 
 3376: =pod
 3377: 
 3378: =back
 3379: 
 3380: =head1 Access .tab File Data
 3381: 
 3382: =over 4
 3383: 
 3384: =item * &languageids() 
 3385: 
 3386: returns list of all language ids
 3387: 
 3388: =cut
 3389: 
 3390: sub languageids {
 3391:     return sort(keys(%language));
 3392: }
 3393: 
 3394: =pod
 3395: 
 3396: =item * &languagedescription() 
 3397: 
 3398: returns description of a specified language id
 3399: 
 3400: =cut
 3401: 
 3402: sub languagedescription {
 3403:     my $code=shift;
 3404:     return  ($supported_language{$code}?'* ':'').
 3405:             $language{$code}.
 3406: 	    ($supported_language{$code}?' ('.&mt('interface available').')':'');
 3407: }
 3408: 
 3409: =pod
 3410: 
 3411: =item * &plainlanguagedescription
 3412: 
 3413: Returns both the plain language description (e.g. 'Creoles and Pidgins, English-based (Other)')
 3414: and the language character encoding (e.g. ISO) separated by a ' - ' string.
 3415: 
 3416: =cut
 3417: 
 3418: sub plainlanguagedescription {
 3419:     my $code=shift;
 3420:     return $language{$code};
 3421: }
 3422: 
 3423: =pod
 3424: 
 3425: =item * &supportedlanguagecode
 3426: 
 3427: Returns the supported language code (e.g. sptutf maps to pt) given a language
 3428: code.
 3429: 
 3430: =cut
 3431: 
 3432: sub supportedlanguagecode {
 3433:     my $code=shift;
 3434:     return $supported_language{$code};
 3435: }
 3436: 
 3437: =pod
 3438: 
 3439: =item * &latexlanguage()
 3440: 
 3441: Given a language key code returns the correspondnig language to use
 3442: to select the correct hyphenation on LaTeX printouts.  This is undef if there
 3443: is no supported hyphenation for the language code.
 3444: 
 3445: =cut
 3446: 
 3447: sub latexlanguage {
 3448:     my $code = shift;
 3449:     return $latex_language{$code};
 3450: }
 3451: 
 3452: =pod
 3453: 
 3454: =item * &latexhyphenation()
 3455: 
 3456: Same as above but what's supplied is the language as it might be stored
 3457: in the metadata.
 3458: 
 3459: =cut
 3460: 
 3461: sub latexhyphenation {
 3462:     my $key = shift;
 3463:     return $latex_language_bykey{$key};
 3464: }
 3465: 
 3466: =pod
 3467: 
 3468: =item * &copyrightids() 
 3469: 
 3470: returns list of all copyrights
 3471: 
 3472: =cut
 3473: 
 3474: sub copyrightids {
 3475:     return sort(keys(%cprtag));
 3476: }
 3477: 
 3478: =pod
 3479: 
 3480: =item * &copyrightdescription() 
 3481: 
 3482: returns description of a specified copyright id
 3483: 
 3484: =cut
 3485: 
 3486: sub copyrightdescription {
 3487:     return &mt($cprtag{shift(@_)});
 3488: }
 3489: 
 3490: =pod
 3491: 
 3492: =item * &source_copyrightids() 
 3493: 
 3494: returns list of all source copyrights
 3495: 
 3496: =cut
 3497: 
 3498: sub source_copyrightids {
 3499:     return sort(keys(%scprtag));
 3500: }
 3501: 
 3502: =pod
 3503: 
 3504: =item * &source_copyrightdescription() 
 3505: 
 3506: returns description of a specified source copyright id
 3507: 
 3508: =cut
 3509: 
 3510: sub source_copyrightdescription {
 3511:     return &mt($scprtag{shift(@_)});
 3512: }
 3513: 
 3514: =pod
 3515: 
 3516: =item * &filecategories() 
 3517: 
 3518: returns list of all file categories
 3519: 
 3520: =cut
 3521: 
 3522: sub filecategories {
 3523:     return sort(keys(%category_extensions));
 3524: }
 3525: 
 3526: =pod
 3527: 
 3528: =item * &filecategorytypes() 
 3529: 
 3530: returns list of file types belonging to a given file
 3531: category
 3532: 
 3533: =cut
 3534: 
 3535: sub filecategorytypes {
 3536:     my ($cat) = @_;
 3537:     return @{$category_extensions{lc($cat)}};
 3538: }
 3539: 
 3540: =pod
 3541: 
 3542: =item * &fileembstyle() 
 3543: 
 3544: returns embedding style for a specified file type
 3545: 
 3546: =cut
 3547: 
 3548: sub fileembstyle {
 3549:     return $fe{lc(shift(@_))};
 3550: }
 3551: 
 3552: sub filemimetype {
 3553:     return $fm{lc(shift(@_))};
 3554: }
 3555: 
 3556: 
 3557: sub filecategoryselect {
 3558:     my ($name,$value)=@_;
 3559:     return &select_form($value,$name,
 3560:                         {'' => &mt('Any category'), map { $_,$_ } sort(keys(%category_extensions))});
 3561: }
 3562: 
 3563: =pod
 3564: 
 3565: =item * &filedescription() 
 3566: 
 3567: returns description for a specified file type
 3568: 
 3569: =cut
 3570: 
 3571: sub filedescription {
 3572:     my $file_description = $fd{lc(shift())};
 3573:     $file_description =~ s:([\[\]]):~$1:g;
 3574:     return &mt($file_description);
 3575: }
 3576: 
 3577: =pod
 3578: 
 3579: =item * &filedescriptionex() 
 3580: 
 3581: returns description for a specified file type with
 3582: extra formatting
 3583: 
 3584: =cut
 3585: 
 3586: sub filedescriptionex {
 3587:     my $ex=shift;
 3588:     my $file_description = $fd{lc($ex)};
 3589:     $file_description =~ s:([\[\]]):~$1:g;
 3590:     return '.'.$ex.' '.&mt($file_description);
 3591: }
 3592: 
 3593: # End of .tab access
 3594: =pod
 3595: 
 3596: =back
 3597: 
 3598: =cut
 3599: 
 3600: # ------------------------------------------------------------------ File Types
 3601: sub fileextensions {
 3602:     return sort(keys(%fe));
 3603: }
 3604: 
 3605: # ----------------------------------------------------------- Display Languages
 3606: # returns a hash with all desired display languages
 3607: #
 3608: 
 3609: sub display_languages {
 3610:     my %languages=();
 3611:     foreach my $lang (&Apache::lonlocal::preferred_languages()) {
 3612: 	$languages{$lang}=1;
 3613:     }
 3614:     &get_unprocessed_cgi($ENV{'QUERY_STRING'},['displaylanguage']);
 3615:     if ($env{'form.displaylanguage'}) {
 3616: 	foreach my $lang (split(/\s*(\,|\;|\:)\s*/,$env{'form.displaylanguage'})) {
 3617: 	    $languages{$lang}=1;
 3618:         }
 3619:     }
 3620:     return %languages;
 3621: }
 3622: 
 3623: sub languages {
 3624:     my ($possible_langs) = @_;
 3625:     my @preferred_langs = &Apache::lonlocal::preferred_languages();
 3626:     if (!ref($possible_langs)) {
 3627: 	if( wantarray ) {
 3628: 	    return @preferred_langs;
 3629: 	} else {
 3630: 	    return $preferred_langs[0];
 3631: 	}
 3632:     }
 3633:     my %possibilities = map { $_ => 1 } (@$possible_langs);
 3634:     my @preferred_possibilities;
 3635:     foreach my $preferred_lang (@preferred_langs) {
 3636: 	if (exists($possibilities{$preferred_lang})) {
 3637: 	    push(@preferred_possibilities, $preferred_lang);
 3638: 	}
 3639:     }
 3640:     if( wantarray ) {
 3641: 	return @preferred_possibilities;
 3642:     }
 3643:     return $preferred_possibilities[0];
 3644: }
 3645: 
 3646: sub user_lang {
 3647:     my ($touname,$toudom,$fromcid) = @_;
 3648:     my @userlangs;
 3649:     if (($fromcid ne '') && ($env{'course.'.$fromcid.'.languages'} ne '')) {
 3650:         @userlangs=(@userlangs,split(/\s*(\,|\;|\:)\s*/,
 3651:                     $env{'course.'.$fromcid.'.languages'}));
 3652:     } else {
 3653:         my %langhash = &getlangs($touname,$toudom);
 3654:         if ($langhash{'languages'} ne '') {
 3655:             @userlangs = split(/\s*(\,|\;|\:)\s*/,$langhash{'languages'});
 3656:         } else {
 3657:             my %domdefs = &Apache::lonnet::get_domain_defaults($toudom);
 3658:             if ($domdefs{'lang_def'} ne '') {
 3659:                 @userlangs = ($domdefs{'lang_def'});
 3660:             }
 3661:         }
 3662:     }
 3663:     my @languages=&Apache::lonlocal::get_genlanguages(@userlangs);
 3664:     my $user_lh = Apache::localize->get_handle(@languages);
 3665:     return $user_lh;
 3666: }
 3667: 
 3668: 
 3669: ###############################################################
 3670: ##               Student Answer Attempts                     ##
 3671: ###############################################################
 3672: 
 3673: =pod
 3674: 
 3675: =head1 Alternate Problem Views
 3676: 
 3677: =over 4
 3678: 
 3679: =item * &get_previous_attempt($symb, $username, $domain, $course,
 3680:     $getattempt, $regexp, $gradesub, $usec, $identifier)
 3681: 
 3682: Return string with previous attempt on problem. Arguments:
 3683: 
 3684: =over 4
 3685: 
 3686: =item * $symb: Problem, including path
 3687: 
 3688: =item * $username: username of the desired student
 3689: 
 3690: =item * $domain: domain of the desired student
 3691: 
 3692: =item * $course: Course ID
 3693: 
 3694: =item * $getattempt: Leave blank for all attempts, otherwise put
 3695:     something
 3696: 
 3697: =item * $regexp: if string matches this regexp, the string will be
 3698:     sent to $gradesub
 3699: 
 3700: =item * $gradesub: routine that processes the string if it matches $regexp
 3701: 
 3702: =item * $usec: section of the desired student
 3703: 
 3704: =item * $identifier: counter for student (multiple students one problem) or
 3705:     problem (one student; whole sequence).
 3706: 
 3707: =back
 3708: 
 3709: The output string is a table containing all desired attempts, if any.
 3710: 
 3711: =cut
 3712: 
 3713: sub get_previous_attempt {
 3714:   my ($symb,$username,$domain,$course,$getattempt,$regexp,$gradesub,$usec,$identifier)=@_;
 3715:   my $prevattempts='';
 3716:   no strict 'refs';
 3717:   if ($symb) {
 3718:     my (%returnhash)=
 3719:       &Apache::lonnet::restore($symb,$course,$domain,$username);
 3720:     if ($returnhash{'version'}) {
 3721:       my %lasthash=();
 3722:       my $version;
 3723:       for ($version=1;$version<=$returnhash{'version'};$version++) {
 3724:         foreach my $key (reverse(sort(split(/\:/,$returnhash{$version.':keys'})))) {
 3725:             if ($key =~ /\.rawrndseed$/) {
 3726:                 my ($id) = ($key =~ /^(.+)\.rawrndseed$/);
 3727:                 $lasthash{$id.'.rndseed'} = $returnhash{$version.':'.$key};
 3728:             } else {
 3729:                 $lasthash{$key}=$returnhash{$version.':'.$key};
 3730:             }
 3731:         }
 3732:       }
 3733:       $prevattempts=&start_data_table().&start_data_table_header_row();
 3734:       $prevattempts.='<th>'.&mt('History').'</th>';
 3735:       my (%typeparts,%lasthidden,%regraded,%hidestatus);
 3736:       my $showsurv=&Apache::lonnet::allowed('vas',$env{'request.course.id'});
 3737:       foreach my $key (sort(keys(%lasthash))) {
 3738: 	my ($ign,@parts) = split(/\./,$key);
 3739: 	if ($#parts > 0) {
 3740: 	  my $data=$parts[-1];
 3741:           next if ($data eq 'foilorder');
 3742: 	  pop(@parts);
 3743:           $prevattempts.='<th>'.&mt('Part ').join('.',@parts).'<br />'.$data.'&nbsp;</th>';
 3744:           if ($data eq 'type') {
 3745:               unless ($showsurv) {
 3746:                   my $id = join(',',@parts);
 3747:                   $typeparts{$ign.'.'.$id} = $lasthash{$key};
 3748:                   if (($lasthash{$key} eq 'anonsurvey') || ($lasthash{$key} eq 'anonsurveycred')) {
 3749:                       $lasthidden{$ign.'.'.$id} = 1;
 3750:                   }
 3751:               }
 3752:               if ($identifier ne '') {
 3753:                   my $id = join(',',@parts);
 3754:                   if (&Apache::lonnet::EXT("resource.$id.problemstatus",$symb,
 3755:                                                $domain,$username,$usec,undef,$course) =~ /^no/) {
 3756:                       $hidestatus{$ign.'.'.$id} = 1;
 3757:                   }
 3758:               }
 3759:           } elsif ($data eq 'regrader') {
 3760:               if (($identifier ne '') && (@parts)) {
 3761:                   my $id = join(',',@parts);
 3762:                   $regraded{$ign.'.'.$id} = 1;
 3763:               }
 3764:           } 
 3765: 	} else {
 3766: 	  if ($#parts == 0) {
 3767: 	    $prevattempts.='<th>'.$parts[0].'</th>';
 3768: 	  } else {
 3769: 	    $prevattempts.='<th>'.$ign.'</th>';
 3770: 	  }
 3771: 	}
 3772:       }
 3773:       $prevattempts.=&end_data_table_header_row();
 3774:       if ($getattempt eq '') {
 3775:         my (%solved,%resets,%probstatus);
 3776:         if (($identifier ne '') && (keys(%regraded) > 0)) {
 3777:             for ($version=1;$version<=$returnhash{'version'};$version++) {
 3778:                 foreach my $id (keys(%regraded)) {
 3779:                     if (($returnhash{$version.':'.$id.'.regrader'}) &&
 3780:                         ($returnhash{$version.':'.$id.'.tries'} eq '') &&
 3781:                         ($returnhash{$version.':'.$id.'.award'} eq '')) {
 3782:                         push(@{$resets{$id}},$version);
 3783:                     }
 3784:                 }
 3785:             }
 3786:         }
 3787: 	for ($version=1;$version<=$returnhash{'version'};$version++) {
 3788:             my (@hidden,@unsolved);
 3789:             if (%typeparts) {
 3790:                 foreach my $id (keys(%typeparts)) {
 3791:                     if (($returnhash{$version.':'.$id.'.type'} eq 'anonsurvey') ||
 3792:                         ($returnhash{$version.':'.$id.'.type'} eq 'anonsurveycred')) {
 3793:                         push(@hidden,$id);
 3794:                     } elsif ($identifier ne '') {
 3795:                         unless (($returnhash{$version.':'.$id.'.type'} eq 'survey') ||
 3796:                                 ($returnhash{$version.':'.$id.'.type'} eq 'surveycred') ||
 3797:                                 ($hidestatus{$id})) {
 3798:                             next if ((ref($resets{$id}) eq 'ARRAY') && grep(/^\Q$version\E$/,@{$resets{$id}}));
 3799:                             if ($returnhash{$version.':'.$id.'.solved'} eq 'correct_by_student') {
 3800:                                 push(@{$solved{$id}},$version);
 3801:                             } elsif (($returnhash{$version.':'.$id.'.solved'} ne '') &&
 3802:                                      (ref($solved{$id}) eq 'ARRAY')) {
 3803:                                 my $skip;
 3804:                                 if (ref($resets{$id}) eq 'ARRAY') {
 3805:                                     foreach my $reset (@{$resets{$id}}) {
 3806:                                         if ($reset > $solved{$id}[-1]) {
 3807:                                             $skip=1;
 3808:                                             last;
 3809:                                         }
 3810:                                     }
 3811:                                 }
 3812:                                 unless ($skip) {
 3813:                                     my ($ign,$partslist) = split(/\./,$id,2);
 3814:                                     push(@unsolved,$partslist);
 3815:                                 }
 3816:                             }
 3817:                         }
 3818:                     }
 3819:                 }
 3820:             }
 3821:             $prevattempts.=&start_data_table_row().
 3822:                            '<td>'.&mt('Transaction [_1]',$version);
 3823:             if (@unsolved) {
 3824:                 $prevattempts .= '<span class="LC_nobreak"><label>'.
 3825:                                  '<input type="checkbox" name="HIDE'.$identifier.'" value="'.$version.':'.join('_',@unsolved).'" />'.
 3826:                                  &mt('Hide').'</label></span>';
 3827:             }
 3828:             $prevattempts .= '</td>';
 3829:             if (@hidden) {
 3830:                 foreach my $key (sort(keys(%lasthash))) {
 3831:                     next if ($key =~ /\.foilorder$/);
 3832:                     my $hide;
 3833:                     foreach my $id (@hidden) {
 3834:                         if ($key =~ /^\Q$id\E/) {
 3835:                             $hide = 1;
 3836:                             last;
 3837:                         }
 3838:                     }
 3839:                     if ($hide) {
 3840:                         my ($id,$data) = ($key =~ /^(.+)\.([^.]+)$/);
 3841:                         if (($data eq 'award') || ($data eq 'awarddetail')) {
 3842:                             my $value = &format_previous_attempt_value($key,
 3843:                                              $returnhash{$version.':'.$key});
 3844:                             $prevattempts.='<td>'.$value.'&nbsp;</td>';
 3845:                         } else {
 3846:                             $prevattempts.='<td>&nbsp;</td>';
 3847:                         }
 3848:                     } else {
 3849:                         if ($key =~ /\./) {
 3850:                             my $value = $returnhash{$version.':'.$key};
 3851:                             if ($key =~ /\.rndseed$/) {
 3852:                                 my ($id) = ($key =~ /^(.+)\.rndseed$/);
 3853:                                 if (exists($returnhash{$version.':'.$id.'.rawrndseed'})) {
 3854:                                     $value = $returnhash{$version.':'.$id.'.rawrndseed'};
 3855:                                 }
 3856:                             }
 3857:                             $prevattempts.='<td>'.&format_previous_attempt_value($key,$value).
 3858:                                            '&nbsp;</td>';
 3859:                         } else {
 3860:                             $prevattempts.='<td>&nbsp;</td>';
 3861:                         }
 3862:                     }
 3863:                 }
 3864:             } else {
 3865: 	        foreach my $key (sort(keys(%lasthash))) {
 3866:                     next if ($key =~ /\.foilorder$/);
 3867:                     my $value = $returnhash{$version.':'.$key};
 3868:                     if ($key =~ /\.rndseed$/) {
 3869:                         my ($id) = ($key =~ /^(.+)\.rndseed$/);
 3870:                         if (exists($returnhash{$version.':'.$id.'.rawrndseed'})) {
 3871:                             $value = $returnhash{$version.':'.$id.'.rawrndseed'};
 3872:                         }
 3873:                     }
 3874:                     $prevattempts.='<td>'.&format_previous_attempt_value($key,$value).
 3875:                                    '&nbsp;</td>';
 3876: 	        }
 3877:             }
 3878: 	    $prevattempts.=&end_data_table_row();
 3879: 	 }
 3880:       }
 3881:       my @currhidden = keys(%lasthidden);
 3882:       $prevattempts.=&start_data_table_row().'<td>'.&mt('Current').'</td>';
 3883:       foreach my $key (sort(keys(%lasthash))) {
 3884:           next if ($key =~ /\.foilorder$/);
 3885:           if (%typeparts) {
 3886:               my $hidden;
 3887:               foreach my $id (@currhidden) {
 3888:                   if ($key =~ /^\Q$id\E/) {
 3889:                       $hidden = 1;
 3890:                       last;
 3891:                   }
 3892:               }
 3893:               if ($hidden) {
 3894:                   my ($id,$data) = ($key =~ /^(.+)\.([^.]+)$/);
 3895:                   if (($data eq 'award') || ($data eq 'awarddetail')) {
 3896:                       my $value = &format_previous_attempt_value($key,$lasthash{$key});
 3897:                       if ($key =~/$regexp$/ && (defined &$gradesub)) {
 3898:                           $value = &$gradesub($value);
 3899:                       }
 3900:                       $prevattempts.='<td>'.$value.'&nbsp;</td>';
 3901:                   } else {
 3902:                       $prevattempts.='<td>&nbsp;</td>';
 3903:                   }
 3904:               } else {
 3905:                   my $value = &format_previous_attempt_value($key,$lasthash{$key});
 3906:                   if ($key =~/$regexp$/ && (defined &$gradesub)) {
 3907:                       $value = &$gradesub($value);
 3908:                   }
 3909:                   $prevattempts.='<td>'.$value.'&nbsp;</td>';
 3910:               }
 3911:           } else {
 3912: 	      my $value = &format_previous_attempt_value($key,$lasthash{$key});
 3913: 	      if ($key =~/$regexp$/ && (defined &$gradesub)) {
 3914:                   $value = &$gradesub($value);
 3915:               }
 3916: 	      $prevattempts.='<td>'.$value.'&nbsp;</td>';
 3917:           }
 3918:       }
 3919:       $prevattempts.= &end_data_table_row().&end_data_table();
 3920:     } else {
 3921:       $prevattempts=
 3922: 	  &start_data_table().&start_data_table_row().
 3923: 	  '<td>'.&mt('Nothing submitted - no attempts.').'</td>'.
 3924: 	  &end_data_table_row().&end_data_table();
 3925:     }
 3926:   } else {
 3927:     $prevattempts=
 3928: 	  &start_data_table().&start_data_table_row().
 3929: 	  '<td>'.&mt('No data.').'</td>'.
 3930: 	  &end_data_table_row().&end_data_table();
 3931:   }
 3932: }
 3933: 
 3934: sub format_previous_attempt_value {
 3935:     my ($key,$value) = @_;
 3936:     if (($key =~ /timestamp/) || ($key=~/duedate/)) {
 3937: 	$value = &Apache::lonlocal::locallocaltime($value);
 3938:     } elsif (ref($value) eq 'ARRAY') {
 3939: 	$value = '('.join(', ', @{ $value }).')';
 3940:     } elsif ($key =~ /answerstring$/) {
 3941:         my %answers = &Apache::lonnet::str2hash($value);
 3942:         my @anskeys = sort(keys(%answers));
 3943:         if (@anskeys == 1) {
 3944:             my $answer = $answers{$anskeys[0]};
 3945:             if ($answer =~ m{\0}) {
 3946:                 $answer =~ s{\0}{,}g;
 3947:             }
 3948:             my $tag_internal_answer_name = 'INTERNAL';
 3949:             if ($anskeys[0] eq $tag_internal_answer_name) {
 3950:                 $value = $answer; 
 3951:             } else {
 3952:                 $value = $anskeys[0].'='.$answer;
 3953:             }
 3954:         } else {
 3955:             foreach my $ans (@anskeys) {
 3956:                 my $answer = $answers{$ans};
 3957:                 if ($answer =~ m{\0}) {
 3958:                     $answer =~ s{\0}{,}g;
 3959:                 }
 3960:                 $value .=  $ans.'='.$answer.'<br />';;
 3961:             } 
 3962:         }
 3963:     } else {
 3964: 	$value = &unescape($value);
 3965:     }
 3966:     return $value;
 3967: }
 3968: 
 3969: 
 3970: sub relative_to_absolute {
 3971:     my ($url,$output)=@_;
 3972:     my $parser=HTML::TokeParser->new(\$output);
 3973:     my $token;
 3974:     my $thisdir=$url;
 3975:     my @rlinks=();
 3976:     while ($token=$parser->get_token) {
 3977: 	if ($token->[0] eq 'S') {
 3978: 	    if ($token->[1] eq 'a') {
 3979: 		if ($token->[2]->{'href'}) {
 3980: 		    $rlinks[$#rlinks+1]=$token->[2]->{'href'};
 3981: 		}
 3982: 	    } elsif ($token->[1] eq 'img' || $token->[1] eq 'embed' ) {
 3983: 		$rlinks[$#rlinks+1]=$token->[2]->{'src'};
 3984: 	    } elsif ($token->[1] eq 'base') {
 3985: 		$thisdir=$token->[2]->{'href'};
 3986: 	    }
 3987: 	}
 3988:     }
 3989:     $thisdir=~s-/[^/]*$--;
 3990:     foreach my $link (@rlinks) {
 3991: 	unless (($link=~/^https?\:\/\//i) ||
 3992: 		($link=~/^\//) ||
 3993: 		($link=~/^javascript:/i) ||
 3994: 		($link=~/^mailto:/i) ||
 3995: 		($link=~/^\#/)) {
 3996: 	    my $newlocation=&Apache::lonnet::hreflocation($thisdir,$link);
 3997: 	    $output=~s/(\"|\'|\=\s*)\Q$link\E(\"|\'|\s|\>)/$1$newlocation$2/;
 3998: 	}
 3999:     }
 4000: # -------------------------------------------------- Deal with Applet codebases
 4001:     $output=~s/(\<applet[^\>]+)(codebase\=[^\S\>]+)*([^\>]*)\>/$1.($2?$2:' codebase="'.$thisdir.'"').$3.'>'/gei;
 4002:     return $output;
 4003: }
 4004: 
 4005: =pod
 4006: 
 4007: =item * &get_student_view()
 4008: 
 4009: show a snapshot of what student was looking at
 4010: 
 4011: =cut
 4012: 
 4013: sub get_student_view {
 4014:   my ($symb,$username,$domain,$courseid,$target,$moreenv) = @_;
 4015:   my ($map,$id,$feedurl) = &Apache::lonnet::decode_symb($symb);
 4016:   my (%form);
 4017:   my @elements=('symb','courseid','domain','username');
 4018:   foreach my $element (@elements) {
 4019:       $form{'grade_'.$element}=eval '$'.$element #'
 4020:   }
 4021:   if (defined($moreenv)) {
 4022:       %form=(%form,%{$moreenv});
 4023:   }
 4024:   if (defined($target)) { $form{'grade_target'} = $target; }
 4025:   $feedurl=&Apache::lonnet::clutter($feedurl);
 4026:   my ($userview,$response)=&Apache::lonnet::ssi_body($feedurl,%form);
 4027:   $userview=~s/\<body[^\>]*\>//gi;
 4028:   $userview=~s/\<\/body\>//gi;
 4029:   $userview=~s/\<html\>//gi;
 4030:   $userview=~s/\<\/html\>//gi;
 4031:   $userview=~s/\<head\>//gi;
 4032:   $userview=~s/\<\/head\>//gi;
 4033:   $userview=~s/action\s*\=/would_be_action\=/gi;
 4034:   $userview=&relative_to_absolute($feedurl,$userview);
 4035:   if (wantarray) {
 4036:      return ($userview,$response);
 4037:   } else {
 4038:      return $userview;
 4039:   }
 4040: }
 4041: 
 4042: sub get_student_view_with_retries {
 4043:   my ($symb,$retries,$username,$domain,$courseid,$target,$moreenv) = @_;
 4044: 
 4045:     my $ok = 0;                 # True if we got a good response.
 4046:     my $content;
 4047:     my $response;
 4048: 
 4049:     # Try to get the student_view done. within the retries count:
 4050:     
 4051:     do {
 4052:          ($content, $response) = &get_student_view($symb,$username,$domain,$courseid,$target,$moreenv);
 4053:          $ok      = $response->is_success;
 4054:          if (!$ok) {
 4055:             &Apache::lonnet::logthis("Failed get_student_view_with_retries on $symb: ".$response->is_success.', '.$response->code.', '.$response->message);
 4056:          }
 4057:          $retries--;
 4058:     } while (!$ok && ($retries > 0));
 4059:     
 4060:     if (!$ok) {
 4061:        $content = '';          # On error return an empty content.
 4062:     }
 4063:     if (wantarray) {
 4064:        return ($content, $response);
 4065:     } else {
 4066:        return $content;
 4067:     }
 4068: }
 4069: 
 4070: =pod
 4071: 
 4072: =item * &get_student_answers() 
 4073: 
 4074: show a snapshot of how student was answering problem
 4075: 
 4076: =cut
 4077: 
 4078: sub get_student_answers {
 4079:   my ($symb,$username,$domain,$courseid,%form) = @_;
 4080:   my ($map,$id,$feedurl) = &Apache::lonnet::decode_symb($symb);
 4081:   my (%moreenv);
 4082:   my @elements=('symb','courseid','domain','username');
 4083:   foreach my $element (@elements) {
 4084:     $moreenv{'grade_'.$element}=eval '$'.$element #'
 4085:   }
 4086:   $moreenv{'grade_target'}='answer';
 4087:   %moreenv=(%form,%moreenv);
 4088:   $feedurl = &Apache::lonnet::clutter($feedurl);
 4089:   my $userview=&Apache::lonnet::ssi($feedurl,%moreenv);
 4090:   return $userview;
 4091: }
 4092: 
 4093: =pod
 4094: 
 4095: =item * &submlink()
 4096: 
 4097: Inputs: $text $uname $udom $symb $target
 4098: 
 4099: Returns: A link to grades.pm such as to see the SUBM view of a student
 4100: 
 4101: =cut
 4102: 
 4103: ###############################################
 4104: sub submlink {
 4105:     my ($text,$uname,$udom,$symb,$target)=@_;
 4106:     if (!($uname && $udom)) {
 4107: 	(my $cursymb, my $courseid,$udom,$uname)=
 4108: 	    &Apache::lonnet::whichuser($symb);
 4109: 	if (!$symb) { $symb=$cursymb; }
 4110:     }
 4111:     if (!$symb) { $symb=&Apache::lonnet::symbread(); }
 4112:     $symb=&escape($symb);
 4113:     if ($target) { $target=" target=\"$target\""; }
 4114:     return
 4115:         '<a href="/adm/grades?command=submission'.
 4116:         '&amp;symb='.$symb.
 4117:         '&amp;student='.$uname.
 4118:         '&amp;userdom='.$udom.'"'.
 4119:         $target.'>'.$text.'</a>';
 4120: }
 4121: ##############################################
 4122: 
 4123: =pod
 4124: 
 4125: =item * &pgrdlink()
 4126: 
 4127: Inputs: $text $uname $udom $symb $target
 4128: 
 4129: Returns: A link to grades.pm such as to see the PGRD view of a student
 4130: 
 4131: =cut
 4132: 
 4133: ###############################################
 4134: sub pgrdlink {
 4135:     my $link=&submlink(@_);
 4136:     $link=~s/(&command=submission)/$1&showgrading=yes/;
 4137:     return $link;
 4138: }
 4139: ##############################################
 4140: 
 4141: =pod
 4142: 
 4143: =item * &pprmlink()
 4144: 
 4145: Inputs: $text $uname $udom $symb $target
 4146: 
 4147: Returns: A link to parmset.pm such as to see the PPRM view of a
 4148: student and a specific resource
 4149: 
 4150: =cut
 4151: 
 4152: ###############################################
 4153: sub pprmlink {
 4154:     my ($text,$uname,$udom,$symb,$target)=@_;
 4155:     if (!($uname && $udom)) {
 4156: 	(my $cursymb, my $courseid,$udom,$uname)=
 4157: 	    &Apache::lonnet::whichuser($symb);
 4158: 	if (!$symb) { $symb=$cursymb; }
 4159:     }
 4160:     if (!$symb) { $symb=&Apache::lonnet::symbread(); }
 4161:     $symb=&escape($symb);
 4162:     if ($target) { $target="target=\"$target\""; }
 4163:     return '<a href="/adm/parmset?command=set&amp;'.
 4164: 	'symb='.$symb.'&amp;uname='.$uname.
 4165: 	'&amp;udom='.$udom.'" '.$target.'>'.$text.'</a>';
 4166: }
 4167: ##############################################
 4168: 
 4169: =pod
 4170: 
 4171: =back
 4172: 
 4173: =cut
 4174: 
 4175: ###############################################
 4176: 
 4177: 
 4178: sub timehash {
 4179:     my ($thistime) = @_;
 4180:     my $timezone = &Apache::lonlocal::gettimezone();
 4181:     my $dt = DateTime->from_epoch(epoch => $thistime)
 4182:                      ->set_time_zone($timezone);
 4183:     my $wday = $dt->day_of_week();
 4184:     if ($wday == 7) { $wday = 0; }
 4185:     return ( 'second' => $dt->second(),
 4186:              'minute' => $dt->minute(),
 4187:              'hour'   => $dt->hour(),
 4188:              'day'     => $dt->day_of_month(),
 4189:              'month'   => $dt->month(),
 4190:              'year'    => $dt->year(),
 4191:              'weekday' => $wday,
 4192:              'dayyear' => $dt->day_of_year(),
 4193:              'dlsav'   => $dt->is_dst() );
 4194: }
 4195: 
 4196: sub utc_string {
 4197:     my ($date)=@_;
 4198:     return strftime("%Y%m%dT%H%M%SZ",gmtime($date));
 4199: }
 4200: 
 4201: sub maketime {
 4202:     my %th=@_;
 4203:     my ($epoch_time,$timezone,$dt);
 4204:     $timezone = &Apache::lonlocal::gettimezone();
 4205:     eval {
 4206:         $dt = DateTime->new( year   => $th{'year'},
 4207:                              month  => $th{'month'},
 4208:                              day    => $th{'day'},
 4209:                              hour   => $th{'hour'},
 4210:                              minute => $th{'minute'},
 4211:                              second => $th{'second'},
 4212:                              time_zone => $timezone,
 4213:                          );
 4214:     };
 4215:     if (!$@) {
 4216:         $epoch_time = $dt->epoch;
 4217:         if ($epoch_time) {
 4218:             return $epoch_time;
 4219:         }
 4220:     }
 4221:     return POSIX::mktime(
 4222:         ($th{'seconds'},$th{'minutes'},$th{'hours'},
 4223:          $th{'day'},$th{'month'}-1,$th{'year'}-1900,0,0,-1));
 4224: }
 4225: 
 4226: #########################################
 4227: 
 4228: sub findallcourses {
 4229:     my ($roles,$uname,$udom) = @_;
 4230:     my %roles;
 4231:     if (ref($roles)) { %roles = map { $_ => 1 } @{$roles}; }
 4232:     my %courses;
 4233:     my $now=time;
 4234:     if (!defined($uname)) {
 4235:         $uname = $env{'user.name'};
 4236:     }
 4237:     if (!defined($udom)) {
 4238:         $udom = $env{'user.domain'};
 4239:     }
 4240:     if (($uname ne $env{'user.name'}) || ($udom ne $env{'user.domain'})) {
 4241:         my %roleshash = &Apache::lonnet::dump('roles',$udom,$uname);
 4242:         if (!%roles) {
 4243:             %roles = (
 4244:                        cc => 1,
 4245:                        co => 1,
 4246:                        in => 1,
 4247:                        ep => 1,
 4248:                        ta => 1,
 4249:                        cr => 1,
 4250:                        st => 1,
 4251:              );
 4252:         }
 4253:         foreach my $entry (keys(%roleshash)) {
 4254:             my ($trole,$tend,$tstart) = split(/_/,$roleshash{$entry});
 4255:             if ($trole =~ /^cr/) { 
 4256:                 next if (!exists($roles{$trole}) && !exists($roles{'cr'}));
 4257:             } else {
 4258:                 next if (!exists($roles{$trole}));
 4259:             }
 4260:             if ($tend) {
 4261:                 next if ($tend < $now);
 4262:             }
 4263:             if ($tstart) {
 4264:                 next if ($tstart > $now);
 4265:             }
 4266:             my ($cdom,$cnum,$sec,$cnumpart,$secpart,$role);
 4267:             (undef,$cdom,$cnumpart,$secpart) = split(/\//,$entry);
 4268:             my $value = $trole.'/'.$cdom.'/';
 4269:             if ($secpart eq '') {
 4270:                 ($cnum,$role) = split(/_/,$cnumpart); 
 4271:                 $sec = 'none';
 4272:                 $value .= $cnum.'/';
 4273:             } else {
 4274:                 $cnum = $cnumpart;
 4275:                 ($sec,$role) = split(/_/,$secpart);
 4276:                 $value .= $cnum.'/'.$sec;
 4277:             }
 4278:             if (ref($courses{$cdom.'_'.$cnum}{$sec}) eq 'ARRAY') {
 4279:                 unless (grep(/^\Q$value\E$/,@{$courses{$cdom.'_'.$cnum}{$sec}})) {
 4280:                     push(@{$courses{$cdom.'_'.$cnum}{$sec}},$value);
 4281:                 }
 4282:             } else {
 4283:                 @{$courses{$cdom.'_'.$cnum}{$sec}} = ($value);
 4284:             }
 4285:         }
 4286:     } else {
 4287:         foreach my $key (keys(%env)) {
 4288: 	    if ( $key=~m{^user\.role\.(\w+)\./($match_domain)/($match_courseid)/?(\w*)$} ||
 4289:                  $key=~m{^user\.role\.(cr/$match_domain/$match_username/\w+)\./($match_domain)/($match_courseid)/?(\w*)$}) {
 4290: 	        my ($role,$cdom,$cnum,$sec) = ($1,$2,$3,$4);
 4291: 	        next if ($role eq 'ca' || $role eq 'aa');
 4292: 	        next if (%roles && !exists($roles{$role}));
 4293: 	        my ($starttime,$endtime)=split(/\./,$env{$key});
 4294:                 my $active=1;
 4295:                 if ($starttime) {
 4296: 		    if ($now<$starttime) { $active=0; }
 4297:                 }
 4298:                 if ($endtime) {
 4299:                     if ($now>$endtime) { $active=0; }
 4300:                 }
 4301:                 if ($active) {
 4302:                     my $value = $role.'/'.$cdom.'/'.$cnum.'/';
 4303:                     if ($sec eq '') {
 4304:                         $sec = 'none';
 4305:                     } else {
 4306:                         $value .= $sec;
 4307:                     }
 4308:                     if (ref($courses{$cdom.'_'.$cnum}{$sec}) eq 'ARRAY') {
 4309:                         unless (grep(/^\Q$value\E$/,@{$courses{$cdom.'_'.$cnum}{$sec}})) {
 4310:                             push(@{$courses{$cdom.'_'.$cnum}{$sec}},$value);
 4311:                         }
 4312:                     } else {
 4313:                         @{$courses{$cdom.'_'.$cnum}{$sec}} = ($value);
 4314:                     }
 4315:                 }
 4316:             }
 4317:         }
 4318:     }
 4319:     return %courses;
 4320: }
 4321: 
 4322: ###############################################
 4323: 
 4324: sub blockcheck {
 4325:     my ($setters,$activity,$uname,$udom,$url,$is_course) = @_;
 4326: 
 4327:     if (defined($udom) && defined($uname)) {
 4328:         # If uname and udom are for a course, check for blocks in the course.
 4329:         if (($is_course) || (&Apache::lonnet::is_course($udom,$uname))) {
 4330:             my ($startblock,$endblock,$triggerblock) =
 4331:                 &get_blocks($setters,$activity,$udom,$uname,$url);
 4332:             return ($startblock,$endblock,$triggerblock);
 4333:         }
 4334:     } else {
 4335:         $udom = $env{'user.domain'};
 4336:         $uname = $env{'user.name'};
 4337:     }
 4338: 
 4339:     my $startblock = 0;
 4340:     my $endblock = 0;
 4341:     my $triggerblock = '';
 4342:     my %live_courses = &findallcourses(undef,$uname,$udom);
 4343: 
 4344:     # If uname is for a user, and activity is course-specific, i.e.,
 4345:     # boards, chat or groups, check for blocking in current course only.
 4346: 
 4347:     if (($activity eq 'boards' || $activity eq 'chat' ||
 4348:          $activity eq 'groups' || $activity eq 'printout') &&
 4349:         ($env{'request.course.id'})) {
 4350:         foreach my $key (keys(%live_courses)) {
 4351:             if ($key ne $env{'request.course.id'}) {
 4352:                 delete($live_courses{$key});
 4353:             }
 4354:         }
 4355:     }
 4356: 
 4357:     my $otheruser = 0;
 4358:     my %own_courses;
 4359:     if ((($uname ne $env{'user.name'})) || ($udom ne $env{'user.domain'})) {
 4360:         # Resource belongs to user other than current user.
 4361:         $otheruser = 1;
 4362:         # Gather courses for current user
 4363:         %own_courses = 
 4364:             &findallcourses(undef,$env{'user.name'},$env{'user.domain'});
 4365:     }
 4366: 
 4367:     # Gather active course roles - course coordinator, instructor, 
 4368:     # exam proctor, ta, student, or custom role.
 4369: 
 4370:     foreach my $course (keys(%live_courses)) {
 4371:         my ($cdom,$cnum);
 4372:         if ((defined($env{'course.'.$course.'.domain'})) && (defined($env{'course.'.$course.'.num'}))) {
 4373:             $cdom = $env{'course.'.$course.'.domain'};
 4374:             $cnum = $env{'course.'.$course.'.num'};
 4375:         } else {
 4376:             ($cdom,$cnum) = split(/_/,$course); 
 4377:         }
 4378:         my $no_ownblock = 0;
 4379:         my $no_userblock = 0;
 4380:         if ($otheruser && $activity ne 'com') {
 4381:             # Check if current user has 'evb' priv for this
 4382:             if (defined($own_courses{$course})) {
 4383:                 foreach my $sec (keys(%{$own_courses{$course}})) {
 4384:                     my $checkrole = 'cm./'.$cdom.'/'.$cnum;
 4385:                     if ($sec ne 'none') {
 4386:                         $checkrole .= '/'.$sec;
 4387:                     }
 4388:                     if (&Apache::lonnet::allowed('evb',undef,undef,$checkrole)) {
 4389:                         $no_ownblock = 1;
 4390:                         last;
 4391:                     }
 4392:                 }
 4393:             }
 4394:             # if they have 'evb' priv and are currently not playing student
 4395:             next if (($no_ownblock) &&
 4396:                  ($env{'request.role'} !~ m{^st\./$cdom/$cnum}));
 4397:         }
 4398:         foreach my $sec (keys(%{$live_courses{$course}})) {
 4399:             my $checkrole = 'cm./'.$cdom.'/'.$cnum;
 4400:             if ($sec ne 'none') {
 4401:                 $checkrole .= '/'.$sec;
 4402:             }
 4403:             if ($otheruser) {
 4404:                 # Resource belongs to user other than current user.
 4405:                 # Assemble privs for that user, and check for 'evb' priv.
 4406:                 my (%allroles,%userroles);
 4407:                 if (ref($live_courses{$course}{$sec}) eq 'ARRAY') {
 4408:                     foreach my $entry (@{$live_courses{$course}{$sec}}) { 
 4409:                         my ($trole,$tdom,$tnum,$tsec);
 4410:                         if ($entry =~ /^cr/) {
 4411:                             ($trole,$tdom,$tnum,$tsec) = 
 4412:                                 ($entry =~ m|^(cr/$match_domain/$match_username/\w+)\./($match_domain)/($match_username)/?(\w*)$|);
 4413:                         } else {
 4414:                            ($trole,$tdom,$tnum,$tsec) = split(/\//,$entry);
 4415:                         }
 4416:                         my ($spec,$area,$trest);
 4417:                         $area = '/'.$tdom.'/'.$tnum;
 4418:                         $trest = $tnum;
 4419:                         if ($tsec ne '') {
 4420:                             $area .= '/'.$tsec;
 4421:                             $trest .= '/'.$tsec;
 4422:                         }
 4423:                         $spec = $trole.'.'.$area;
 4424:                         if ($trole =~ /^cr/) {
 4425:                             &Apache::lonnet::custom_roleprivs(\%allroles,$trole,
 4426:                                                               $tdom,$spec,$trest,$area);
 4427:                         } else {
 4428:                             &Apache::lonnet::standard_roleprivs(\%allroles,$trole,
 4429:                                                                 $tdom,$spec,$trest,$area);
 4430:                         }
 4431:                     }
 4432:                     my ($author,$adv) = &Apache::lonnet::set_userprivs(\%userroles,\%allroles);
 4433:                     if ($userroles{'user.priv.'.$checkrole} =~ /evb\&([^\:]*)/) {
 4434:                         if ($1) {
 4435:                             $no_userblock = 1;
 4436:                             last;
 4437:                         }
 4438:                     }
 4439:                 }
 4440:             } else {
 4441:                 # Resource belongs to current user
 4442:                 # Check for 'evb' priv via lonnet::allowed().
 4443:                 if (&Apache::lonnet::allowed('evb',undef,undef,$checkrole)) {
 4444:                     $no_ownblock = 1;
 4445:                     last;
 4446:                 }
 4447:             }
 4448:         }
 4449:         # if they have the evb priv and are currently not playing student
 4450:         next if (($no_ownblock) &&
 4451:                  ($env{'request.role'} !~ m{^st\./\Q$cdom\E/\Q$cnum\E}));
 4452:         next if ($no_userblock);
 4453: 
 4454:         # Retrieve blocking times and identity of locker for course
 4455:         # of specified user, unless user has 'evb' privilege.
 4456:         
 4457:         my ($start,$end,$trigger) = 
 4458:             &get_blocks($setters,$activity,$cdom,$cnum,$url);
 4459:         if (($start != 0) && 
 4460:             (($startblock == 0) || ($startblock > $start))) {
 4461:             $startblock = $start;
 4462:             if ($trigger ne '') {
 4463:                 $triggerblock = $trigger;
 4464:             }
 4465:         }
 4466:         if (($end != 0)  &&
 4467:             (($endblock == 0) || ($endblock < $end))) {
 4468:             $endblock = $end;
 4469:             if ($trigger ne '') {
 4470:                 $triggerblock = $trigger;
 4471:             }
 4472:         }
 4473:     }
 4474:     return ($startblock,$endblock,$triggerblock);
 4475: }
 4476: 
 4477: sub get_blocks {
 4478:     my ($setters,$activity,$cdom,$cnum,$url) = @_;
 4479:     my $startblock = 0;
 4480:     my $endblock = 0;
 4481:     my $triggerblock = '';
 4482:     my $course = $cdom.'_'.$cnum;
 4483:     $setters->{$course} = {};
 4484:     $setters->{$course}{'staff'} = [];
 4485:     $setters->{$course}{'times'} = [];
 4486:     $setters->{$course}{'triggers'} = [];
 4487:     my (@blockers,%triggered);
 4488:     my $now = time;
 4489:     my %commblocks = &Apache::lonnet::get_comm_blocks($cdom,$cnum);
 4490:     if ($activity eq 'docs') {
 4491:         @blockers = &Apache::lonnet::has_comm_blocking('bre',undef,$url,\%commblocks);
 4492:         foreach my $block (@blockers) {
 4493:             if ($block =~ /^firstaccess____(.+)$/) {
 4494:                 my $item = $1;
 4495:                 my $type = 'map';
 4496:                 my $timersymb = $item;
 4497:                 if ($item eq 'course') {
 4498:                     $type = 'course';
 4499:                 } elsif ($item =~ /___\d+___/) {
 4500:                     $type = 'resource';
 4501:                 } else {
 4502:                     $timersymb = &Apache::lonnet::symbread($item);
 4503:                 }
 4504:                 my $start = $env{'course.'.$cdom.'_'.$cnum.'.firstaccess.'.$timersymb};
 4505:                 my $end = $start + $env{'course.'.$cdom.'_'.$cnum.'.timerinterval.'.$timersymb};
 4506:                 $triggered{$block} = {
 4507:                                        start => $start,
 4508:                                        end   => $end,
 4509:                                        type  => $type,
 4510:                                      };
 4511:             }
 4512:         }
 4513:     } else {
 4514:         foreach my $block (keys(%commblocks)) {
 4515:             if ($block =~ m/^(\d+)____(\d+)$/) { 
 4516:                 my ($start,$end) = ($1,$2);
 4517:                 if ($start <= time && $end >= time) {
 4518:                     if (ref($commblocks{$block}) eq 'HASH') {
 4519:                         if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
 4520:                             if ($commblocks{$block}{'blocks'}{$activity} eq 'on') {
 4521:                                 unless(grep(/^\Q$block\E$/,@blockers)) {
 4522:                                     push(@blockers,$block);
 4523:                                 }
 4524:                             }
 4525:                         }
 4526:                     }
 4527:                 }
 4528:             } elsif ($block =~ /^firstaccess____(.+)$/) {
 4529:                 my $item = $1;
 4530:                 my $timersymb = $item; 
 4531:                 my $type = 'map';
 4532:                 if ($item eq 'course') {
 4533:                     $type = 'course';
 4534:                 } elsif ($item =~ /___\d+___/) {
 4535:                     $type = 'resource';
 4536:                 } else {
 4537:                     $timersymb = &Apache::lonnet::symbread($item);
 4538:                 }
 4539:                 my $start = $env{'course.'.$cdom.'_'.$cnum.'.firstaccess.'.$timersymb};
 4540:                 my $end = $start + $env{'course.'.$cdom.'_'.$cnum.'.timerinterval.'.$timersymb}; 
 4541:                 if ($start && $end) {
 4542:                     if (($start <= time) && ($end >= time)) {
 4543:                         unless (grep(/^\Q$block\E$/,@blockers)) {
 4544:                             push(@blockers,$block);
 4545:                             $triggered{$block} = {
 4546:                                                    start => $start,
 4547:                                                    end   => $end,
 4548:                                                    type  => $type,
 4549:                                                  };
 4550:                         }
 4551:                     }
 4552:                 }
 4553:             }
 4554:         }
 4555:     }
 4556:     foreach my $blocker (@blockers) {
 4557:         my ($staff_name,$staff_dom,$title,$blocks) =
 4558:             &parse_block_record($commblocks{$blocker});
 4559:         push(@{$$setters{$course}{'staff'}},[$staff_name,$staff_dom]);
 4560:         my ($start,$end,$triggertype);
 4561:         if ($blocker =~ m/^(\d+)____(\d+)$/) {
 4562:             ($start,$end) = ($1,$2);
 4563:         } elsif (ref($triggered{$blocker}) eq 'HASH') {
 4564:             $start = $triggered{$blocker}{'start'};
 4565:             $end = $triggered{$blocker}{'end'};
 4566:             $triggertype = $triggered{$blocker}{'type'};
 4567:         }
 4568:         if ($start) {
 4569:             push(@{$$setters{$course}{'times'}}, [$start,$end]);
 4570:             if ($triggertype) {
 4571:                 push(@{$$setters{$course}{'triggers'}},$triggertype);
 4572:             } else {
 4573:                 push(@{$$setters{$course}{'triggers'}},0);
 4574:             }
 4575:             if ( ($startblock == 0) || ($startblock > $start) ) {
 4576:                 $startblock = $start;
 4577:                 if ($triggertype) {
 4578:                     $triggerblock = $blocker;
 4579:                 }
 4580:             }
 4581:             if ( ($endblock == 0) || ($endblock < $end) ) {
 4582:                $endblock = $end;
 4583:                if ($triggertype) {
 4584:                    $triggerblock = $blocker;
 4585:                }
 4586:             }
 4587:         }
 4588:     }
 4589:     return ($startblock,$endblock,$triggerblock);
 4590: }
 4591: 
 4592: sub parse_block_record {
 4593:     my ($record) = @_;
 4594:     my ($setuname,$setudom,$title,$blocks);
 4595:     if (ref($record) eq 'HASH') {
 4596:         ($setuname,$setudom) = split(/:/,$record->{'setter'});
 4597:         $title = &unescape($record->{'event'});
 4598:         $blocks = $record->{'blocks'};
 4599:     } else {
 4600:         my @data = split(/:/,$record,3);
 4601:         if (scalar(@data) eq 2) {
 4602:             $title = $data[1];
 4603:             ($setuname,$setudom) = split(/@/,$data[0]);
 4604:         } else {
 4605:             ($setuname,$setudom,$title) = @data;
 4606:         }
 4607:         $blocks = { 'com' => 'on' };
 4608:     }
 4609:     return ($setuname,$setudom,$title,$blocks);
 4610: }
 4611: 
 4612: sub blocking_status {
 4613:     my ($activity,$uname,$udom,$url,$is_course) = @_;
 4614:     my %setters;
 4615: 
 4616: # check for active blocking
 4617:     my ($startblock,$endblock,$triggerblock) = 
 4618:         &blockcheck(\%setters,$activity,$uname,$udom,$url,$is_course);
 4619:     my $blocked = 0;
 4620:     if ($startblock && $endblock) {
 4621:         $blocked = 1;
 4622:     }
 4623: 
 4624: # caller just wants to know whether a block is active
 4625:     if (!wantarray) { return $blocked; }
 4626: 
 4627: # build a link to a popup window containing the details
 4628:     my $querystring  = "?activity=$activity";
 4629: # $uname and $udom decide whose portfolio the user is trying to look at
 4630:     if ($activity eq 'port') {
 4631:         $querystring .= "&amp;udom=$udom"      if $udom;
 4632:         $querystring .= "&amp;uname=$uname"    if $uname;
 4633:     } elsif ($activity eq 'docs') {
 4634:         $querystring .= '&amp;url='.&HTML::Entities::encode($url,'&"');
 4635:     }
 4636: 
 4637:     my $output .= <<'END_MYBLOCK';
 4638: function openWindow(url, wdwName, w, h, toolbar,scrollbar) {
 4639:     var options = "width=" + w + ",height=" + h + ",";
 4640:     options += "resizable=yes,scrollbars="+scrollbar+",status=no,";
 4641:     options += "menubar=no,toolbar="+toolbar+",location=no,directories=no";
 4642:     var newWin = window.open(url, wdwName, options);
 4643:     newWin.focus();
 4644: }
 4645: END_MYBLOCK
 4646: 
 4647:     $output = Apache::lonhtmlcommon::scripttag($output);
 4648:   
 4649:     my $popupUrl = "/adm/blockingstatus/$querystring";
 4650:     my $text = &mt('Communication Blocked');
 4651:     if ($activity eq 'docs') {
 4652:         $text = &mt('Content Access Blocked');
 4653:     } elsif ($activity eq 'printout') {
 4654:         $text = &mt('Printing Blocked');
 4655:     }
 4656:     $output .= <<"END_BLOCK";
 4657: <div class='LC_comblock'>
 4658:   <a onclick='openWindow("$popupUrl","Blocking Table",600,300,"no","no");return false;' href='/adm/blockingstatus/$querystring'
 4659:   title='$text'>
 4660:   <img class='LC_noBorder LC_middle' title='$text' src='/res/adm/pages/comblock.png' alt='$text'/></a>
 4661:   <a onclick='openWindow("$popupUrl","Blocking Table",600,300,"no","no");return false;' href='/adm/blockingstatus/$querystring' 
 4662:   title='$text'>$text</a>
 4663: </div>
 4664: 
 4665: END_BLOCK
 4666: 
 4667:     return ($blocked, $output);
 4668: }
 4669: 
 4670: ###############################################
 4671: 
 4672: sub check_ip_acc {
 4673:     my ($acc)=@_;
 4674:     &Apache::lonxml::debug("acc is $acc");
 4675:     if (!defined($acc) || $acc =~ /^\s*$/ || $acc =~/^\s*no\s*$/i) {
 4676:         return 1;
 4677:     }
 4678:     my $allowed=0;
 4679:     my $ip=$env{'request.host'} || $ENV{'REMOTE_ADDR'};
 4680: 
 4681:     my $name;
 4682:     foreach my $pattern (split(',',$acc)) {
 4683:         $pattern =~ s/^\s*//;
 4684:         $pattern =~ s/\s*$//;
 4685:         if ($pattern =~ /\*$/) {
 4686:             #35.8.*
 4687:             $pattern=~s/\*//;
 4688:             if ($ip =~ /^\Q$pattern\E/) { $allowed=1; }
 4689:         } elsif ($pattern =~ /(\d+\.\d+\.\d+)\.\[(\d+)-(\d+)\]$/) {
 4690:             #35.8.3.[34-56]
 4691:             my $low=$2;
 4692:             my $high=$3;
 4693:             $pattern=$1;
 4694:             if ($ip =~ /^\Q$pattern\E/) {
 4695:                 my $last=(split(/\./,$ip))[3];
 4696:                 if ($last <=$high && $last >=$low) { $allowed=1; }
 4697:             }
 4698:         } elsif ($pattern =~ /^\*/) {
 4699:             #*.msu.edu
 4700:             $pattern=~s/\*//;
 4701:             if (!defined($name)) {
 4702:                 use Socket;
 4703:                 my $netaddr=inet_aton($ip);
 4704:                 ($name)=gethostbyaddr($netaddr,AF_INET);
 4705:             }
 4706:             if ($name =~ /\Q$pattern\E$/i) { $allowed=1; }
 4707:         } elsif ($pattern =~ /\d+\.\d+\.\d+\.\d+/) {
 4708:             #127.0.0.1
 4709:             if ($ip =~ /^\Q$pattern\E/) { $allowed=1; }
 4710:         } else {
 4711:             #some.name.com
 4712:             if (!defined($name)) {
 4713:                 use Socket;
 4714:                 my $netaddr=inet_aton($ip);
 4715:                 ($name)=gethostbyaddr($netaddr,AF_INET);
 4716:             }
 4717:             if ($name =~ /\Q$pattern\E$/i) { $allowed=1; }
 4718:         }
 4719:         if ($allowed) { last; }
 4720:     }
 4721:     return $allowed;
 4722: }
 4723: 
 4724: ###############################################
 4725: 
 4726: =pod
 4727: 
 4728: =head1 Domain Template Functions
 4729: 
 4730: =over 4
 4731: 
 4732: =item * &determinedomain()
 4733: 
 4734: Inputs: $domain (usually will be undef)
 4735: 
 4736: Returns: Determines which domain should be used for designs
 4737: 
 4738: =cut
 4739: 
 4740: ###############################################
 4741: sub determinedomain {
 4742:     my $domain=shift;
 4743:     if (! $domain) {
 4744:         # Determine domain if we have not been given one
 4745:         $domain = &Apache::lonnet::default_login_domain();
 4746:         if ($env{'user.domain'}) { $domain=$env{'user.domain'}; }
 4747:         if ($env{'request.role.domain'}) { 
 4748:             $domain=$env{'request.role.domain'}; 
 4749:         }
 4750:     }
 4751:     return $domain;
 4752: }
 4753: ###############################################
 4754: 
 4755: sub devalidate_domconfig_cache {
 4756:     my ($udom)=@_;
 4757:     &Apache::lonnet::devalidate_cache_new('domainconfig',$udom);
 4758: }
 4759: 
 4760: # ---------------------- Get domain configuration for a domain
 4761: sub get_domainconf {
 4762:     my ($udom) = @_;
 4763:     my $cachetime=1800;
 4764:     my ($result,$cached)=&Apache::lonnet::is_cached_new('domainconfig',$udom);
 4765:     if (defined($cached)) { return %{$result}; }
 4766: 
 4767:     my %domconfig = &Apache::lonnet::get_dom('configuration',
 4768: 					     ['login','rolecolors','autoenroll'],$udom);
 4769:     my (%designhash,%legacy);
 4770:     if (keys(%domconfig) > 0) {
 4771:         if (ref($domconfig{'login'}) eq 'HASH') {
 4772:             if (keys(%{$domconfig{'login'}})) {
 4773:                 foreach my $key (keys(%{$domconfig{'login'}})) {
 4774:                     if (ref($domconfig{'login'}{$key}) eq 'HASH') {
 4775:                         if (($key eq 'loginvia') || ($key eq 'headtag')) {
 4776:                             if (ref($domconfig{'login'}{$key}) eq 'HASH') {
 4777:                                 foreach my $hostname (keys(%{$domconfig{'login'}{$key}})) {
 4778:                                     if (ref($domconfig{'login'}{$key}{$hostname}) eq 'HASH') {
 4779:                                         if ($key eq 'loginvia') {
 4780:                                             if ($domconfig{'login'}{'loginvia'}{$hostname}{'server'}) {
 4781:                                                 my $server = $domconfig{'login'}{'loginvia'}{$hostname}{'server'};
 4782:                                                 $designhash{$udom.'.login.loginvia'} = $server;
 4783:                                                 if ($domconfig{'login'}{'loginvia'}{$hostname}{'serverpath'} eq 'custom') {
 4784:                                                     $designhash{$udom.'.login.loginvia_'.$hostname} = $server.':'.$domconfig{'login'}{'loginvia'}{$hostname}{'custompath'};
 4785:                                                 } else {
 4786:                                                     $designhash{$udom.'.login.loginvia_'.$hostname} = $server.':'.$domconfig{'login'}{'loginvia'}{$hostname}{'serverpath'};
 4787:                                                 }
 4788:                                             }
 4789:                                         } elsif ($key eq 'headtag') {
 4790:                                             if ($domconfig{'login'}{'headtag'}{$hostname}{'url'}) {
 4791:                                                 $designhash{$udom.'.login.headtag_'.$hostname} = $domconfig{'login'}{'headtag'}{$hostname}{'url'};
 4792:                                             }
 4793:                                         }
 4794:                                         if ($domconfig{'login'}{$key}{$hostname}{'exempt'}) {
 4795:                                             $designhash{$udom.'.login.'.$key.'_exempt_'.$hostname} = $domconfig{'login'}{$key}{$hostname}{'exempt'};
 4796:                                         }
 4797:                                     }
 4798:                                 }
 4799:                             }
 4800:                         } else {
 4801:                             foreach my $img (keys(%{$domconfig{'login'}{$key}})) {
 4802:                                 $designhash{$udom.'.login.'.$key.'_'.$img} = 
 4803:                                     $domconfig{'login'}{$key}{$img};
 4804:                             }
 4805:                         }
 4806:                     } else {
 4807:                         $designhash{$udom.'.login.'.$key}=$domconfig{'login'}{$key};
 4808:                     }
 4809:                 }
 4810:             } else {
 4811:                 $legacy{'login'} = 1;
 4812:             }
 4813:         } else {
 4814:             $legacy{'login'} = 1;
 4815:         }
 4816:         if (ref($domconfig{'rolecolors'}) eq 'HASH') {
 4817:             if (keys(%{$domconfig{'rolecolors'}})) {
 4818:                 foreach my $role (keys(%{$domconfig{'rolecolors'}})) {
 4819:                     if (ref($domconfig{'rolecolors'}{$role}) eq 'HASH') {
 4820:                         foreach my $item (keys(%{$domconfig{'rolecolors'}{$role}})) {
 4821:                             $designhash{$udom.'.'.$role.'.'.$item}=$domconfig{'rolecolors'}{$role}{$item};
 4822:                         }
 4823:                     }
 4824:                 }
 4825:             } else {
 4826:                 $legacy{'rolecolors'} = 1;
 4827:             }
 4828:         } else {
 4829:             $legacy{'rolecolors'} = 1;
 4830:         }
 4831:         if (ref($domconfig{'autoenroll'}) eq 'HASH') {
 4832:             if ($domconfig{'autoenroll'}{'co-owners'}) {
 4833:                 $designhash{$udom.'.autoassign.co-owners'}=$domconfig{'autoenroll'}{'co-owners'};
 4834:             }
 4835:         }
 4836:         if (keys(%legacy) > 0) {
 4837:             my %legacyhash = &get_legacy_domconf($udom);
 4838:             foreach my $item (keys(%legacyhash)) {
 4839:                 if ($item =~ /^\Q$udom\E\.login/) {
 4840:                     if ($legacy{'login'}) { 
 4841:                         $designhash{$item} = $legacyhash{$item};
 4842:                     }
 4843:                 } else {
 4844:                     if ($legacy{'rolecolors'}) {
 4845:                         $designhash{$item} = $legacyhash{$item};
 4846:                     }
 4847:                 }
 4848:             }
 4849:         }
 4850:     } else {
 4851:         %designhash = &get_legacy_domconf($udom); 
 4852:     }
 4853:     &Apache::lonnet::do_cache_new('domainconfig',$udom,\%designhash,
 4854: 				  $cachetime);
 4855:     return %designhash;
 4856: }
 4857: 
 4858: sub get_legacy_domconf {
 4859:     my ($udom) = @_;
 4860:     my %legacyhash;
 4861:     my $designdir=$Apache::lonnet::perlvar{'lonTabDir'}.'/lonDomColors';
 4862:     my $designfile =  $designdir.'/'.$udom.'.tab';
 4863:     if (-e $designfile) {
 4864:         if ( open (my $fh,"<$designfile") ) {
 4865:             while (my $line = <$fh>) {
 4866:                 next if ($line =~ /^\#/);
 4867:                 chomp($line);
 4868:                 my ($key,$val)=(split(/\=/,$line));
 4869:                 if ($val) { $legacyhash{$udom.'.'.$key}=$val; }
 4870:             }
 4871:             close($fh);
 4872:         }
 4873:     }
 4874:     if (-e $Apache::lonnet::perlvar{'lonDocRoot'}.'/adm/lonDomLogos/'.$udom.'.gif') {
 4875:         $legacyhash{$udom.'.login.domlogo'} = "/adm/lonDomLogos/$udom.gif";
 4876:     }
 4877:     return %legacyhash;
 4878: }
 4879: 
 4880: =pod
 4881: 
 4882: =item * &domainlogo()
 4883: 
 4884: Inputs: $domain (usually will be undef)
 4885: 
 4886: Returns: A link to a domain logo, if the domain logo exists.
 4887: If the domain logo does not exist, a description of the domain.
 4888: 
 4889: =cut
 4890: 
 4891: ###############################################
 4892: sub domainlogo {
 4893:     my $domain = &determinedomain(shift);
 4894:     my %designhash = &get_domainconf($domain);    
 4895:     # See if there is a logo
 4896:     if ($designhash{$domain.'.login.domlogo'} ne '') {
 4897:         my $imgsrc = $designhash{$domain.'.login.domlogo'};
 4898:         if ($imgsrc =~ m{^/(adm|res)/}) {
 4899: 	    if ($imgsrc =~ m{^/res/}) {
 4900: 		my $local_name = &Apache::lonnet::filelocation('',$imgsrc);
 4901: 		&Apache::lonnet::repcopy($local_name);
 4902: 	    }
 4903: 	   $imgsrc = &lonhttpdurl($imgsrc);
 4904:         } 
 4905:         return '<img src="'.$imgsrc.'" alt="'.$domain.'" />';
 4906:     } elsif (defined(&Apache::lonnet::domain($domain,'description'))) {
 4907:         return &Apache::lonnet::domain($domain,'description');
 4908:     } else {
 4909:         return '';
 4910:     }
 4911: }
 4912: ##############################################
 4913: 
 4914: =pod
 4915: 
 4916: =item * &designparm()
 4917: 
 4918: Inputs: $which parameter; $domain (usually will be undef)
 4919: 
 4920: Returns: value of designparamter $which
 4921: 
 4922: =cut
 4923: 
 4924: 
 4925: ##############################################
 4926: sub designparm {
 4927:     my ($which,$domain)=@_;
 4928:     if (exists($env{'environment.color.'.$which})) {
 4929:         return $env{'environment.color.'.$which};
 4930:     }
 4931:     $domain=&determinedomain($domain);
 4932:     my %domdesign;
 4933:     unless ($domain eq 'public') {
 4934:         %domdesign = &get_domainconf($domain);
 4935:     }
 4936:     my $output;
 4937:     if ($domdesign{$domain.'.'.$which} ne '') {
 4938:         $output = $domdesign{$domain.'.'.$which};
 4939:     } else {
 4940:         $output = $defaultdesign{$which};
 4941:     }
 4942:     if (($which =~ /^(student|coordinator|author|admin)\.img$/) ||
 4943:         ($which =~ /login\.(img|logo|domlogo|login)/)) {
 4944:         if ($output =~ m{^/(adm|res)/}) {
 4945:             if ($output =~ m{^/res/}) {
 4946:                 my $local_name = &Apache::lonnet::filelocation('',$output);
 4947:                 &Apache::lonnet::repcopy($local_name);
 4948:             }
 4949:             $output = &lonhttpdurl($output);
 4950:         }
 4951:     }
 4952:     return $output;
 4953: }
 4954: 
 4955: ##############################################
 4956: =pod
 4957: 
 4958: =item * &authorspace()
 4959: 
 4960: Inputs: $url (usually will be undef).
 4961: 
 4962: Returns: Path to Authoring Space containing the resource or 
 4963:          directory being viewed (or for which action is being taken). 
 4964:          If $url is provided, and begins /priv/<domain>/<uname>
 4965:          the path will be that portion of the $context argument.
 4966:          Otherwise the path will be for the author space of the current
 4967:          user when the current role is author, or for that of the 
 4968:          co-author/assistant co-author space when the current role 
 4969:          is co-author or assistant co-author.
 4970: 
 4971: =cut
 4972: 
 4973: sub authorspace {
 4974:     my ($url) = @_;
 4975:     if ($url ne '') {
 4976:         if ($url =~ m{^(/priv/$match_domain/$match_username/)}) {
 4977:            return $1;
 4978:         }
 4979:     }
 4980:     my $caname = '';
 4981:     my $cadom = '';
 4982:     if ($env{'request.role'} =~ /^(?:ca|aa)/) {
 4983:         ($cadom,$caname) =
 4984:             ($env{'request.role'}=~/($match_domain)\/($match_username)$/);
 4985:     } elsif ($env{'request.role'} =~ m{^au\./($match_domain)/}) {
 4986:         $caname = $env{'user.name'};
 4987:         $cadom = $env{'user.domain'};
 4988:     }
 4989:     if (($caname ne '') && ($cadom ne '')) {
 4990:         return "/priv/$cadom/$caname/";
 4991:     }
 4992:     return;
 4993: }
 4994: 
 4995: ##############################################
 4996: =pod
 4997: 
 4998: =item * &head_subbox()
 4999: 
 5000: Inputs: $content (contains HTML code with page functions, etc.)
 5001: 
 5002: Returns: HTML div with $content
 5003:          To be included in page header
 5004: 
 5005: =cut
 5006: 
 5007: sub head_subbox {
 5008:     my ($content)=@_;
 5009:     my $output =
 5010:         '<div class="LC_head_subbox">'
 5011:        .$content
 5012:        .'</div>'
 5013: }
 5014: 
 5015: ##############################################
 5016: =pod
 5017: 
 5018: =item * &CSTR_pageheader()
 5019: 
 5020: Input: (optional) filename from which breadcrumb trail is built.
 5021:        In most cases no input as needed, as $env{'request.filename'}
 5022:        is appropriate for use in building the breadcrumb trail.
 5023: 
 5024: Returns: HTML div with CSTR path and recent box
 5025:          To be included on Authoring Space pages
 5026: 
 5027: =cut
 5028: 
 5029: sub CSTR_pageheader {
 5030:     my ($trailfile) = @_;
 5031:     if ($trailfile eq '') {
 5032:         $trailfile = $env{'request.filename'};
 5033:     }
 5034: 
 5035: # this is for resources; directories have customtitle, and crumbs
 5036: # and select recent are created in lonpubdir.pm
 5037: 
 5038:     my $londocroot = $Apache::lonnet::perlvar{'lonDocRoot'};
 5039:     my ($udom,$uname,$thisdisfn)=
 5040:         ($trailfile =~ m{^\Q$londocroot\E/priv/([^/]+)/([^/]+)(?:|/(.*))$});
 5041:     my $formaction = "/priv/$udom/$uname/$thisdisfn";
 5042:     $formaction =~ s{/+}{/}g;
 5043: 
 5044:     my $parentpath = '';
 5045:     my $lastitem = '';
 5046:     if ($thisdisfn =~ m-(.+/)([^/]*)$-) {
 5047:         $parentpath = $1;
 5048:         $lastitem = $2;
 5049:     } else {
 5050:         $lastitem = $thisdisfn;
 5051:     }
 5052: 
 5053:     my $output =
 5054:          '<div>'
 5055:         .&Apache::loncommon::help_open_menu('','',3,'Authoring') #FIXME: Broken? Where is it?
 5056:         .'<b>'.&mt('Authoring Space:').'</b> '
 5057:         .'<form name="dirs" method="post" action="'.$formaction
 5058:         .'" target="_top">' #FIXME lonpubdir: target="_parent"
 5059:         .&Apache::lonhtmlcommon::crumbs($uname.'/'.$parentpath,'_top','/priv/'.$udom,undef,undef);
 5060: 
 5061:     if ($lastitem) {
 5062:         $output .=
 5063:              '<span class="LC_filename">'
 5064:             .$lastitem
 5065:             .'</span>';
 5066:     }
 5067:     $output .=
 5068:          '<br />'
 5069:         #FIXME lonpubdir: &Apache::lonhtmlcommon::crumbs($uname.$thisdisfn.'/','_top','/priv','','+1',1)."</b></tt><br />"
 5070:         .&Apache::lonhtmlcommon::select_recent('construct','recent','this.form.action=this.form.recent.value;this.form.submit()')
 5071:         .'</form>'
 5072:         .&Apache::lonmenu::constspaceform()
 5073:         .'</div>';
 5074: 
 5075:     return $output;
 5076: }
 5077: 
 5078: ###############################################
 5079: ###############################################
 5080: 
 5081: =pod
 5082: 
 5083: =back
 5084: 
 5085: =head1 HTML Helpers
 5086: 
 5087: =over 4
 5088: 
 5089: =item * &bodytag()
 5090: 
 5091: Returns a uniform header for LON-CAPA web pages.
 5092: 
 5093: Inputs: 
 5094: 
 5095: =over 4
 5096: 
 5097: =item * $title, A title to be displayed on the page.
 5098: 
 5099: =item * $function, the current role (can be undef).
 5100: 
 5101: =item * $addentries, extra parameters for the <body> tag.
 5102: 
 5103: =item * $bodyonly, if defined, only return the <body> tag.
 5104: 
 5105: =item * $domain, if defined, force a given domain.
 5106: 
 5107: =item * $forcereg, if page should register as content page (relevant for 
 5108:             text interface only)
 5109: 
 5110: =item * $no_nav_bar, if true, keep the 'what is this' info but remove the
 5111:                      navigational links
 5112: 
 5113: =item * $bgcolor, used to override the bgcolor on a webpage to a specific value
 5114: 
 5115: =item * $no_inline_link, if true and in remote mode, don't show the
 5116:          'Switch To Inline Menu' link
 5117: 
 5118: =item * $args, optional argument valid values are
 5119:             no_auto_mt_title -> prevents &mt()ing the title arg
 5120:             inherit_jsmath -> when creating popup window in a page,
 5121:                               should it have jsmath forced on by the
 5122:                               current page
 5123: 
 5124: =item * $advtoolsref, optional argument, ref to an array containing
 5125:             inlineremote items to be added in "Functions" menu below
 5126:             breadcrumbs.
 5127: 
 5128: =back
 5129: 
 5130: Returns: A uniform header for LON-CAPA web pages.  
 5131: If $bodyonly is nonzero, a string containing a <body> tag will be returned.
 5132: If $bodyonly is undef or zero, an html string containing a <body> tag and 
 5133: other decorations will be returned.
 5134: 
 5135: =cut
 5136: 
 5137: sub bodytag {
 5138:     my ($title,$function,$addentries,$bodyonly,$domain,$forcereg,
 5139:         $no_nav_bar,$bgcolor,$no_inline_link,$args,$advtoolsref)=@_;
 5140: 
 5141:     my $public;
 5142:     if ((($env{'user.name'} eq 'public') && ($env{'user.domain'} eq 'public'))
 5143:         || ($env{'user.name'} eq '') && ($env{'user.domain'} eq '')) {
 5144:         $public = 1;
 5145:     }
 5146:     if (!$args->{'no_auto_mt_title'}) { $title = &mt($title); }
 5147:     my $httphost = $args->{'use_absolute'};
 5148: 
 5149:     $function = &get_users_function() if (!$function);
 5150:     my $img =    &designparm($function.'.img',$domain);
 5151:     my $font =   &designparm($function.'.font',$domain);
 5152:     my $pgbg   = $bgcolor || &designparm($function.'.pgbg',$domain);
 5153: 
 5154:     my %design = ( 'style'   => 'margin-top: 0',
 5155: 		   'bgcolor' => $pgbg,
 5156: 		   'text'    => $font,
 5157:                    'alink'   => &designparm($function.'.alink',$domain),
 5158: 		   'vlink'   => &designparm($function.'.vlink',$domain),
 5159: 		   'link'    => &designparm($function.'.link',$domain),);
 5160:     @design{keys(%$addentries)} = @$addentries{keys(%$addentries)}; 
 5161: 
 5162:  # role and realm
 5163:     my ($role,$realm) = split(m{\./},$env{'request.role'},2);
 5164:     if ($realm) {
 5165:         $realm = '/'.$realm;
 5166:     }
 5167:     if ($role  eq 'ca') {
 5168:         my ($rdom,$rname) = ($realm =~ m{^/($match_domain)/($match_username)$});
 5169:         $realm = &plainname($rname,$rdom);
 5170:     } 
 5171: # realm
 5172:     if ($env{'request.course.id'}) {
 5173:         if ($env{'request.role'} !~ /^cr/) {
 5174:             $role = &Apache::lonnet::plaintext($role,&course_type());
 5175:         }
 5176:         if ($env{'request.course.sec'}) {
 5177:             $role .= ('&nbsp;'x2).'-&nbsp;'.&mt('section:').'&nbsp;'.$env{'request.course.sec'};
 5178:         }   
 5179: 	$realm = $env{'course.'.$env{'request.course.id'}.'.description'};
 5180:     } else {
 5181:         $role = &Apache::lonnet::plaintext($role);
 5182:     }
 5183: 
 5184:     if (!$realm) { $realm='&nbsp;'; }
 5185: 
 5186:     my $extra_body_attr = &make_attr_string($forcereg,\%design);
 5187: 
 5188: # construct main body tag
 5189:     my $bodytag = "<body $extra_body_attr>".
 5190: 	&Apache::lontexconvert::init_math_support($args->{'inherit_jsmath'});
 5191: 
 5192:     &get_unprocessed_cgi($ENV{'QUERY_STRING'}, ['inhibitmenu']);
 5193: 
 5194:     if (($bodyonly) || ($no_nav_bar) || ($env{'form.inhibitmenu'} eq 'yes')) {
 5195:         return $bodytag;
 5196:     }
 5197: 
 5198:     if ($public) {
 5199: 	undef($role);
 5200:     }
 5201:     
 5202:     my $titleinfo = '<h1>'.$title.'</h1>';
 5203:     #
 5204:     # Extra info if you are the DC
 5205:     my $dc_info = '';
 5206:     if ($env{'user.adv'} && exists($env{'user.role.dc./'.
 5207:                         $env{'course.'.$env{'request.course.id'}.
 5208:                                  '.domain'}.'/'})) {
 5209:         my $cid = $env{'request.course.id'};
 5210:         $dc_info = $cid.' '.$env{'course.'.$cid.'.internal.coursecode'};
 5211:         $dc_info =~ s/\s+$//;
 5212:     }
 5213: 
 5214:     $role = '<span class="LC_nobreak">('.$role.')</span>' if $role;
 5215: 
 5216:     if ($env{'request.state'} eq 'construct') { $forcereg=1; }
 5217: 
 5218: 
 5219: 
 5220:     my $funclist;
 5221:     if (($env{'environment.remote'} eq 'on') && ($env{'request.state'} ne 'construct')) {
 5222:         $bodytag .= Apache::lonhtmlcommon::scripttag(Apache::lonmenu::utilityfunctions($httphost), 'start')."\n".
 5223:                     Apache::lonmenu::serverform();
 5224:         my $forbodytag;
 5225:         &Apache::lonmenu::prepare_functions($env{'request.noversionuri'},
 5226:                                             $forcereg,$args->{'group'},
 5227:                                             $args->{'bread_crumbs'},
 5228:                                             $advtoolsref,'',\$forbodytag);
 5229:         unless (ref($args->{'bread_crumbs'}) eq 'ARRAY') {
 5230:             $funclist = $forbodytag;
 5231:         }
 5232:     } else {
 5233: 
 5234:         #    if ($env{'request.state'} eq 'construct') {
 5235:         #        $titleinfo = &CSTR_pageheader(); #FIXME: Will be removed once all scripts have their own calls
 5236:         #    }
 5237: 
 5238:         $bodytag .= Apache::lonhtmlcommon::scripttag(
 5239:             Apache::lonmenu::utilityfunctions($httphost), 'start');
 5240: 
 5241:         my ($left,$right) = Apache::lonmenu::primary_menu();
 5242: 
 5243:         if ($env{'request.noversionuri'} =~ m{^/res/adm/pages/}) {
 5244:             if ($dc_info) {
 5245:                  $dc_info = qq|<span class="LC_cusr_subheading">$dc_info</span>|;
 5246:             }
 5247:             $bodytag .= qq|<div id="LC_nav_bar">$left $role<br />
 5248:                            <em>$realm</em> $dc_info</div>|;
 5249:             return $bodytag;
 5250:         }
 5251: 
 5252:         unless ($env{'request.symb'} =~ m/\.page___\d+___/) {
 5253:             $bodytag .= qq|<div id="LC_nav_bar">$left $role</div>|;
 5254:         }
 5255: 
 5256:         $bodytag .= $right;
 5257: 
 5258:         if ($dc_info) {
 5259:             $dc_info = &dc_courseid_toggle($dc_info);
 5260:         }
 5261:         $bodytag .= qq|<div id="LC_realm">$realm $dc_info</div>|;
 5262: 
 5263:         #if directed to not display the secondary menu, don't.
 5264:         if ($args->{'no_secondary_menu'}) {
 5265:             return $bodytag;
 5266:         }
 5267:         #don't show menus for public users
 5268:         if (!$public){
 5269:             $bodytag .= Apache::lonmenu::secondary_menu($httphost);
 5270:             $bodytag .= Apache::lonmenu::serverform();
 5271:             $bodytag .= Apache::lonhtmlcommon::scripttag('', 'end');
 5272:             if ($env{'request.state'} eq 'construct') {
 5273:                 $bodytag .= &Apache::lonmenu::innerregister($forcereg,
 5274:                                 $args->{'bread_crumbs'});
 5275:             } elsif ($forcereg) { 
 5276:                 $bodytag .= &Apache::lonmenu::innerregister($forcereg,undef,
 5277:                                                             $args->{'group'});
 5278:             } else {
 5279:                 my $forbodytag;
 5280:                 &Apache::lonmenu::prepare_functions($env{'request.noversionuri'},
 5281:                                                     $forcereg,$args->{'group'},
 5282:                                                     $args->{'bread_crumbs'},
 5283:                                                     $advtoolsref,'',\$forbodytag);
 5284:                 unless (ref($args->{'bread_crumbs'}) eq 'ARRAY') {
 5285:                     $bodytag .= $forbodytag;
 5286:                 }
 5287:             }
 5288:         }else{
 5289:             # this is to seperate menu from content when there's no secondary
 5290:             # menu. Especially needed for public accessible ressources.
 5291:             $bodytag .= '<hr style="clear:both" />';
 5292:             $bodytag .= Apache::lonhtmlcommon::scripttag('', 'end'); 
 5293:         }
 5294: 
 5295:         return $bodytag;
 5296:     }
 5297: 
 5298: #
 5299: # Top frame rendering, Remote is up
 5300: #
 5301: 
 5302:     my $imgsrc = $img;
 5303:     if ($img =~ /^\/adm/) {
 5304:         $imgsrc = &lonhttpdurl($img);
 5305:     }
 5306:     my $upperleft='<img src="'.$imgsrc.'" alt="'.$function.'" />';
 5307: 
 5308:     my $help=($no_inline_link?''
 5309:               :&Apache::loncommon::top_nav_help('Help'));
 5310: 
 5311:     # Explicit link to get inline menu
 5312:     my $menu= ($no_inline_link?''
 5313:                :'<a href="/adm/remote?action=collapse" target="_top">'.&mt('Switch to Inline Menu Mode').'</a>');
 5314: 
 5315:     if ($dc_info) {
 5316:         $dc_info = qq|<span class="LC_cusr_subheading">($dc_info)</span>|;
 5317:     }
 5318: 
 5319:     my $name = &plainname($env{'user.name'},$env{'user.domain'});
 5320:     unless ($public) {
 5321:         $name = &aboutmewrapper($name,$env{'user.name'},$env{'user.domain'},
 5322:                                 undef,'LC_menubuttons_link');
 5323:     }
 5324: 
 5325:     unless ($env{'form.inhibitmenu'}) {
 5326:         $bodytag .= qq|<div id="LC_nav_bar">$name $role</div>
 5327:                        <ol class="LC_primary_menu LC_floatright LC_right">
 5328:                        <li>$help</li>
 5329:                        <li>$menu</li>
 5330:                        </ol><div id="LC_realm"> $realm $dc_info</div>|;
 5331:     }
 5332:     if ($env{'request.state'} eq 'construct') {
 5333:         if (!$public){
 5334:             if ($env{'request.state'} eq 'construct') {
 5335:                 $funclist = &Apache::lonhtmlcommon::scripttag(
 5336:                                 &Apache::lonmenu::utilityfunctions($httphost), 'start').
 5337:                             &Apache::lonhtmlcommon::scripttag('','end').
 5338:                             &Apache::lonmenu::innerregister($forcereg,
 5339:                                                             $args->{'bread_crumbs'});
 5340:             }
 5341:         }
 5342:     }
 5343:     return $bodytag."\n".$funclist;
 5344: }
 5345: 
 5346: sub dc_courseid_toggle {
 5347:     my ($dc_info) = @_;
 5348:     return ' <span id="dccidtext" class="LC_cusr_subheading LC_nobreak">'.
 5349:            '<a href="javascript:showCourseID();" class="LC_menubuttons_link">'.
 5350:            &mt('(More ...)').'</a></span>'.
 5351:            '<div id="dccid" class="LC_dccid">'.$dc_info.'</div>';
 5352: }
 5353: 
 5354: sub make_attr_string {
 5355:     my ($register,$attr_ref) = @_;
 5356: 
 5357:     if ($attr_ref && !ref($attr_ref)) {
 5358: 	die("addentries Must be a hash ref ".
 5359: 	    join(':',caller(1))." ".
 5360: 	    join(':',caller(0))." ");
 5361:     }
 5362: 
 5363:     if ($register) {
 5364: 	my ($on_load,$on_unload);
 5365: 	foreach my $key (keys(%{$attr_ref})) {
 5366: 	    if      (lc($key) eq 'onload') {
 5367: 		$on_load.=$attr_ref->{$key}.';';
 5368: 		delete($attr_ref->{$key});
 5369: 
 5370: 	    } elsif (lc($key) eq 'onunload') {
 5371: 		$on_unload.=$attr_ref->{$key}.';';
 5372: 		delete($attr_ref->{$key});
 5373: 	    }
 5374: 	}
 5375:         if ($env{'environment.remote'} eq 'on') {
 5376:             $attr_ref->{'onload'}  =
 5377:                 &Apache::lonmenu::loadevents().  $on_load;
 5378:             $attr_ref->{'onunload'}=
 5379:                 &Apache::lonmenu::unloadevents().$on_unload;
 5380:         } else {  
 5381: 	    $attr_ref->{'onload'}  = $on_load;
 5382: 	    $attr_ref->{'onunload'}= $on_unload;
 5383:         }
 5384:     }
 5385: 
 5386:     my $attr_string;
 5387:     foreach my $attr (sort(keys(%$attr_ref))) {
 5388: 	$attr_string .= " $attr=\"".$attr_ref->{$attr}.'" ';
 5389:     }
 5390:     return $attr_string;
 5391: }
 5392: 
 5393: 
 5394: ###############################################
 5395: ###############################################
 5396: 
 5397: =pod
 5398: 
 5399: =item * &endbodytag()
 5400: 
 5401: Returns a uniform footer for LON-CAPA web pages.
 5402: 
 5403: Inputs: 1 - optional reference to an args hash
 5404: If in the hash, key for noredirectlink has a value which evaluates to true,
 5405: a 'Continue' link is not displayed if the page contains an
 5406: internal redirect in the <head></head> section,
 5407: i.e., $env{'internal.head.redirect'} exists   
 5408: 
 5409: =cut
 5410: 
 5411: sub endbodytag {
 5412:     my ($args) = @_;
 5413:     my $endbodytag;
 5414:     unless ((ref($args) eq 'HASH') && ($args->{'notbody'})) {
 5415:         $endbodytag='</body>';
 5416:     }
 5417:     $endbodytag=&Apache::lontexconvert::jsMath_process()."\n".$endbodytag;
 5418:     if ( exists( $env{'internal.head.redirect'} ) ) {
 5419:         if (!(ref($args) eq 'HASH' && $args->{'noredirectlink'})) {
 5420: 	    $endbodytag=
 5421: 	        "<br /><a href=\"$env{'internal.head.redirect'}\">".
 5422: 	        &mt('Continue').'</a>'.
 5423: 	        $endbodytag;
 5424:         }
 5425:     }
 5426:     return $endbodytag;
 5427: }
 5428: 
 5429: =pod
 5430: 
 5431: =item * &standard_css()
 5432: 
 5433: Returns a style sheet
 5434: 
 5435: Inputs: (all optional)
 5436:             domain         -> force to color decorate a page for a specific
 5437:                                domain
 5438:             function       -> force usage of a specific rolish color scheme
 5439:             bgcolor        -> override the default page bgcolor
 5440: 
 5441: =cut
 5442: 
 5443: sub standard_css {
 5444:     my ($function,$domain,$bgcolor) = @_;
 5445:     $function  = &get_users_function() if (!$function);
 5446:     my $img    = &designparm($function.'.img',   $domain);
 5447:     my $tabbg  = &designparm($function.'.tabbg', $domain);
 5448:     my $font   = &designparm($function.'.font',  $domain);
 5449:     my $fontmenu = &designparm($function.'.fontmenu', $domain);
 5450: #second colour for later usage
 5451:     my $sidebg = &designparm($function.'.sidebg',$domain);
 5452:     my $pgbg_or_bgcolor =
 5453: 	         $bgcolor ||
 5454: 	         &designparm($function.'.pgbg',  $domain);
 5455:     my $pgbg   = &designparm($function.'.pgbg',  $domain);
 5456:     my $alink  = &designparm($function.'.alink', $domain);
 5457:     my $vlink  = &designparm($function.'.vlink', $domain);
 5458:     my $link   = &designparm($function.'.link',  $domain);
 5459: 
 5460:     my $sans                 = 'Verdana,Arial,Helvetica,sans-serif';
 5461:     my $mono                 = 'monospace';
 5462:     my $data_table_head      = $sidebg;
 5463:     my $data_table_light     = '#FAFAFA';
 5464:     my $data_table_dark      = '#E0E0E0';
 5465:     my $data_table_darker    = '#CCCCCC';
 5466:     my $data_table_highlight = '#FFFF00';
 5467:     my $mail_new             = '#FFBB77';
 5468:     my $mail_new_hover       = '#DD9955';
 5469:     my $mail_read            = '#BBBB77';
 5470:     my $mail_read_hover      = '#999944';
 5471:     my $mail_replied         = '#AAAA88';
 5472:     my $mail_replied_hover   = '#888855';
 5473:     my $mail_other           = '#99BBBB';
 5474:     my $mail_other_hover     = '#669999';
 5475:     my $table_header         = '#DDDDDD';
 5476:     my $feedback_link_bg     = '#BBBBBB';
 5477:     my $lg_border_color      = '#C8C8C8';
 5478:     my $button_hover         = '#BF2317';
 5479: 
 5480:     my $border = ($env{'browser.type'} eq 'explorer' ||
 5481:       $env{'browser.type'} eq 'safari'     ) ? '0 2px 0 2px'
 5482:                                              : '0 3px 0 4px';
 5483: 
 5484: 
 5485:     return <<END;
 5486: 
 5487: /* needed for iframe to allow 100% height in FF */
 5488: body, html { 
 5489:     margin: 0;
 5490:     padding: 0 0.5%;
 5491:     height: 99%; /* to avoid scrollbars */
 5492: }
 5493: 
 5494: body {
 5495:   font-family: $sans;
 5496:   line-height:130%;
 5497:   font-size:0.83em;
 5498:   color:$font;
 5499: }
 5500: 
 5501: a:focus,
 5502: a:focus img {
 5503:   color: red;
 5504: }
 5505: 
 5506: form, .inline {
 5507:   display: inline;
 5508: }
 5509: 
 5510: .LC_right {
 5511:   text-align:right;
 5512: }
 5513: 
 5514: .LC_middle {
 5515:   vertical-align:middle;
 5516: }
 5517: 
 5518: .LC_floatleft {
 5519:   float: left;
 5520: }
 5521: 
 5522: .LC_floatright {
 5523:   float: right;
 5524: }
 5525: 
 5526: .LC_400Box {
 5527:   width:400px;
 5528: }
 5529: 
 5530: .LC_iframecontainer {
 5531:     width: 98%;
 5532:     margin: 0;
 5533:     position: fixed;
 5534:     top: 8.5em;
 5535:     bottom: 0;
 5536: }
 5537: 
 5538: .LC_iframecontainer iframe{
 5539:     border: none;
 5540:     width: 100%;
 5541:     height: 100%;
 5542: }
 5543: 
 5544: .LC_filename {
 5545:   font-family: $mono;
 5546:   white-space:pre;
 5547:   font-size: 120%;
 5548: }
 5549: 
 5550: .LC_fileicon {
 5551:   border: none;
 5552:   height: 1.3em;
 5553:   vertical-align: text-bottom;
 5554:   margin-right: 0.3em;
 5555:   text-decoration:none;
 5556: }
 5557: 
 5558: .LC_setting {
 5559:   text-decoration:underline;
 5560: }
 5561: 
 5562: .LC_error {
 5563:   color: red;
 5564: }
 5565: 
 5566: .LC_warning {
 5567:   color: darkorange;
 5568: }
 5569: 
 5570: .LC_diff_removed {
 5571:   color: red;
 5572: }
 5573: 
 5574: .LC_info,
 5575: .LC_success,
 5576: .LC_diff_added {
 5577:   color: green;
 5578: }
 5579: 
 5580: div.LC_confirm_box {
 5581:   background-color: #FAFAFA;
 5582:   border: 1px solid $lg_border_color;
 5583:   margin-right: 0;
 5584:   padding: 5px;
 5585: }
 5586: 
 5587: div.LC_confirm_box .LC_error img,
 5588: div.LC_confirm_box .LC_success img {
 5589:   vertical-align: middle;
 5590: }
 5591: 
 5592: .LC_icon {
 5593:   border: none;
 5594:   vertical-align: middle;
 5595: }
 5596: 
 5597: .LC_docs_spacer {
 5598:   width: 25px;
 5599:   height: 1px;
 5600:   border: none;
 5601: }
 5602: 
 5603: .LC_internal_info {
 5604:   color: #999999;
 5605: }
 5606: 
 5607: .LC_discussion {
 5608:   background: $data_table_dark;
 5609:   border: 1px solid black;
 5610:   margin: 2px;
 5611: }
 5612: 
 5613: .LC_disc_action_left {
 5614:   background: $sidebg;
 5615:   text-align: left;
 5616:   padding: 4px;
 5617:   margin: 2px;
 5618: }
 5619: 
 5620: .LC_disc_action_right {
 5621:   background: $sidebg;
 5622:   text-align: right;
 5623:   padding: 4px;
 5624:   margin: 2px;
 5625: }
 5626: 
 5627: .LC_disc_new_item {
 5628:   background: white;
 5629:   border: 2px solid red;
 5630:   margin: 4px;
 5631:   padding: 4px;
 5632: }
 5633: 
 5634: .LC_disc_old_item {
 5635:   background: white;
 5636:   margin: 4px;
 5637:   padding: 4px;
 5638: }
 5639: 
 5640: table.LC_pastsubmission {
 5641:   border: 1px solid black;
 5642:   margin: 2px;
 5643: }
 5644: 
 5645: table#LC_menubuttons {
 5646:   width: 100%;
 5647:   background: $pgbg;
 5648:   border: 2px;
 5649:   border-collapse: separate;
 5650:   padding: 0;
 5651: }
 5652: 
 5653: table#LC_title_bar a {
 5654:   color: $fontmenu;
 5655: }
 5656: 
 5657: table#LC_title_bar {
 5658:   clear: both;
 5659:   display: none;
 5660: }
 5661: 
 5662: table#LC_title_bar,
 5663: table.LC_breadcrumbs, /* obsolete? */
 5664: table#LC_title_bar.LC_with_remote {
 5665:   width: 100%;
 5666:   border-color: $pgbg;
 5667:   border-style: solid;
 5668:   border-width: $border;
 5669:   background: $pgbg;
 5670:   color: $fontmenu;
 5671:   border-collapse: collapse;
 5672:   padding: 0;
 5673:   margin: 0;
 5674: }
 5675: 
 5676: ul.LC_breadcrumb_tools_outerlist {
 5677:     margin: 0;
 5678:     padding: 0;
 5679:     position: relative;
 5680:     list-style: none;
 5681: }
 5682: ul.LC_breadcrumb_tools_outerlist li {
 5683:     display: inline;
 5684: }
 5685: 
 5686: .LC_breadcrumb_tools_navigation {
 5687:     padding: 0;
 5688:     margin: 0;
 5689:     float: left;
 5690: }
 5691: .LC_breadcrumb_tools_tools {
 5692:     padding: 0;
 5693:     margin: 0;
 5694:     float: right;
 5695: }
 5696: 
 5697: table#LC_title_bar td {
 5698:   background: $tabbg;
 5699: }
 5700: 
 5701: table#LC_menubuttons img {
 5702:   border: none;
 5703: }
 5704: 
 5705: .LC_breadcrumbs_component {
 5706:   float: right;
 5707:   margin: 0 1em;
 5708: }
 5709: .LC_breadcrumbs_component img {
 5710:   vertical-align: middle;
 5711: }
 5712: 
 5713: td.LC_table_cell_checkbox {
 5714:   text-align: center;
 5715: }
 5716: 
 5717: .LC_fontsize_small {
 5718:   font-size: 70%;
 5719: }
 5720: 
 5721: #LC_breadcrumbs {
 5722:   clear:both;
 5723:   background: $sidebg;
 5724:   border-bottom: 1px solid $lg_border_color;
 5725:   line-height: 2.5em;
 5726:   overflow: hidden;
 5727:   margin: 0;
 5728:   padding: 0;
 5729:   text-align: left;
 5730: }
 5731: 
 5732: .LC_head_subbox, .LC_actionbox {
 5733:   clear:both;
 5734:   background: #F8F8F8; /* $sidebg; */
 5735:   border: 1px solid $sidebg;
 5736:   margin: 0 0 10px 0;
 5737:   padding: 3px;
 5738:   text-align: left;
 5739: }
 5740: 
 5741: .LC_fontsize_medium {
 5742:   font-size: 85%;
 5743: }
 5744: 
 5745: .LC_fontsize_large {
 5746:   font-size: 120%;
 5747: }
 5748: 
 5749: .LC_menubuttons_inline_text {
 5750:   color: $font;
 5751:   font-size: 90%;
 5752:   padding-left:3px;
 5753: }
 5754: 
 5755: .LC_menubuttons_inline_text img{
 5756:   vertical-align: middle;
 5757: }
 5758: 
 5759: li.LC_menubuttons_inline_text img {
 5760:   cursor:pointer;
 5761:   text-decoration: none;
 5762: }
 5763: 
 5764: .LC_menubuttons_link {
 5765:   text-decoration: none;
 5766: }
 5767: 
 5768: .LC_menubuttons_category {
 5769:   color: $font;
 5770:   background: $pgbg;
 5771:   font-size: larger;
 5772:   font-weight: bold;
 5773: }
 5774: 
 5775: td.LC_menubuttons_text {
 5776:   color: $font;
 5777: }
 5778: 
 5779: .LC_current_location {
 5780:   background: $tabbg;
 5781: }
 5782: 
 5783: table.LC_data_table {
 5784:   border: 1px solid #000000;
 5785:   border-collapse: separate;
 5786:   border-spacing: 1px;
 5787:   background: $pgbg;
 5788: }
 5789: 
 5790: .LC_data_table_dense {
 5791:   font-size: small;
 5792: }
 5793: 
 5794: table.LC_nested_outer {
 5795:   border: 1px solid #000000;
 5796:   border-collapse: collapse;
 5797:   border-spacing: 0;
 5798:   width: 100%;
 5799: }
 5800: 
 5801: table.LC_innerpickbox,
 5802: table.LC_nested {
 5803:   border: none;
 5804:   border-collapse: collapse;
 5805:   border-spacing: 0;
 5806:   width: 100%;
 5807: }
 5808: 
 5809: table.LC_data_table tr th,
 5810: table.LC_calendar tr th,
 5811: table.LC_prior_tries tr th,
 5812: table.LC_innerpickbox tr th {
 5813:   font-weight: bold;
 5814:   background-color: $data_table_head;
 5815:   color:$fontmenu;
 5816:   font-size:90%;
 5817: }
 5818: 
 5819: table.LC_innerpickbox tr th,
 5820: table.LC_innerpickbox tr td {
 5821:   vertical-align: top;
 5822: }
 5823: 
 5824: table.LC_data_table tr.LC_info_row > td {
 5825:   background-color: #CCCCCC;
 5826:   font-weight: bold;
 5827:   text-align: left;
 5828: }
 5829: 
 5830: table.LC_data_table tr.LC_odd_row > td {
 5831:   background-color: $data_table_light;
 5832:   padding: 2px;
 5833:   vertical-align: top;
 5834: }
 5835: 
 5836: table.LC_pick_box tr > td.LC_odd_row {
 5837:   background-color: $data_table_light;
 5838:   vertical-align: top;
 5839: }
 5840: 
 5841: table.LC_data_table tr.LC_even_row > td {
 5842:   background-color: $data_table_dark;
 5843:   padding: 2px;
 5844:   vertical-align: top;
 5845: }
 5846: 
 5847: table.LC_pick_box tr > td.LC_even_row {
 5848:   background-color: $data_table_dark;
 5849:   vertical-align: top;
 5850: }
 5851: 
 5852: table.LC_data_table tr.LC_data_table_highlight td {
 5853:   background-color: $data_table_darker;
 5854: }
 5855: 
 5856: table.LC_data_table tr td.LC_leftcol_header {
 5857:   background-color: $data_table_head;
 5858:   font-weight: bold;
 5859: }
 5860: 
 5861: table.LC_data_table tr.LC_empty_row td,
 5862: table.LC_nested tr.LC_empty_row td {
 5863:   font-weight: bold;
 5864:   font-style: italic;
 5865:   text-align: center;
 5866:   padding: 8px;
 5867: }
 5868: 
 5869: table.LC_data_table tr.LC_empty_row td,
 5870: table.LC_data_table tr.LC_footer_row td {
 5871:   background-color: $sidebg;
 5872: }
 5873: 
 5874: table.LC_nested tr.LC_empty_row td {
 5875:   background-color: #FFFFFF;
 5876: }
 5877: 
 5878: table.LC_caption {
 5879: }
 5880: 
 5881: table.LC_nested tr.LC_empty_row td {
 5882:   padding: 4ex
 5883: }
 5884: 
 5885: table.LC_nested_outer tr th {
 5886:   font-weight: bold;
 5887:   color:$fontmenu;
 5888:   background-color: $data_table_head;
 5889:   font-size: small;
 5890:   border-bottom: 1px solid #000000;
 5891: }
 5892: 
 5893: table.LC_nested_outer tr td.LC_subheader {
 5894:   background-color: $data_table_head;
 5895:   font-weight: bold;
 5896:   font-size: small;
 5897:   border-bottom: 1px solid #000000;
 5898:   text-align: right;
 5899: }
 5900: 
 5901: table.LC_nested tr.LC_info_row td {
 5902:   background-color: #CCCCCC;
 5903:   font-weight: bold;
 5904:   font-size: small;
 5905:   text-align: center;
 5906: }
 5907: 
 5908: table.LC_nested tr.LC_info_row td.LC_left_item,
 5909: table.LC_nested_outer tr th.LC_left_item {
 5910:   text-align: left;
 5911: }
 5912: 
 5913: table.LC_nested td {
 5914:   background-color: #FFFFFF;
 5915:   font-size: small;
 5916: }
 5917: 
 5918: table.LC_nested_outer tr th.LC_right_item,
 5919: table.LC_nested tr.LC_info_row td.LC_right_item,
 5920: table.LC_nested tr.LC_odd_row td.LC_right_item,
 5921: table.LC_nested tr td.LC_right_item {
 5922:   text-align: right;
 5923: }
 5924: 
 5925: table.LC_nested tr.LC_odd_row td {
 5926:   background-color: #EEEEEE;
 5927: }
 5928: 
 5929: table.LC_createuser {
 5930: }
 5931: 
 5932: table.LC_createuser tr.LC_section_row td {
 5933:   font-size: small;
 5934: }
 5935: 
 5936: table.LC_createuser tr.LC_info_row td  {
 5937:   background-color: #CCCCCC;
 5938:   font-weight: bold;
 5939:   text-align: center;
 5940: }
 5941: 
 5942: table.LC_calendar {
 5943:   border: 1px solid #000000;
 5944:   border-collapse: collapse;
 5945:   width: 98%;
 5946: }
 5947: 
 5948: table.LC_calendar_pickdate {
 5949:   font-size: xx-small;
 5950: }
 5951: 
 5952: table.LC_calendar tr td {
 5953:   border: 1px solid #000000;
 5954:   vertical-align: top;
 5955:   width: 14%;
 5956: }
 5957: 
 5958: table.LC_calendar tr td.LC_calendar_day_empty {
 5959:   background-color: $data_table_dark;
 5960: }
 5961: 
 5962: table.LC_calendar tr td.LC_calendar_day_current {
 5963:   background-color: $data_table_highlight;
 5964: }
 5965: 
 5966: table.LC_data_table tr td.LC_mail_new {
 5967:   background-color: $mail_new;
 5968: }
 5969: 
 5970: table.LC_data_table tr.LC_mail_new:hover {
 5971:   background-color: $mail_new_hover;
 5972: }
 5973: 
 5974: table.LC_data_table tr td.LC_mail_read {
 5975:   background-color: $mail_read;
 5976: }
 5977: 
 5978: /*
 5979: table.LC_data_table tr.LC_mail_read:hover {
 5980:   background-color: $mail_read_hover;
 5981: }
 5982: */
 5983: 
 5984: table.LC_data_table tr td.LC_mail_replied {
 5985:   background-color: $mail_replied;
 5986: }
 5987: 
 5988: /*
 5989: table.LC_data_table tr.LC_mail_replied:hover {
 5990:   background-color: $mail_replied_hover;
 5991: }
 5992: */
 5993: 
 5994: table.LC_data_table tr td.LC_mail_other {
 5995:   background-color: $mail_other;
 5996: }
 5997: 
 5998: /*
 5999: table.LC_data_table tr.LC_mail_other:hover {
 6000:   background-color: $mail_other_hover;
 6001: }
 6002: */
 6003: 
 6004: table.LC_data_table tr > td.LC_browser_file,
 6005: table.LC_data_table tr > td.LC_browser_file_published {
 6006:   background: #AAEE77;
 6007: }
 6008: 
 6009: table.LC_data_table tr > td.LC_browser_file_locked,
 6010: table.LC_data_table tr > td.LC_browser_file_unpublished {
 6011:   background: #FFAA99;
 6012: }
 6013: 
 6014: table.LC_data_table tr > td.LC_browser_file_obsolete {
 6015:   background: #888888;
 6016: }
 6017: 
 6018: table.LC_data_table tr > td.LC_browser_file_modified,
 6019: table.LC_data_table tr > td.LC_browser_file_metamodified {
 6020:   background: #F8F866;
 6021: }
 6022: 
 6023: table.LC_data_table tr.LC_browser_folder > td {
 6024:   background: #E0E8FF;
 6025: }
 6026: 
 6027: table.LC_data_table tr > td.LC_roles_is {
 6028:   /* background: #77FF77; */
 6029: }
 6030: 
 6031: table.LC_data_table tr > td.LC_roles_future {
 6032:   border-right: 8px solid #FFFF77;
 6033: }
 6034: 
 6035: table.LC_data_table tr > td.LC_roles_will {
 6036:   border-right: 8px solid #FFAA77;
 6037: }
 6038: 
 6039: table.LC_data_table tr > td.LC_roles_expired {
 6040:   border-right: 8px solid #FF7777;
 6041: }
 6042: 
 6043: table.LC_data_table tr > td.LC_roles_will_not {
 6044:   border-right: 8px solid #AAFF77;
 6045: }
 6046: 
 6047: table.LC_data_table tr > td.LC_roles_selected {
 6048:   border-right: 8px solid #11CC55;
 6049: }
 6050: 
 6051: span.LC_current_location {
 6052:   font-size:larger;
 6053:   background: $pgbg;
 6054: }
 6055: 
 6056: span.LC_current_nav_location {
 6057:   font-weight:bold;
 6058:   background: $sidebg;
 6059: }
 6060: 
 6061: span.LC_parm_menu_item {
 6062:   font-size: larger;
 6063: }
 6064: 
 6065: span.LC_parm_scope_all {
 6066:   color: red;
 6067: }
 6068: 
 6069: span.LC_parm_scope_folder {
 6070:   color: green;
 6071: }
 6072: 
 6073: span.LC_parm_scope_resource {
 6074:   color: orange;
 6075: }
 6076: 
 6077: span.LC_parm_part {
 6078:   color: blue;
 6079: }
 6080: 
 6081: span.LC_parm_folder,
 6082: span.LC_parm_symb {
 6083:   font-size: x-small;
 6084:   font-family: $mono;
 6085:   color: #AAAAAA;
 6086: }
 6087: 
 6088: ul.LC_parm_parmlist li {
 6089:   display: inline-block;
 6090:   padding: 0.3em 0.8em;
 6091:   vertical-align: top;
 6092:   width: 150px;
 6093:   border-top:1px solid $lg_border_color;
 6094: }
 6095: 
 6096: td.LC_parm_overview_level_menu,
 6097: td.LC_parm_overview_map_menu,
 6098: td.LC_parm_overview_parm_selectors,
 6099: td.LC_parm_overview_restrictions  {
 6100:   border: 1px solid black;
 6101:   border-collapse: collapse;
 6102: }
 6103: 
 6104: table.LC_parm_overview_restrictions td {
 6105:   border-width: 1px 4px 1px 4px;
 6106:   border-style: solid;
 6107:   border-color: $pgbg;
 6108:   text-align: center;
 6109: }
 6110: 
 6111: table.LC_parm_overview_restrictions th {
 6112:   background: $tabbg;
 6113:   border-width: 1px 4px 1px 4px;
 6114:   border-style: solid;
 6115:   border-color: $pgbg;
 6116: }
 6117: 
 6118: table#LC_helpmenu {
 6119:   border: none;
 6120:   height: 55px;
 6121:   border-spacing: 0;
 6122: }
 6123: 
 6124: table#LC_helpmenu fieldset legend {
 6125:   font-size: larger;
 6126: }
 6127: 
 6128: table#LC_helpmenu_links {
 6129:   width: 100%;
 6130:   border: 1px solid black;
 6131:   background: $pgbg;
 6132:   padding: 0;
 6133:   border-spacing: 1px;
 6134: }
 6135: 
 6136: table#LC_helpmenu_links tr td {
 6137:   padding: 1px;
 6138:   background: $tabbg;
 6139:   text-align: center;
 6140:   font-weight: bold;
 6141: }
 6142: 
 6143: table#LC_helpmenu_links a:link,
 6144: table#LC_helpmenu_links a:visited,
 6145: table#LC_helpmenu_links a:active {
 6146:   text-decoration: none;
 6147:   color: $font;
 6148: }
 6149: 
 6150: table#LC_helpmenu_links a:hover {
 6151:   text-decoration: underline;
 6152:   color: $vlink;
 6153: }
 6154: 
 6155: .LC_chrt_popup_exists {
 6156:   border: 1px solid #339933;
 6157:   margin: -1px;
 6158: }
 6159: 
 6160: .LC_chrt_popup_up {
 6161:   border: 1px solid yellow;
 6162:   margin: -1px;
 6163: }
 6164: 
 6165: .LC_chrt_popup {
 6166:   border: 1px solid #8888FF;
 6167:   background: #CCCCFF;
 6168: }
 6169: 
 6170: table.LC_pick_box {
 6171:   border-collapse: separate;
 6172:   background: white;
 6173:   border: 1px solid black;
 6174:   border-spacing: 1px;
 6175: }
 6176: 
 6177: table.LC_pick_box td.LC_pick_box_title {
 6178:   background: $sidebg;
 6179:   font-weight: bold;
 6180:   text-align: left;
 6181:   vertical-align: top;
 6182:   width: 184px;
 6183:   padding: 8px;
 6184: }
 6185: 
 6186: table.LC_pick_box td.LC_pick_box_value {
 6187:   text-align: left;
 6188:   padding: 8px;
 6189: }
 6190: 
 6191: table.LC_pick_box td.LC_pick_box_select {
 6192:   text-align: left;
 6193:   padding: 8px;
 6194: }
 6195: 
 6196: table.LC_pick_box td.LC_pick_box_separator {
 6197:   padding: 0;
 6198:   height: 1px;
 6199:   background: black;
 6200: }
 6201: 
 6202: table.LC_pick_box td.LC_pick_box_submit {
 6203:   text-align: right;
 6204: }
 6205: 
 6206: table.LC_pick_box td.LC_evenrow_value {
 6207:   text-align: left;
 6208:   padding: 8px;
 6209:   background-color: $data_table_light;
 6210: }
 6211: 
 6212: table.LC_pick_box td.LC_oddrow_value {
 6213:   text-align: left;
 6214:   padding: 8px;
 6215:   background-color: $data_table_light;
 6216: }
 6217: 
 6218: span.LC_helpform_receipt_cat {
 6219:   font-weight: bold;
 6220: }
 6221: 
 6222: table.LC_group_priv_box {
 6223:   background: white;
 6224:   border: 1px solid black;
 6225:   border-spacing: 1px;
 6226: }
 6227: 
 6228: table.LC_group_priv_box td.LC_pick_box_title {
 6229:   background: $tabbg;
 6230:   font-weight: bold;
 6231:   text-align: right;
 6232:   width: 184px;
 6233: }
 6234: 
 6235: table.LC_group_priv_box td.LC_groups_fixed {
 6236:   background: $data_table_light;
 6237:   text-align: center;
 6238: }
 6239: 
 6240: table.LC_group_priv_box td.LC_groups_optional {
 6241:   background: $data_table_dark;
 6242:   text-align: center;
 6243: }
 6244: 
 6245: table.LC_group_priv_box td.LC_groups_functionality {
 6246:   background: $data_table_darker;
 6247:   text-align: center;
 6248:   font-weight: bold;
 6249: }
 6250: 
 6251: table.LC_group_priv td {
 6252:   text-align: left;
 6253:   padding: 0;
 6254: }
 6255: 
 6256: .LC_navbuttons {
 6257:   margin: 2ex 0ex 2ex 0ex;
 6258: }
 6259: 
 6260: .LC_topic_bar {
 6261:   font-weight: bold;
 6262:   background: $tabbg;
 6263:   margin: 1em 0em 1em 2em;
 6264:   padding: 3px;
 6265:   font-size: 1.2em;
 6266: }
 6267: 
 6268: .LC_topic_bar span {
 6269:   left: 0.5em;
 6270:   position: absolute;
 6271:   vertical-align: middle;
 6272:   font-size: 1.2em;
 6273: }
 6274: 
 6275: table.LC_course_group_status {
 6276:   margin: 20px;
 6277: }
 6278: 
 6279: table.LC_status_selector td {
 6280:   vertical-align: top;
 6281:   text-align: center;
 6282:   padding: 4px;
 6283: }
 6284: 
 6285: div.LC_feedback_link {
 6286:   clear: both;
 6287:   background: $sidebg;
 6288:   width: 100%;
 6289:   padding-bottom: 10px;
 6290:   border: 1px $tabbg solid;
 6291:   height: 22px;
 6292:   line-height: 22px;
 6293:   padding-top: 5px;
 6294: }
 6295: 
 6296: div.LC_feedback_link img {
 6297:   height: 22px;
 6298:   vertical-align:middle;
 6299: }
 6300: 
 6301: div.LC_feedback_link a {
 6302:   text-decoration: none;
 6303: }
 6304: 
 6305: div.LC_comblock {
 6306:   display:inline;
 6307:   color:$font;
 6308:   font-size:90%;
 6309: }
 6310: 
 6311: div.LC_feedback_link div.LC_comblock {
 6312:   padding-left:5px;
 6313: }
 6314: 
 6315: div.LC_feedback_link div.LC_comblock a {
 6316:   color:$font;
 6317: }
 6318: 
 6319: span.LC_feedback_link {
 6320:   /* background: $feedback_link_bg; */
 6321:   font-size: larger;
 6322: }
 6323: 
 6324: span.LC_message_link {
 6325:   /* background: $feedback_link_bg; */
 6326:   font-size: larger;
 6327:   position: absolute;
 6328:   right: 1em;
 6329: }
 6330: 
 6331: table.LC_prior_tries {
 6332:   border: 1px solid #000000;
 6333:   border-collapse: separate;
 6334:   border-spacing: 1px;
 6335: }
 6336: 
 6337: table.LC_prior_tries td {
 6338:   padding: 2px;
 6339: }
 6340: 
 6341: .LC_answer_correct {
 6342:   background: lightgreen;
 6343:   color: darkgreen;
 6344:   padding: 6px;
 6345: }
 6346: 
 6347: .LC_answer_charged_try {
 6348:   background: #FFAAAA;
 6349:   color: darkred;
 6350:   padding: 6px;
 6351: }
 6352: 
 6353: .LC_answer_not_charged_try,
 6354: .LC_answer_no_grade,
 6355: .LC_answer_late {
 6356:   background: lightyellow;
 6357:   color: black;
 6358:   padding: 6px;
 6359: }
 6360: 
 6361: .LC_answer_previous {
 6362:   background: lightblue;
 6363:   color: darkblue;
 6364:   padding: 6px;
 6365: }
 6366: 
 6367: .LC_answer_no_message {
 6368:   background: #FFFFFF;
 6369:   color: black;
 6370:   padding: 6px;
 6371: }
 6372: 
 6373: .LC_answer_unknown {
 6374:   background: orange;
 6375:   color: black;
 6376:   padding: 6px;
 6377: }
 6378: 
 6379: span.LC_prior_numerical,
 6380: span.LC_prior_string,
 6381: span.LC_prior_custom,
 6382: span.LC_prior_reaction,
 6383: span.LC_prior_math {
 6384:   font-family: $mono;
 6385:   white-space: pre;
 6386: }
 6387: 
 6388: span.LC_prior_string {
 6389:   font-family: $mono;
 6390:   white-space: pre;
 6391: }
 6392: 
 6393: table.LC_prior_option {
 6394:   width: 100%;
 6395:   border-collapse: collapse;
 6396: }
 6397: 
 6398: table.LC_prior_rank,
 6399: table.LC_prior_match {
 6400:   border-collapse: collapse;
 6401: }
 6402: 
 6403: table.LC_prior_option tr td,
 6404: table.LC_prior_rank tr td,
 6405: table.LC_prior_match tr td {
 6406:   border: 1px solid #000000;
 6407: }
 6408: 
 6409: .LC_nobreak {
 6410:   white-space: nowrap;
 6411: }
 6412: 
 6413: span.LC_cusr_emph {
 6414:   font-style: italic;
 6415: }
 6416: 
 6417: span.LC_cusr_subheading {
 6418:   font-weight: normal;
 6419:   font-size: 85%;
 6420: }
 6421: 
 6422: div.LC_docs_entry_move {
 6423:   border: 1px solid #BBBBBB;
 6424:   background: #DDDDDD;
 6425:   width: 22px;
 6426:   padding: 1px;
 6427:   margin: 0;
 6428: }
 6429: 
 6430: table.LC_data_table tr > td.LC_docs_entry_commands,
 6431: table.LC_data_table tr > td.LC_docs_entry_parameter {
 6432:   font-size: x-small;
 6433: }
 6434: 
 6435: .LC_docs_entry_parameter {
 6436:   white-space: nowrap;
 6437: }
 6438: 
 6439: .LC_docs_copy {
 6440:   color: #000099;
 6441: }
 6442: 
 6443: .LC_docs_cut {
 6444:   color: #550044;
 6445: }
 6446: 
 6447: .LC_docs_rename {
 6448:   color: #009900;
 6449: }
 6450: 
 6451: .LC_docs_remove {
 6452:   color: #990000;
 6453: }
 6454: 
 6455: .LC_docs_reinit_warn,
 6456: .LC_docs_ext_edit {
 6457:   font-size: x-small;
 6458: }
 6459: 
 6460: table.LC_docs_adddocs td,
 6461: table.LC_docs_adddocs th {
 6462:   border: 1px solid #BBBBBB;
 6463:   padding: 4px;
 6464:   background: #DDDDDD;
 6465: }
 6466: 
 6467: table.LC_sty_begin {
 6468:   background: #BBFFBB;
 6469: }
 6470: 
 6471: table.LC_sty_end {
 6472:   background: #FFBBBB;
 6473: }
 6474: 
 6475: table.LC_double_column {
 6476:   border-width: 0;
 6477:   border-collapse: collapse;
 6478:   width: 100%;
 6479:   padding: 2px;
 6480: }
 6481: 
 6482: table.LC_double_column tr td.LC_left_col {
 6483:   top: 2px;
 6484:   left: 2px;
 6485:   width: 47%;
 6486:   vertical-align: top;
 6487: }
 6488: 
 6489: table.LC_double_column tr td.LC_right_col {
 6490:   top: 2px;
 6491:   right: 2px;
 6492:   width: 47%;
 6493:   vertical-align: top;
 6494: }
 6495: 
 6496: div.LC_left_float {
 6497:   float: left;
 6498:   padding-right: 5%;
 6499:   padding-bottom: 4px;
 6500: }
 6501: 
 6502: div.LC_clear_float_header {
 6503:   padding-bottom: 2px;
 6504: }
 6505: 
 6506: div.LC_clear_float_footer {
 6507:   padding-top: 10px;
 6508:   clear: both;
 6509: }
 6510: 
 6511: div.LC_grade_show_user {
 6512: /*  border-left: 5px solid $sidebg; */
 6513:   border-top: 5px solid #000000;
 6514:   margin: 50px 0 0 0;
 6515:   padding: 15px 0 5px 10px;
 6516: }
 6517: 
 6518: div.LC_grade_show_user_odd_row {
 6519: /*  border-left: 5px solid #000000; */
 6520: }
 6521: 
 6522: div.LC_grade_show_user div.LC_Box {
 6523:   margin-right: 50px;
 6524: }
 6525: 
 6526: div.LC_grade_submissions,
 6527: div.LC_grade_message_center,
 6528: div.LC_grade_info_links {
 6529:   margin: 5px;
 6530:   width: 99%;
 6531:   background: #FFFFFF;
 6532: }
 6533: 
 6534: div.LC_grade_submissions_header,
 6535: div.LC_grade_message_center_header {
 6536:   font-weight: bold;
 6537:   font-size: large;
 6538: }
 6539: 
 6540: div.LC_grade_submissions_body,
 6541: div.LC_grade_message_center_body {
 6542:   border: 1px solid black;
 6543:   width: 99%;
 6544:   background: #FFFFFF;
 6545: }
 6546: 
 6547: table.LC_scantron_action {
 6548:   width: 100%;
 6549: }
 6550: 
 6551: table.LC_scantron_action tr th {
 6552:   font-weight:bold;
 6553:   font-style:normal;
 6554: }
 6555: 
 6556: .LC_edit_problem_header,
 6557: div.LC_edit_problem_footer {
 6558:   font-weight: normal;
 6559:   font-size:  medium;
 6560:   margin: 2px;
 6561:   background-color: $sidebg;
 6562: }
 6563: 
 6564: div.LC_edit_problem_header,
 6565: div.LC_edit_problem_header div,
 6566: div.LC_edit_problem_footer,
 6567: div.LC_edit_problem_footer div,
 6568: div.LC_edit_problem_editxml_header,
 6569: div.LC_edit_problem_editxml_header div {
 6570:   margin-top: 5px;
 6571: }
 6572: 
 6573: div.LC_edit_problem_header_title {
 6574:   font-weight: bold;
 6575:   font-size: larger;
 6576:   background: $tabbg;
 6577:   padding: 3px;
 6578:   margin: 0 0 5px 0;
 6579: }
 6580: 
 6581: table.LC_edit_problem_header_title {
 6582:   width: 100%;
 6583:   background: $tabbg;
 6584: }
 6585: 
 6586: div.LC_edit_problem_discards {
 6587:   float: left;
 6588:   padding-bottom: 5px;
 6589: }
 6590: 
 6591: div.LC_edit_problem_saves {
 6592:   float: right;
 6593:   padding-bottom: 5px;
 6594: }
 6595: 
 6596: .LC_edit_opt {
 6597:   padding-left: 1em;
 6598:   white-space: nowrap;
 6599: }
 6600: 
 6601: .LC_edit_problem_latexhelper{
 6602:     text-align: right;
 6603: }
 6604: 
 6605: #LC_edit_problem_colorful div{
 6606:     margin-left: 40px;
 6607: }
 6608: 
 6609: img.stift {
 6610:   border-width: 0;
 6611:   vertical-align: middle;
 6612: }
 6613: 
 6614: table td.LC_mainmenu_col_fieldset {
 6615:   vertical-align: top;
 6616: }
 6617: 
 6618: div.LC_createcourse {
 6619:   margin: 10px 10px 10px 10px;
 6620: }
 6621: 
 6622: .LC_dccid {
 6623:   float: right;
 6624:   margin: 0.2em 0 0 0;
 6625:   padding: 0;
 6626:   font-size: 90%;
 6627:   display:none;
 6628: }
 6629: 
 6630: ol.LC_primary_menu a:hover,
 6631: ol#LC_MenuBreadcrumbs a:hover,
 6632: ol#LC_PathBreadcrumbs a:hover,
 6633: ul#LC_secondary_menu a:hover,
 6634: .LC_FormSectionClearButton input:hover
 6635: ul.LC_TabContent   li:hover a {
 6636:   color:$button_hover;
 6637:   text-decoration:none;
 6638: }
 6639: 
 6640: h1 {
 6641:   padding: 0;
 6642:   line-height:130%;
 6643: }
 6644: 
 6645: h2,
 6646: h3,
 6647: h4,
 6648: h5,
 6649: h6 {
 6650:   margin: 5px 0 5px 0;
 6651:   padding: 0;
 6652:   line-height:130%;
 6653: }
 6654: 
 6655: .LC_hcell {
 6656:   padding:3px 15px 3px 15px;
 6657:   margin: 0;
 6658:   background-color:$tabbg;
 6659:   color:$fontmenu;
 6660:   border-bottom:solid 1px $lg_border_color;
 6661: }
 6662: 
 6663: .LC_Box > .LC_hcell {
 6664:   margin: 0 -10px 10px -10px;
 6665: }
 6666: 
 6667: .LC_noBorder {
 6668:   border: 0;
 6669: }
 6670: 
 6671: .LC_FormSectionClearButton input {
 6672:   background-color:transparent;
 6673:   border: none;
 6674:   cursor:pointer;
 6675:   text-decoration:underline;
 6676: }
 6677: 
 6678: .LC_help_open_topic {
 6679:   color: #FFFFFF;
 6680:   background-color: #EEEEFF;
 6681:   margin: 1px;
 6682:   padding: 4px;
 6683:   border: 1px solid #000033;
 6684:   white-space: nowrap;
 6685:   /* vertical-align: middle; */
 6686: }
 6687: 
 6688: dl,
 6689: ul,
 6690: div,
 6691: fieldset {
 6692:   margin: 10px 10px 10px 0;
 6693:   /* overflow: hidden; */
 6694: }
 6695: 
 6696: article.geogebraweb div {
 6697:     margin: 0;
 6698: }
 6699: 
 6700: fieldset > legend {
 6701:   font-weight: bold;
 6702:   padding: 0 5px 0 5px;
 6703: }
 6704: 
 6705: #LC_nav_bar {
 6706:   float: left;
 6707:   background-color: $pgbg_or_bgcolor;
 6708:   margin: 0 0 2px 0;
 6709: }
 6710: 
 6711: #LC_realm {
 6712:   margin: 0.2em 0 0 0;
 6713:   padding: 0;
 6714:   font-weight: bold;
 6715:   text-align: center;
 6716:   background-color: $pgbg_or_bgcolor;
 6717: }
 6718: 
 6719: #LC_nav_bar em {
 6720:   font-weight: bold;
 6721:   font-style: normal;
 6722: }
 6723: 
 6724: ol.LC_primary_menu {
 6725:   margin: 0;
 6726:   padding: 0;
 6727:   background-color: $pgbg_or_bgcolor;
 6728: }
 6729: 
 6730: ol#LC_PathBreadcrumbs {
 6731:   margin: 0;
 6732: }
 6733: 
 6734: ol.LC_primary_menu li {
 6735:   color: RGB(80, 80, 80);
 6736:   vertical-align: middle;
 6737:   text-align: left;
 6738:   list-style: none;
 6739:   float: left;
 6740: }
 6741: 
 6742: ol.LC_primary_menu li a {
 6743:   display: block;
 6744:   margin: 0;
 6745:   padding: 0 5px 0 10px;
 6746:   text-decoration: none;
 6747: }
 6748: 
 6749: ol.LC_primary_menu li ul {
 6750:   display: none;
 6751:   width: 10em;
 6752:   background-color: $data_table_light;
 6753: }
 6754: 
 6755: ol.LC_primary_menu li:hover ul, ol.LC_primary_menu li.hover ul {
 6756:   display: block;
 6757:   position: absolute;
 6758:   margin: 0;
 6759:   padding: 0;
 6760:   z-index: 2;
 6761: }
 6762: 
 6763: ol.LC_primary_menu li:hover li, ol.LC_primary_menu li.hover li {
 6764:   font-size: 90%;
 6765:   vertical-align: top;
 6766:   float: none;
 6767:   border-left: 1px solid black;
 6768:   border-right: 1px solid black;
 6769: }
 6770: 
 6771: ol.LC_primary_menu li:hover li a, ol.LC_primary_menu li.hover li a {
 6772:   background-color:$data_table_light;
 6773: }
 6774: 
 6775: ol.LC_primary_menu li li a:hover {
 6776:    color:$button_hover;
 6777:    background-color:$data_table_dark;
 6778: }
 6779: 
 6780: ol.LC_primary_menu li img {
 6781:   vertical-align: bottom;
 6782:   height: 1.1em;
 6783:   margin: 0.2em 0 0 0;
 6784: }
 6785: 
 6786: ol.LC_primary_menu a {
 6787:   color: RGB(80, 80, 80);
 6788:   text-decoration: none;
 6789: }
 6790: 
 6791: ol.LC_primary_menu a.LC_new_message {
 6792:   font-weight:bold;
 6793:   color: darkred;
 6794: }
 6795: 
 6796: ol.LC_docs_parameters {
 6797:   margin-left: 0;
 6798:   padding: 0;
 6799:   list-style: none;
 6800: }
 6801: 
 6802: ol.LC_docs_parameters li {
 6803:   margin: 0;
 6804:   padding-right: 20px;
 6805:   display: inline;
 6806: }
 6807: 
 6808: ol.LC_docs_parameters li:before {
 6809:   content: "\\002022 \\0020";
 6810: }
 6811: 
 6812: li.LC_docs_parameters_title {
 6813:   font-weight: bold;
 6814: }
 6815: 
 6816: ol.LC_docs_parameters li.LC_docs_parameters_title:before {
 6817:   content: "";
 6818: }
 6819: 
 6820: ul#LC_secondary_menu {
 6821:   clear: right;
 6822:   color: $fontmenu;
 6823:   background: $tabbg;
 6824:   list-style: none;
 6825:   padding: 0;
 6826:   margin: 0;
 6827:   width: 100%;
 6828:   text-align: left;
 6829:   float: left;
 6830: }
 6831: 
 6832: ul#LC_secondary_menu li {
 6833:   font-weight: bold;
 6834:   line-height: 1.8em;
 6835:   border-right: 1px solid black;
 6836:   vertical-align: middle;
 6837:   float: left;
 6838: }
 6839: 
 6840: ul#LC_secondary_menu li.LC_hoverable:hover, ul#LC_secondary_menu li.hover {
 6841:   background-color: $data_table_light;
 6842: }
 6843: 
 6844: ul#LC_secondary_menu li a {
 6845:   padding: 0 0.8em;
 6846: }
 6847: 
 6848: ul#LC_secondary_menu li ul {
 6849:   display: none;
 6850: }
 6851: 
 6852: ul#LC_secondary_menu li:hover ul, ul#LC_secondary_menu li.hover ul {
 6853:   display: block;
 6854:   position: absolute;
 6855:   margin: 0;
 6856:   padding: 0;
 6857:   list-style:none;
 6858:   float: none;
 6859:   background-color: $data_table_light;
 6860:   z-index: 2;
 6861:   margin-left: -1px;
 6862: }
 6863: 
 6864: ul#LC_secondary_menu li ul li {
 6865:   font-size: 90%;
 6866:   vertical-align: top;
 6867:   border-left: 1px solid black;
 6868:   border-right: 1px solid black;
 6869:   background-color: $data_table_light;
 6870:   list-style:none;
 6871:   float: none;
 6872: }
 6873: 
 6874: ul#LC_secondary_menu li ul li:hover, ul#LC_secondary_menu li ul li.hover {
 6875:   background-color: $data_table_dark;
 6876: }
 6877: 
 6878: ul.LC_TabContent {
 6879:   display:block;
 6880:   background: $sidebg;
 6881:   border-bottom: solid 1px $lg_border_color;
 6882:   list-style:none;
 6883:   margin: -1px -10px 0 -10px;
 6884:   padding: 0;
 6885: }
 6886: 
 6887: ul.LC_TabContent li,
 6888: ul.LC_TabContentBigger li {
 6889:   float:left;
 6890: }
 6891: 
 6892: ul#LC_secondary_menu li a {
 6893:   color: $fontmenu;
 6894:   text-decoration: none;
 6895: }
 6896: 
 6897: ul.LC_TabContent {
 6898:   min-height:20px;
 6899: }
 6900: 
 6901: ul.LC_TabContent li {
 6902:   vertical-align:middle;
 6903:   padding: 0 16px 0 10px;
 6904:   background-color:$tabbg;
 6905:   border-bottom:solid 1px $lg_border_color;
 6906:   border-left: solid 1px $font;
 6907: }
 6908: 
 6909: ul.LC_TabContent .right {
 6910:   float:right;
 6911: }
 6912: 
 6913: ul.LC_TabContent li a,
 6914: ul.LC_TabContent li {
 6915:   color:rgb(47,47,47);
 6916:   text-decoration:none;
 6917:   font-size:95%;
 6918:   font-weight:bold;
 6919:   min-height:20px;
 6920: }
 6921: 
 6922: ul.LC_TabContent li a:hover,
 6923: ul.LC_TabContent li a:focus {
 6924:   color: $button_hover;
 6925:   background:none;
 6926:   outline:none;
 6927: }
 6928: 
 6929: ul.LC_TabContent li:hover {
 6930:   color: $button_hover;
 6931:   cursor:pointer;
 6932: }
 6933: 
 6934: ul.LC_TabContent li.active {
 6935:   color: $font;
 6936:   background:#FFFFFF url(/adm/lonIcons/open.gif) no-repeat scroll right center;
 6937:   border-bottom:solid 1px #FFFFFF;
 6938:   cursor: default;
 6939: }
 6940: 
 6941: ul.LC_TabContent li.active a {
 6942:   color:$font;
 6943:   background:#FFFFFF;
 6944:   outline: none;
 6945: }
 6946: 
 6947: ul.LC_TabContent li.goback {
 6948:   float: left;
 6949:   border-left: none;
 6950: }
 6951: 
 6952: #maincoursedoc {
 6953:   clear:both;
 6954: }
 6955: 
 6956: ul.LC_TabContentBigger {
 6957:   display:block;
 6958:   list-style:none;
 6959:   padding: 0;
 6960: }
 6961: 
 6962: ul.LC_TabContentBigger li {
 6963:   vertical-align:bottom;
 6964:   height: 30px;
 6965:   font-size:110%;
 6966:   font-weight:bold;
 6967:   color: #737373;
 6968: }
 6969: 
 6970: ul.LC_TabContentBigger li.active {
 6971:   position: relative;
 6972:   top: 1px;
 6973: }
 6974: 
 6975: ul.LC_TabContentBigger li a {
 6976:   background:url('/adm/lonIcons/tabbgleft.gif') left bottom no-repeat;
 6977:   height: 30px;
 6978:   line-height: 30px;
 6979:   text-align: center;
 6980:   display: block;
 6981:   text-decoration: none;
 6982:   outline: none;  
 6983: }
 6984: 
 6985: ul.LC_TabContentBigger li.active a {
 6986:   background:url('/adm/lonIcons/tabbgleft.gif') left top no-repeat;
 6987:   color:$font;
 6988: }
 6989: 
 6990: ul.LC_TabContentBigger li b {
 6991:   background: url('/adm/lonIcons/tabbgright.gif') no-repeat right bottom;
 6992:   display: block;
 6993:   float: left;
 6994:   padding: 0 30px;
 6995:   border-bottom: 1px solid $lg_border_color;
 6996: }
 6997: 
 6998: ul.LC_TabContentBigger li:hover b {
 6999:   color:$button_hover;
 7000: }
 7001: 
 7002: ul.LC_TabContentBigger li.active b {
 7003:   background:url('/adm/lonIcons/tabbgright.gif') right top no-repeat;
 7004:   color:$font;
 7005:   border: 0;
 7006: }
 7007: 
 7008: 
 7009: ul.LC_CourseBreadcrumbs {
 7010:   background: $sidebg;
 7011:   height: 2em;
 7012:   padding-left: 10px;
 7013:   margin: 0;
 7014:   list-style-position: inside;
 7015: }
 7016: 
 7017: ol#LC_MenuBreadcrumbs,
 7018: ol#LC_PathBreadcrumbs {
 7019:   padding-left: 10px;
 7020:   margin: 0;
 7021:   height: 2.5em;  /* equal to #LC_breadcrumbs line-height */
 7022: }
 7023: 
 7024: ol#LC_MenuBreadcrumbs li,
 7025: ol#LC_PathBreadcrumbs li,
 7026: ul.LC_CourseBreadcrumbs li {
 7027:   display: inline;
 7028:   white-space: normal;  
 7029: }
 7030: 
 7031: ol#LC_MenuBreadcrumbs li a,
 7032: ul.LC_CourseBreadcrumbs li a {
 7033:   text-decoration: none;
 7034:   font-size:90%;
 7035: }
 7036: 
 7037: ol#LC_MenuBreadcrumbs h1 {
 7038:   display: inline;
 7039:   font-size: 90%;
 7040:   line-height: 2.5em;
 7041:   margin: 0;
 7042:   padding: 0;
 7043: }
 7044: 
 7045: ol#LC_PathBreadcrumbs li a {
 7046:   text-decoration:none;
 7047:   font-size:100%;
 7048:   font-weight:bold;
 7049: }
 7050: 
 7051: .LC_Box {
 7052:   border: solid 1px $lg_border_color;
 7053:   padding: 0 10px 10px 10px;
 7054: }
 7055: 
 7056: .LC_DocsBox {
 7057:   border: solid 1px $lg_border_color;
 7058:   padding: 0 0 10px 10px;
 7059: }
 7060: 
 7061: .LC_AboutMe_Image {
 7062:   float:left;
 7063:   margin-right:10px;
 7064: }
 7065: 
 7066: .LC_Clear_AboutMe_Image {
 7067:   clear:left;
 7068: }
 7069: 
 7070: dl.LC_ListStyleClean dt {
 7071:   padding-right: 5px;
 7072:   display: table-header-group;
 7073: }
 7074: 
 7075: dl.LC_ListStyleClean dd {
 7076:   display: table-row;
 7077: }
 7078: 
 7079: .LC_ListStyleClean,
 7080: .LC_ListStyleSimple,
 7081: .LC_ListStyleNormal,
 7082: .LC_ListStyleSpecial {
 7083:   /* display:block; */
 7084:   list-style-position: inside;
 7085:   list-style-type: none;
 7086:   overflow: hidden;
 7087:   padding: 0;
 7088: }
 7089: 
 7090: .LC_ListStyleSimple li,
 7091: .LC_ListStyleSimple dd,
 7092: .LC_ListStyleNormal li,
 7093: .LC_ListStyleNormal dd,
 7094: .LC_ListStyleSpecial li,
 7095: .LC_ListStyleSpecial dd {
 7096:   margin: 0;
 7097:   padding: 5px 5px 5px 10px;
 7098:   clear: both;
 7099: }
 7100: 
 7101: .LC_ListStyleClean li,
 7102: .LC_ListStyleClean dd {
 7103:   padding-top: 0;
 7104:   padding-bottom: 0;
 7105: }
 7106: 
 7107: .LC_ListStyleSimple dd,
 7108: .LC_ListStyleSimple li {
 7109:   border-bottom: solid 1px $lg_border_color;
 7110: }
 7111: 
 7112: .LC_ListStyleSpecial li,
 7113: .LC_ListStyleSpecial dd {
 7114:   list-style-type: none;
 7115:   background-color: RGB(220, 220, 220);
 7116:   margin-bottom: 4px;
 7117: }
 7118: 
 7119: table.LC_SimpleTable {
 7120:   margin:5px;
 7121:   border:solid 1px $lg_border_color;
 7122: }
 7123: 
 7124: table.LC_SimpleTable tr {
 7125:   padding: 0;
 7126:   border:solid 1px $lg_border_color;
 7127: }
 7128: 
 7129: table.LC_SimpleTable thead {
 7130:   background:rgb(220,220,220);
 7131: }
 7132: 
 7133: div.LC_columnSection {
 7134:   display: block;
 7135:   clear: both;
 7136:   overflow: hidden;
 7137:   margin: 0;
 7138: }
 7139: 
 7140: div.LC_columnSection>* {
 7141:   float: left;
 7142:   margin: 10px 20px 10px 0;
 7143:   overflow:hidden;
 7144: }
 7145: 
 7146: table em {
 7147:   font-weight: bold;
 7148:   font-style: normal;
 7149: }
 7150: 
 7151: table.LC_tableBrowseRes,
 7152: table.LC_tableOfContent {
 7153:   border:none;
 7154:   border-spacing: 1px;
 7155:   padding: 3px;
 7156:   background-color: #FFFFFF;
 7157:   font-size: 90%;
 7158: }
 7159: 
 7160: table.LC_tableOfContent {
 7161:   border-collapse: collapse;
 7162: }
 7163: 
 7164: table.LC_tableBrowseRes a,
 7165: table.LC_tableOfContent a {
 7166:   background-color: transparent;
 7167:   text-decoration: none;
 7168: }
 7169: 
 7170: table.LC_tableOfContent img {
 7171:   border: none;
 7172:   height: 1.3em;
 7173:   vertical-align: text-bottom;
 7174:   margin-right: 0.3em;
 7175: }
 7176: 
 7177: a#LC_content_toolbar_firsthomework {
 7178:   background-image:url(/res/adm/pages/open-first-problem.gif);
 7179: }
 7180: 
 7181: a#LC_content_toolbar_everything {
 7182:   background-image:url(/res/adm/pages/show-all.gif);
 7183: }
 7184: 
 7185: a#LC_content_toolbar_uncompleted {
 7186:   background-image:url(/res/adm/pages/show-incomplete-problems.gif);
 7187: }
 7188: 
 7189: #LC_content_toolbar_clearbubbles {
 7190:   background-image:url(/res/adm/pages/mark-discussionentries-read.gif);
 7191: }
 7192: 
 7193: a#LC_content_toolbar_changefolder {
 7194:   background : url(/res/adm/pages/close-all-folders.gif) top center ;
 7195: }
 7196: 
 7197: a#LC_content_toolbar_changefolder_toggled {
 7198:   background-image:url(/res/adm/pages/open-all-folders.gif);
 7199: }
 7200: 
 7201: a#LC_content_toolbar_edittoplevel {
 7202:   background-image:url(/res/adm/pages/edittoplevel.gif);
 7203: }
 7204: 
 7205: ul#LC_toolbar li a:hover {
 7206:   background-position: bottom center;
 7207: }
 7208: 
 7209: ul#LC_toolbar {
 7210:   padding: 0;
 7211:   margin: 2px;
 7212:   list-style:none;
 7213:   position:relative;
 7214:   background-color:white;
 7215:   overflow: auto;
 7216: }
 7217: 
 7218: ul#LC_toolbar li {
 7219:   border:1px solid white;
 7220:   padding: 0;
 7221:   margin: 0;
 7222:   float: left;
 7223:   display:inline;
 7224:   vertical-align:middle;
 7225:   white-space: nowrap;
 7226: }
 7227: 
 7228: 
 7229: a.LC_toolbarItem {
 7230:   display:block;
 7231:   padding: 0;
 7232:   margin: 0;
 7233:   height: 32px;
 7234:   width: 32px;
 7235:   color:white;
 7236:   border: none;
 7237:   background-repeat:no-repeat;
 7238:   background-color:transparent;
 7239: }
 7240: 
 7241: ul.LC_funclist {
 7242:     margin: 0;
 7243:     padding: 0.5em 1em 0.5em 0;
 7244: }
 7245: 
 7246: ul.LC_funclist > li:first-child {
 7247:     font-weight:bold; 
 7248:     margin-left:0.8em;
 7249: }
 7250: 
 7251: ul.LC_funclist + ul.LC_funclist {
 7252:     /* 
 7253:        left border as a seperator if we have more than
 7254:        one list 
 7255:     */
 7256:     border-left: 1px solid $sidebg;
 7257:     /* 
 7258:        this hides the left border behind the border of the 
 7259:        outer box if element is wrapped to the next 'line' 
 7260:     */
 7261:     margin-left: -1px;
 7262: }
 7263: 
 7264: ul.LC_funclist li {
 7265:   display: inline;
 7266:   white-space: nowrap;
 7267:   margin: 0 0 0 25px;
 7268:   line-height: 150%;
 7269: }
 7270: 
 7271: .LC_hidden {
 7272:   display: none;
 7273: }
 7274: 
 7275: .LCmodal-overlay {
 7276: 		position:fixed;
 7277: 		top:0;
 7278: 		right:0;
 7279: 		bottom:0;
 7280: 		left:0;
 7281: 		height:100%;
 7282: 		width:100%;
 7283: 		margin:0;
 7284: 		padding:0;
 7285: 		background:#999;
 7286: 		opacity:.75;
 7287: 		filter: alpha(opacity=75);
 7288: 		-moz-opacity: 0.75;
 7289: 		z-index:101;
 7290: }
 7291: 
 7292: * html .LCmodal-overlay {   
 7293: 		position: absolute;
 7294: 		height: expression(document.body.scrollHeight > document.body.offsetHeight ? document.body.scrollHeight : document.body.offsetHeight + 'px');
 7295: }
 7296: 
 7297: .LCmodal-window {
 7298: 		position:fixed;
 7299: 		top:50%;
 7300: 		left:50%;
 7301: 		margin:0;
 7302: 		padding:0;
 7303: 		z-index:102;
 7304: 	}
 7305: 
 7306: * html .LCmodal-window {
 7307: 		position:absolute;
 7308: }
 7309: 
 7310: .LCclose-window {
 7311: 		position:absolute;
 7312: 		width:32px;
 7313: 		height:32px;
 7314: 		right:8px;
 7315: 		top:8px;
 7316: 		background:transparent url('/res/adm/pages/process-stop.png') no-repeat scroll right top;
 7317: 		text-indent:-99999px;
 7318: 		overflow:hidden;
 7319: 		cursor:pointer;
 7320: }
 7321: 
 7322: /*
 7323:   styles used by TTH when "Default set of options to pass to tth/m
 7324:   when converting TeX" in course settings has been set
 7325: 
 7326:   option passed: -t
 7327: 
 7328: */
 7329: 
 7330: td div.comp { margin-top: -0.6ex; margin-bottom: -1ex;}
 7331: td div.comb { margin-top: -0.6ex; margin-bottom: -.6ex;}
 7332: td div.hrcomp { line-height: 0.9; margin-top: -0.8ex; margin-bottom: -1ex;}
 7333: td div.norm {line-height:normal;}
 7334: 
 7335: /*
 7336:   option passed -y3
 7337: */
 7338: 
 7339: span.roman {font-family: serif; font-style: normal; font-weight: normal;}
 7340: span.overacc2 {position: relative;  left: .8em; top: -1.2ex;}
 7341: span.overacc1 {position: relative;  left: .6em; top: -1.2ex;}
 7342: 
 7343: END
 7344: }
 7345: 
 7346: =pod
 7347: 
 7348: =item * &headtag()
 7349: 
 7350: Returns a uniform footer for LON-CAPA web pages.
 7351: 
 7352: Inputs: $title - optional title for the head
 7353:         $head_extra - optional extra HTML to put inside the <head>
 7354:         $args - optional arguments
 7355:             force_register - if is true call registerurl so the remote is 
 7356:                              informed
 7357:             redirect       -> array ref of
 7358:                                    1- seconds before redirect occurs
 7359:                                    2- url to redirect to
 7360:                                    3- whether the side effect should occur
 7361:                            (side effect of setting 
 7362:                                $env{'internal.head.redirect'} to the url 
 7363:                                redirected too)
 7364:             domain         -> force to color decorate a page for a specific
 7365:                                domain
 7366:             function       -> force usage of a specific rolish color scheme
 7367:             bgcolor        -> override the default page bgcolor
 7368:             no_auto_mt_title
 7369:                            -> prevent &mt()ing the title arg
 7370: 
 7371: =cut
 7372: 
 7373: sub headtag {
 7374:     my ($title,$head_extra,$args) = @_;
 7375:     
 7376:     my $function = $args->{'function'} || &get_users_function();
 7377:     my $domain   = $args->{'domain'}   || &determinedomain();
 7378:     my $bgcolor  = $args->{'bgcolor'}  || &designparm($function.'.pgbg',$domain);
 7379:     my $httphost = $args->{'use_absolute'};
 7380:     my $url = join(':',$env{'user.name'},$env{'user.domain'},
 7381: 		   $Apache::lonnet::perlvar{'lonVersion'},
 7382: 		   #time(),
 7383: 		   $env{'environment.color.timestamp'},
 7384: 		   $function,$domain,$bgcolor);
 7385: 
 7386:     $url = '/adm/css/'.&escape($url).'.css';
 7387: 
 7388:     my $result =
 7389: 	'<head>'.
 7390: 	&font_settings($args);
 7391: 
 7392:     my $inhibitprint;
 7393:     if ($args->{'print_suppress'}) {
 7394:         $inhibitprint = &print_suppression();
 7395:     }
 7396: 
 7397:     if (!$args->{'frameset'}) {
 7398: 	$result .= &Apache::lonhtmlcommon::htmlareaheaders();
 7399:     }
 7400:     if ($args->{'force_register'}) {
 7401:         $result .= &Apache::lonmenu::registerurl(1);
 7402:     }
 7403:     if (!$args->{'no_nav_bar'} 
 7404: 	&& !$args->{'only_body'}
 7405: 	&& !$args->{'frameset'}) {
 7406: 	$result .= &help_menu_js($httphost);
 7407:         $result.=&modal_window();
 7408:         $result.=&togglebox_script();
 7409:         $result.=&wishlist_window();
 7410:         $result.=&LCprogressbarUpdate_script();
 7411:     } else {
 7412:         if ($args->{'add_modal'}) {
 7413:            $result.=&modal_window();
 7414:         }
 7415:         if ($args->{'add_wishlist'}) {
 7416:            $result.=&wishlist_window();
 7417:         }
 7418:         if ($args->{'add_togglebox'}) {
 7419:            $result.=&togglebox_script();
 7420:         }
 7421:         if ($args->{'add_progressbar'}) {
 7422:            $result.=&LCprogressbarUpdate_script();
 7423:         }
 7424:     }
 7425:     if (ref($args->{'redirect'})) {
 7426: 	my ($time,$url,$inhibit_continue) = @{$args->{'redirect'}};
 7427: 	$url = &Apache::lonenc::check_encrypt($url);
 7428: 	if (!$inhibit_continue) {
 7429: 	    $env{'internal.head.redirect'} = $url;
 7430: 	}
 7431: 	$result.=<<ADDMETA
 7432: <meta http-equiv="pragma" content="no-cache" />
 7433: <meta http-equiv="Refresh" content="$time; url=$url" />
 7434: ADDMETA
 7435:     } else {
 7436:         unless (($args->{'frameset'}) || ($args->{'js_ready'}) || ($args->{'only_body'}) || ($args->{'no_nav_bar'})) {
 7437:             my $requrl = $env{'request.uri'};
 7438:             if ($requrl eq '') {
 7439:                 $requrl = $ENV{'REQUEST_URI'};
 7440:                 $requrl =~ s/\?.+$//;
 7441:             }
 7442:             unless (($requrl =~ m{^/adm/(?:switchserver|login|authenticate|logout|groupsort|cleanup|helper|slotrequest|grades)(\?|$)}) ||
 7443:                     (($requrl =~ m{^/res/}) && (($env{'form.submitted'} eq 'scantron') ||
 7444:                      ($env{'form.grade_symb'}) || ($Apache::lonhomework::scantronmode)))) {
 7445:                 my $dom_in_use = $Apache::lonnet::perlvar{'lonDefDomain'};
 7446:                 unless (&Apache::lonnet::allowed('mau',$dom_in_use)) {
 7447:                     my %domdefs = &Apache::lonnet::get_domain_defaults($dom_in_use);
 7448:                     if (ref($domdefs{'offloadnow'}) eq 'HASH') {
 7449:                         my $lonhost = $Apache::lonnet::perlvar{'lonHostID'};
 7450:                         if ($domdefs{'offloadnow'}{$lonhost}) {
 7451:                             my $newserver = &Apache::lonnet::spareserver(30000,undef,1,$dom_in_use);
 7452:                             if (($newserver) && ($newserver ne $lonhost)) {
 7453:                                 my $numsec = 5;
 7454:                                 my $timeout = $numsec * 1000;
 7455:                                 my ($newurl,$locknum,%locks,$msg);
 7456:                                 if ($env{'request.role.adv'}) {
 7457:                                     ($locknum,%locks) = &Apache::lonnet::get_locks();
 7458:                                 }
 7459:                                 my $disable_submit = 0;
 7460:                                 if ($requrl =~ /$LONCAPA::assess_re/) {
 7461:                                     $disable_submit = 1;
 7462:                                 }
 7463:                                 if ($locknum) {
 7464:                                     my @lockinfo = sort(values(%locks));
 7465:                                     $msg = &mt('Once the following tasks are complete: ')."\\n".
 7466:                                            join(", ",sort(values(%locks)))."\\n".
 7467:                                            &mt('your session will be transferred to a different server, after you click "Roles".');
 7468:                                 } else {
 7469:                                     if (($requrl =~ m{^/res/}) && ($env{'form.submitted'} =~ /^part_/)) {
 7470:                                         $msg = &mt('Your LON-CAPA submission has been recorded')."\\n";
 7471:                                     }
 7472:                                     $msg .= &mt('Your current LON-CAPA session will be transferred to a different server in [quant,_1,second].',$numsec);
 7473:                                     $newurl = '/adm/switchserver?otherserver='.$newserver;
 7474:                                     if (($env{'request.role'}) && ($env{'request.role'} ne 'cm')) {
 7475:                                         $newurl .= '&role='.$env{'request.role'};
 7476:                                     }
 7477:                                     if ($env{'request.symb'}) {
 7478:                                         $newurl .= '&symb='.$env{'request.symb'};
 7479:                                     } else {
 7480:                                         $newurl .= '&origurl='.$requrl;
 7481:                                     }
 7482:                                 }
 7483:                                 $result.=<<OFFLOAD
 7484: <meta http-equiv="pragma" content="no-cache" />
 7485: <script type="text/javascript">
 7486: function LC_Offload_Now() {
 7487:     var dest = "$newurl";
 7488:     if (dest != '') {
 7489:         window.location.href="$newurl";
 7490:     }
 7491: }
 7492: window.alert('$msg');
 7493: if ($disable_submit) {
 7494:     \$(document).ready(function () {
 7495:         \$(".LC_hwk_submit").prop("disabled", true);
 7496:         \$( ".LC_textline" ).prop( "readonly", "readonly");
 7497:     });
 7498: }
 7499: setTimeout('LC_Offload_Now()', $timeout);
 7500: </script>
 7501: OFFLOAD
 7502:                             }
 7503:                         }
 7504:                     }
 7505:                 }
 7506:             }
 7507:         }
 7508:     }
 7509:     if (!defined($title)) {
 7510: 	$title = 'The LearningOnline Network with CAPA';
 7511:     }
 7512:     if (!$args->{'no_auto_mt_title'}) { $title = &mt($title); }
 7513:     $result .= '<title> LON-CAPA '.$title.'</title>'
 7514: 	.'<link rel="stylesheet" type="text/css" href="'.$url.'"';
 7515:     if (!$args->{'frameset'}) {
 7516:         $result .= ' /';
 7517:     }
 7518:     $result .= '>'
 7519:         .$inhibitprint
 7520: 	.$head_extra;
 7521:     if ($env{'browser.mobile'}) {
 7522:         $result .= '
 7523: <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=0, minimum-scale=1.0, maximum-scale=1.0">
 7524: <meta name="apple-mobile-web-app-capable" content="yes" />';
 7525:     }
 7526:     return $result.'</head>';
 7527: }
 7528: 
 7529: =pod
 7530: 
 7531: =item * &font_settings()
 7532: 
 7533: Returns neccessary <meta> to set the proper encoding
 7534: 
 7535: Inputs: optional reference to HASH -- $args passed to &headtag()
 7536: 
 7537: =cut
 7538: 
 7539: sub font_settings {
 7540:     my ($args) = @_;
 7541:     my $headerstring='';
 7542:     if ((!$env{'browser.mathml'} && $env{'browser.unicode'}) ||
 7543:         ((ref($args) eq 'HASH') && ($args->{'browser.unicode'}))) {
 7544: 	$headerstring.=
 7545: 	    '<meta http-equiv="Content-Type" content="text/html; charset=utf-8"';
 7546:         if (!$args->{'frameset'}) {
 7547:             $headerstring.= ' /';
 7548:         }
 7549:         $headerstring .= '>'."\n";
 7550:     }
 7551:     return $headerstring;
 7552: }
 7553: 
 7554: =pod
 7555: 
 7556: =item * &print_suppression()
 7557: 
 7558: In course context returns css which causes the body to be blank when media="print",
 7559: if printout generation is unavailable for the current resource.
 7560: 
 7561: This could be because:
 7562: 
 7563: (a) printstartdate is in the future
 7564: 
 7565: (b) printenddate is in the past
 7566: 
 7567: (c) there is an active exam block with "printout"
 7568: functionality blocked
 7569: 
 7570: Users with pav, pfo or evb privileges are exempt.
 7571: 
 7572: Inputs: none
 7573: 
 7574: =cut
 7575: 
 7576: 
 7577: sub print_suppression {
 7578:     my $noprint;
 7579:     if ($env{'request.course.id'}) {
 7580:         my $scope = $env{'request.course.id'};
 7581:         if ((&Apache::lonnet::allowed('pav',$scope)) ||
 7582:             (&Apache::lonnet::allowed('pfo',$scope))) {
 7583:             return;
 7584:         }
 7585:         if ($env{'request.course.sec'} ne '') {
 7586:             $scope .= "/$env{'request.course.sec'}";
 7587:             if ((&Apache::lonnet::allowed('pav',$scope)) ||
 7588:                 (&Apache::lonnet::allowed('pfo',$scope))) {
 7589:                 return;
 7590:             }
 7591:         }
 7592:         my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 7593:         my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 7594:         my $blocked = &blocking_status('printout',$cnum,$cdom,undef,1);
 7595:         if ($blocked) {
 7596:             my $checkrole = "cm./$cdom/$cnum";
 7597:             if ($env{'request.course.sec'} ne '') {
 7598:                 $checkrole .= "/$env{'request.course.sec'}";
 7599:             }
 7600:             unless ((&Apache::lonnet::allowed('evb',undef,undef,$checkrole)) &&
 7601:                     ($env{'request.role'} !~ m{^st\./$cdom/$cnum})) {
 7602:                 $noprint = 1;
 7603:             }
 7604:         }
 7605:         unless ($noprint) {
 7606:             my $symb = &Apache::lonnet::symbread();
 7607:             if ($symb ne '') {
 7608:                 my $navmap = Apache::lonnavmaps::navmap->new();
 7609:                 if (ref($navmap)) {
 7610:                     my $res = $navmap->getBySymb($symb);
 7611:                     if (ref($res)) {
 7612:                         if (!$res->resprintable()) {
 7613:                             $noprint = 1;
 7614:                         }
 7615:                     }
 7616:                 }
 7617:             }
 7618:         }
 7619:         if ($noprint) {
 7620:             return <<"ENDSTYLE";
 7621: <style type="text/css" media="print">
 7622:     body { display:none }
 7623: </style>
 7624: ENDSTYLE
 7625:         }
 7626:     }
 7627:     return;
 7628: }
 7629: 
 7630: =pod
 7631: 
 7632: =item * &xml_begin()
 7633: 
 7634: Returns the needed doctype and <html>
 7635: 
 7636: Inputs: none
 7637: 
 7638: =cut
 7639: 
 7640: sub xml_begin {
 7641:     my ($is_frameset) = @_;
 7642:     my $output='';
 7643: 
 7644:     if ($env{'browser.mathml'}) {
 7645: 	$output='<?xml version="1.0"?>'
 7646:             #.'<?xml-stylesheet type="text/css" href="/adm/MathML/mathml.css"?>'."\n"
 7647: #            .'<!DOCTYPE html SYSTEM "/adm/MathML/mathml.dtd" '
 7648:             
 7649: #	    .'<!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">] >'
 7650: 	    .'<!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">'
 7651:             .'<html xmlns:math="http://www.w3.org/1998/Math/MathML" ' 
 7652: 	    .'xmlns="http://www.w3.org/1999/xhtml">';
 7653:     } elsif ($is_frameset) {
 7654:         $output='<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Frameset//EN" "http://www.w3.org/TR/html4/frameset.dtd">'."\n".
 7655:                 '<html>'."\n";
 7656:     } else {
 7657: 	$output='<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">'."\n".
 7658:                 '<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">'."\n";
 7659:     }
 7660:     return $output;
 7661: }
 7662: 
 7663: =pod
 7664: 
 7665: =item * &start_page()
 7666: 
 7667: Returns a complete <html> .. <body> section for LON-CAPA web pages.
 7668: 
 7669: Inputs:
 7670: 
 7671: =over 4
 7672: 
 7673: $title - optional title for the page
 7674: 
 7675: $head_extra - optional extra HTML to incude inside the <head>
 7676: 
 7677: $args - additional optional args supported are:
 7678: 
 7679: =over 8
 7680: 
 7681:              only_body      -> is true will set &bodytag() onlybodytag
 7682:                                     arg on
 7683:              no_nav_bar     -> is true will set &bodytag() no_nav_bar arg on
 7684:              add_entries    -> additional attributes to add to the  <body>
 7685:              domain         -> force to color decorate a page for a 
 7686:                                     specific domain
 7687:              function       -> force usage of a specific rolish color
 7688:                                     scheme
 7689:              redirect       -> see &headtag()
 7690:              bgcolor        -> override the default page bg color
 7691:              js_ready       -> return a string ready for being used in 
 7692:                                     a javascript writeln
 7693:              html_encode    -> return a string ready for being used in 
 7694:                                     a html attribute
 7695:              force_register -> if is true will turn on the &bodytag()
 7696:                                     $forcereg arg
 7697:              frameset       -> if true will start with a <frameset>
 7698:                                     rather than <body>
 7699:              skip_phases    -> hash ref of 
 7700:                                     head -> skip the <html><head> generation
 7701:                                     body -> skip all <body> generation
 7702:              no_inline_link -> if true and in remote mode, don't show the
 7703:                                     'Switch To Inline Menu' link
 7704:              no_auto_mt_title -> prevent &mt()ing the title arg
 7705:              inherit_jsmath -> when creating popup window in a page,
 7706:                                     should it have jsmath forced on by the
 7707:                                     current page
 7708:              bread_crumbs ->             Array containing breadcrumbs
 7709:              bread_crumbs_component ->  if exists show it as headline else show only the breadcrumbs
 7710:              group          -> includes the current group, if page is for a
 7711:                                specific group
 7712: 
 7713: =back
 7714: 
 7715: =back
 7716: 
 7717: =cut
 7718: 
 7719: sub start_page {
 7720:     my ($title,$head_extra,$args) = @_;
 7721:     #&Apache::lonnet::logthis("start_page ".join(':',caller(0)));
 7722: 
 7723:     $env{'internal.start_page'}++;
 7724:     my ($result,@advtools);
 7725: 
 7726:     if (! exists($args->{'skip_phases'}{'head'}) ) {
 7727:         $result .= &xml_begin($args->{'frameset'}) . &headtag($title, $head_extra, $args);
 7728:     }
 7729:     
 7730:     if (! exists($args->{'skip_phases'}{'body'}) ) {
 7731: 	if ($args->{'frameset'}) {
 7732: 	    my $attr_string = &make_attr_string($args->{'force_register'},
 7733: 						$args->{'add_entries'});
 7734: 	    $result .= "\n<frameset $attr_string>\n";
 7735:         } else {
 7736:             $result .=
 7737:                 &bodytag($title, 
 7738:                          $args->{'function'},       $args->{'add_entries'},
 7739:                          $args->{'only_body'},      $args->{'domain'},
 7740:                          $args->{'force_register'}, $args->{'no_nav_bar'},
 7741:                          $args->{'bgcolor'},        $args->{'no_inline_link'},
 7742:                          $args,                     \@advtools);
 7743:         }
 7744:     }
 7745: 
 7746:     if ($args->{'js_ready'}) {
 7747: 		$result = &js_ready($result);
 7748:     }
 7749:     if ($args->{'html_encode'}) {
 7750: 		$result = &html_encode($result);
 7751:     }
 7752: 
 7753:     # Preparation for new and consistent functionlist at top of screen
 7754:     # if ($args->{'functionlist'}) {
 7755:     #            $result .= &build_functionlist();
 7756:     #}
 7757: 
 7758:     # Don't add anything more if only_body wanted or in const space
 7759:     return $result if    $args->{'only_body'} 
 7760:                       || $env{'request.state'} eq 'construct';
 7761: 
 7762:     #Breadcrumbs
 7763:     if (exists($args->{'bread_crumbs'}) or exists($args->{'bread_crumbs_component'})) {
 7764: 		&Apache::lonhtmlcommon::clear_breadcrumbs();
 7765: 		#if any br links exists, add them to the breadcrumbs
 7766: 		if (exists($args->{'bread_crumbs'}) and ref($args->{'bread_crumbs'}) eq 'ARRAY') {         
 7767: 			foreach my $crumb (@{$args->{'bread_crumbs'}}){
 7768: 				&Apache::lonhtmlcommon::add_breadcrumb($crumb);
 7769: 			}
 7770: 		}
 7771:                 # if @advtools array contains items add then to the breadcrumbs
 7772:                 if (@advtools > 0) {
 7773:                     &Apache::lonmenu::advtools_crumbs(@advtools);
 7774:                 }
 7775: 
 7776: 		#if bread_crumbs_component exists show it as headline else show only the breadcrumbs
 7777: 		if(exists($args->{'bread_crumbs_component'})){
 7778: 			$result .= &Apache::lonhtmlcommon::breadcrumbs($args->{'bread_crumbs_component'});
 7779: 		}else{
 7780: 			$result .= &Apache::lonhtmlcommon::breadcrumbs();
 7781: 		}
 7782:     } elsif (($env{'environment.remote'} eq 'on') &&
 7783:              ($env{'form.inhibitmenu'} ne 'yes') &&
 7784:              ($env{'request.noversionuri'} =~ m{^/res/}) &&
 7785:              ($env{'request.noversionuri'} !~ m{^/res/adm/pages/})) {
 7786:         $result .= '<div style="padding:0;margin:0;clear:both"><hr /></div>';
 7787:     }
 7788:     return $result;
 7789: }
 7790: 
 7791: sub end_page {
 7792:     my ($args) = @_;
 7793:     $env{'internal.end_page'}++;
 7794:     my $result;
 7795:     if ($args->{'discussion'}) {
 7796: 	my ($target,$parser);
 7797: 	if (ref($args->{'discussion'})) {
 7798: 	    ($target,$parser) =($args->{'discussion'}{'target'},
 7799: 				$args->{'discussion'}{'parser'});
 7800: 	}
 7801: 	$result .= &Apache::lonxml::xmlend($target,$parser);
 7802:     }
 7803:     if ($args->{'frameset'}) {
 7804: 	$result .= '</frameset>';
 7805:     } else {
 7806: 	$result .= &endbodytag($args);
 7807:     }
 7808:     unless ($args->{'notbody'}) {
 7809:         $result .= "\n</html>";
 7810:     }
 7811: 
 7812:     if ($args->{'js_ready'}) {
 7813: 	$result = &js_ready($result);
 7814:     }
 7815: 
 7816:     if ($args->{'html_encode'}) {
 7817: 	$result = &html_encode($result);
 7818:     }
 7819: 
 7820:     return $result;
 7821: }
 7822: 
 7823: sub wishlist_window {
 7824:     return(<<'ENDWISHLIST');
 7825: <script type="text/javascript">
 7826: // <![CDATA[
 7827: // <!-- BEGIN LON-CAPA Internal
 7828: function set_wishlistlink(title, path) {
 7829:     if (!title) {
 7830:         title = document.title;
 7831:         title = title.replace(/^LON-CAPA /,'');
 7832:     }
 7833:     title = encodeURIComponent(title);
 7834:     title = title.replace("'","\\\'");
 7835:     if (!path) {
 7836:         path = location.pathname;
 7837:     }
 7838:     path = encodeURIComponent(path);
 7839:     path = path.replace("'","\\\'");
 7840:     Win = window.open('/adm/wishlist?mode=newLink&setTitle='+title+'&setPath='+path,
 7841:                       'wishlistNewLink','width=560,height=350,scrollbars=0');
 7842: }
 7843: // END LON-CAPA Internal -->
 7844: // ]]>
 7845: </script>
 7846: ENDWISHLIST
 7847: }
 7848: 
 7849: sub modal_window {
 7850:     return(<<'ENDMODAL');
 7851: <script type="text/javascript">
 7852: // <![CDATA[
 7853: // <!-- BEGIN LON-CAPA Internal
 7854: var modalWindow = {
 7855: 	parent:"body",
 7856: 	windowId:null,
 7857: 	content:null,
 7858: 	width:null,
 7859: 	height:null,
 7860: 	close:function()
 7861: 	{
 7862: 	        $(".LCmodal-window").remove();
 7863: 	        $(".LCmodal-overlay").remove();
 7864: 	},
 7865: 	open:function()
 7866: 	{
 7867: 		var modal = "";
 7868: 		modal += "<div class=\"LCmodal-overlay\"></div>";
 7869: 		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;\">";
 7870: 		modal += this.content;
 7871: 		modal += "</div>";	
 7872: 
 7873: 		$(this.parent).append(modal);
 7874: 
 7875: 		$(".LCmodal-window").append("<a class=\"LCclose-window\"></a>");
 7876: 		$(".LCclose-window").click(function(){modalWindow.close();});
 7877: 		$(".LCmodal-overlay").click(function(){modalWindow.close();});
 7878: 	}
 7879: };
 7880: 	var openMyModal = function(source,width,height,scrolling,transparency,style)
 7881: 	{
 7882:                 source = source.replace("'","&#39;");
 7883: 		modalWindow.windowId = "myModal";
 7884: 		modalWindow.width = width;
 7885: 		modalWindow.height = height;
 7886: 		modalWindow.content = "<iframe width='"+width+"' height='"+height+"' frameborder='0' scrolling='"+scrolling+"' allowtransparency='"+transparency+"' src='" + source + "' style='"+style+"'></iframe>";
 7887: 		modalWindow.open();
 7888: 	};
 7889: // END LON-CAPA Internal -->
 7890: // ]]>
 7891: </script>
 7892: ENDMODAL
 7893: }
 7894: 
 7895: sub modal_link {
 7896:     my ($link,$linktext,$width,$height,$target,$scrolling,$title,$transparency,$style)=@_;
 7897:     unless ($width) { $width=480; }
 7898:     unless ($height) { $height=400; }
 7899:     unless ($scrolling) { $scrolling='yes'; }
 7900:     unless ($transparency) { $transparency='true'; }
 7901: 
 7902:     my $target_attr;
 7903:     if (defined($target)) {
 7904:         $target_attr = 'target="'.$target.'"';
 7905:     }
 7906:     return <<"ENDLINK";
 7907: <a href="$link" $target_attr title="$title" onclick="javascript:openMyModal('$link',$width,$height,'$scrolling','$transparency','$style'); return false;">
 7908:            $linktext</a>
 7909: ENDLINK
 7910: }
 7911: 
 7912: sub modal_adhoc_script {
 7913:     my ($funcname,$width,$height,$content)=@_;
 7914:     return (<<ENDADHOC);
 7915: <script type="text/javascript">
 7916: // <![CDATA[
 7917:         var $funcname = function()
 7918:         {
 7919:                 modalWindow.windowId = "myModal";
 7920:                 modalWindow.width = $width;
 7921:                 modalWindow.height = $height;
 7922:                 modalWindow.content = '$content';
 7923:                 modalWindow.open();
 7924:         };  
 7925: // ]]>
 7926: </script>
 7927: ENDADHOC
 7928: }
 7929: 
 7930: sub modal_adhoc_inner {
 7931:     my ($funcname,$width,$height,$content)=@_;
 7932:     my $innerwidth=$width-20;
 7933:     $content=&js_ready(
 7934:                &start_page('Dialog',undef,{'only_body'=>1,'bgcolor'=>'#FFFFFF'}).
 7935:                  &start_scrollbox($width.'px',$innerwidth.'px',$height.'px','myModal','#FFFFFF',undef,1).
 7936:                  $content.
 7937:                  &end_scrollbox().
 7938:                  &end_page()
 7939:              );
 7940:     return &modal_adhoc_script($funcname,$width,$height,$content);
 7941: }
 7942: 
 7943: sub modal_adhoc_window {
 7944:     my ($funcname,$width,$height,$content,$linktext)=@_;
 7945:     return &modal_adhoc_inner($funcname,$width,$height,$content).
 7946:            "<a href=\"javascript:$funcname();void(0);\">".$linktext."</a>";
 7947: }
 7948: 
 7949: sub modal_adhoc_launch {
 7950:     my ($funcname,$width,$height,$content)=@_;
 7951:     return &modal_adhoc_inner($funcname,$width,$height,$content).(<<ENDLAUNCH);
 7952: <script type="text/javascript">
 7953: // <![CDATA[
 7954: $funcname();
 7955: // ]]>
 7956: </script>
 7957: ENDLAUNCH
 7958: }
 7959: 
 7960: sub modal_adhoc_close {
 7961:     return (<<ENDCLOSE);
 7962: <script type="text/javascript">
 7963: // <![CDATA[
 7964: modalWindow.close();
 7965: // ]]>
 7966: </script>
 7967: ENDCLOSE
 7968: }
 7969: 
 7970: sub togglebox_script {
 7971:    return(<<ENDTOGGLE);
 7972: <script type="text/javascript"> 
 7973: // <![CDATA[
 7974: function LCtoggleDisplay(id,hidetext,showtext) {
 7975:    link = document.getElementById(id + "link").childNodes[0];
 7976:    with (document.getElementById(id).style) {
 7977:       if (display == "none" ) {
 7978:           display = "inline";
 7979:           link.nodeValue = hidetext;
 7980:         } else {
 7981:           display = "none";
 7982:           link.nodeValue = showtext;
 7983:        }
 7984:    }
 7985: }
 7986: // ]]>
 7987: </script>
 7988: ENDTOGGLE
 7989: }
 7990: 
 7991: sub start_togglebox {
 7992:     my ($id,$heading,$headerbg,$hidetext,$showtext)=@_;
 7993:     unless ($heading) { $heading=''; } else { $heading.=' '; }
 7994:     unless ($showtext) { $showtext=&mt('show'); }
 7995:     unless ($hidetext) { $hidetext=&mt('hide'); }
 7996:     unless ($headerbg) { $headerbg='#FFFFFF'; }
 7997:     return &start_data_table().
 7998:            &start_data_table_header_row().
 7999:            '<td bgcolor="'.$headerbg.'">'.$heading.
 8000:            '[<a id="'.$id.'link" href="javascript:LCtoggleDisplay(\''.$id.'\',\''.$hidetext.'\',\''.
 8001:            $showtext.'\')">'.$showtext.'</a>]</td>'.
 8002:            &end_data_table_header_row().
 8003:            '<tr id="'.$id.'" style="display:none""><td>';
 8004: }
 8005: 
 8006: sub end_togglebox {
 8007:     return '</td></tr>'.&end_data_table();
 8008: }
 8009: 
 8010: sub LCprogressbar_script {
 8011:    my ($id)=@_;
 8012:    return(<<ENDPROGRESS);
 8013: <script type="text/javascript">
 8014: // <![CDATA[
 8015: \$('#progressbar$id').progressbar({
 8016:   value: 0,
 8017:   change: function(event, ui) {
 8018:     var newVal = \$(this).progressbar('option', 'value');
 8019:     \$('.pblabel', this).text(LCprogressTxt);
 8020:   }
 8021: });
 8022: // ]]>
 8023: </script>
 8024: ENDPROGRESS
 8025: }
 8026: 
 8027: sub LCprogressbarUpdate_script {
 8028:    return(<<ENDPROGRESSUPDATE);
 8029: <style type="text/css">
 8030: .ui-progressbar { position:relative; }
 8031: .pblabel { position: absolute; width: 100%; text-align: center; line-height: 1.9em; }
 8032: </style>
 8033: <script type="text/javascript">
 8034: // <![CDATA[
 8035: var LCprogressTxt='---';
 8036: 
 8037: function LCupdateProgress(percent,progresstext,id) {
 8038:    LCprogressTxt=progresstext;
 8039:    \$('#progressbar'+id).progressbar('value',percent);
 8040: }
 8041: // ]]>
 8042: </script>
 8043: ENDPROGRESSUPDATE
 8044: }
 8045: 
 8046: my $LClastpercent;
 8047: my $LCidcnt;
 8048: my $LCcurrentid;
 8049: 
 8050: sub LCprogressbar {
 8051:     my ($r)=(@_);
 8052:     $LClastpercent=0;
 8053:     $LCidcnt++;
 8054:     $LCcurrentid=$$.'_'.$LCidcnt;
 8055:     my $starting=&mt('Starting');
 8056:     my $content=(<<ENDPROGBAR);
 8057:   <div id="progressbar$LCcurrentid">
 8058:     <span class="pblabel">$starting</span>
 8059:   </div>
 8060: ENDPROGBAR
 8061:     &r_print($r,$content.&LCprogressbar_script($LCcurrentid));
 8062: }
 8063: 
 8064: sub LCprogressbarUpdate {
 8065:     my ($r,$val,$text)=@_;
 8066:     unless ($val) { 
 8067:        if ($LClastpercent) {
 8068:            $val=$LClastpercent;
 8069:        } else {
 8070:            $val=0;
 8071:        }
 8072:     }
 8073:     if ($val<0) { $val=0; }
 8074:     if ($val>100) { $val=0; }
 8075:     $LClastpercent=$val;
 8076:     unless ($text) { $text=$val.'%'; }
 8077:     $text=&js_ready($text);
 8078:     &r_print($r,<<ENDUPDATE);
 8079: <script type="text/javascript">
 8080: // <![CDATA[
 8081: LCupdateProgress($val,'$text','$LCcurrentid');
 8082: // ]]>
 8083: </script>
 8084: ENDUPDATE
 8085: }
 8086: 
 8087: sub LCprogressbarClose {
 8088:     my ($r)=@_;
 8089:     $LClastpercent=0;
 8090:     &r_print($r,<<ENDCLOSE);
 8091: <script type="text/javascript">
 8092: // <![CDATA[
 8093: \$("#progressbar$LCcurrentid").hide('slow'); 
 8094: // ]]>
 8095: </script>
 8096: ENDCLOSE
 8097: }
 8098: 
 8099: sub r_print {
 8100:     my ($r,$to_print)=@_;
 8101:     if ($r) {
 8102:       $r->print($to_print);
 8103:       $r->rflush();
 8104:     } else {
 8105:       print($to_print);
 8106:     }
 8107: }
 8108: 
 8109: sub html_encode {
 8110:     my ($result) = @_;
 8111: 
 8112:     $result = &HTML::Entities::encode($result,'<>&"');
 8113:     
 8114:     return $result;
 8115: }
 8116: 
 8117: sub js_ready {
 8118:     my ($result) = @_;
 8119: 
 8120:     $result =~ s/[\n\r]/ /xmsg;
 8121:     $result =~ s/\\/\\\\/xmsg;
 8122:     $result =~ s/'/\\'/xmsg;
 8123:     $result =~ s{</}{<\\/}xmsg;
 8124:     
 8125:     return $result;
 8126: }
 8127: 
 8128: sub validate_page {
 8129:     if (  exists($env{'internal.start_page'})
 8130: 	  &&     $env{'internal.start_page'} > 1) {
 8131: 	&Apache::lonnet::logthis('start_page called multiple times '.
 8132: 				 $env{'internal.start_page'}.' '.
 8133: 				 $ENV{'request.filename'});
 8134:     }
 8135:     if (  exists($env{'internal.end_page'})
 8136: 	  &&     $env{'internal.end_page'} > 1) {
 8137: 	&Apache::lonnet::logthis('end_page called multiple times '.
 8138: 				 $env{'internal.end_page'}.' '.
 8139: 				 $env{'request.filename'});
 8140:     }
 8141:     if (     exists($env{'internal.start_page'})
 8142: 	&& ! exists($env{'internal.end_page'})) {
 8143: 	&Apache::lonnet::logthis('start_page called without end_page '.
 8144: 				 $env{'request.filename'});
 8145:     }
 8146:     if (   ! exists($env{'internal.start_page'})
 8147: 	&&   exists($env{'internal.end_page'})) {
 8148: 	&Apache::lonnet::logthis('end_page called without start_page'.
 8149: 				 $env{'request.filename'});
 8150:     }
 8151: }
 8152: 
 8153: 
 8154: sub start_scrollbox {
 8155:     my ($outerwidth,$width,$height,$id,$bgcolor,$cursor,$needjsready) = @_;
 8156:     unless ($outerwidth) { $outerwidth='520px'; }
 8157:     unless ($width) { $width='500px'; }
 8158:     unless ($height) { $height='200px'; }
 8159:     my ($table_id,$div_id,$tdcol);
 8160:     if ($id ne '') {
 8161:         $table_id = ' id="table_'.$id.'"';
 8162:         $div_id = ' id="div_'.$id.'"';
 8163:     }
 8164:     if ($bgcolor ne '') {
 8165:         $tdcol = "background-color: $bgcolor;";
 8166:     }
 8167:     my $nicescroll_js;
 8168:     if ($env{'browser.mobile'}) {
 8169:         $nicescroll_js = &nicescroll_javascript('div_'.$id,$cursor,$needjsready);
 8170:     }
 8171:     return <<"END";
 8172: $nicescroll_js
 8173: 
 8174: <table style="width: $outerwidth; border: 1px solid none;"$table_id><tr><td style="width: $width;$tdcol">
 8175: <div style="overflow:auto; width:$width; height:$height;"$div_id>
 8176: END
 8177: }
 8178: 
 8179: sub end_scrollbox {
 8180:     return '</div></td></tr></table>';
 8181: }
 8182: 
 8183: sub nicescroll_javascript {
 8184:     my ($id,$cursor,$needjsready,$framecheck,$location) = @_;
 8185:     my %options;
 8186:     if (ref($cursor) eq 'HASH') {
 8187:         %options = %{$cursor};
 8188:     }
 8189:     unless ($options{'railalign'} =~ /^left|right$/) {
 8190:         $options{'railalign'} = 'left';
 8191:     }
 8192:     unless ($options{'cursorcolor'} =~ /^\#\w+$/) {
 8193:         my $function  = &get_users_function();
 8194:         $options{'cursorcolor'} = &designparm($function.'.sidebg',$env{'request.role.domain'});
 8195:         unless ($options{'cursorcolor'} =~ /^\#\w+$/) {
 8196:             $options{'cursorcolor'} = '#00F';
 8197:         }
 8198:     }
 8199:     if ($options{'cursoropacity'} =~ /^[\d.]+$/) {
 8200:         unless ($options{'cursoropacity'} >= 0.0 && $options{'cursoropacity'} <=1.0) {
 8201:             $options{'cursoropacity'}='1.0';
 8202:         }
 8203:     } else {
 8204:         $options{'cursoropacity'}='1.0';
 8205:     }
 8206:     if ($options{'cursorfixedheight'} eq 'none') {
 8207:         delete($options{'cursorfixedheight'});
 8208:     } else {
 8209:         unless ($options{'cursorfixedheight'} =~ /^\d+$/) { $options{'cursorfixedheight'}='50'; }
 8210:     }
 8211:     unless ($options{'railoffset'} =~ /^{[\w\:\d\-,]+}$/) {
 8212:         delete($options{'railoffset'});
 8213:     }
 8214:     my @niceoptions;
 8215:     while (my($key,$value) = each(%options)) {
 8216:         if ($value =~ /^\{.+\}$/) {
 8217:             push(@niceoptions,$key.':'.$value);
 8218:         } else {
 8219:             push(@niceoptions,$key.':"'.$value.'"');
 8220:         }
 8221:     }
 8222:     my $nicescroll_js = '
 8223: $(document).ready(
 8224:       function() {
 8225:           $("#'.$id.'").niceScroll({'.join(',',@niceoptions).'});
 8226:       }
 8227: );
 8228: ';
 8229:     if ($framecheck) {
 8230:         $nicescroll_js .= '
 8231: function expand_div(caller) {
 8232:     if (top === self) {
 8233:         document.getElementById("'.$id.'").style.width = "auto";
 8234:         document.getElementById("'.$id.'").style.height = "auto";
 8235:     } else {
 8236:         try {
 8237:             if (parent.frames) {
 8238:                 if (parent.frames.length > 1) {
 8239:                     var framesrc = parent.frames[1].location.href;
 8240:                     var currsrc = framesrc.replace(/\#.*$/,"");
 8241:                     if ((caller == "search") || (currsrc == "'.$location.'")) {
 8242:                         document.getElementById("'.$id.'").style.width = "auto";
 8243:                         document.getElementById("'.$id.'").style.height = "auto";
 8244:                     }
 8245:                 }
 8246:             }
 8247:         } catch (e) {
 8248:             return;
 8249:         }
 8250:     }
 8251:     return;
 8252: }
 8253: ';
 8254:     }
 8255:     if ($needjsready) {
 8256:         $nicescroll_js = '
 8257: <script type="text/javascript">'."\n".$nicescroll_js."\n</script>\n";
 8258:     } else {
 8259:         $nicescroll_js = &Apache::lonhtmlcommon::scripttag($nicescroll_js);
 8260:     }
 8261:     return $nicescroll_js;
 8262: }
 8263: 
 8264: sub simple_error_page {
 8265:     my ($r,$title,$msg,$args) = @_;
 8266:     if (ref($args) eq 'HASH') {
 8267:         if (!$args->{'no_auto_mt_msg'}) { $msg = &mt($msg); }
 8268:     } else {
 8269:         $msg = &mt($msg);
 8270:     }
 8271: 
 8272:     my $page =
 8273: 	&Apache::loncommon::start_page($title).
 8274: 	'<p class="LC_error">'.$msg.'</p>'.
 8275: 	&Apache::loncommon::end_page();
 8276:     if (ref($r)) {
 8277: 	$r->print($page);
 8278: 	return;
 8279:     }
 8280:     return $page;
 8281: }
 8282: 
 8283: {
 8284:     my @row_count;
 8285: 
 8286:     sub start_data_table_count {
 8287:         unshift(@row_count, 0);
 8288:         return;
 8289:     }
 8290: 
 8291:     sub end_data_table_count {
 8292:         shift(@row_count);
 8293:         return;
 8294:     }
 8295: 
 8296:     sub start_data_table {
 8297: 	my ($add_class,$id) = @_;
 8298: 	my $css_class = (join(' ','LC_data_table',$add_class));
 8299:         my $table_id;
 8300:         if (defined($id)) {
 8301:             $table_id = ' id="'.$id.'"';
 8302:         }
 8303: 	&start_data_table_count();
 8304: 	return '<table class="'.$css_class.'"'.$table_id.'>'."\n";
 8305:     }
 8306: 
 8307:     sub end_data_table {
 8308: 	&end_data_table_count();
 8309: 	return '</table>'."\n";;
 8310:     }
 8311: 
 8312:     sub start_data_table_row {
 8313: 	my ($add_class, $id) = @_;
 8314: 	$row_count[0]++;
 8315: 	my $css_class = ($row_count[0] % 2)?'LC_odd_row':'LC_even_row';
 8316: 	$css_class = (join(' ',$css_class,$add_class)) unless ($add_class eq '');
 8317:         $id = (' id="'.$id.'"') unless ($id eq '');
 8318:         return  '<tr class="'.$css_class.'"'.$id.'>'."\n";
 8319:     }
 8320:     
 8321:     sub continue_data_table_row {
 8322: 	my ($add_class, $id) = @_;
 8323: 	my $css_class = ($row_count[0] % 2)?'LC_odd_row':'LC_even_row';
 8324: 	$css_class = (join(' ',$css_class,$add_class)) unless ($add_class eq '');
 8325:         $id = (' id="'.$id.'"') unless ($id eq '');
 8326:         return  '<tr class="'.$css_class.'"'.$id.'>'."\n";
 8327:     }
 8328: 
 8329:     sub end_data_table_row {
 8330: 	return '</tr>'."\n";;
 8331:     }
 8332: 
 8333:     sub start_data_table_empty_row {
 8334: #	$row_count[0]++;
 8335: 	return  '<tr class="LC_empty_row" >'."\n";;
 8336:     }
 8337: 
 8338:     sub end_data_table_empty_row {
 8339: 	return '</tr>'."\n";;
 8340:     }
 8341: 
 8342:     sub start_data_table_header_row {
 8343: 	return  '<tr class="LC_header_row">'."\n";;
 8344:     }
 8345: 
 8346:     sub end_data_table_header_row {
 8347: 	return '</tr>'."\n";;
 8348:     }
 8349: 
 8350:     sub data_table_caption {
 8351:         my $caption = shift;
 8352:         return "<caption class=\"LC_caption\">$caption</caption>";
 8353:     }
 8354: }
 8355: 
 8356: =pod
 8357: 
 8358: =item * &inhibit_menu_check($arg)
 8359: 
 8360: Checks for a inhibitmenu state and generates output to preserve it
 8361: 
 8362: Inputs:         $arg - can be any of
 8363:                      - undef - in which case the return value is a string 
 8364:                                to add  into arguments list of a uri
 8365:                      - 'input' - in which case the return value is a HTML
 8366:                                  <form> <input> field of type hidden to
 8367:                                  preserve the value
 8368:                      - a url - in which case the return value is the url with
 8369:                                the neccesary cgi args added to preserve the
 8370:                                inhibitmenu state
 8371:                      - a ref to a url - no return value, but the string is
 8372:                                         updated to include the neccessary cgi
 8373:                                         args to preserve the inhibitmenu state
 8374: 
 8375: =cut
 8376: 
 8377: sub inhibit_menu_check {
 8378:     my ($arg) = @_;
 8379:     &get_unprocessed_cgi($ENV{'QUERY_STRING'}, ['inhibitmenu']);
 8380:     if ($arg eq 'input') {
 8381: 	if ($env{'form.inhibitmenu'}) {
 8382: 	    return '<input type="hidden" name="inhibitmenu" value="'.$env{'form.inhibitmenu'}.'" />';
 8383: 	} else {
 8384: 	    return
 8385: 	}
 8386:     }
 8387:     if ($env{'form.inhibitmenu'}) {
 8388: 	if (ref($arg)) {
 8389: 	    $$arg .= '?inhibitmenu='.$env{'form.inhibitmenu'};
 8390: 	} elsif ($arg eq '') {
 8391: 	    $arg .= 'inhibitmenu='.$env{'form.inhibitmenu'};
 8392: 	} else {
 8393: 	    $arg .= '?inhibitmenu='.$env{'form.inhibitmenu'};
 8394: 	}
 8395:     }
 8396:     if (!ref($arg)) {
 8397: 	return $arg;
 8398:     }
 8399: }
 8400: 
 8401: ###############################################
 8402: 
 8403: =pod
 8404: 
 8405: =back
 8406: 
 8407: =head1 User Information Routines
 8408: 
 8409: =over 4
 8410: 
 8411: =item * &get_users_function()
 8412: 
 8413: Used by &bodytag to determine the current users primary role.
 8414: Returns either 'student','coordinator','admin', or 'author'.
 8415: 
 8416: =cut
 8417: 
 8418: ###############################################
 8419: sub get_users_function {
 8420:     my $function = 'norole';
 8421:     if ($env{'request.role'}=~/^(st)/) {
 8422:         $function='student';
 8423:     }
 8424:     if ($env{'request.role'}=~/^(cc|co|in|ta|ep)/) {
 8425:         $function='coordinator';
 8426:     }
 8427:     if ($env{'request.role'}=~/^(su|dc|ad|li)/) {
 8428:         $function='admin';
 8429:     }
 8430:     if (($env{'request.role'}=~/^(au|ca|aa)/) ||
 8431:         ($ENV{'REQUEST_URI'}=~ m{/^(/priv)})) {
 8432:         $function='author';
 8433:     }
 8434:     return $function;
 8435: }
 8436: 
 8437: ###############################################
 8438: 
 8439: =pod
 8440: 
 8441: =item * &show_course()
 8442: 
 8443: Used by lonmenu.pm and lonroles.pm to determine whether to use the word
 8444: 'Courses' or 'Roles' in inline navigation and on screen displaying user's roles.
 8445: 
 8446: Inputs:
 8447: None
 8448: 
 8449: Outputs:
 8450: Scalar: 1 if 'Course' to be used, 0 otherwise.
 8451: 
 8452: =cut
 8453: 
 8454: ###############################################
 8455: sub show_course {
 8456:     my $course = !$env{'user.adv'};
 8457:     if (!$env{'user.adv'}) {
 8458:         foreach my $env (keys(%env)) {
 8459:             next if ($env !~ m/^user\.priv\./);
 8460:             if ($env !~ m/^user\.priv\.(?:st|cm)/) {
 8461:                 $course = 0;
 8462:                 last;
 8463:             }
 8464:         }
 8465:     }
 8466:     return $course;
 8467: }
 8468: 
 8469: ###############################################
 8470: 
 8471: =pod
 8472: 
 8473: =item * &check_user_status()
 8474: 
 8475: Determines current status of supplied role for a
 8476: specific user. Roles can be active, previous or future.
 8477: 
 8478: Inputs: 
 8479: user's domain, user's username, course's domain,
 8480: course's number, optional section ID.
 8481: 
 8482: Outputs:
 8483: role status: active, previous or future. 
 8484: 
 8485: =cut
 8486: 
 8487: sub check_user_status {
 8488:     my ($udom,$uname,$cdom,$crs,$role,$sec) = @_;
 8489:     my %userinfo = &Apache::lonnet::dump('roles',$udom,$uname);
 8490:     my @uroles = keys(%userinfo);
 8491:     my $srchstr;
 8492:     my $active_chk = 'none';
 8493:     my $now = time;
 8494:     if (@uroles > 0) {
 8495:         if (($role eq 'cc') || ($role eq 'co') || ($sec eq '') || (!defined($sec))) {
 8496:             $srchstr = '/'.$cdom.'/'.$crs.'_'.$role;
 8497:         } else {
 8498:             $srchstr = '/'.$cdom.'/'.$crs.'/'.$sec.'_'.$role;
 8499:         }
 8500:         if (grep/^\Q$srchstr\E$/,@uroles) {
 8501:             my $role_end = 0;
 8502:             my $role_start = 0;
 8503:             $active_chk = 'active';
 8504:             if ($userinfo{$srchstr} =~ m/^\Q$role\E_(\d+)/) {
 8505:                 $role_end = $1;
 8506:                 if ($userinfo{$srchstr} =~ m/^\Q$role\E_\Q$role_end\E_(\d+)$/) {
 8507:                     $role_start = $1;
 8508:                 }
 8509:             }
 8510:             if ($role_start > 0) {
 8511:                 if ($now < $role_start) {
 8512:                     $active_chk = 'future';
 8513:                 }
 8514:             }
 8515:             if ($role_end > 0) {
 8516:                 if ($now > $role_end) {
 8517:                     $active_chk = 'previous';
 8518:                 }
 8519:             }
 8520:         }
 8521:     }
 8522:     return $active_chk;
 8523: }
 8524: 
 8525: ###############################################
 8526: 
 8527: =pod
 8528: 
 8529: =item * &get_sections()
 8530: 
 8531: Determines all the sections for a course including
 8532: sections with students and sections containing other roles.
 8533: Incoming parameters: 
 8534: 
 8535: 1. domain
 8536: 2. course number 
 8537: 3. reference to array containing roles for which sections should 
 8538: be gathered (optional).
 8539: 4. reference to array containing status types for which sections 
 8540: should be gathered (optional).
 8541: 
 8542: If the third argument is undefined, sections are gathered for any role. 
 8543: If the fourth argument is undefined, sections are gathered for any status.
 8544: Permissible values are 'active' or 'future' or 'previous'.
 8545:  
 8546: Returns section hash (keys are section IDs, values are
 8547: number of users in each section), subject to the
 8548: optional roles filter, optional status filter 
 8549: 
 8550: =cut
 8551: 
 8552: ###############################################
 8553: sub get_sections {
 8554:     my ($cdom,$cnum,$possible_roles,$possible_status) = @_;
 8555:     if (!defined($cdom) || !defined($cnum)) {
 8556:         my $cid =  $env{'request.course.id'};
 8557: 
 8558: 	return if (!defined($cid));
 8559: 
 8560:         $cdom = $env{'course.'.$cid.'.domain'};
 8561:         $cnum = $env{'course.'.$cid.'.num'};
 8562:     }
 8563: 
 8564:     my %sectioncount;
 8565:     my $now = time;
 8566: 
 8567:     my $check_students = 1;
 8568:     my $only_students = 0;
 8569:     if (ref($possible_roles) eq 'ARRAY') {
 8570:         if (grep(/^st$/,@{$possible_roles})) {
 8571:             if (@{$possible_roles} == 1) {
 8572:                 $only_students = 1;
 8573:             }
 8574:         } else {
 8575:             $check_students = 0;
 8576:         }
 8577:     }
 8578: 
 8579:     if ($check_students) {
 8580: 	my ($classlist) = &Apache::loncoursedata::get_classlist($cdom,$cnum);
 8581: 	my $sec_index = &Apache::loncoursedata::CL_SECTION();
 8582: 	my $status_index = &Apache::loncoursedata::CL_STATUS();
 8583:         my $start_index = &Apache::loncoursedata::CL_START();
 8584:         my $end_index = &Apache::loncoursedata::CL_END();
 8585:         my $status;
 8586: 	while (my ($student,$data) = each(%$classlist)) {
 8587: 	    my ($section,$stu_status,$start,$end) = ($data->[$sec_index],
 8588: 				                     $data->[$status_index],
 8589:                                                      $data->[$start_index],
 8590:                                                      $data->[$end_index]);
 8591:             if ($stu_status eq 'Active') {
 8592:                 $status = 'active';
 8593:             } elsif ($end < $now) {
 8594:                 $status = 'previous';
 8595:             } elsif ($start > $now) {
 8596:                 $status = 'future';
 8597:             } 
 8598: 	    if ($section ne '-1' && $section !~ /^\s*$/) {
 8599:                 if ((!defined($possible_status)) || (($status ne '') && 
 8600:                     (grep/^\Q$status\E$/,@{$possible_status}))) { 
 8601: 		    $sectioncount{$section}++;
 8602:                 }
 8603: 	    }
 8604: 	}
 8605:     }
 8606:     if ($only_students) {
 8607:         return %sectioncount;
 8608:     }
 8609:     my %courseroles = &Apache::lonnet::dump('nohist_userroles',$cdom,$cnum);
 8610:     foreach my $user (sort(keys(%courseroles))) {
 8611: 	if ($user !~ /^(\w{2})/) { next; }
 8612: 	my ($role) = ($user =~ /^(\w{2})/);
 8613: 	if ($possible_roles && !(grep(/^$role$/,@$possible_roles))) { next; }
 8614: 	my ($section,$status);
 8615: 	if ($role eq 'cr' &&
 8616: 	    $user =~ m-^$role/[^/]*/[^/]*/[^/]*:[^:]*:[^:]*:(\w+)-) {
 8617: 	    $section=$1;
 8618: 	}
 8619: 	if ($user =~ /^$role:[^:]*:[^:]*:(\w+)/) { $section=$1; }
 8620: 	if (!defined($section) || $section eq '-1') { next; }
 8621:         my ($end,$start) = ($courseroles{$user} =~ /^([^:]*):([^:]*)$/);
 8622:         if ($end == -1 && $start == -1) {
 8623:             next; #deleted role
 8624:         }
 8625:         if (!defined($possible_status)) { 
 8626:             $sectioncount{$section}++;
 8627:         } else {
 8628:             if ((!$end || $end >= $now) && (!$start || $start <= $now)) {
 8629:                 $status = 'active';
 8630:             } elsif ($end < $now) {
 8631:                 $status = 'future';
 8632:             } elsif ($start > $now) {
 8633:                 $status = 'previous';
 8634:             }
 8635:             if (($status ne '') && (grep/^\Q$status\E$/,@{$possible_status})) {
 8636:                 $sectioncount{$section}++;
 8637:             }
 8638:         }
 8639:     }
 8640:     return %sectioncount;
 8641: }
 8642: 
 8643: ###############################################
 8644: 
 8645: =pod
 8646: 
 8647: =item * &get_course_users()
 8648: 
 8649: Retrieves usernames:domains for users in the specified course
 8650: with specific role(s), and access status. 
 8651: 
 8652: Incoming parameters:
 8653: 1. course domain
 8654: 2. course number
 8655: 3. access status: users must have - either active, 
 8656: previous, future, or all.
 8657: 4. reference to array of permissible roles
 8658: 5. reference to array of section restrictions (optional)
 8659: 6. reference to results object (hash of hashes).
 8660: 7. reference to optional userdata hash
 8661: 8. reference to optional statushash
 8662: 9. flag if privileged users (except those set to unhide in
 8663:    course settings) should be excluded    
 8664: Keys of top level results hash are roles.
 8665: Keys of inner hashes are username:domain, with 
 8666: values set to access type.
 8667: Optional userdata hash returns an array with arguments in the 
 8668: same order as loncoursedata::get_classlist() for student data.
 8669: 
 8670: Optional statushash returns
 8671: 
 8672: Entries for end, start, section and status are blank because
 8673: of the possibility of multiple values for non-student roles.
 8674: 
 8675: =cut
 8676: 
 8677: ###############################################
 8678: 
 8679: sub get_course_users {
 8680:     my ($cdom,$cnum,$types,$roles,$sections,$users,$userdata,$statushash,$hidepriv) = @_;
 8681:     my %idx = ();
 8682:     my %seclists;
 8683: 
 8684:     $idx{udom} = &Apache::loncoursedata::CL_SDOM();
 8685:     $idx{uname} =  &Apache::loncoursedata::CL_SNAME();
 8686:     $idx{end} = &Apache::loncoursedata::CL_END();
 8687:     $idx{start} = &Apache::loncoursedata::CL_START();
 8688:     $idx{id} = &Apache::loncoursedata::CL_ID();
 8689:     $idx{section} = &Apache::loncoursedata::CL_SECTION();
 8690:     $idx{fullname} = &Apache::loncoursedata::CL_FULLNAME();
 8691:     $idx{status} = &Apache::loncoursedata::CL_STATUS();
 8692: 
 8693:     if (grep(/^st$/,@{$roles})) {
 8694:         my ($classlist,$keylist)=&Apache::loncoursedata::get_classlist($cdom,$cnum);
 8695:         my $now = time;
 8696:         foreach my $student (keys(%{$classlist})) {
 8697:             my $match = 0;
 8698:             my $secmatch = 0;
 8699:             my $section = $$classlist{$student}[$idx{section}];
 8700:             my $status = $$classlist{$student}[$idx{status}];
 8701:             if ($section eq '') {
 8702:                 $section = 'none';
 8703:             }
 8704:             if ((ref($sections) eq 'ARRAY') && (@{$sections} > 0)) {
 8705:                 if (grep(/^all$/,@{$sections})) {
 8706:                     $secmatch = 1;
 8707:                 } elsif ($$classlist{$student}[$idx{section}] eq '') {
 8708:                     if (grep(/^none$/,@{$sections})) {
 8709:                         $secmatch = 1;
 8710:                     }
 8711:                 } else {  
 8712: 		    if (grep(/^\Q$section\E$/,@{$sections})) {
 8713: 		        $secmatch = 1;
 8714:                     }
 8715: 		}
 8716:                 if (!$secmatch) {
 8717:                     next;
 8718:                 }
 8719:             }
 8720:             if (defined($$types{'active'})) {
 8721:                 if ($$classlist{$student}[$idx{status}] eq 'Active') {
 8722:                     push(@{$$users{st}{$student}},'active');
 8723:                     $match = 1;
 8724:                 }
 8725:             }
 8726:             if (defined($$types{'previous'})) {
 8727:                 if ($$classlist{$student}[$idx{status}] eq 'Expired') {
 8728:                     push(@{$$users{st}{$student}},'previous');
 8729:                     $match = 1;
 8730:                 }
 8731:             }
 8732:             if (defined($$types{'future'})) {
 8733:                 if ($$classlist{$student}[$idx{status}] eq 'Future') {
 8734:                     push(@{$$users{st}{$student}},'future');
 8735:                     $match = 1;
 8736:                 }
 8737:             }
 8738:             if ($match) {
 8739:                 push(@{$seclists{$student}},$section);
 8740:                 if (ref($userdata) eq 'HASH') {
 8741:                     $$userdata{$student} = $$classlist{$student};
 8742:                 }
 8743:                 if (ref($statushash) eq 'HASH') {
 8744:                     $statushash->{$student}{'st'}{$section} = $status;
 8745:                 }
 8746:             }
 8747:         }
 8748:     }
 8749:     if ((@{$roles} > 1) || ((@{$roles} == 1) && ($$roles[0] ne "st"))) {
 8750:         my %coursepersonnel = &Apache::lonnet::dump('nohist_userroles',$cdom,$cnum);
 8751:         my $now = time;
 8752:         my %displaystatus = ( previous => 'Expired',
 8753:                               active   => 'Active',
 8754:                               future   => 'Future',
 8755:                             );
 8756:         my (%nothide,@possdoms);
 8757:         if ($hidepriv) {
 8758:             my %coursehash=&Apache::lonnet::coursedescription($cdom.'_'.$cnum);
 8759:             foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
 8760:                 if ($user !~ /:/) {
 8761:                     $nothide{join(':',split(/[\@]/,$user))}=1;
 8762:                 } else {
 8763:                     $nothide{$user} = 1;
 8764:                 }
 8765:             }
 8766:             my @possdoms = ($cdom);
 8767:             if ($coursehash{'checkforpriv'}) {
 8768:                 push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
 8769:             }
 8770:         }
 8771:         foreach my $person (sort(keys(%coursepersonnel))) {
 8772:             my $match = 0;
 8773:             my $secmatch = 0;
 8774:             my $status;
 8775:             my ($role,$user,$usec) = ($person =~ /^([^:]*):([^:]+:[^:]+):([^:]*)/);
 8776:             $user =~ s/:$//;
 8777:             my ($end,$start) = split(/:/,$coursepersonnel{$person});
 8778:             if ($end == -1 || $start == -1) {
 8779:                 next;
 8780:             }
 8781:             if (($role) && ((grep(/^\Q$role\E$/,@{$roles})) ||
 8782:                 (grep(/^cr$/,@{$roles}) && $role =~ /^cr\//))) {
 8783:                 my ($uname,$udom) = split(/:/,$user);
 8784:                 if ((ref($sections) eq 'ARRAY') && (@{$sections} > 0)) {
 8785:                     if (grep(/^all$/,@{$sections})) {
 8786:                         $secmatch = 1;
 8787:                     } elsif ($usec eq '') {
 8788:                         if (grep(/^none$/,@{$sections})) {
 8789:                             $secmatch = 1;
 8790:                         }
 8791:                     } else {
 8792:                         if (grep(/^\Q$usec\E$/,@{$sections})) {
 8793:                             $secmatch = 1;
 8794:                         }
 8795:                     }
 8796:                     if (!$secmatch) {
 8797:                         next;
 8798:                     }
 8799:                 }
 8800:                 if ($usec eq '') {
 8801:                     $usec = 'none';
 8802:                 }
 8803:                 if ($uname ne '' && $udom ne '') {
 8804:                     if ($hidepriv) {
 8805:                         if ((&Apache::lonnet::privileged($uname,$udom,\@possdoms)) &&
 8806:                             (!$nothide{$uname.':'.$udom})) {
 8807:                             next;
 8808:                         }
 8809:                     }
 8810:                     if ($end > 0 && $end < $now) {
 8811:                         $status = 'previous';
 8812:                     } elsif ($start > $now) {
 8813:                         $status = 'future';
 8814:                     } else {
 8815:                         $status = 'active';
 8816:                     }
 8817:                     foreach my $type (keys(%{$types})) { 
 8818:                         if ($status eq $type) {
 8819:                             if (!grep(/^\Q$type\E$/,@{$$users{$role}{$user}})) {
 8820:                                 push(@{$$users{$role}{$user}},$type);
 8821:                             }
 8822:                             $match = 1;
 8823:                         }
 8824:                     }
 8825:                     if (($match) && (ref($userdata) eq 'HASH')) {
 8826:                         if (!exists($$userdata{$uname.':'.$udom})) {
 8827: 			    &get_user_info($udom,$uname,\%idx,$userdata);
 8828:                         }
 8829:                         if (!grep(/^\Q$usec\E$/,@{$seclists{$uname.':'.$udom}})) {
 8830:                             push(@{$seclists{$uname.':'.$udom}},$usec);
 8831:                         }
 8832:                         if (ref($statushash) eq 'HASH') {
 8833:                             $statushash->{$uname.':'.$udom}{$role}{$usec} = $displaystatus{$status};
 8834:                         }
 8835:                     }
 8836:                 }
 8837:             }
 8838:         }
 8839:         if (grep(/^ow$/,@{$roles})) {
 8840:             if ((defined($cdom)) && (defined($cnum))) {
 8841:                 my %csettings = &Apache::lonnet::get('environment',['internal.courseowner'],$cdom,$cnum);
 8842:                 if ( defined($csettings{'internal.courseowner'}) ) {
 8843:                     my $owner = $csettings{'internal.courseowner'};
 8844:                     next if ($owner eq '');
 8845:                     my ($ownername,$ownerdom);
 8846:                     if ($owner =~ /^([^:]+):([^:]+)$/) {
 8847:                         $ownername = $1;
 8848:                         $ownerdom = $2;
 8849:                     } else {
 8850:                         $ownername = $owner;
 8851:                         $ownerdom = $cdom;
 8852:                         $owner = $ownername.':'.$ownerdom;
 8853:                     }
 8854:                     @{$$users{'ow'}{$owner}} = 'any';
 8855:                     if (defined($userdata) && 
 8856: 			!exists($$userdata{$owner})) {
 8857: 			&get_user_info($ownerdom,$ownername,\%idx,$userdata);
 8858:                         if (!grep(/^none$/,@{$seclists{$owner}})) {
 8859:                             push(@{$seclists{$owner}},'none');
 8860:                         }
 8861:                         if (ref($statushash) eq 'HASH') {
 8862:                             $statushash->{$owner}{'ow'}{'none'} = 'Any';
 8863:                         }
 8864: 		    }
 8865:                 }
 8866:             }
 8867:         }
 8868:         foreach my $user (keys(%seclists)) {
 8869:             @{$seclists{$user}} = (sort {$a <=> $b} @{$seclists{$user}});
 8870:             $$userdata{$user}[$idx{section}] = join(',',@{$seclists{$user}});
 8871:         }
 8872:     }
 8873:     return;
 8874: }
 8875: 
 8876: sub get_user_info {
 8877:     my ($udom,$uname,$idx,$userdata) = @_;
 8878:     $$userdata{$uname.':'.$udom}[$$idx{fullname}] = 
 8879: 	&plainname($uname,$udom,'lastname');
 8880:     $$userdata{$uname.':'.$udom}[$$idx{uname}] = $uname;
 8881:     $$userdata{$uname.':'.$udom}[$$idx{udom}] = $udom;
 8882:     my %idhash =  &Apache::lonnet::idrget($udom,($uname));
 8883:     $$userdata{$uname.':'.$udom}[$$idx{id}] = $idhash{$uname}; 
 8884:     return;
 8885: }
 8886: 
 8887: ###############################################
 8888: 
 8889: =pod
 8890: 
 8891: =item * &get_user_quota()
 8892: 
 8893: Retrieves quota assigned for storage of user files.
 8894: Default is to report quota for portfolio files.
 8895: 
 8896: Incoming parameters:
 8897: 1. user's username
 8898: 2. user's domain
 8899: 3. quota name - portfolio, author, or course
 8900:    (if no quota name provided, defaults to portfolio).
 8901: 4. crstype - official, unofficial, textbook or community, if quota name is
 8902:    course
 8903: 
 8904: Returns:
 8905: 1. Disk quota (in MB) assigned to student.
 8906: 2. (Optional) Type of setting: custom or default
 8907:    (individually assigned or default for user's 
 8908:    institutional status).
 8909: 3. (Optional) - User's institutional status (e.g., faculty, staff
 8910:    or student - types as defined in localenroll::inst_usertypes 
 8911:    for user's domain, which determines default quota for user.
 8912: 4. (Optional) - Default quota which would apply to the user.
 8913: 
 8914: If a value has been stored in the user's environment, 
 8915: it will return that, otherwise it returns the maximal default
 8916: defined for the user's institutional status(es) in the domain.
 8917: 
 8918: =cut
 8919: 
 8920: ###############################################
 8921: 
 8922: 
 8923: sub get_user_quota {
 8924:     my ($uname,$udom,$quotaname,$crstype) = @_;
 8925:     my ($quota,$quotatype,$settingstatus,$defquota);
 8926:     if (!defined($udom)) {
 8927:         $udom = $env{'user.domain'};
 8928:     }
 8929:     if (!defined($uname)) {
 8930:         $uname = $env{'user.name'};
 8931:     }
 8932:     if (($udom eq '' || $uname eq '') ||
 8933:         ($udom eq 'public') && ($uname eq 'public')) {
 8934:         $quota = 0;
 8935:         $quotatype = 'default';
 8936:         $defquota = 0; 
 8937:     } else {
 8938:         my $inststatus;
 8939:         if ($quotaname eq 'course') {
 8940:             if (($env{'course.'.$udom.'_'.$uname.'.num'} eq $uname) &&
 8941:                 ($env{'course.'.$udom.'_'.$uname.'.domain'} eq $udom)) {
 8942:                 $quota = $env{'course.'.$udom.'_'.$uname.'.internal.uploadquota'};
 8943:             } else {
 8944:                 my %cenv = &Apache::lonnet::coursedescription("$udom/$uname");
 8945:                 $quota = $cenv{'internal.uploadquota'};
 8946:             }
 8947:         } else {
 8948:             if ($udom eq $env{'user.domain'} && $uname eq $env{'user.name'}) {
 8949:                 if ($quotaname eq 'author') {
 8950:                     $quota = $env{'environment.authorquota'};
 8951:                 } else {
 8952:                     $quota = $env{'environment.portfolioquota'};
 8953:                 }
 8954:                 $inststatus = $env{'environment.inststatus'};
 8955:             } else {
 8956:                 my %userenv = 
 8957:                     &Apache::lonnet::get('environment',['portfolioquota',
 8958:                                          'authorquota','inststatus'],$udom,$uname);
 8959:                 my ($tmp) = keys(%userenv);
 8960:                 if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
 8961:                     if ($quotaname eq 'author') {
 8962:                         $quota = $userenv{'authorquota'};
 8963:                     } else {
 8964:                         $quota = $userenv{'portfolioquota'};
 8965:                     }
 8966:                     $inststatus = $userenv{'inststatus'};
 8967:                 } else {
 8968:                     undef(%userenv);
 8969:                 }
 8970:             }
 8971:         }
 8972:         if ($quota eq '' || wantarray) {
 8973:             if ($quotaname eq 'course') {
 8974:                 my %domdefs = &Apache::lonnet::get_domain_defaults($udom);
 8975:                 if (($crstype eq 'official') || ($crstype eq 'unofficial') ||
 8976:                     ($crstype eq 'community') || ($crstype eq 'textbook')) {
 8977:                     $defquota = $domdefs{$crstype.'quota'};
 8978:                 }
 8979:                 if ($defquota eq '') {
 8980:                     $defquota = 500;
 8981:                 }
 8982:             } else {
 8983:                 ($defquota,$settingstatus) = &default_quota($udom,$inststatus,$quotaname);
 8984:             }
 8985:             if ($quota eq '') {
 8986:                 $quota = $defquota;
 8987:                 $quotatype = 'default';
 8988:             } else {
 8989:                 $quotatype = 'custom';
 8990:             }
 8991:         }
 8992:     }
 8993:     if (wantarray) {
 8994:         return ($quota,$quotatype,$settingstatus,$defquota);
 8995:     } else {
 8996:         return $quota;
 8997:     }
 8998: }
 8999: 
 9000: ###############################################
 9001: 
 9002: =pod
 9003: 
 9004: =item * &default_quota()
 9005: 
 9006: Retrieves default quota assigned for storage of user portfolio files,
 9007: given an (optional) user's institutional status.
 9008: 
 9009: Incoming parameters:
 9010: 
 9011: 1. domain
 9012: 2. (Optional) institutional status(es).  This is a : separated list of 
 9013:    status types (e.g., faculty, staff, student etc.)
 9014:    which apply to the user for whom the default is being retrieved.
 9015:    If the institutional status string in undefined, the domain
 9016:    default quota will be returned.
 9017: 3.  quota name - portfolio, author, or course
 9018:    (if no quota name provided, defaults to portfolio).
 9019: 
 9020: Returns:
 9021: 
 9022: 1. Default disk quota (in MB) for user portfolios in the domain.
 9023: 2. (Optional) institutional type which determined the value of the
 9024:    default quota.
 9025: 
 9026: If a value has been stored in the domain's configuration db,
 9027: it will return that, otherwise it returns 20 (for backwards 
 9028: compatibility with domains which have not set up a configuration
 9029: db file; the original statically defined portfolio quota was 20 MB). 
 9030: 
 9031: If the user's status includes multiple types (e.g., staff and student),
 9032: the largest default quota which applies to the user determines the
 9033: default quota returned.
 9034: 
 9035: =cut
 9036: 
 9037: ###############################################
 9038: 
 9039: 
 9040: sub default_quota {
 9041:     my ($udom,$inststatus,$quotaname) = @_;
 9042:     my ($defquota,$settingstatus);
 9043:     my %quotahash = &Apache::lonnet::get_dom('configuration',
 9044:                                             ['quotas'],$udom);
 9045:     my $key = 'defaultquota';
 9046:     if ($quotaname eq 'author') {
 9047:         $key = 'authorquota';
 9048:     }
 9049:     if (ref($quotahash{'quotas'}) eq 'HASH') {
 9050:         if ($inststatus ne '') {
 9051:             my @statuses = map { &unescape($_); } split(/:/,$inststatus);
 9052:             foreach my $item (@statuses) {
 9053:                 if (ref($quotahash{'quotas'}{$key}) eq 'HASH') {
 9054:                     if ($quotahash{'quotas'}{$key}{$item} ne '') {
 9055:                         if ($defquota eq '') {
 9056:                             $defquota = $quotahash{'quotas'}{$key}{$item};
 9057:                             $settingstatus = $item;
 9058:                         } elsif ($quotahash{'quotas'}{$key}{$item} > $defquota) {
 9059:                             $defquota = $quotahash{'quotas'}{$key}{$item};
 9060:                             $settingstatus = $item;
 9061:                         }
 9062:                     }
 9063:                 } elsif ($key eq 'defaultquota') {
 9064:                     if ($quotahash{'quotas'}{$item} ne '') {
 9065:                         if ($defquota eq '') {
 9066:                             $defquota = $quotahash{'quotas'}{$item};
 9067:                             $settingstatus = $item;
 9068:                         } elsif ($quotahash{'quotas'}{$item} > $defquota) {
 9069:                             $defquota = $quotahash{'quotas'}{$item};
 9070:                             $settingstatus = $item;
 9071:                         }
 9072:                     }
 9073:                 }
 9074:             }
 9075:         }
 9076:         if ($defquota eq '') {
 9077:             if (ref($quotahash{'quotas'}{$key}) eq 'HASH') {
 9078:                 $defquota = $quotahash{'quotas'}{$key}{'default'};
 9079:             } elsif ($key eq 'defaultquota') {
 9080:                 $defquota = $quotahash{'quotas'}{'default'};
 9081:             }
 9082:             $settingstatus = 'default';
 9083:             if ($defquota eq '') {
 9084:                 if ($quotaname eq 'author') {
 9085:                     $defquota = 500;
 9086:                 }
 9087:             }
 9088:         }
 9089:     } else {
 9090:         $settingstatus = 'default';
 9091:         if ($quotaname eq 'author') {
 9092:             $defquota = 500;
 9093:         } else {
 9094:             $defquota = 20;
 9095:         }
 9096:     }
 9097:     if (wantarray) {
 9098:         return ($defquota,$settingstatus);
 9099:     } else {
 9100:         return $defquota;
 9101:     }
 9102: }
 9103: 
 9104: ###############################################
 9105: 
 9106: =pod
 9107: 
 9108: =item * &excess_filesize_warning()
 9109: 
 9110: Returns warning message if upload of file to authoring space, or copying
 9111: of existing file within authoring space will cause quota for the authoring
 9112: space to be exceeded.
 9113: 
 9114: Same, if upload of a file directly to a course/community via Course Editor
 9115: will cause quota for uploaded content for the course to be exceeded.
 9116: 
 9117: Inputs: 7 
 9118: 1. username or coursenum
 9119: 2. domain
 9120: 3. context ('author' or 'course')
 9121: 4. filename of file for which action is being requested
 9122: 5. filesize (kB) of file
 9123: 6. action being taken: copy or upload.
 9124: 7. quotatype (in course context -- official, unofficial, community or textbook).
 9125: 
 9126: Returns: 1 scalar: HTML to display containing warning if quota would be exceeded,
 9127:          otherwise return null.
 9128: 
 9129: =back
 9130: 
 9131: =cut
 9132: 
 9133: sub excess_filesize_warning {
 9134:     my ($uname,$udom,$context,$filename,$filesize,$action,$quotatype) = @_;
 9135:     my $current_disk_usage = 0;
 9136:     my $disk_quota = &get_user_quota($uname,$udom,$context,$quotatype); #expressed in MB
 9137:     if ($context eq 'author') {
 9138:         my $authorspace = $Apache::lonnet::perlvar{'lonDocRoot'}."/priv/$udom/$uname";
 9139:         $current_disk_usage = &Apache::lonnet::diskusage($udom,$uname,$authorspace);
 9140:     } else {
 9141:         foreach my $subdir ('docs','supplemental') {
 9142:             $current_disk_usage += &Apache::lonnet::diskusage($udom,$uname,"userfiles/$subdir",1);
 9143:         }
 9144:     }
 9145:     $disk_quota = int($disk_quota * 1000);
 9146:     if (($current_disk_usage + $filesize) > $disk_quota) {
 9147:         return '<p class="LC_warning">'.
 9148:                 &mt("Unable to $action [_1]. (size = [_2] kilobytes). Disk quota will be exceeded.",
 9149:                     '<span class="LC_filename">'.$filename.'</span>',$filesize).'</p>'.
 9150:                '<p>'.&mt('Disk quota is [_1] kilobytes. Your current disk usage is [_2] kilobytes.',
 9151:                             $disk_quota,$current_disk_usage).
 9152:                '</p>';
 9153:     }
 9154:     return;
 9155: }
 9156: 
 9157: ###############################################
 9158: 
 9159: 
 9160: sub get_secgrprole_info {
 9161:     my ($cdom,$cnum,$needroles,$type)  = @_;
 9162:     my %sections_count = &get_sections($cdom,$cnum);
 9163:     my @sections =  (sort {$a <=> $b} keys(%sections_count));
 9164:     my %curr_groups = &Apache::longroup::coursegroups($cdom,$cnum);
 9165:     my @groups = sort(keys(%curr_groups));
 9166:     my $allroles = [];
 9167:     my $rolehash;
 9168:     my $accesshash = {
 9169:                      active => 'Currently has access',
 9170:                      future => 'Will have future access',
 9171:                      previous => 'Previously had access',
 9172:                   };
 9173:     if ($needroles) {
 9174:         $rolehash = {'all' => 'all'};
 9175:         my %user_roles = &Apache::lonnet::dump('nohist_userroles',$cdom,$cnum);
 9176: 	if (&Apache::lonnet::error(%user_roles)) {
 9177: 	    undef(%user_roles);
 9178: 	}
 9179:         foreach my $item (keys(%user_roles)) {
 9180:             my ($role)=split(/\:/,$item,2);
 9181:             if ($role eq 'cr') { next; }
 9182:             if ($role =~ /^cr/) {
 9183:                 $$rolehash{$role} = (split('/',$role))[3];
 9184:             } else {
 9185:                 $$rolehash{$role} = &Apache::lonnet::plaintext($role,$type);
 9186:             }
 9187:         }
 9188:         foreach my $key (sort(keys(%{$rolehash}))) {
 9189:             push(@{$allroles},$key);
 9190:         }
 9191:         push (@{$allroles},'st');
 9192:         $$rolehash{'st'} = &Apache::lonnet::plaintext('st',$type);
 9193:     }
 9194:     return (\@sections,\@groups,$allroles,$rolehash,$accesshash);
 9195: }
 9196: 
 9197: sub user_picker {
 9198:     my ($dom,$srch,$forcenewuser,$caller,$cancreate,$usertype,$context) = @_;
 9199:     my $currdom = $dom;
 9200:     my %curr_selected = (
 9201:                         srchin => 'dom',
 9202:                         srchby => 'lastname',
 9203:                       );
 9204:     my $srchterm;
 9205:     if ((ref($srch) eq 'HASH') && ($env{'form.origform'} ne 'crtusername')) {
 9206:         if ($srch->{'srchby'} ne '') {
 9207:             $curr_selected{'srchby'} = $srch->{'srchby'};
 9208:         }
 9209:         if ($srch->{'srchin'} ne '') {
 9210:             $curr_selected{'srchin'} = $srch->{'srchin'};
 9211:         }
 9212:         if ($srch->{'srchtype'} ne '') {
 9213:             $curr_selected{'srchtype'} = $srch->{'srchtype'};
 9214:         }
 9215:         if ($srch->{'srchdomain'} ne '') {
 9216:             $currdom = $srch->{'srchdomain'};
 9217:         }
 9218:         $srchterm = $srch->{'srchterm'};
 9219:     }
 9220:     my %lt=&Apache::lonlocal::texthash(
 9221:                     'usr'       => 'Search criteria',
 9222:                     'doma'      => 'Domain/institution to search',
 9223:                     'uname'     => 'username',
 9224:                     'lastname'  => 'last name',
 9225:                     'lastfirst' => 'last name, first name',
 9226:                     'crs'       => 'in this course',
 9227:                     'dom'       => 'in selected LON-CAPA domain', 
 9228:                     'alc'       => 'all LON-CAPA',
 9229:                     'instd'     => 'in institutional directory for selected domain',
 9230:                     'exact'     => 'is',
 9231:                     'contains'  => 'contains',
 9232:                     'begins'    => 'begins with',
 9233:                     'youm'      => "You must include some text to search for.",
 9234:                     'thte'      => "The text you are searching for must contain at least two characters when using a 'begins' type search.",
 9235:                     'thet'      => "The text you are searching for must contain at least three characters when using a 'contains' type search.",
 9236:                     'yomc'      => "You must choose a domain when using an institutional directory search.",
 9237:                     'ymcd'      => "You must choose a domain when using a domain search.",
 9238:                     'whus'      => "When using searching by last,first you must include a comma as separator between last name and first name.",
 9239:                     'whse'      => "When searching by last,first you must include at least one character in the first name.",
 9240:                      'thfo'     => "The following need to be corrected before the search can be run:",
 9241:                                        );
 9242:     my $domform = &select_dom_form($currdom,'srchdomain',1,1);
 9243:     my $srchinsel = ' <select name="srchin">';
 9244: 
 9245:     my @srchins = ('crs','dom','alc','instd');
 9246: 
 9247:     foreach my $option (@srchins) {
 9248:         # FIXME 'alc' option unavailable until 
 9249:         #       loncreateuser::print_user_query_page()
 9250:         #       has been completed.
 9251:         next if ($option eq 'alc');
 9252:         next if (($option eq 'crs') && ($env{'form.form'} eq 'requestcrs'));  
 9253:         next if ($option eq 'crs' && !$env{'request.course.id'});
 9254:         if ($curr_selected{'srchin'} eq $option) {
 9255:             $srchinsel .= ' 
 9256:    <option value="'.$option.'" selected="selected">'.$lt{$option}.'</option>';
 9257:         } else {
 9258:             $srchinsel .= '
 9259:    <option value="'.$option.'">'.$lt{$option}.'</option>';
 9260:         }
 9261:     }
 9262:     $srchinsel .= "\n  </select>\n";
 9263: 
 9264:     my $srchbysel =  ' <select name="srchby">';
 9265:     foreach my $option ('lastname','lastfirst','uname') {
 9266:         if ($curr_selected{'srchby'} eq $option) {
 9267:             $srchbysel .= '
 9268:    <option value="'.$option.'" selected="selected">'.$lt{$option}.'</option>';
 9269:         } else {
 9270:             $srchbysel .= '
 9271:    <option value="'.$option.'">'.$lt{$option}.'</option>';
 9272:          }
 9273:     }
 9274:     $srchbysel .= "\n  </select>\n";
 9275: 
 9276:     my $srchtypesel = ' <select name="srchtype">';
 9277:     foreach my $option ('begins','contains','exact') {
 9278:         if ($curr_selected{'srchtype'} eq $option) {
 9279:             $srchtypesel .= '
 9280:    <option value="'.$option.'" selected="selected">'.$lt{$option}.'</option>';
 9281:         } else {
 9282:             $srchtypesel .= '
 9283:    <option value="'.$option.'">'.$lt{$option}.'</option>';
 9284:         }
 9285:     }
 9286:     $srchtypesel .= "\n  </select>\n";
 9287: 
 9288:     my ($newuserscript,$new_user_create);
 9289:     my $context_dom = $env{'request.role.domain'};
 9290:     if ($context eq 'requestcrs') {
 9291:         if ($env{'form.coursedom'} ne '') { 
 9292:             $context_dom = $env{'form.coursedom'};
 9293:         }
 9294:     }
 9295:     if ($forcenewuser) {
 9296:         if (ref($srch) eq 'HASH') {
 9297:             if ($srch->{'srchby'} eq 'uname' && $srch->{'srchtype'} eq 'exact' && $srch->{'srchin'} eq 'dom' && $srch->{'srchdomain'} eq $context_dom) {
 9298:                 if ($cancreate) {
 9299:                     $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>';
 9300:                 } else {
 9301:                     my $helplink = 'javascript:helpMenu('."'display'".')';
 9302:                     my %usertypetext = (
 9303:                         official   => 'institutional',
 9304:                         unofficial => 'non-institutional',
 9305:                     );
 9306:                     $new_user_create = '<p class="LC_warning">'
 9307:                                       .&mt("You are not authorized to create new $usertypetext{$usertype} users in this domain.")
 9308:                                       .' '
 9309:                                       .&mt('Please contact the [_1]helpdesk[_2] for assistance.'
 9310:                                           ,'<a href="'.$helplink.'">','</a>')
 9311:                                       .'</p><br />';
 9312:                 }
 9313:             }
 9314:         }
 9315: 
 9316:         $newuserscript = <<"ENDSCRIPT";
 9317: 
 9318: function setSearch(createnew,callingForm) {
 9319:     if (createnew == 1) {
 9320:         for (var i=0; i<callingForm.srchby.length; i++) {
 9321:             if (callingForm.srchby.options[i].value == 'uname') {
 9322:                 callingForm.srchby.selectedIndex = i;
 9323:             }
 9324:         }
 9325:         for (var i=0; i<callingForm.srchin.length; i++) {
 9326:             if ( callingForm.srchin.options[i].value == 'dom') {
 9327: 		callingForm.srchin.selectedIndex = i;
 9328:             }
 9329:         }
 9330:         for (var i=0; i<callingForm.srchtype.length; i++) {
 9331:             if (callingForm.srchtype.options[i].value == 'exact') {
 9332:                 callingForm.srchtype.selectedIndex = i;
 9333:             }
 9334:         }
 9335:         for (var i=0; i<callingForm.srchdomain.length; i++) {
 9336:             if (callingForm.srchdomain.options[i].value == '$context_dom') {
 9337:                 callingForm.srchdomain.selectedIndex = i;
 9338:             }
 9339:         }
 9340:     }
 9341: }
 9342: ENDSCRIPT
 9343: 
 9344:     }
 9345: 
 9346:     my $output = <<"END_BLOCK";
 9347: <script type="text/javascript">
 9348: // <![CDATA[
 9349: function validateEntry(callingForm) {
 9350: 
 9351:     var checkok = 1;
 9352:     var srchin;
 9353:     for (var i=0; i<callingForm.srchin.length; i++) {
 9354: 	if ( callingForm.srchin[i].checked ) {
 9355: 	    srchin = callingForm.srchin[i].value;
 9356: 	}
 9357:     }
 9358: 
 9359:     var srchtype = callingForm.srchtype.options[callingForm.srchtype.selectedIndex].value;
 9360:     var srchby = callingForm.srchby.options[callingForm.srchby.selectedIndex].value;
 9361:     var srchdomain = callingForm.srchdomain.options[callingForm.srchdomain.selectedIndex].value;
 9362:     var srchterm =  callingForm.srchterm.value;
 9363:     var srchin = callingForm.srchin.options[callingForm.srchin.selectedIndex].value;
 9364:     var msg = "";
 9365: 
 9366:     if (srchterm == "") {
 9367:         checkok = 0;
 9368:         msg += "$lt{'youm'}\\n";
 9369:     }
 9370: 
 9371:     if (srchtype== 'begins') {
 9372:         if (srchterm.length < 2) {
 9373:             checkok = 0;
 9374:             msg += "$lt{'thte'}\\n";
 9375:         }
 9376:     }
 9377: 
 9378:     if (srchtype== 'contains') {
 9379:         if (srchterm.length < 3) {
 9380:             checkok = 0;
 9381:             msg += "$lt{'thet'}\\n";
 9382:         }
 9383:     }
 9384:     if (srchin == 'instd') {
 9385:         if (srchdomain == '') {
 9386:             checkok = 0;
 9387:             msg += "$lt{'yomc'}\\n";
 9388:         }
 9389:     }
 9390:     if (srchin == 'dom') {
 9391:         if (srchdomain == '') {
 9392:             checkok = 0;
 9393:             msg += "$lt{'ymcd'}\\n";
 9394:         }
 9395:     }
 9396:     if (srchby == 'lastfirst') {
 9397:         if (srchterm.indexOf(",") == -1) {
 9398:             checkok = 0;
 9399:             msg += "$lt{'whus'}\\n";
 9400:         }
 9401:         if (srchterm.indexOf(",") == srchterm.length -1) {
 9402:             checkok = 0;
 9403:             msg += "$lt{'whse'}\\n";
 9404:         }
 9405:     }
 9406:     if (checkok == 0) {
 9407:         alert("$lt{'thfo'}\\n"+msg);
 9408:         return;
 9409:     }
 9410:     if (checkok == 1) {
 9411:         callingForm.submit();
 9412:     }
 9413: }
 9414: 
 9415: $newuserscript
 9416: 
 9417: // ]]>
 9418: </script>
 9419: 
 9420: $new_user_create
 9421: 
 9422: END_BLOCK
 9423: 
 9424:     $output .= &Apache::lonhtmlcommon::start_pick_box().
 9425:                &Apache::lonhtmlcommon::row_title($lt{'doma'}).
 9426:                $domform.
 9427:                &Apache::lonhtmlcommon::row_closure().
 9428:                &Apache::lonhtmlcommon::row_title($lt{'usr'}).
 9429:                $srchbysel.
 9430:                $srchtypesel. 
 9431:                '<input type="text" size="15" name="srchterm" value="'.$srchterm.'" />'.
 9432:                $srchinsel.
 9433:                &Apache::lonhtmlcommon::row_closure(1). 
 9434:                &Apache::lonhtmlcommon::end_pick_box().
 9435:                '<br />';
 9436:     return $output;
 9437: }
 9438: 
 9439: sub user_rule_check {
 9440:     my ($usershash,$checks,$alerts,$rulematch,$inst_results,$curr_rules,$got_rules) = @_;
 9441:     my $response;
 9442:     if (ref($usershash) eq 'HASH') {
 9443:         foreach my $user (keys(%{$usershash})) {
 9444:             my ($uname,$udom) = split(/:/,$user);
 9445:             next if ($udom eq '' || $uname eq '');
 9446:             my ($id,$newuser);
 9447:             if (ref($usershash->{$user}) eq 'HASH') {
 9448:                 $newuser = $usershash->{$user}->{'newuser'};
 9449:                 $id = $usershash->{$user}->{'id'};
 9450:             }
 9451:             my $inst_response;
 9452:             if (ref($checks) eq 'HASH') {
 9453:                 if (defined($checks->{'username'})) {
 9454:                     ($inst_response,%{$inst_results->{$user}}) = 
 9455:                         &Apache::lonnet::get_instuser($udom,$uname);
 9456:                 } elsif (defined($checks->{'id'})) {
 9457:                     ($inst_response,%{$inst_results->{$user}}) =
 9458:                         &Apache::lonnet::get_instuser($udom,undef,$id);
 9459:                 }
 9460:             } else {
 9461:                 ($inst_response,%{$inst_results->{$user}}) =
 9462:                     &Apache::lonnet::get_instuser($udom,$uname);
 9463:                 return;
 9464:             }
 9465:             if (!$got_rules->{$udom}) {
 9466:                 my %domconfig = &Apache::lonnet::get_dom('configuration',
 9467:                                                   ['usercreation'],$udom);
 9468:                 if (ref($domconfig{'usercreation'}) eq 'HASH') {
 9469:                     foreach my $item ('username','id') {
 9470:                         if (ref($domconfig{'usercreation'}{$item.'_rule'}) eq 'ARRAY') {
 9471:                             $$curr_rules{$udom}{$item} = 
 9472:                                 $domconfig{'usercreation'}{$item.'_rule'};
 9473:                         }
 9474:                     }
 9475:                 }
 9476:                 $got_rules->{$udom} = 1;  
 9477:             }
 9478:             foreach my $item (keys(%{$checks})) {
 9479:                 if (ref($$curr_rules{$udom}) eq 'HASH') {
 9480:                     if (ref($$curr_rules{$udom}{$item}) eq 'ARRAY') {
 9481:                         if (@{$$curr_rules{$udom}{$item}} > 0) {
 9482:                             my %rule_check = &Apache::lonnet::inst_rulecheck($udom,$uname,$id,$item,$$curr_rules{$udom}{$item});
 9483:                             foreach my $rule (@{$$curr_rules{$udom}{$item}}) {
 9484:                                 if ($rule_check{$rule}) {
 9485:                                     $$rulematch{$user}{$item} = $rule;
 9486:                                     if ($inst_response eq 'ok') {
 9487:                                         if (ref($inst_results) eq 'HASH') {
 9488:                                             if (ref($inst_results->{$user}) eq 'HASH') {
 9489:                                                 if (keys(%{$inst_results->{$user}}) == 0) {
 9490:                                                     $$alerts{$item}{$udom}{$uname} = 1;
 9491:                                                 }
 9492:                                             }
 9493:                                         }
 9494:                                     }
 9495:                                     last;
 9496:                                 }
 9497:                             }
 9498:                         }
 9499:                     }
 9500:                 }
 9501:             }
 9502:         }
 9503:     }
 9504:     return;
 9505: }
 9506: 
 9507: sub user_rule_formats {
 9508:     my ($domain,$domdesc,$curr_rules,$check) = @_;
 9509:     my %text = ( 
 9510:                  'username' => 'Usernames',
 9511:                  'id'       => 'IDs',
 9512:                );
 9513:     my $output;
 9514:     my ($rules,$ruleorder) = &Apache::lonnet::inst_userrules($domain,$check);
 9515:     if ((ref($rules) eq 'HASH') && (ref($ruleorder) eq 'ARRAY')) {
 9516:         if (@{$ruleorder} > 0) {
 9517:             $output = '<br />'.
 9518:                       &mt($text{$check}.' with the following format(s) may [_1]only[_2] be used for verified users at [_3]:',
 9519:                           '<span class="LC_cusr_emph">','</span>',$domdesc).
 9520:                       ' <ul>';
 9521:             foreach my $rule (@{$ruleorder}) {
 9522:                 if (ref($curr_rules) eq 'ARRAY') {
 9523:                     if (grep(/^\Q$rule\E$/,@{$curr_rules})) {
 9524:                         if (ref($rules->{$rule}) eq 'HASH') {
 9525:                             $output .= '<li>'.$rules->{$rule}{'name'}.': '.
 9526:                                         $rules->{$rule}{'desc'}.'</li>';
 9527:                         }
 9528:                     }
 9529:                 }
 9530:             }
 9531:             $output .= '</ul>';
 9532:         }
 9533:     }
 9534:     return $output;
 9535: }
 9536: 
 9537: sub instrule_disallow_msg {
 9538:     my ($checkitem,$domdesc,$count,$mode) = @_;
 9539:     my $response;
 9540:     my %text = (
 9541:                   item   => 'username',
 9542:                   items  => 'usernames',
 9543:                   match  => 'matches',
 9544:                   do     => 'does',
 9545:                   action => 'a username',
 9546:                   one    => 'one',
 9547:                );
 9548:     if ($count > 1) {
 9549:         $text{'item'} = 'usernames';
 9550:         $text{'match'} ='match';
 9551:         $text{'do'} = 'do';
 9552:         $text{'action'} = 'usernames',
 9553:         $text{'one'} = 'ones';
 9554:     }
 9555:     if ($checkitem eq 'id') {
 9556:         $text{'items'} = 'IDs';
 9557:         $text{'item'} = 'ID';
 9558:         $text{'action'} = 'an ID';
 9559:         if ($count > 1) {
 9560:             $text{'item'} = 'IDs';
 9561:             $text{'action'} = 'IDs';
 9562:         }
 9563:     }
 9564:     $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 />';
 9565:     if ($mode eq 'upload') {
 9566:         if ($checkitem eq 'username') {
 9567:             $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'}.");
 9568:         } elsif ($checkitem eq 'id') {
 9569:             $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.");
 9570:         }
 9571:     } elsif ($mode eq 'selfcreate') {
 9572:         if ($checkitem eq 'id') {
 9573:             $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.");
 9574:         }
 9575:     } else {
 9576:         if ($checkitem eq 'username') {
 9577:             $response .= &mt("You must choose $text{'action'} with a different format --  $text{'one'} that will not conflict with 'official' institutional $text{'items'}.");
 9578:         } elsif ($checkitem eq 'id') {
 9579:             $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.");
 9580:         }
 9581:     }
 9582:     return $response;
 9583: }
 9584: 
 9585: sub personal_data_fieldtitles {
 9586:     my %fieldtitles = &Apache::lonlocal::texthash (
 9587:                         id => 'Student/Employee ID',
 9588:                         permanentemail => 'E-mail address',
 9589:                         lastname => 'Last Name',
 9590:                         firstname => 'First Name',
 9591:                         middlename => 'Middle Name',
 9592:                         generation => 'Generation',
 9593:                         gen => 'Generation',
 9594:                         inststatus => 'Affiliation',
 9595:                    );
 9596:     return %fieldtitles;
 9597: }
 9598: 
 9599: sub sorted_inst_types {
 9600:     my ($dom) = @_;
 9601:     my ($usertypes,$order);
 9602:     my %domdefaults = &Apache::lonnet::get_domain_defaults($dom);
 9603:     if (ref($domdefaults{'inststatus'}) eq 'HASH') {
 9604:         $usertypes = $domdefaults{'inststatus'}{'inststatustypes'};
 9605:         $order = $domdefaults{'inststatus'}{'inststatusorder'};
 9606:     } else {
 9607:         ($usertypes,$order) = &Apache::lonnet::retrieve_inst_usertypes($dom);
 9608:     }
 9609:     my $othertitle = &mt('All users');
 9610:     if ($env{'request.course.id'}) {
 9611:         $othertitle  = &mt('Any users');
 9612:     }
 9613:     my @types;
 9614:     if (ref($order) eq 'ARRAY') {
 9615:         @types = @{$order};
 9616:     }
 9617:     if (@types == 0) {
 9618:         if (ref($usertypes) eq 'HASH') {
 9619:             @types = sort(keys(%{$usertypes}));
 9620:         }
 9621:     }
 9622:     if (keys(%{$usertypes}) > 0) {
 9623:         $othertitle = &mt('Other users');
 9624:     }
 9625:     return ($othertitle,$usertypes,\@types);
 9626: }
 9627: 
 9628: sub get_institutional_codes {
 9629:     my ($settings,$allcourses,$LC_code) = @_;
 9630: # Get complete list of course sections to update
 9631:     my @currsections = ();
 9632:     my @currxlists = ();
 9633:     my $coursecode = $$settings{'internal.coursecode'};
 9634: 
 9635:     if ($$settings{'internal.sectionnums'} ne '') {
 9636:         @currsections = split(/,/,$$settings{'internal.sectionnums'});
 9637:     }
 9638: 
 9639:     if ($$settings{'internal.crosslistings'} ne '') {
 9640:         @currxlists = split(/,/,$$settings{'internal.crosslistings'});
 9641:     }
 9642: 
 9643:     if (@currxlists > 0) {
 9644:         foreach (@currxlists) {
 9645:             if (m/^([^:]+):(\w*)$/) {
 9646:                 unless (grep/^$1$/,@{$allcourses}) {
 9647:                     push @{$allcourses},$1;
 9648:                     $$LC_code{$1} = $2;
 9649:                 }
 9650:             }
 9651:         }
 9652:     }
 9653:  
 9654:     if (@currsections > 0) {
 9655:         foreach (@currsections) {
 9656:             if (m/^(\w+):(\w*)$/) {
 9657:                 my $sec = $coursecode.$1;
 9658:                 my $lc_sec = $2;
 9659:                 unless (grep/^$sec$/,@{$allcourses}) {
 9660:                     push @{$allcourses},$sec;
 9661:                     $$LC_code{$sec} = $lc_sec;
 9662:                 }
 9663:             }
 9664:         }
 9665:     }
 9666:     return;
 9667: }
 9668: 
 9669: sub get_standard_codeitems {
 9670:     return ('Year','Semester','Department','Number','Section');
 9671: }
 9672: 
 9673: =pod
 9674: 
 9675: =head1 Slot Helpers
 9676: 
 9677: =over 4
 9678: 
 9679: =item * sorted_slots()
 9680: 
 9681: Sorts an array of slot names in order of an optional sort key,
 9682: default sort is by slot start time (earliest first). 
 9683: 
 9684: Inputs:
 9685: 
 9686: =over 4
 9687: 
 9688: slotsarr  - Reference to array of unsorted slot names.
 9689: 
 9690: slots     - Reference to hash of hash, where outer hash keys are slot names.
 9691: 
 9692: sortkey   - Name of key in inner hash to be sorted on (e.g., starttime).
 9693: 
 9694: =back
 9695: 
 9696: Returns:
 9697: 
 9698: =over 4
 9699: 
 9700: sorted   - An array of slot names sorted by a specified sort key 
 9701:            (default sort key is start time of the slot).
 9702: 
 9703: =back
 9704: 
 9705: =cut
 9706: 
 9707: 
 9708: sub sorted_slots {
 9709:     my ($slotsarr,$slots,$sortkey) = @_;
 9710:     if ($sortkey eq '') {
 9711:         $sortkey = 'starttime';
 9712:     }
 9713:     my @sorted;
 9714:     if ((ref($slotsarr) eq 'ARRAY') && (ref($slots) eq 'HASH')) {
 9715:         @sorted =
 9716:             sort {
 9717:                      if (ref($slots->{$a}) && ref($slots->{$b})) {
 9718:                          return $slots->{$a}{$sortkey} <=> $slots->{$b}{$sortkey}
 9719:                      }
 9720:                      if (ref($slots->{$a})) { return -1;}
 9721:                      if (ref($slots->{$b})) { return 1;}
 9722:                      return 0;
 9723:                  } @{$slotsarr};
 9724:     }
 9725:     return @sorted;
 9726: }
 9727: 
 9728: =pod
 9729: 
 9730: =item * get_future_slots()
 9731: 
 9732: Inputs:
 9733: 
 9734: =over 4
 9735: 
 9736: cnum - course number
 9737: 
 9738: cdom - course domain
 9739: 
 9740: now - current UNIX time
 9741: 
 9742: symb - optional symb
 9743: 
 9744: =back
 9745: 
 9746: Returns:
 9747: 
 9748: =over 4
 9749: 
 9750: sorted_reservable - ref to array of student_schedulable slots currently 
 9751:                     reservable, ordered by end date of reservation period.
 9752: 
 9753: reservable_now - ref to hash of student_schedulable slots currently
 9754:                  reservable.
 9755: 
 9756:     Keys in inner hash are:
 9757:     (a) symb: either blank or symb to which slot use is restricted.
 9758:     (b) endreserve: end date of reservation period. 
 9759: 
 9760: sorted_future - ref to array of student_schedulable slots reservable in
 9761:                 the future, ordered by start date of reservation period.
 9762: 
 9763: future_reservable - ref to hash of student_schedulable slots reservable
 9764:                     in the future.
 9765: 
 9766:     Keys in inner hash are:
 9767:     (a) symb: either blank or symb to which slot use is restricted.
 9768:     (b) startreserve:  start date of reservation period.
 9769: 
 9770: =back
 9771: 
 9772: =cut
 9773: 
 9774: sub get_future_slots {
 9775:     my ($cnum,$cdom,$now,$symb) = @_;
 9776:     my (%reservable_now,%future_reservable,@sorted_reservable,@sorted_future);
 9777:     my %slots = &Apache::lonnet::get_course_slots($cnum,$cdom);
 9778:     foreach my $slot (keys(%slots)) {
 9779:         next unless($slots{$slot}->{'type'} eq 'schedulable_student');
 9780:         if ($symb) {
 9781:             next if (($slots{$slot}->{'symb'} ne '') && 
 9782:                      ($slots{$slot}->{'symb'} ne $symb));
 9783:         }
 9784:         if (($slots{$slot}->{'starttime'} > $now) &&
 9785:             ($slots{$slot}->{'endtime'} > $now)) {
 9786:             if (($slots{$slot}->{'allowedsections'}) || ($slots{$slot}->{'allowedusers'})) {
 9787:                 my $userallowed = 0;
 9788:                 if ($slots{$slot}->{'allowedsections'}) {
 9789:                     my @allowed_sec = split(',',$slots{$slot}->{'allowedsections'});
 9790:                     if (!defined($env{'request.role.sec'})
 9791:                         && grep(/^No section assigned$/,@allowed_sec)) {
 9792:                         $userallowed=1;
 9793:                     } else {
 9794:                         if (grep(/^\Q$env{'request.role.sec'}\E$/,@allowed_sec)) {
 9795:                             $userallowed=1;
 9796:                         }
 9797:                     }
 9798:                     unless ($userallowed) {
 9799:                         if (defined($env{'request.course.groups'})) {
 9800:                             my @groups = split(/:/,$env{'request.course.groups'});
 9801:                             foreach my $group (@groups) {
 9802:                                 if (grep(/^\Q$group\E$/,@allowed_sec)) {
 9803:                                     $userallowed=1;
 9804:                                     last;
 9805:                                 }
 9806:                             }
 9807:                         }
 9808:                     }
 9809:                 }
 9810:                 if ($slots{$slot}->{'allowedusers'}) {
 9811:                     my @allowed_users = split(',',$slots{$slot}->{'allowedusers'});
 9812:                     my $user = $env{'user.name'}.':'.$env{'user.domain'};
 9813:                     if (grep(/^\Q$user\E$/,@allowed_users)) {
 9814:                         $userallowed = 1;
 9815:                     }
 9816:                 }
 9817:                 next unless($userallowed);
 9818:             }
 9819:             my $startreserve = $slots{$slot}->{'startreserve'};
 9820:             my $endreserve = $slots{$slot}->{'endreserve'};
 9821:             my $symb = $slots{$slot}->{'symb'};
 9822:             if (($startreserve < $now) &&
 9823:                 (!$endreserve || $endreserve > $now)) {
 9824:                 my $lastres = $endreserve;
 9825:                 if (!$lastres) {
 9826:                     $lastres = $slots{$slot}->{'starttime'};
 9827:                 }
 9828:                 $reservable_now{$slot} = {
 9829:                                            symb       => $symb,
 9830:                                            endreserve => $lastres
 9831:                                          };
 9832:             } elsif (($startreserve > $now) &&
 9833:                      (!$endreserve || $endreserve > $startreserve)) {
 9834:                 $future_reservable{$slot} = {
 9835:                                               symb         => $symb,
 9836:                                               startreserve => $startreserve
 9837:                                             };
 9838:             }
 9839:         }
 9840:     }
 9841:     my @unsorted_reservable = keys(%reservable_now);
 9842:     if (@unsorted_reservable > 0) {
 9843:         @sorted_reservable = 
 9844:             &sorted_slots(\@unsorted_reservable,\%reservable_now,'endreserve');
 9845:     }
 9846:     my @unsorted_future = keys(%future_reservable);
 9847:     if (@unsorted_future > 0) {
 9848:         @sorted_future =
 9849:             &sorted_slots(\@unsorted_future,\%future_reservable,'startreserve');
 9850:     }
 9851:     return (\@sorted_reservable,\%reservable_now,\@sorted_future,\%future_reservable);
 9852: }
 9853: 
 9854: =pod
 9855: 
 9856: =back
 9857: 
 9858: =head1 HTTP Helpers
 9859: 
 9860: =over 4
 9861: 
 9862: =item * &get_unprocessed_cgi($query,$possible_names)
 9863: 
 9864: Modify the %env hash to contain unprocessed CGI form parameters held in
 9865: $query.  The parameters listed in $possible_names (an array reference),
 9866: will be set in $env{'form.name'} if they do not already exist.
 9867: 
 9868: Typically called with $ENV{'QUERY_STRING'} as the first parameter.  
 9869: $possible_names is an ref to an array of form element names.  As an example:
 9870: get_unprocessed_cgi($ENV{'QUERY_STRING'},['uname','udom']);
 9871: will result in $env{'form.uname'} and $env{'form.udom'} being set.
 9872: 
 9873: =cut
 9874: 
 9875: sub get_unprocessed_cgi {
 9876:   my ($query,$possible_names)= @_;
 9877:   # $Apache::lonxml::debug=1;
 9878:   foreach my $pair (split(/&/,$query)) {
 9879:     my ($name, $value) = split(/=/,$pair);
 9880:     $name = &unescape($name);
 9881:     if (!defined($possible_names) || (grep {$_ eq $name} @$possible_names)) {
 9882:       $value =~ tr/+/ /;
 9883:       $value =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack("C",hex($1))/eg;
 9884:       unless (defined($env{'form.'.$name})) { &add_to_env('form.'.$name,$value) };
 9885:     }
 9886:   }
 9887: }
 9888: 
 9889: =pod
 9890: 
 9891: =item * &cacheheader() 
 9892: 
 9893: returns cache-controlling header code
 9894: 
 9895: =cut
 9896: 
 9897: sub cacheheader {
 9898:     unless ($env{'request.method'} eq 'GET') { return ''; }
 9899:     my $date=strftime("%a, %d %b %Y %H:%M:%S GMT",gmtime);
 9900:     my $output .='<meta HTTP-EQUIV="Expires" CONTENT="'.$date.'" />
 9901:                 <meta HTTP-EQUIV="Cache-control" CONTENT="no-cache" />
 9902:                 <meta HTTP-EQUIV="Pragma" CONTENT="no-cache" />';
 9903:     return $output;
 9904: }
 9905: 
 9906: =pod
 9907: 
 9908: =item * &no_cache($r) 
 9909: 
 9910: specifies header code to not have cache
 9911: 
 9912: =cut
 9913: 
 9914: sub no_cache {
 9915:     my ($r) = @_;
 9916:     if ($ENV{'REQUEST_METHOD'} ne 'GET' &&
 9917: 	$env{'request.method'} ne 'GET') { return ''; }
 9918:     my $date=strftime("%a, %d %b %Y %H:%M:%S GMT",gmtime(time));
 9919:     $r->no_cache(1);
 9920:     $r->header_out("Expires" => $date);
 9921:     $r->header_out("Pragma" => "no-cache");
 9922: }
 9923: 
 9924: sub content_type {
 9925:     my ($r,$type,$charset) = @_;
 9926:     if ($r) {
 9927: 	#  Note that printout.pl calls this with undef for $r.
 9928: 	&no_cache($r);
 9929:     }
 9930:     if ($env{'browser.mathml'} && $type eq 'text/html') { $type='text/xml'; }
 9931:     unless ($charset) {
 9932: 	$charset=&Apache::lonlocal::current_encoding;
 9933:     }
 9934:     if ($charset) { $type.='; charset='.$charset; }
 9935:     if ($r) {
 9936: 	$r->content_type($type);
 9937:     } else {
 9938: 	print("Content-type: $type\n\n");
 9939:     }
 9940: }
 9941: 
 9942: =pod
 9943: 
 9944: =item * &add_to_env($name,$value) 
 9945: 
 9946: adds $name to the %env hash with value
 9947: $value, if $name already exists, the entry is converted to an array
 9948: reference and $value is added to the array.
 9949: 
 9950: =cut
 9951: 
 9952: sub add_to_env {
 9953:   my ($name,$value)=@_;
 9954:   if (defined($env{$name})) {
 9955:     if (ref($env{$name})) {
 9956:       #already have multiple values
 9957:       push(@{ $env{$name} },$value);
 9958:     } else {
 9959:       #first time seeing multiple values, convert hash entry to an arrayref
 9960:       my $first=$env{$name};
 9961:       undef($env{$name});
 9962:       push(@{ $env{$name} },$first,$value);
 9963:     }
 9964:   } else {
 9965:     $env{$name}=$value;
 9966:   }
 9967: }
 9968: 
 9969: =pod
 9970: 
 9971: =item * &get_env_multiple($name) 
 9972: 
 9973: gets $name from the %env hash, it seemlessly handles the cases where multiple
 9974: values may be defined and end up as an array ref.
 9975: 
 9976: returns an array of values
 9977: 
 9978: =cut
 9979: 
 9980: sub get_env_multiple {
 9981:     my ($name) = @_;
 9982:     my @values;
 9983:     if (defined($env{$name})) {
 9984:         # exists is it an array
 9985:         if (ref($env{$name})) {
 9986:             @values=@{ $env{$name} };
 9987:         } else {
 9988:             $values[0]=$env{$name};
 9989:         }
 9990:     }
 9991:     return(@values);
 9992: }
 9993: 
 9994: sub ask_for_embedded_content {
 9995:     my ($actionurl,$state,$allfiles,$codebase,$args)=@_;
 9996:     my (%subdependencies,%dependencies,%mapping,%existing,%newfiles,%pathchanges,
 9997:         %currsubfile,%unused,$rem);
 9998:     my $counter = 0;
 9999:     my $numnew = 0;
10000:     my $numremref = 0;
10001:     my $numinvalid = 0;
10002:     my $numpathchg = 0;
10003:     my $numexisting = 0;
10004:     my $numunused = 0;
10005:     my ($output,$upload_output,$toplevel,$url,$udom,$uname,$getpropath,$cdom,$cnum,
10006:         $fileloc,$filename,$delete_output,$modify_output,$title,$symb,$path,$navmap);
10007:     my $heading = &mt('Upload embedded files');
10008:     my $buttontext = &mt('Upload');
10009: 
10010:     if ($env{'request.course.id'}) {
10011:         if ($actionurl eq '/adm/dependencies') {
10012:             $navmap = Apache::lonnavmaps::navmap->new();
10013:         }
10014:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
10015:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
10016:     }
10017:     if (($actionurl eq '/adm/portfolio') ||
10018:         ($actionurl eq '/adm/coursegrp_portfolio')) {
10019:         my $current_path='/';
10020:         if ($env{'form.currentpath'}) {
10021:             $current_path = $env{'form.currentpath'};
10022:         }
10023:         if ($actionurl eq '/adm/coursegrp_portfolio') {
10024:             $udom = $cdom;
10025:             $uname = $cnum;
10026:             $url = '/userfiles/groups/'.$env{'form.group'}.'/portfolio';
10027:         } else {
10028:             $udom = $env{'user.domain'};
10029:             $uname = $env{'user.name'};
10030:             $url = '/userfiles/portfolio';
10031:         }
10032:         $toplevel = $url.'/';
10033:         $url .= $current_path;
10034:         $getpropath = 1;
10035:     } elsif (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank') ||
10036:              ($actionurl eq '/adm/imsimport')) { 
10037:         my ($udom,$uname,$rest) = ($args->{'current_path'} =~ m{/priv/($match_domain)/($match_username)/?(.*)$});
10038:         $url = $Apache::lonnet::perlvar{'lonDocRoot'}."/priv/$udom/$uname/";
10039:         $toplevel = $url;
10040:         if ($rest ne '') {
10041:             $url .= $rest;
10042:         }
10043:     } elsif ($actionurl eq '/adm/coursedocs') {
10044:         if (ref($args) eq 'HASH') {
10045:             $url = $args->{'docs_url'};
10046:             $toplevel = $url;
10047:             if ($args->{'context'} eq 'paste') {
10048:                 ($cdom,$cnum) = ($url =~ m{^\Q/uploaded/\E($match_domain)/($match_courseid)/});
10049:                 ($path) =
10050:                     ($toplevel =~ m{^(\Q/uploaded/$cdom/$cnum/\E(?:docs|supplemental)/(?:default|\d+)/\d+)/});
10051:                 $fileloc = &Apache::lonnet::filelocation('',$toplevel);
10052:                 $fileloc =~ s{^/}{};
10053:             }
10054:         }
10055:     } elsif ($actionurl eq '/adm/dependencies') {
10056:         if ($env{'request.course.id'} ne '') {
10057:             if (ref($args) eq 'HASH') {
10058:                 $url = $args->{'docs_url'};
10059:                 $title = $args->{'docs_title'};
10060:                 $toplevel = $url;
10061:                 unless ($toplevel =~ m{^/}) {
10062:                     $toplevel = "/$url";
10063:                 }
10064:                 ($rem) = ($toplevel =~ m{^(.+/)[^/]+$});
10065:                 if ($toplevel =~ m{^(\Q/uploaded/$cdom/$cnum/portfolio/syllabus\E)}) {
10066:                     $path = $1;
10067:                 } else {
10068:                     ($path) =
10069:                         ($toplevel =~ m{^(\Q/uploaded/$cdom/$cnum/\E(?:docs|supplemental)/(?:default|\d+)/\d+)/});
10070:                 }
10071:                 if ($toplevel=~/^\/*(uploaded|editupload)/) {
10072:                     $fileloc = $toplevel;
10073:                     $fileloc=~ s/^\s*(\S+)\s*$/$1/;
10074:                     my ($udom,$uname,$fname) =
10075:                         ($fileloc=~ m{^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$});
10076:                     $fileloc = propath($udom,$uname).'/userfiles/'.$fname;
10077:                 } else {
10078:                     $fileloc = &Apache::lonnet::filelocation('',$toplevel);
10079:                 }
10080:                 $fileloc =~ s{^/}{};
10081:                 ($filename) = ($fileloc =~ m{.+/([^/]+)$});
10082:                 $heading = &mt('Status of dependencies in [_1]',"$title ($filename)");
10083:             }
10084:         }
10085:     } elsif ($actionurl eq "/public/$cdom/$cnum/syllabus") {
10086:         $udom = $cdom;
10087:         $uname = $cnum;
10088:         $url = "/uploaded/$cdom/$cnum/portfolio/syllabus";
10089:         $toplevel = $url;
10090:         $path = $url;
10091:         $fileloc = &Apache::lonnet::filelocation('',$toplevel).'/';
10092:         $fileloc =~ s{^/}{};
10093:     }
10094:     foreach my $file (keys(%{$allfiles})) {
10095:         my $embed_file;
10096:         if (($path eq "/uploaded/$cdom/$cnum/portfolio/syllabus") && ($file =~ m{^\Q$path/\E(.+)$})) {
10097:             $embed_file = $1;
10098:         } else {
10099:             $embed_file = $file;
10100:         }
10101:         my ($absolutepath,$cleaned_file);
10102:         if ($embed_file =~ m{^\w+://}) {
10103:             $cleaned_file = $embed_file;
10104:             $newfiles{$cleaned_file} = 1;
10105:             $mapping{$cleaned_file} = $embed_file;
10106:         } else {
10107:             $cleaned_file = &clean_path($embed_file);
10108:             if ($embed_file =~ m{^/}) {
10109:                 $absolutepath = $embed_file;
10110:             }
10111:             if ($cleaned_file =~ m{/}) {
10112:                 my ($path,$fname) = ($cleaned_file =~ m{^(.+)/([^/]*)$});
10113:                 $path = &check_for_traversal($path,$url,$toplevel);
10114:                 my $item = $fname;
10115:                 if ($path ne '') {
10116:                     $item = $path.'/'.$fname;
10117:                     $subdependencies{$path}{$fname} = 1;
10118:                 } else {
10119:                     $dependencies{$item} = 1;
10120:                 }
10121:                 if ($absolutepath) {
10122:                     $mapping{$item} = $absolutepath;
10123:                 } else {
10124:                     $mapping{$item} = $embed_file;
10125:                 }
10126:             } else {
10127:                 $dependencies{$embed_file} = 1;
10128:                 if ($absolutepath) {
10129:                     $mapping{$cleaned_file} = $absolutepath;
10130:                 } else {
10131:                     $mapping{$cleaned_file} = $embed_file;
10132:                 }
10133:             }
10134:         }
10135:     }
10136:     my $dirptr = 16384;
10137:     foreach my $path (keys(%subdependencies)) {
10138:         $currsubfile{$path} = {};
10139:         if (($actionurl eq '/adm/portfolio') ||
10140:             ($actionurl eq '/adm/coursegrp_portfolio')) { 
10141:             my ($sublistref,$listerror) =
10142:                 &Apache::lonnet::dirlist($url.$path,$udom,$uname,$getpropath);
10143:             if (ref($sublistref) eq 'ARRAY') {
10144:                 foreach my $line (@{$sublistref}) {
10145:                     my ($file_name,$rest) = split(/\&/,$line,2);
10146:                     $currsubfile{$path}{$file_name} = 1;
10147:                 }
10148:             }
10149:         } elsif (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank')) {
10150:             if (opendir(my $dir,$url.'/'.$path)) {
10151:                 my @subdir_list = grep(!/^\./,readdir($dir));
10152:                 map {$currsubfile{$path}{$_} = 1;} @subdir_list;
10153:             }
10154:         } elsif (($actionurl eq '/adm/dependencies') ||
10155:                  (($actionurl eq '/adm/coursedocs') && (ref($args) eq 'HASH') &&
10156:                   ($args->{'context'} eq 'paste')) ||
10157:                  ($actionurl eq "/public/$cdom/$cnum/syllabus")) {
10158:             if ($env{'request.course.id'} ne '') {
10159:                 my $dir;
10160:                 if ($actionurl eq "/public/$cdom/$cnum/syllabus") {
10161:                     $dir = $fileloc;
10162:                 } else {
10163:                     ($dir) = ($fileloc =~ m{^(.+/)[^/]+$});
10164:                 }
10165:                 if ($dir ne '') {
10166:                     my ($sublistref,$listerror) =
10167:                         &Apache::lonnet::dirlist($dir.$path,$cdom,$cnum,$getpropath,undef,'/');
10168:                     if (ref($sublistref) eq 'ARRAY') {
10169:                         foreach my $line (@{$sublistref}) {
10170:                             my ($file_name,$dom,undef,$testdir,undef,undef,undef,undef,$size,
10171:                                 undef,$mtime)=split(/\&/,$line,12);
10172:                             unless (($testdir&$dirptr) ||
10173:                                     ($file_name =~ /^\.\.?$/)) {
10174:                                 $currsubfile{$path}{$file_name} = [$size,$mtime];
10175:                             }
10176:                         }
10177:                     }
10178:                 }
10179:             }
10180:         }
10181:         foreach my $file (keys(%{$subdependencies{$path}})) {
10182:             if (exists($currsubfile{$path}{$file})) {
10183:                 my $item = $path.'/'.$file;
10184:                 unless ($mapping{$item} eq $item) {
10185:                     $pathchanges{$item} = 1;
10186:                 }
10187:                 $existing{$item} = 1;
10188:                 $numexisting ++;
10189:             } else {
10190:                 $newfiles{$path.'/'.$file} = 1;
10191:             }
10192:         }
10193:         if ($actionurl eq '/adm/dependencies') {
10194:             foreach my $path (keys(%currsubfile)) {
10195:                 if (ref($currsubfile{$path}) eq 'HASH') {
10196:                     foreach my $file (keys(%{$currsubfile{$path}})) {
10197:                          unless ($subdependencies{$path}{$file}) {
10198:                              next if (($rem ne '') &&
10199:                                       (($env{"httpref.$rem"."$path/$file"} ne '') ||
10200:                                        (ref($navmap) &&
10201:                                        (($navmap->getResourceByUrl($rem."$path/$file") ne '') ||
10202:                                         (($file =~ /^(.*\.s?html?)\.bak$/i) &&
10203:                                          ($navmap->getResourceByUrl($rem."$path/$1")))))));
10204:                              $unused{$path.'/'.$file} = 1; 
10205:                          }
10206:                     }
10207:                 }
10208:             }
10209:         }
10210:     }
10211:     my %currfile;
10212:     if (($actionurl eq '/adm/portfolio') ||
10213:         ($actionurl eq '/adm/coursegrp_portfolio')) {
10214:         my ($dirlistref,$listerror) =
10215:             &Apache::lonnet::dirlist($url,$udom,$uname,$getpropath);
10216:         if (ref($dirlistref) eq 'ARRAY') {
10217:             foreach my $line (@{$dirlistref}) {
10218:                 my ($file_name,$rest) = split(/\&/,$line,2);
10219:                 $currfile{$file_name} = 1;
10220:             }
10221:         }
10222:     } elsif (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank')) {
10223:         if (opendir(my $dir,$url)) {
10224:             my @dir_list = grep(!/^\./,readdir($dir));
10225:             map {$currfile{$_} = 1;} @dir_list;
10226:         }
10227:     } elsif (($actionurl eq '/adm/dependencies') ||
10228:              (($actionurl eq '/adm/coursedocs') && (ref($args) eq 'HASH') &&
10229:               ($args->{'context'} eq 'paste')) ||
10230:              ($actionurl eq "/public/$cdom/$cnum/syllabus")) {
10231:         if ($env{'request.course.id'} ne '') {
10232:             my ($dir) = ($fileloc =~ m{^(.+/)[^/]+$});
10233:             if ($dir ne '') {
10234:                 my ($dirlistref,$listerror) =
10235:                     &Apache::lonnet::dirlist($dir,$cdom,$cnum,$getpropath,undef,'/');
10236:                 if (ref($dirlistref) eq 'ARRAY') {
10237:                     foreach my $line (@{$dirlistref}) {
10238:                         my ($file_name,$dom,undef,$testdir,undef,undef,undef,undef,
10239:                             $size,undef,$mtime)=split(/\&/,$line,12);
10240:                         unless (($testdir&$dirptr) ||
10241:                                 ($file_name =~ /^\.\.?$/)) {
10242:                             $currfile{$file_name} = [$size,$mtime];
10243:                         }
10244:                     }
10245:                 }
10246:             }
10247:         }
10248:     }
10249:     foreach my $file (keys(%dependencies)) {
10250:         if (exists($currfile{$file})) {
10251:             unless ($mapping{$file} eq $file) {
10252:                 $pathchanges{$file} = 1;
10253:             }
10254:             $existing{$file} = 1;
10255:             $numexisting ++;
10256:         } else {
10257:             $newfiles{$file} = 1;
10258:         }
10259:     }
10260:     foreach my $file (keys(%currfile)) {
10261:         unless (($file eq $filename) ||
10262:                 ($file eq $filename.'.bak') ||
10263:                 ($dependencies{$file})) {
10264:             if ($actionurl eq '/adm/dependencies') {
10265:                 unless ($toplevel =~ m{^\Q/uploaded/$cdom/$cnum/portfolio/syllabus\E}) {
10266:                     next if (($rem ne '') &&
10267:                              (($env{"httpref.$rem".$file} ne '') ||
10268:                               (ref($navmap) &&
10269:                               (($navmap->getResourceByUrl($rem.$file) ne '') ||
10270:                                (($file =~ /^(.*\.s?html?)\.bak$/i) &&
10271:                                 ($navmap->getResourceByUrl($rem.$1)))))));
10272:                 }
10273:             }
10274:             $unused{$file} = 1;
10275:         }
10276:     }
10277:     if (($actionurl eq '/adm/coursedocs') && (ref($args) eq 'HASH') &&
10278:         ($args->{'context'} eq 'paste')) {
10279:         $counter = scalar(keys(%existing));
10280:         $numpathchg = scalar(keys(%pathchanges));
10281:         return ($output,$counter,$numpathchg,\%existing);
10282:     } elsif (($actionurl eq "/public/$cdom/$cnum/syllabus") &&
10283:              (ref($args) eq 'HASH') && ($args->{'context'} eq 'rewrites')) {
10284:         $counter = scalar(keys(%existing));
10285:         $numpathchg = scalar(keys(%pathchanges));
10286:         return ($output,$counter,$numpathchg,\%existing,\%mapping);
10287:     }
10288:     foreach my $embed_file (sort {lc($a) cmp lc($b)} keys(%newfiles)) {
10289:         if ($actionurl eq '/adm/dependencies') {
10290:             next if ($embed_file =~ m{^\w+://});
10291:         }
10292:         $upload_output .= &start_data_table_row().
10293:                           '<td valign="top"><img src="'.&icon($embed_file).'" />&nbsp;'.
10294:                           '<span class="LC_filename">'.$embed_file.'</span>';
10295:         unless ($mapping{$embed_file} eq $embed_file) {
10296:             $upload_output .= '<br /><span class="LC_info" style="font-size:smaller;">'.
10297:                               &mt('changed from: [_1]',$mapping{$embed_file}).'</span>';
10298:         }
10299:         $upload_output .= '</td>';
10300:         if ($args->{'ignore_remote_references'} && $embed_file =~ m{^\w+://}) { 
10301:             $upload_output.='<td align="right">'.
10302:                             '<span class="LC_info LC_fontsize_medium">'.
10303:                             &mt("URL points to web address").'</span>';
10304:             $numremref++;
10305:         } elsif ($args->{'error_on_invalid_names'}
10306:             && $embed_file ne &Apache::lonnet::clean_filename($embed_file,{'keep_path' => 1,})) {
10307:             $upload_output.='<td align="right"><span class="LC_warning">'.
10308:                             &mt('Invalid characters').'</span>';
10309:             $numinvalid++;
10310:         } else {
10311:             $upload_output .= '<td>'.
10312:                               &embedded_file_element('upload_embedded',$counter,
10313:                                                      $embed_file,\%mapping,
10314:                                                      $allfiles,$codebase,'upload');
10315:             $counter ++;
10316:             $numnew ++;
10317:         }
10318:         $upload_output .= '</td>'.&Apache::loncommon::end_data_table_row()."\n";
10319:     }
10320:     foreach my $embed_file (sort {lc($a) cmp lc($b)} keys(%existing)) {
10321:         if ($actionurl eq '/adm/dependencies') {
10322:             my ($size,$mtime) = &get_dependency_details(\%currfile,\%currsubfile,$embed_file);
10323:             $modify_output .= &start_data_table_row().
10324:                               '<td><a href="'.$path.'/'.$embed_file.'" style="text-decoration:none;">'.
10325:                               '<img src="'.&icon($embed_file).'" border="0" />'.
10326:                               '&nbsp;<span class="LC_filename">'.$embed_file.'</span></a></td>'.
10327:                               '<td>'.$size.'</td>'.
10328:                               '<td>'.$mtime.'</td>'.
10329:                               '<td><label><input type="checkbox" name="mod_upload_dep" '.
10330:                               'onclick="toggleBrowse('."'$counter'".')" id="mod_upload_dep_'.
10331:                               $counter.'" value="'.$counter.'" />'.&mt('Yes').'</label>'.
10332:                               '<div id="moduploaddep_'.$counter.'" style="display:none;">'.
10333:                               &embedded_file_element('upload_embedded',$counter,
10334:                                                      $embed_file,\%mapping,
10335:                                                      $allfiles,$codebase,'modify').
10336:                               '</div></td>'.
10337:                               &end_data_table_row()."\n";
10338:             $counter ++;
10339:         } else {
10340:             $upload_output .= &start_data_table_row().
10341:                               '<td valign="top"><img src="'.&icon($embed_file).'" />&nbsp;'.
10342:                               '<span class="LC_filename">'.$embed_file.'</span></td>'.
10343:                               '<td align="right"><span class="LC_info LC_fontsize_medium">'.&mt('Already exists').'</span></td>'.
10344:                               &Apache::loncommon::end_data_table_row()."\n";
10345:         }
10346:     }
10347:     my $delidx = $counter;
10348:     foreach my $oldfile (sort {lc($a) cmp lc($b)} keys(%unused)) {
10349:         my ($size,$mtime) = &get_dependency_details(\%currfile,\%currsubfile,$oldfile);
10350:         $delete_output .= &start_data_table_row().
10351:                           '<td><img src="'.&icon($oldfile).'" />'.
10352:                           '&nbsp;<span class="LC_filename">'.$oldfile.'</span></td>'.
10353:                           '<td>'.$size.'</td>'.
10354:                           '<td>'.$mtime.'</td>'.
10355:                           '<td><label><input type="checkbox" name="del_upload_dep" '.
10356:                           ' value="'.$delidx.'" />'.&mt('Yes').'</label>'.
10357:                           &embedded_file_element('upload_embedded',$delidx,
10358:                                                  $oldfile,\%mapping,$allfiles,
10359:                                                  $codebase,'delete').'</td>'.
10360:                           &end_data_table_row()."\n"; 
10361:         $numunused ++;
10362:         $delidx ++;
10363:     }
10364:     if ($upload_output) {
10365:         $upload_output = &start_data_table().
10366:                          $upload_output.
10367:                          &end_data_table()."\n";
10368:     }
10369:     if ($modify_output) {
10370:         $modify_output = &start_data_table().
10371:                          &start_data_table_header_row().
10372:                          '<th>'.&mt('File').'</th>'.
10373:                          '<th>'.&mt('Size (KB)').'</th>'.
10374:                          '<th>'.&mt('Modified').'</th>'.
10375:                          '<th>'.&mt('Upload replacement?').'</th>'.
10376:                          &end_data_table_header_row().
10377:                          $modify_output.
10378:                          &end_data_table()."\n";
10379:     }
10380:     if ($delete_output) {
10381:         $delete_output = &start_data_table().
10382:                          &start_data_table_header_row().
10383:                          '<th>'.&mt('File').'</th>'.
10384:                          '<th>'.&mt('Size (KB)').'</th>'.
10385:                          '<th>'.&mt('Modified').'</th>'.
10386:                          '<th>'.&mt('Delete?').'</th>'.
10387:                          &end_data_table_header_row().
10388:                          $delete_output.
10389:                          &end_data_table()."\n";
10390:     }
10391:     my $applies = 0;
10392:     if ($numremref) {
10393:         $applies ++;
10394:     }
10395:     if ($numinvalid) {
10396:         $applies ++;
10397:     }
10398:     if ($numexisting) {
10399:         $applies ++;
10400:     }
10401:     if ($counter || $numunused) {
10402:         $output = '<form name="upload_embedded" action="'.$actionurl.'"'.
10403:                   ' method="post" enctype="multipart/form-data">'."\n".
10404:                   $state.'<h3>'.$heading.'</h3>'; 
10405:         if ($actionurl eq '/adm/dependencies') {
10406:             if ($numnew) {
10407:                 $output .= '<h4>'.&mt('Missing dependencies').'</h4>'.
10408:                            '<p>'.&mt('The following files need to be uploaded.').'</p>'."\n".
10409:                            $upload_output.'<br />'."\n";
10410:             }
10411:             if ($numexisting) {
10412:                 $output .= '<h4>'.&mt('Uploaded dependencies (in use)').'</h4>'.
10413:                            '<p>'.&mt('Upload a new file to replace the one currently in use.').'</p>'."\n".
10414:                            $modify_output.'<br />'."\n";
10415:                            $buttontext = &mt('Save changes');
10416:             }
10417:             if ($numunused) {
10418:                 $output .= '<h4>'.&mt('Unused files').'</h4>'.
10419:                            '<p>'.&mt('The following uploaded files are no longer used.').'</p>'."\n".
10420:                            $delete_output.'<br />'."\n";
10421:                            $buttontext = &mt('Save changes');
10422:             }
10423:         } else {
10424:             $output .= $upload_output.'<br />'."\n";
10425:         }
10426:         $output .= '<input type ="hidden" name="number_embedded_items" value="'.
10427:                    $counter.'" />'."\n";
10428:         if ($actionurl eq '/adm/dependencies') { 
10429:             $output .= '<input type ="hidden" name="number_newemb_items" value="'.
10430:                        $numnew.'" />'."\n";
10431:         } elsif ($actionurl eq '') {
10432:             $output .=  '<input type="hidden" name="phase" value="three" />';
10433:         }
10434:     } elsif ($applies) {
10435:         $output = '<b>'.&mt('Referenced files').'</b>:<br />';
10436:         if ($applies > 1) {
10437:             $output .=  
10438:                 &mt('No dependencies need to be uploaded, as one of the following applies to each reference:').'<ul>';
10439:             if ($numremref) {
10440:                 $output .= '<li>'.&mt('reference is to a URL which points to another server').'</li>'."\n";
10441:             }
10442:             if ($numinvalid) {
10443:                 $output .= '<li>'.&mt('reference is to file with a name containing invalid characters').'</li>'."\n";
10444:             }
10445:             if ($numexisting) {
10446:                 $output .= '<li>'.&mt('reference is to an existing file at the specified location').'</li>'."\n";
10447:             }
10448:             $output .= '</ul><br />';
10449:         } elsif ($numremref) {
10450:             $output .= '<p>'.&mt('None to upload, as all references are to URLs pointing to another server.').'</p>';
10451:         } elsif ($numinvalid) {
10452:             $output .= '<p>'.&mt('None to upload, as all references are to files with names containing invalid characters.').'</p>';
10453:         } elsif ($numexisting) {
10454:             $output .= '<p>'.&mt('None to upload, as all references are to existing files.').'</p>';
10455:         }
10456:         $output .= $upload_output.'<br />';
10457:     }
10458:     my ($pathchange_output,$chgcount);
10459:     $chgcount = $counter;
10460:     if (keys(%pathchanges) > 0) {
10461:         foreach my $embed_file (sort {lc($a) cmp lc($b)} keys(%pathchanges)) {
10462:             if ($counter) {
10463:                 $output .= &embedded_file_element('pathchange',$chgcount,
10464:                                                   $embed_file,\%mapping,
10465:                                                   $allfiles,$codebase,'change');
10466:             } else {
10467:                 $pathchange_output .= 
10468:                     &start_data_table_row().
10469:                     '<td><input type ="checkbox" name="namechange" value="'.
10470:                     $chgcount.'" checked="checked" /></td>'.
10471:                     '<td>'.$mapping{$embed_file}.'</td>'.
10472:                     '<td>'.$embed_file.
10473:                     &embedded_file_element('pathchange',$numpathchg,$embed_file,
10474:                                            \%mapping,$allfiles,$codebase,'change').
10475:                     '</td>'.&end_data_table_row();
10476:             }
10477:             $numpathchg ++;
10478:             $chgcount ++;
10479:         }
10480:     }
10481:     if (($counter) || ($numunused)) {
10482:         if ($numpathchg) {
10483:             $output .= '<input type ="hidden" name="number_pathchange_items" value="'.
10484:                        $numpathchg.'" />'."\n";
10485:         }
10486:         if (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank') || 
10487:             ($actionurl eq '/adm/imsimport')) {
10488:             $output .= '<input type="hidden" name="phase" value="three" />'."\n";
10489:         } elsif ($actionurl eq '/adm/portfolio' || $actionurl eq '/adm/coursegrp_portfolio') {
10490:             $output .= '<input type="hidden" name="action" value="upload_embedded" />';
10491:         } elsif ($actionurl eq '/adm/dependencies') {
10492:             $output .= '<input type="hidden" name="action" value="process_changes" />';
10493:         }
10494:         $output .= '<input type ="submit" value="'.$buttontext.'" />'."\n".'</form>'."\n";
10495:     } elsif ($numpathchg) {
10496:         my %pathchange = ();
10497:         $output .= &modify_html_form('pathchange',$actionurl,$state,\%pathchange,$pathchange_output);
10498:         if (($actionurl eq '/adm/portfolio') || ($actionurl eq '/adm/coursegrp_portfolio')) {
10499:             $output .= '<p>'.&mt('or').'</p>'; 
10500:         }
10501:     }
10502:     return ($output,$counter,$numpathchg);
10503: }
10504: 
10505: =pod
10506: 
10507: =item * clean_path($name)
10508: 
10509: Performs clean-up of directories, subdirectories and filename in an
10510: embedded object, referenced in an HTML file which is being uploaded
10511: to a course or portfolio, where
10512: "Upload embedded images/multimedia files if HTML file" checkbox was
10513: checked.
10514: 
10515: Clean-up is similar to replacements in lonnet::clean_filename()
10516: except each / between sub-directory and next level is preserved.
10517: 
10518: =cut
10519: 
10520: sub clean_path {
10521:     my ($embed_file) = @_;
10522:     $embed_file =~s{^/+}{};
10523:     my @contents;
10524:     if ($embed_file =~ m{/}) {
10525:         @contents = split(/\//,$embed_file);
10526:     } else {
10527:         @contents = ($embed_file);
10528:     }
10529:     my $lastidx = scalar(@contents)-1;
10530:     for (my $i=0; $i<=$lastidx; $i++) {
10531:         $contents[$i]=~s{\\}{/}g;
10532:         $contents[$i]=~s/\s+/\_/g;
10533:         $contents[$i]=~s{[^/\w\.\-]}{}g;
10534:         if ($i == $lastidx) {
10535:             $contents[$i]=~s/\.(\d+)(?=\.)/_$1/g;
10536:         }
10537:     }
10538:     if ($lastidx > 0) {
10539:         return join('/',@contents);
10540:     } else {
10541:         return $contents[0];
10542:     }
10543: }
10544: 
10545: sub embedded_file_element {
10546:     my ($context,$num,$embed_file,$mapping,$allfiles,$codebase,$type) = @_;
10547:     return unless ((ref($mapping) eq 'HASH') && (ref($allfiles) eq 'HASH') &&
10548:                    (ref($codebase) eq 'HASH'));
10549:     my $output;
10550:     if (($context eq 'upload_embedded') && ($type ne 'delete')) {
10551:        $output = '<input name="embedded_item_'.$num.'" type="file" value="" />'."\n";
10552:     }
10553:     $output .= '<input name="embedded_orig_'.$num.'" type="hidden" value="'.
10554:                &escape($embed_file).'" />';
10555:     unless (($context eq 'upload_embedded') && 
10556:             ($mapping->{$embed_file} eq $embed_file)) {
10557:         $output .='
10558:         <input name="embedded_ref_'.$num.'" type="hidden" value="'.&escape($mapping->{$embed_file}).'" />';
10559:     }
10560:     my $attrib;
10561:     if (ref($allfiles->{$mapping->{$embed_file}}) eq 'ARRAY') {
10562:         $attrib = &escape(join(':',@{$allfiles->{$mapping->{$embed_file}}}));
10563:     }
10564:     $output .=
10565:         "\n\t\t".
10566:         '<input name="embedded_attrib_'.$num.'" type="hidden" value="'.
10567:         $attrib.'" />';
10568:     if (exists($codebase->{$mapping->{$embed_file}})) {
10569:         $output .=
10570:             "\n\t\t".
10571:             '<input name="codebase_'.$num.'" type="hidden" value="'.
10572:             &escape($codebase->{$mapping->{$embed_file}}).'" />';
10573:     }
10574:     return $output;
10575: }
10576: 
10577: sub get_dependency_details {
10578:     my ($currfile,$currsubfile,$embed_file) = @_;
10579:     my ($size,$mtime,$showsize,$showmtime);
10580:     if ((ref($currfile) eq 'HASH') && (ref($currsubfile))) {
10581:         if ($embed_file =~ m{/}) {
10582:             my ($path,$fname) = split(/\//,$embed_file);
10583:             if (ref($currsubfile->{$path}{$fname}) eq 'ARRAY') {
10584:                 ($size,$mtime) = @{$currsubfile->{$path}{$fname}};
10585:             }
10586:         } else {
10587:             if (ref($currfile->{$embed_file}) eq 'ARRAY') {
10588:                 ($size,$mtime) = @{$currfile->{$embed_file}};
10589:             }
10590:         }
10591:         $showsize = $size/1024.0;
10592:         $showsize = sprintf("%.1f",$showsize);
10593:         if ($mtime > 0) {
10594:             $showmtime = &Apache::lonlocal::locallocaltime($mtime);
10595:         }
10596:     }
10597:     return ($showsize,$showmtime);
10598: }
10599: 
10600: sub ask_embedded_js {
10601:     return <<"END";
10602: <script type="text/javascript"">
10603: // <![CDATA[
10604: function toggleBrowse(counter) {
10605:     var chkboxid = document.getElementById('mod_upload_dep_'+counter);
10606:     var fileid = document.getElementById('embedded_item_'+counter);
10607:     var uploaddivid = document.getElementById('moduploaddep_'+counter);
10608:     if (chkboxid.checked == true) {
10609:         uploaddivid.style.display='block';
10610:     } else {
10611:         uploaddivid.style.display='none';
10612:         fileid.value = '';
10613:     }
10614: }
10615: // ]]>
10616: </script>
10617: 
10618: END
10619: }
10620: 
10621: sub upload_embedded {
10622:     my ($context,$dirpath,$uname,$udom,$dir_root,$url_root,$group,$disk_quota,
10623:         $current_disk_usage,$hiddenstate,$actionurl) = @_;
10624:     my (%pathchange,$output,$modifyform,$footer,$returnflag);
10625:     for (my $i=0; $i<$env{'form.number_embedded_items'}; $i++) {
10626:         next if (!exists($env{'form.embedded_item_'.$i.'.filename'}));
10627:         my $orig_uploaded_filename =
10628:             $env{'form.embedded_item_'.$i.'.filename'};
10629:         foreach my $type ('orig','ref','attrib','codebase') {
10630:             if ($env{'form.embedded_'.$type.'_'.$i} ne '') {
10631:                 $env{'form.embedded_'.$type.'_'.$i} =
10632:                     &unescape($env{'form.embedded_'.$type.'_'.$i});
10633:             }
10634:         }
10635:         my ($path,$fname) =
10636:             ($env{'form.embedded_orig_'.$i} =~ m{(.*/)([^/]*)});
10637:         # no path, whole string is fname
10638:         if (!$fname) { $fname = $env{'form.embedded_orig_'.$i} };
10639:         $fname = &Apache::lonnet::clean_filename($fname);
10640:         # See if there is anything left
10641:         next if ($fname eq '');
10642: 
10643:         # Check if file already exists as a file or directory.
10644:         my ($state,$msg);
10645:         if ($context eq 'portfolio') {
10646:             my $port_path = $dirpath;
10647:             if ($group ne '') {
10648:                 $port_path = "groups/$group/$port_path";
10649:             }
10650:             ($state,$msg) = &check_for_upload($env{'form.currentpath'}.$path,
10651:                                               $fname,$group,'embedded_item_'.$i,
10652:                                               $dir_root,$port_path,$disk_quota,
10653:                                               $current_disk_usage,$uname,$udom);
10654:             if ($state eq 'will_exceed_quota'
10655:                 || $state eq 'file_locked') {
10656:                 $output .= $msg;
10657:                 next;
10658:             }
10659:         } elsif (($context eq 'author') || ($context eq 'testbank')) {
10660:             ($state,$msg) = &check_for_existing($path,$fname,'embedded_item_'.$i);
10661:             if ($state eq 'exists') {
10662:                 $output .= $msg;
10663:                 next;
10664:             }
10665:         }
10666:         # Check if extension is valid
10667:         if (($fname =~ /\.(\w+)$/) &&
10668:             (&Apache::loncommon::fileembstyle($1) eq 'hdn')) {
10669:             $output .= &mt('Invalid file extension ([_1]) - reserved for internal use.',$1)
10670:                       .' '.&mt('Rename the file with a different extension and re-upload.').'<br />';
10671:             next;
10672:         } elsif (($fname =~ /\.(\w+)$/) &&
10673:                  (!defined(&Apache::loncommon::fileembstyle($1)))) {
10674:             $output .= &mt('Unrecognized file extension ([_1]) - rename the file with a proper extension and re-upload.',$1).'<br />';
10675:             next;
10676:         } elsif ($fname=~/\.(\d+)\.(\w+)$/) {
10677:             $output .= &mt('Filename not allowed - rename the file to remove the number immediately before the file extension([_1]) and re-upload.',$2).'<br />';
10678:             next;
10679:         }
10680:         $env{'form.embedded_item_'.$i.'.filename'}=$fname;
10681:         my $subdir = $path;
10682:         $subdir =~ s{/+$}{};
10683:         if ($context eq 'portfolio') {
10684:             my $result;
10685:             if ($state eq 'existingfile') {
10686:                 $result=
10687:                     &Apache::lonnet::userfileupload('embedded_item_'.$i,'existingfile',
10688:                                                     $dirpath.$env{'form.currentpath'}.$subdir);
10689:             } else {
10690:                 $result=
10691:                     &Apache::lonnet::userfileupload('embedded_item_'.$i,'',
10692:                                                     $dirpath.
10693:                                                     $env{'form.currentpath'}.$subdir);
10694:                 if ($result !~ m|^/uploaded/|) {
10695:                     $output .= '<span class="LC_error">'
10696:                                .&mt('An error occurred ([_1]) while trying to upload [_2] for embedded element [_3].'
10697:                                ,$result,$orig_uploaded_filename,$env{'form.embedded_orig_'.$i})
10698:                                .'</span><br />';
10699:                     next;
10700:                 } else {
10701:                     $output .= &mt('Uploaded [_1]','<span class="LC_filename">'.
10702:                                $path.$fname.'</span>').'<br />';     
10703:                 }
10704:             }
10705:         } elsif (($context eq 'coursedoc') || ($context eq 'syllabus')) {
10706:             my $extendedsubdir = $dirpath.'/'.$subdir;
10707:             $extendedsubdir =~ s{/+$}{};
10708:             my $result =
10709:                 &Apache::lonnet::userfileupload('embedded_item_'.$i,$context,$extendedsubdir);
10710:             if ($result !~ m|^/uploaded/|) {
10711:                 $output .= '<span class="LC_error">'
10712:                            .&mt('An error occurred ([_1]) while trying to upload [_2] for embedded element [_3].'
10713:                            ,$result,$orig_uploaded_filename,$env{'form.embedded_orig_'.$i})
10714:                            .'</span><br />';
10715:                     next;
10716:             } else {
10717:                 $output .= &mt('Uploaded [_1]','<span class="LC_filename">'.
10718:                            $path.$fname.'</span>').'<br />';
10719:                 if ($context eq 'syllabus') {
10720:                     &Apache::lonnet::make_public_indefinitely($result);
10721:                 }
10722:             }
10723:         } else {
10724: # Save the file
10725:             my $target = $env{'form.embedded_item_'.$i};
10726:             my $fullpath = $dir_root.$dirpath.'/'.$path;
10727:             my $dest = $fullpath.$fname;
10728:             my $url = $url_root.$dirpath.'/'.$path.$fname;
10729:             my @parts=split(/\//,"$dirpath/$path");
10730:             my $count;
10731:             my $filepath = $dir_root;
10732:             foreach my $subdir (@parts) {
10733:                 $filepath .= "/$subdir";
10734:                 if (!-e $filepath) {
10735:                     mkdir($filepath,0770);
10736:                 }
10737:             }
10738:             my $fh;
10739:             if (!open($fh,'>'.$dest)) {
10740:                 &Apache::lonnet::logthis('Failed to create '.$dest);
10741:                 $output .= '<span class="LC_error">'.
10742:                            &mt('An error occurred while trying to upload [_1] for embedded element [_2].',
10743:                                $orig_uploaded_filename,$env{'form.embedded_orig_'.$i}).
10744:                            '</span><br />';
10745:             } else {
10746:                 if (!print $fh $env{'form.embedded_item_'.$i}) {
10747:                     &Apache::lonnet::logthis('Failed to write to '.$dest);
10748:                     $output .= '<span class="LC_error">'.
10749:                               &mt('An error occurred while writing the file [_1] for embedded element [_2].',
10750:                                   $orig_uploaded_filename,$env{'form.embedded_orig_'.$i}).
10751:                               '</span><br />';
10752:                 } else {
10753:                     $output .= &mt('Uploaded [_1]','<span class="LC_filename">'.
10754:                                $url.'</span>').'<br />';
10755:                     unless ($context eq 'testbank') {
10756:                         $footer .= &mt('View embedded file: [_1]',
10757:                                        '<a href="'.$url.'">'.$fname.'</a>').'<br />';
10758:                     }
10759:                 }
10760:                 close($fh);
10761:             }
10762:         }
10763:         if ($env{'form.embedded_ref_'.$i}) {
10764:             $pathchange{$i} = 1;
10765:         }
10766:     }
10767:     if ($output) {
10768:         $output = '<p>'.$output.'</p>';
10769:     }
10770:     $output .= &modify_html_form('upload_embedded',$actionurl,$hiddenstate,\%pathchange);
10771:     $returnflag = 'ok';
10772:     my $numpathchgs = scalar(keys(%pathchange));
10773:     if ($numpathchgs > 0) {
10774:         if ($context eq 'portfolio') {
10775:             $output .= '<p>'.&mt('or').'</p>';
10776:         } elsif ($context eq 'testbank') {
10777:             $output .=  '<p>'.&mt('Or [_1]continue[_2] the testbank import without modifying the reference(s).',
10778:                                   '<a href="javascript:document.testbankForm.submit();">','</a>').'</p>';
10779:             $returnflag = 'modify_orightml';
10780:         }
10781:     }
10782:     return ($output.$footer,$returnflag,$numpathchgs);
10783: }
10784: 
10785: sub modify_html_form {
10786:     my ($context,$actionurl,$hiddenstate,$pathchange,$pathchgtable) = @_;
10787:     my $end = 0;
10788:     my $modifyform;
10789:     if ($context eq 'upload_embedded') {
10790:         return unless (ref($pathchange) eq 'HASH');
10791:         if ($env{'form.number_embedded_items'}) {
10792:             $end += $env{'form.number_embedded_items'};
10793:         }
10794:         if ($env{'form.number_pathchange_items'}) {
10795:             $end += $env{'form.number_pathchange_items'};
10796:         }
10797:         if ($end) {
10798:             for (my $i=0; $i<$end; $i++) {
10799:                 if ($i < $env{'form.number_embedded_items'}) {
10800:                     next unless($pathchange->{$i});
10801:                 }
10802:                 $modifyform .=
10803:                     &start_data_table_row().
10804:                     '<td><input type ="checkbox" name="namechange" value="'.$i.'" '.
10805:                     'checked="checked" /></td>'.
10806:                     '<td>'.$env{'form.embedded_ref_'.$i}.
10807:                     '<input type="hidden" name="embedded_ref_'.$i.'" value="'.
10808:                     &escape($env{'form.embedded_ref_'.$i}).'" />'.
10809:                     '<input type="hidden" name="embedded_codebase_'.$i.'" value="'.
10810:                     &escape($env{'form.embedded_codebase_'.$i}).'" />'.
10811:                     '<input type="hidden" name="embedded_attrib_'.$i.'" value="'.
10812:                     &escape($env{'form.embedded_attrib_'.$i}).'" /></td>'.
10813:                     '<td>'.$env{'form.embedded_orig_'.$i}.
10814:                     '<input type="hidden" name="embedded_orig_'.$i.'" value="'.
10815:                     &escape($env{'form.embedded_orig_'.$i}).'" /></td>'.
10816:                     &end_data_table_row();
10817:             }
10818:         }
10819:     } else {
10820:         $modifyform = $pathchgtable;
10821:         if (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank')) {
10822:             $hiddenstate .= '<input type="hidden" name="phase" value="four" />';
10823:         } elsif (($actionurl eq '/adm/portfolio') || ($actionurl eq '/adm/coursegrp_portfolio')) {
10824:             $hiddenstate .= '<input type="hidden" name="action" value="modify_orightml" />';
10825:         }
10826:     }
10827:     if ($modifyform) {
10828:         if ($actionurl eq '/adm/dependencies') {
10829:             $hiddenstate .= '<input type="hidden" name="action" value="modifyhrefs" />';
10830:         }
10831:         return '<h3>'.&mt('Changes in content of HTML file required').'</h3>'."\n".
10832:                '<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".
10833:                '<li>'.&mt('For consistency between the reference(s) and the location of the corresponding stored file within LON-CAPA.').'</li>'."\n".
10834:                '<li>'.&mt('To change absolute paths to relative paths, or replace directory traversal via "../" within the original reference.').'</li>'."\n".
10835:                '</ol></p>'."\n".'<p>'.
10836:                &mt('LON-CAPA can make the required changes to your HTML file.').'</p>'."\n".
10837:                '<form method="post" name="refchanger" action="'.$actionurl.'">'.
10838:                &start_data_table()."\n".
10839:                &start_data_table_header_row().
10840:                '<th>'.&mt('Change?').'</th>'.
10841:                '<th>'.&mt('Current reference').'</th>'.
10842:                '<th>'.&mt('Required reference').'</th>'.
10843:                &end_data_table_header_row()."\n".
10844:                $modifyform.
10845:                &end_data_table().'<br />'."\n".$hiddenstate.
10846:                '<input type="submit" name="pathchanges" value="'.&mt('Modify HTML file').'" />'.
10847:                '</form>'."\n";
10848:     }
10849:     return;
10850: }
10851: 
10852: sub modify_html_refs {
10853:     my ($context,$dirpath,$uname,$udom,$dir_root,$url) = @_;
10854:     my $container;
10855:     if ($context eq 'portfolio') {
10856:         $container = $env{'form.container'};
10857:     } elsif ($context eq 'coursedoc') {
10858:         $container = $env{'form.primaryurl'};
10859:     } elsif ($context eq 'manage_dependencies') {
10860:         (undef,undef,$container) = &Apache::lonnet::decode_symb($env{'form.symb'});
10861:         $container = "/$container";
10862:     } elsif ($context eq 'syllabus') {
10863:         $container = $url;
10864:     } else {
10865:         $container = $Apache::lonnet::perlvar{'lonDocRoot'}.$env{'form.filename'};
10866:     }
10867:     my (%allfiles,%codebase,$output,$content);
10868:     my @changes = &get_env_multiple('form.namechange');
10869:     unless ((@changes > 0)  || ($context eq 'syllabus')) {
10870:         if (wantarray) {
10871:             return ('',0,0); 
10872:         } else {
10873:             return;
10874:         }
10875:     }
10876:     if (($context eq 'portfolio') || ($context eq 'coursedoc') || 
10877:         ($context eq 'manage_dependencies') || ($context eq 'syllabus')) {
10878:         unless ($container =~ m{^/uploaded/\Q$udom\E/\Q$uname\E/}) {
10879:             if (wantarray) {
10880:                 return ('',0,0);
10881:             } else {
10882:                 return;
10883:             }
10884:         } 
10885:         $content = &Apache::lonnet::getfile($container);
10886:         if ($content eq '-1') {
10887:             if (wantarray) {
10888:                 return ('',0,0);
10889:             } else {
10890:                 return;
10891:             }
10892:         }
10893:     } else {
10894:         unless ($container =~ /^\Q$dir_root\E/) {
10895:             if (wantarray) {
10896:                 return ('',0,0);
10897:             } else {
10898:                 return;
10899:             }
10900:         } 
10901:         if (open(my $fh,"<$container")) {
10902:             $content = join('', <$fh>);
10903:             close($fh);
10904:         } else {
10905:             if (wantarray) {
10906:                 return ('',0,0);
10907:             } else {
10908:                 return;
10909:             }
10910:         }
10911:     }
10912:     my ($count,$codebasecount) = (0,0);
10913:     my $mm = new File::MMagic;
10914:     my $mime_type = $mm->checktype_contents($content);
10915:     if ($mime_type eq 'text/html') {
10916:         my $parse_result = 
10917:             &Apache::lonnet::extract_embedded_items($container,\%allfiles,
10918:                                                     \%codebase,\$content);
10919:         if ($parse_result eq 'ok') {
10920:             foreach my $i (@changes) {
10921:                 my $orig = &unescape($env{'form.embedded_orig_'.$i});
10922:                 my $ref = &unescape($env{'form.embedded_ref_'.$i});
10923:                 if ($allfiles{$ref}) {
10924:                     my $newname =  $orig;
10925:                     my ($attrib_regexp,$codebase);
10926:                     $attrib_regexp = &unescape($env{'form.embedded_attrib_'.$i});
10927:                     if ($attrib_regexp =~ /:/) {
10928:                         $attrib_regexp =~ s/\:/|/g;
10929:                     }
10930:                     if ($content =~ m{($attrib_regexp\s*=\s*['"]?)\Q$ref\E(['"]?)}) {
10931:                         my $numchg = ($content =~ s{($attrib_regexp\s*=\s*['"]?)\Q$ref\E(['"]?)}{$1$newname$2}gi);
10932:                         $count += $numchg;
10933:                         $allfiles{$newname} = $allfiles{$ref};
10934:                         delete($allfiles{$ref});
10935:                     }
10936:                     if ($env{'form.embedded_codebase_'.$i} ne '') {
10937:                         $codebase = &unescape($env{'form.embedded_codebase_'.$i});
10938:                         my $numchg = ($content =~ s/(codebase\s*=\s*["']?)\Q$codebase\E(["']?)/$1.$2/i); #' stupid emacs
10939:                         $codebasecount ++;
10940:                     }
10941:                 }
10942:             }
10943:             my $skiprewrites;
10944:             if ($count || $codebasecount) {
10945:                 my $saveresult;
10946:                 if (($context eq 'portfolio') || ($context eq 'coursedoc') || 
10947:                     ($context eq 'manage_dependencies') || ($context eq 'syllabus')) {
10948:                     my $url = &Apache::lonnet::store_edited_file($container,$content,$udom,$uname,\$saveresult);
10949:                     if ($url eq $container) {
10950:                         my ($fname) = ($container =~ m{/([^/]+)$});
10951:                         $output = '<p>'.&mt('Updated [quant,_1,reference] in [_2].',
10952:                                             $count,'<span class="LC_filename">'.
10953:                                             $fname.'</span>').'</p>';
10954:                     } else {
10955:                          $output = '<p class="LC_error">'.
10956:                                    &mt('Error: update failed for: [_1].',
10957:                                    '<span class="LC_filename">'.
10958:                                    $container.'</span>').'</p>';
10959:                     }
10960:                     if ($context eq 'syllabus') {
10961:                         unless ($saveresult eq 'ok') {
10962:                             $skiprewrites = 1;
10963:                         }
10964:                     }
10965:                 } else {
10966:                     if (open(my $fh,">$container")) {
10967:                         print $fh $content;
10968:                         close($fh);
10969:                         $output = '<p>'.&mt('Updated [quant,_1,reference] in [_2].',
10970:                                   $count,'<span class="LC_filename">'.
10971:                                   $container.'</span>').'</p>';
10972:                     } else {
10973:                          $output = '<p class="LC_error">'.
10974:                                    &mt('Error: could not update [_1].',
10975:                                    '<span class="LC_filename">'.
10976:                                    $container.'</span>').'</p>';
10977:                     }
10978:                 }
10979:             }
10980:             if (($context eq 'syllabus') && (!$skiprewrites)) {
10981:                 my ($actionurl,$state);
10982:                 $actionurl = "/public/$udom/$uname/syllabus";
10983:                 my ($ignore,$num,$numpathchanges,$existing,$mapping) =
10984:                     &ask_for_embedded_content($actionurl,$state,\%allfiles,
10985:                                               \%codebase,
10986:                                               {'context' => 'rewrites',
10987:                                                'ignore_remote_references' => 1,});
10988:                 if (ref($mapping) eq 'HASH') {
10989:                     my $rewrites = 0;
10990:                     foreach my $key (keys(%{$mapping})) {
10991:                         next if ($key =~ m{^https?://});
10992:                         my $ref = $mapping->{$key};
10993:                         my $newname = "/uploaded/$udom/$uname/portfolio/syllabus/$key";
10994:                         my $attrib;
10995:                         if (ref($allfiles{$mapping->{$key}}) eq 'ARRAY') {
10996:                             $attrib = join('|',@{$allfiles{$mapping->{$key}}});
10997:                         }
10998:                         if ($content =~ m{($attrib\s*=\s*['"]?)\Q$ref\E(['"]?)}) {
10999:                             my $numchg = ($content =~ s{($attrib\s*=\s*['"]?)\Q$ref\E(['"]?)}{$1$newname$2}gi);
11000:                             $rewrites += $numchg;
11001:                         }
11002:                     }
11003:                     if ($rewrites) {
11004:                         my $saveresult;
11005:                         my $url = &Apache::lonnet::store_edited_file($container,$content,$udom,$uname,\$saveresult);
11006:                         if ($url eq $container) {
11007:                             my ($fname) = ($container =~ m{/([^/]+)$});
11008:                             $output .= '<p>'.&mt('Rewrote [quant,_1,link] as [quant,_1,absolute link] in [_2].',
11009:                                             $count,'<span class="LC_filename">'.
11010:                                             $fname.'</span>').'</p>';
11011:                         } else {
11012:                             $output .= '<p class="LC_error">'.
11013:                                        &mt('Error: could not update links in [_1].',
11014:                                        '<span class="LC_filename">'.
11015:                                        $container.'</span>').'</p>';
11016: 
11017:                         }
11018:                     }
11019:                 }
11020:             }
11021:         } else {
11022:             &logthis('Failed to parse '.$container.
11023:                      ' to modify references: '.$parse_result);
11024:         }
11025:     }
11026:     if (wantarray) {
11027:         return ($output,$count,$codebasecount);
11028:     } else {
11029:         return $output;
11030:     }
11031: }
11032: 
11033: sub check_for_existing {
11034:     my ($path,$fname,$element) = @_;
11035:     my ($state,$msg);
11036:     if (-d $path.'/'.$fname) {
11037:         $state = 'exists';
11038:         $msg = &mt('Unable to upload [_1]. A directory by that name was found in [_2].','<span class="LC_filename">'.$fname.'</span>',$path);
11039:     } elsif (-e $path.'/'.$fname) {
11040:         $state = 'exists';
11041:         $msg = &mt('Unable to upload [_1]. A file by that name was found in [_2].','<span class="LC_filename">'.$fname.'</span>',$path);
11042:     }
11043:     if ($state eq 'exists') {
11044:         $msg = '<span class="LC_error">'.$msg.'</span><br />';
11045:     }
11046:     return ($state,$msg);
11047: }
11048: 
11049: sub check_for_upload {
11050:     my ($path,$fname,$group,$element,$portfolio_root,$port_path,
11051:         $disk_quota,$current_disk_usage,$uname,$udom) = @_;
11052:     my $filesize = length($env{'form.'.$element});
11053:     if (!$filesize) {
11054:         my $msg = '<span class="LC_error">'.
11055:                   &mt('Unable to upload [_1]. (size = [_2] bytes)', 
11056:                       '<span class="LC_filename">'.$fname.'</span>',
11057:                       $filesize).'<br />'.
11058:                   &mt('Either the file you attempted to upload was empty, or your web browser was unable to read its contents.').'<br />'.
11059:                   '</span>';
11060:         return ('zero_bytes',$msg);
11061:     }
11062:     $filesize =  $filesize/1000; #express in k (1024?)
11063:     my $getpropath = 1;
11064:     my ($dirlistref,$listerror) =
11065:          &Apache::lonnet::dirlist($portfolio_root.$path,$udom,$uname,$getpropath);
11066:     my $found_file = 0;
11067:     my $locked_file = 0;
11068:     my @lockers;
11069:     my $navmap;
11070:     if ($env{'request.course.id'}) {
11071:         $navmap = Apache::lonnavmaps::navmap->new();
11072:     }
11073:     if (ref($dirlistref) eq 'ARRAY') {
11074:         foreach my $line (@{$dirlistref}) {
11075:             my ($file_name,$rest)=split(/\&/,$line,2);
11076:             if ($file_name eq $fname){
11077:                 $file_name = $path.$file_name;
11078:                 if ($group ne '') {
11079:                     $file_name = $group.$file_name;
11080:                 }
11081:                 $found_file = 1;
11082:                 if (&Apache::lonnet::is_locked($file_name,$udom,$uname,\@lockers) eq 'true') {
11083:                     foreach my $lock (@lockers) {
11084:                         if (ref($lock) eq 'ARRAY') {
11085:                             my ($symb,$crsid) = @{$lock};
11086:                             if ($crsid eq $env{'request.course.id'}) {
11087:                                 if (ref($navmap)) {
11088:                                     my $res = $navmap->getBySymb($symb);
11089:                                     foreach my $part (@{$res->parts()}) { 
11090:                                         my ($slot_status,$slot_time,$slot_name)=$res->check_for_slot($part);
11091:                                         unless (($slot_status == $res->RESERVED) ||
11092:                                                 ($slot_status == $res->RESERVED_LOCATION)) {
11093:                                             $locked_file = 1;
11094:                                         }
11095:                                     }
11096:                                 } else {
11097:                                     $locked_file = 1;
11098:                                 }
11099:                             } else {
11100:                                 $locked_file = 1;
11101:                             }
11102:                         }
11103:                    }
11104:                 } else {
11105:                     my @info = split(/\&/,$rest);
11106:                     my $currsize = $info[6]/1000;
11107:                     if ($currsize < $filesize) {
11108:                         my $extra = $filesize - $currsize;
11109:                         if (($current_disk_usage + $extra) > $disk_quota) {
11110:                             my $msg = '<p class="LC_warning">'.
11111:                                       &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.',
11112:                                           '<span class="LC_filename">'.$fname.'</span>',$filesize,$currsize).'</p>'.
11113:                                       '<p>'.&mt('Disk quota is [_1] kilobytes. Your current disk usage is [_2] kilobytes.',
11114:                                                    $disk_quota,$current_disk_usage).'</p>';
11115:                             return ('will_exceed_quota',$msg);
11116:                         }
11117:                     }
11118:                 }
11119:             }
11120:         }
11121:     }
11122:     if (($current_disk_usage + $filesize) > $disk_quota){
11123:         my $msg = '<p class="LC_warning">'.
11124:                 &mt('Unable to upload [_1]. (size = [_2] kilobytes). Disk quota will be exceeded.','<span class="LC_filename">'.$fname.'</span>',$filesize).'</p>'.
11125:                   '<p>'.&mt('Disk quota is [_1] kilobytes. Your current disk usage is [_2] kilobytes.',$disk_quota,$current_disk_usage).'</p>';
11126:         return ('will_exceed_quota',$msg);
11127:     } elsif ($found_file) {
11128:         if ($locked_file) {
11129:             my $msg = '<p class="LC_warning">';
11130:             $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>');
11131:             $msg .= '</p>';
11132:             $msg .= &mt('You will be able to rename or delete existing [_1] after a grade has been assigned.','<span class="LC_filename">'.$fname.'</span>');
11133:             return ('file_locked',$msg);
11134:         } else {
11135:             my $msg = '<p class="LC_error">';
11136:             $msg .= &mt(' A file by that name: [_1] was found in [_2].','<span class="LC_filename">'.$fname.'</span>',$port_path.$env{'form.currentpath'});
11137:             $msg .= '</p>';
11138:             return ('existingfile',$msg);
11139:         }
11140:     }
11141: }
11142: 
11143: sub check_for_traversal {
11144:     my ($path,$url,$toplevel) = @_;
11145:     my @parts=split(/\//,$path);
11146:     my $cleanpath;
11147:     my $fullpath = $url;
11148:     for (my $i=0;$i<@parts;$i++) {
11149:         next if ($parts[$i] eq '.');
11150:         if ($parts[$i] eq '..') {
11151:             $fullpath =~ s{([^/]+/)$}{};
11152:         } else {
11153:             $fullpath .= $parts[$i].'/';
11154:         }
11155:     }
11156:     if ($fullpath =~ /^\Q$url\E(.*)$/) {
11157:         $cleanpath = $1;
11158:     } elsif ($fullpath =~ /^\Q$toplevel\E(.*)$/) {
11159:         my $curr_toprel = $1;
11160:         my @parts = split(/\//,$curr_toprel);
11161:         my ($url_toprel) = ($url =~ /^\Q$toplevel\E(.*)$/);
11162:         my @urlparts = split(/\//,$url_toprel);
11163:         my $doubledots;
11164:         my $startdiff = -1;
11165:         for (my $i=0; $i<@urlparts; $i++) {
11166:             if ($startdiff == -1) {
11167:                 unless ($urlparts[$i] eq $parts[$i]) {
11168:                     $startdiff = $i;
11169:                     $doubledots .= '../';
11170:                 }
11171:             } else {
11172:                 $doubledots .= '../';
11173:             }
11174:         }
11175:         if ($startdiff > -1) {
11176:             $cleanpath = $doubledots;
11177:             for (my $i=$startdiff; $i<@parts; $i++) {
11178:                 $cleanpath .= $parts[$i].'/';
11179:             }
11180:         }
11181:     }
11182:     $cleanpath =~ s{(/)$}{};
11183:     return $cleanpath;
11184: }
11185: 
11186: sub is_archive_file {
11187:     my ($mimetype) = @_;
11188:     if (($mimetype eq 'application/octet-stream') ||
11189:         ($mimetype eq 'application/x-stuffit') ||
11190:         ($mimetype =~ m{^application/(x\-)?(compressed|tar|zip|tgz|gz|gtar|gzip|gunzip|bz|bz2|bzip2)})) {
11191:         return 1;
11192:     }
11193:     return;
11194: }
11195: 
11196: sub decompress_form {
11197:     my ($mimetype,$archiveurl,$action,$noextract,$hiddenelements,$dirlist) = @_;
11198:     my %lt = &Apache::lonlocal::texthash (
11199:         this => 'This file is an archive file.',
11200:         camt => 'This file is a Camtasia archive file.',
11201:         itsc => 'Its contents are as follows:',
11202:         youm => 'You may wish to extract its contents.',
11203:         extr => 'Extract contents',
11204:         auto => 'LON-CAPA can process the files automatically, or you can decide how each should be handled.',
11205:         proa => 'Process automatically?',
11206:         yes  => 'Yes',
11207:         no   => 'No',
11208:         fold => 'Title for folder containing movie',
11209:         movi => 'Title for page containing embedded movie', 
11210:     );
11211:     my $fileloc = &Apache::lonnet::filelocation(undef,$archiveurl);
11212:     my ($is_camtasia,$topdir,%toplevel,@paths);
11213:     my $info = &list_archive_contents($fileloc,\@paths);
11214:     if (@paths) {
11215:         foreach my $path (@paths) {
11216:             $path =~ s{^/}{};
11217:             if ($path =~ m{^([^/]+)/$}) {
11218:                 $topdir = $1;
11219:             }
11220:             if ($path =~ m{^([^/]+)/}) {
11221:                 $toplevel{$1} = $path;
11222:             } else {
11223:                 $toplevel{$path} = $path;
11224:             }
11225:         }
11226:     }
11227:     if ($mimetype =~ m{^application/(x\-)?(compressed|zip)}) {
11228:         my @camtasia6 = ("$topdir/","$topdir/index.html",
11229:                         "$topdir/media/",
11230:                         "$topdir/media/$topdir.mp4",
11231:                         "$topdir/media/FirstFrame.png",
11232:                         "$topdir/media/player.swf",
11233:                         "$topdir/media/swfobject.js",
11234:                         "$topdir/media/expressInstall.swf");
11235:         my @camtasia8_1 = ("$topdir/","$topdir/$topdir.html",
11236:                          "$topdir/$topdir.mp4",
11237:                          "$topdir/$topdir\_config.xml",
11238:                          "$topdir/$topdir\_controller.swf",
11239:                          "$topdir/$topdir\_embed.css",
11240:                          "$topdir/$topdir\_First_Frame.png",
11241:                          "$topdir/$topdir\_player.html",
11242:                          "$topdir/$topdir\_Thumbnails.png",
11243:                          "$topdir/playerProductInstall.swf",
11244:                          "$topdir/scripts/",
11245:                          "$topdir/scripts/config_xml.js",
11246:                          "$topdir/scripts/handlebars.js",
11247:                          "$topdir/scripts/jquery-1.7.1.min.js",
11248:                          "$topdir/scripts/jquery-ui-1.8.15.custom.min.js",
11249:                          "$topdir/scripts/modernizr.js",
11250:                          "$topdir/scripts/player-min.js",
11251:                          "$topdir/scripts/swfobject.js",
11252:                          "$topdir/skins/",
11253:                          "$topdir/skins/configuration_express.xml",
11254:                          "$topdir/skins/express_show/",
11255:                          "$topdir/skins/express_show/player-min.css",
11256:                          "$topdir/skins/express_show/spritesheet.png");
11257:         my @camtasia8_4 = ("$topdir/","$topdir/$topdir.html",
11258:                          "$topdir/$topdir.mp4",
11259:                          "$topdir/$topdir\_config.xml",
11260:                          "$topdir/$topdir\_controller.swf",
11261:                          "$topdir/$topdir\_embed.css",
11262:                          "$topdir/$topdir\_First_Frame.png",
11263:                          "$topdir/$topdir\_player.html",
11264:                          "$topdir/$topdir\_Thumbnails.png",
11265:                          "$topdir/playerProductInstall.swf",
11266:                          "$topdir/scripts/",
11267:                          "$topdir/scripts/config_xml.js",
11268:                          "$topdir/scripts/techsmith-smart-player.min.js",
11269:                          "$topdir/skins/",
11270:                          "$topdir/skins/configuration_express.xml",
11271:                          "$topdir/skins/express_show/",
11272:                          "$topdir/skins/express_show/spritesheet.min.css",
11273:                          "$topdir/skins/express_show/spritesheet.png",
11274:                          "$topdir/skins/express_show/techsmith-smart-player.min.css");
11275:         my @diffs = &compare_arrays(\@paths,\@camtasia6);
11276:         if (@diffs == 0) {
11277:             $is_camtasia = 6;
11278:         } else {
11279:             @diffs = &compare_arrays(\@paths,\@camtasia8_1);
11280:             if (@diffs == 0) {
11281:                 $is_camtasia = 8;
11282:             } else {
11283:                 @diffs = &compare_arrays(\@paths,\@camtasia8_4);
11284:                 if (@diffs == 0) {
11285:                     $is_camtasia = 8;
11286:                 }
11287:             }
11288:         }
11289:     }
11290:     my $output;
11291:     if ($is_camtasia) {
11292:         $output = <<"ENDCAM";
11293: <script type="text/javascript" language="Javascript">
11294: // <![CDATA[
11295: 
11296: function camtasiaToggle() {
11297:     for (var i=0; i<document.uploaded_decompress.autoextract_camtasia.length; i++) {
11298:         if (document.uploaded_decompress.autoextract_camtasia[i].checked) {
11299:             if (document.uploaded_decompress.autoextract_camtasia[i].value == $is_camtasia) {
11300:                 document.getElementById('camtasia_titles').style.display='block';
11301:             } else {
11302:                 document.getElementById('camtasia_titles').style.display='none';
11303:             }
11304:         }
11305:     }
11306:     return;
11307: }
11308: 
11309: // ]]>
11310: </script>
11311: <p>$lt{'camt'}</p>
11312: ENDCAM
11313:     } else {
11314:         $output = '<p>'.$lt{'this'};
11315:         if ($info eq '') {
11316:             $output .= ' '.$lt{'youm'}.'</p>'."\n";
11317:         } else {
11318:             $output .= ' '.$lt{'itsc'}.'</p>'."\n".
11319:                        '<div><pre>'.$info.'</pre></div>';
11320:         }
11321:     }
11322:     $output .= '<form name="uploaded_decompress" action="'.$action.'" method="post">'."\n";
11323:     my $duplicates;
11324:     my $num = 0;
11325:     if (ref($dirlist) eq 'ARRAY') {
11326:         foreach my $item (@{$dirlist}) {
11327:             if (ref($item) eq 'ARRAY') {
11328:                 if (exists($toplevel{$item->[0]})) {
11329:                     $duplicates .= 
11330:                         &start_data_table_row().
11331:                         '<td><label><input type="radio" name="archive_overwrite_'.$num.'" '.
11332:                         'value="0" checked="checked" />'.&mt('No').'</label>'.
11333:                         '&nbsp;<label><input type="radio" name="archive_overwrite_'.$num.'" '.
11334:                         'value="1" />'.&mt('Yes').'</label>'.
11335:                         '<input type="hidden" name="archive_overwrite_name_'.$num.'" value="'.$item->[0].'" /></td>'."\n".
11336:                         '<td>'.$item->[0].'</td>';
11337:                     if ($item->[2]) {
11338:                         $duplicates .= '<td>'.&mt('Directory').'</td>';
11339:                     } else {
11340:                         $duplicates .= '<td>'.&mt('File').'</td>';
11341:                     }
11342:                     $duplicates .= '<td>'.$item->[3].'</td>'.
11343:                                    '<td>'.
11344:                                    &Apache::lonlocal::locallocaltime($item->[4]).
11345:                                    '</td>'.
11346:                                    &end_data_table_row();
11347:                     $num ++;
11348:                 }
11349:             }
11350:         }
11351:     }
11352:     my $itemcount;
11353:     if (@paths > 0) {
11354:         $itemcount = scalar(@paths);
11355:     } else {
11356:         $itemcount = 1;
11357:     }
11358:     if ($is_camtasia) {
11359:         $output .= $lt{'auto'}.'<br />'.
11360:                    '<span class="LC_nobreak">'.$lt{'proa'}.'<label>'.
11361:                    '<input type="radio" name="autoextract_camtasia" value="'.$is_camtasia.'" onclick="javascript:camtasiaToggle();" checked="checked" />'.
11362:                    $lt{'yes'}.'</label>&nbsp;<label>'.
11363:                    '<input type="radio" name="autoextract_camtasia" value="0" onclick="javascript:camtasiaToggle();" />'.
11364:                    $lt{'no'}.'</label></span><br />'.
11365:                    '<div id="camtasia_titles" style="display:block">'.
11366:                    &Apache::lonhtmlcommon::start_pick_box().
11367:                    &Apache::lonhtmlcommon::row_title($lt{'fold'}).
11368:                    '<input type="textbox" name="camtasia_foldername" value="'.$env{'form.comment'}.'" />'."\n".
11369:                    &Apache::lonhtmlcommon::row_closure().
11370:                    &Apache::lonhtmlcommon::row_title($lt{'movi'}).
11371:                    '<input type="textbox" name="camtasia_moviename" value="" />'."\n".
11372:                    &Apache::lonhtmlcommon::row_closure(1).
11373:                    &Apache::lonhtmlcommon::end_pick_box().
11374:                    '</div>';
11375:     }
11376:     $output .= 
11377:         '<input type="hidden" name="archive_overwrite_total" value="'.$num.'" />'.
11378:         '<input type="hidden" name="archive_itemcount" value="'.$itemcount.'" />'.
11379:         "\n";
11380:     if ($duplicates ne '') {
11381:         $output .= '<p><span class="LC_warning">'.
11382:                    &mt('Warning: decompression of the archive will overwrite the following items which already exist:').'</span><br />'.  
11383:                    &start_data_table().
11384:                    &start_data_table_header_row().
11385:                    '<th>'.&mt('Overwrite?').'</th>'.
11386:                    '<th>'.&mt('Name').'</th>'.
11387:                    '<th>'.&mt('Type').'</th>'.
11388:                    '<th>'.&mt('Size').'</th>'.
11389:                    '<th>'.&mt('Last modified').'</th>'.
11390:                    &end_data_table_header_row().
11391:                    $duplicates.
11392:                    &end_data_table().
11393:                    '</p>';
11394:     }
11395:     $output .= '<input type="hidden" name="archiveurl" value="'.$archiveurl.'" />'."\n";
11396:     if (ref($hiddenelements) eq 'HASH') {
11397:         foreach my $hidden (sort(keys(%{$hiddenelements}))) {
11398:             $output .= '<input type="hidden" name="'.$hidden.'" value="'.$hiddenelements->{$hidden}.'" />'."\n";
11399:         }
11400:     }
11401:     $output .= <<"END";
11402: <br />
11403: <input type="submit" name="decompress" value="$lt{'extr'}" />
11404: </form>
11405: $noextract
11406: END
11407:     return $output;
11408: }
11409: 
11410: sub decompression_utility {
11411:     my ($program) = @_;
11412:     my @utilities = ('tar','gunzip','bunzip2','unzip'); 
11413:     my $location;
11414:     if (grep(/^\Q$program\E$/,@utilities)) { 
11415:         foreach my $dir ('/bin/','/usr/bin/','/usr/local/bin/','/sbin/',
11416:                          '/usr/sbin/') {
11417:             if (-x $dir.$program) {
11418:                 $location = $dir.$program;
11419:                 last;
11420:             }
11421:         }
11422:     }
11423:     return $location;
11424: }
11425: 
11426: sub list_archive_contents {
11427:     my ($file,$pathsref) = @_;
11428:     my (@cmd,$output);
11429:     my $needsregexp;
11430:     if ($file =~ /\.zip$/) {
11431:         @cmd = (&decompression_utility('unzip'),"-l");
11432:         $needsregexp = 1;
11433:     } elsif (($file =~ m/\.tar\.gz$/) ||
11434:              ($file =~ /\.tgz$/)) {
11435:         @cmd = (&decompression_utility('tar'),"-ztf");
11436:     } elsif ($file =~ /\.tar\.bz2$/) {
11437:         @cmd = (&decompression_utility('tar'),"-jtf");
11438:     } elsif ($file =~ m|\.tar$|) {
11439:         @cmd = (&decompression_utility('tar'),"-tf");
11440:     }
11441:     if (@cmd) {
11442:         undef($!);
11443:         undef($@);
11444:         if (open(my $fh,"-|", @cmd, $file)) {
11445:             while (my $line = <$fh>) {
11446:                 $output .= $line;
11447:                 chomp($line);
11448:                 my $item;
11449:                 if ($needsregexp) {
11450:                     ($item) = ($line =~ /^\s*\d+\s+[\d\-]+\s+[\d:]+\s*(.+)$/); 
11451:                 } else {
11452:                     $item = $line;
11453:                 }
11454:                 if ($item ne '') {
11455:                     unless (grep(/^\Q$item\E$/,@{$pathsref})) {
11456:                         push(@{$pathsref},$item);
11457:                     } 
11458:                 }
11459:             }
11460:             close($fh);
11461:         }
11462:     }
11463:     return $output;
11464: }
11465: 
11466: sub decompress_uploaded_file {
11467:     my ($file,$dir) = @_;
11468:     &Apache::lonnet::appenv({'cgi.file' => $file});
11469:     &Apache::lonnet::appenv({'cgi.dir' => $dir});
11470:     my $result = &Apache::lonnet::ssi_body('/cgi-bin/decompress.pl');
11471:     my ($handle) = ($env{'user.environment'} =~m{/([^/]+)\.id$});
11472:     my $lonidsdir = $Apache::lonnet::perlvar{'lonIDsDir'};
11473:     &Apache::lonnet::transfer_profile_to_env($lonidsdir,$handle,1);
11474:     my $decompressed = $env{'cgi.decompressed'};
11475:     &Apache::lonnet::delenv('cgi.file');
11476:     &Apache::lonnet::delenv('cgi.dir');
11477:     &Apache::lonnet::delenv('cgi.decompressed');
11478:     return ($decompressed,$result);
11479: }
11480: 
11481: sub process_decompression {
11482:     my ($docudom,$docuname,$file,$destination,$dir_root,$hiddenelem) = @_;
11483:     my ($dir,$error,$warning,$output);
11484:     if ($file !~ /\.(zip|tar|bz2|gz|tar.gz|tar.bz2|tgz)$/i) {
11485:         $error = &mt('Filename not a supported archive file type.').
11486:                  '<br />'.&mt('Filename should end with one of: [_1].',
11487:                               '.zip, .tar, .bz2, .gz, .tar.gz, .tar.bz2, .tgz');
11488:     } else {
11489:         my $docuhome = &Apache::lonnet::homeserver($docuname,$docudom);
11490:         if ($docuhome eq 'no_host') {
11491:             $error = &mt('Could not determine home server for course.');
11492:         } else {
11493:             my @ids=&Apache::lonnet::current_machine_ids();
11494:             my $currdir = "$dir_root/$destination";
11495:             if (grep(/^\Q$docuhome\E$/,@ids)) {
11496:                 $dir = &LONCAPA::propath($docudom,$docuname).
11497:                        "$dir_root/$destination";
11498:             } else {
11499:                 $dir = $Apache::lonnet::perlvar{'lonDocRoot'}.
11500:                        "$dir_root/$docudom/$docuname/$destination";
11501:                 unless (&Apache::lonnet::repcopy_userfile("$dir/$file") eq 'ok') {
11502:                     $error = &mt('Archive file not found.');
11503:                 }
11504:             }
11505:             my (@to_overwrite,@to_skip);
11506:             if ($env{'form.archive_overwrite_total'} > 0) {
11507:                 my $total = $env{'form.archive_overwrite_total'};
11508:                 for (my $i=0; $i<$total; $i++) {
11509:                     if ($env{'form.archive_overwrite_'.$i} == 1) {
11510:                         push(@to_overwrite,$env{'form.archive_overwrite_name_'.$i});
11511:                     } elsif ($env{'form.archive_overwrite_'.$i} == 0) {
11512:                         push(@to_skip,$env{'form.archive_overwrite_name_'.$i});
11513:                     }
11514:                 }
11515:             }
11516:             my $numskip = scalar(@to_skip);
11517:             if (($numskip > 0) && 
11518:                 ($numskip == $env{'form.archive_itemcount'})) {
11519:                 $warning = &mt('All items in the archive file already exist, and no overwriting of existing files has been requested.');         
11520:             } elsif ($dir eq '') {
11521:                 $error = &mt('Directory containing archive file unavailable.');
11522:             } elsif (!$error) {
11523:                 my ($decompressed,$display);
11524:                 if ($numskip > 0) {
11525:                     my $tempdir = time.'_'.$$.int(rand(10000));
11526:                     mkdir("$dir/$tempdir",0755);
11527:                     system("mv $dir/$file $dir/$tempdir/$file");
11528:                     ($decompressed,$display) = 
11529:                         &decompress_uploaded_file($file,"$dir/$tempdir");
11530:                     foreach my $item (@to_skip) {
11531:                         if (($item ne '') && ($item !~ /\.\./)) {
11532:                             if (-f "$dir/$tempdir/$item") { 
11533:                                 unlink("$dir/$tempdir/$item");
11534:                             } elsif (-d "$dir/$tempdir/$item") {
11535:                                 system("rm -rf $dir/$tempdir/$item");
11536:                             }
11537:                         }
11538:                     }
11539:                     system("mv $dir/$tempdir/* $dir");
11540:                     rmdir("$dir/$tempdir");   
11541:                 } else {
11542:                     ($decompressed,$display) = 
11543:                         &decompress_uploaded_file($file,$dir);
11544:                 }
11545:                 if ($decompressed eq 'ok') {
11546:                     $output = '<p class="LC_info">'.
11547:                               &mt('Files extracted successfully from archive.').
11548:                               '</p>'."\n";
11549:                     my ($warning,$result,@contents);
11550:                     my ($newdirlistref,$newlisterror) =
11551:                         &Apache::lonnet::dirlist($currdir,$docudom,
11552:                                                  $docuname,1);
11553:                     my (%is_dir,%changes,@newitems);
11554:                     my $dirptr = 16384;
11555:                     if (ref($newdirlistref) eq 'ARRAY') {
11556:                         foreach my $dir_line (@{$newdirlistref}) {
11557:                             my ($item,undef,undef,$testdir)=split(/\&/,$dir_line,5);
11558:                             unless (($item =~ /^\.+$/) || ($item eq $file) || 
11559:                                     ((@to_skip > 0) && (grep(/^\Q$item\E$/,@to_skip)))) {
11560:                                 push(@newitems,$item);
11561:                                 if ($dirptr&$testdir) {
11562:                                     $is_dir{$item} = 1;
11563:                                 }
11564:                                 $changes{$item} = 1;
11565:                             }
11566:                         }
11567:                     }
11568:                     if (keys(%changes) > 0) {
11569:                         foreach my $item (sort(@newitems)) {
11570:                             if ($changes{$item}) {
11571:                                 push(@contents,$item);
11572:                             }
11573:                         }
11574:                     }
11575:                     if (@contents > 0) {
11576:                         my $wantform;
11577:                         unless ($env{'form.autoextract_camtasia'}) {
11578:                             $wantform = 1;
11579:                         }
11580:                         my (%children,%parent,%dirorder,%titles);
11581:                         my ($count,$datatable) = &get_extracted($docudom,$docuname,
11582:                                                                 $currdir,\%is_dir,
11583:                                                                 \%children,\%parent,
11584:                                                                 \@contents,\%dirorder,
11585:                                                                 \%titles,$wantform);
11586:                         if ($datatable ne '') {
11587:                             $output .= &archive_options_form('decompressed',$datatable,
11588:                                                              $count,$hiddenelem);
11589:                             my $startcount = 6;
11590:                             $output .= &archive_javascript($startcount,$count,
11591:                                                            \%titles,\%children);
11592:                         }
11593:                         if ($env{'form.autoextract_camtasia'}) {
11594:                             my $version = $env{'form.autoextract_camtasia'};
11595:                             my %displayed;
11596:                             my $total = 1;
11597:                             $env{'form.archive_directory'} = [];
11598:                             foreach my $i (sort { $a <=> $b } keys(%dirorder)) {
11599:                                 my $path = join('/',map { $titles{$_}; } @{$dirorder{$i}});
11600:                                 $path =~ s{/$}{};
11601:                                 my $item;
11602:                                 if ($path ne '') {
11603:                                     $item = "$path/$titles{$i}";
11604:                                 } else {
11605:                                     $item = $titles{$i};
11606:                                 }
11607:                                 $env{'form.archive_content_'.$i} = "$dir_root/$destination/$item";
11608:                                 if ($item eq $contents[0]) {
11609:                                     push(@{$env{'form.archive_directory'}},$i);
11610:                                     $env{'form.archive_'.$i} = 'display';
11611:                                     $env{'form.archive_title_'.$i} = $env{'form.camtasia_foldername'};
11612:                                     $displayed{'folder'} = $i;
11613:                                 } elsif ((($item eq "$contents[0]/index.html") && ($version == 6)) ||
11614:                                          (($item eq "$contents[0]/$contents[0]".'.html') && ($version == 8))) {
11615:                                     $env{'form.archive_'.$i} = 'display';
11616:                                     $env{'form.archive_title_'.$i} = $env{'form.camtasia_moviename'};
11617:                                     $displayed{'web'} = $i;
11618:                                 } else {
11619:                                     if ((($item eq "$contents[0]/media") && ($version == 6)) ||
11620:                                         ((($item eq "$contents[0]/scripts") || ($item eq "$contents[0]/skins") ||
11621:                                              ($item eq "$contents[0]/skins/express_show")) && ($version == 8))) {
11622:                                         push(@{$env{'form.archive_directory'}},$i);
11623:                                     }
11624:                                     $env{'form.archive_'.$i} = 'dependency';
11625:                                 }
11626:                                 $total ++;
11627:                             }
11628:                             for (my $i=1; $i<$total; $i++) {
11629:                                 next if ($i == $displayed{'web'});
11630:                                 next if ($i == $displayed{'folder'});
11631:                                 $env{'form.archive_dependent_on_'.$i} = $displayed{'web'};
11632:                             }
11633:                             $env{'form.phase'} = 'decompress_cleanup';
11634:                             $env{'form.archivedelete'} = 1;
11635:                             $env{'form.archive_count'} = $total-1;
11636:                             $output .=
11637:                                 &process_extracted_files('coursedocs',$docudom,
11638:                                                          $docuname,$destination,
11639:                                                          $dir_root,$hiddenelem);
11640:                         }
11641:                     } else {
11642:                         $warning = &mt('No new items extracted from archive file.');
11643:                     }
11644:                 } else {
11645:                     $output = $display;
11646:                     $error = &mt('An error occurred during extraction from the archive file.');
11647:                 }
11648:             }
11649:         }
11650:     }
11651:     if ($error) {
11652:         $output .= '<p class="LC_error">'.&mt('Not extracted.').'<br />'.
11653:                    $error.'</p>'."\n";
11654:     }
11655:     if ($warning) {
11656:         $output .= '<p class="LC_warning">'.$warning.'</p>'."\n";
11657:     }
11658:     return $output;
11659: }
11660: 
11661: sub get_extracted {
11662:     my ($docudom,$docuname,$currdir,$is_dir,$children,$parent,$contents,$dirorder,
11663:         $titles,$wantform) = @_;
11664:     my $count = 0;
11665:     my $depth = 0;
11666:     my $datatable;
11667:     my @hierarchy;
11668:     return unless ((ref($is_dir) eq 'HASH') && (ref($children) eq 'HASH') &&
11669:                    (ref($parent) eq 'HASH') && (ref($contents) eq 'ARRAY') &&
11670:                    (ref($dirorder) eq 'HASH') && (ref($titles) eq 'HASH'));
11671:     foreach my $item (@{$contents}) {
11672:         $count ++;
11673:         @{$dirorder->{$count}} = @hierarchy;
11674:         $titles->{$count} = $item;
11675:         &archive_hierarchy($depth,$count,$parent,$children);
11676:         if ($wantform) {
11677:             $datatable .= &archive_row($is_dir->{$item},$item,
11678:                                        $currdir,$depth,$count);
11679:         }
11680:         if ($is_dir->{$item}) {
11681:             $depth ++;
11682:             push(@hierarchy,$count);
11683:             $parent->{$depth} = $count;
11684:             $datatable .=
11685:                 &recurse_extracted_archive("$currdir/$item",$docudom,$docuname,
11686:                                            \$depth,\$count,\@hierarchy,$dirorder,
11687:                                            $children,$parent,$titles,$wantform);
11688:             $depth --;
11689:             pop(@hierarchy);
11690:         }
11691:     }
11692:     return ($count,$datatable);
11693: }
11694: 
11695: sub recurse_extracted_archive {
11696:     my ($currdir,$docudom,$docuname,$depth,$count,$hierarchy,$dirorder,
11697:         $children,$parent,$titles,$wantform) = @_;
11698:     my $result='';
11699:     unless ((ref($depth)) && (ref($count)) && (ref($hierarchy) eq 'ARRAY') &&
11700:             (ref($children) eq 'HASH') && (ref($parent) eq 'HASH') &&
11701:             (ref($dirorder) eq 'HASH')) {
11702:         return $result;
11703:     }
11704:     my $dirptr = 16384;
11705:     my ($newdirlistref,$newlisterror) =
11706:         &Apache::lonnet::dirlist($currdir,$docudom,$docuname,1);
11707:     if (ref($newdirlistref) eq 'ARRAY') {
11708:         foreach my $dir_line (@{$newdirlistref}) {
11709:             my ($item,undef,undef,$testdir)=split(/\&/,$dir_line,5);
11710:             unless ($item =~ /^\.+$/) {
11711:                 $$count ++;
11712:                 @{$dirorder->{$$count}} = @{$hierarchy};
11713:                 $titles->{$$count} = $item;
11714:                 &archive_hierarchy($$depth,$$count,$parent,$children);
11715: 
11716:                 my $is_dir;
11717:                 if ($dirptr&$testdir) {
11718:                     $is_dir = 1;
11719:                 }
11720:                 if ($wantform) {
11721:                     $result .= &archive_row($is_dir,$item,$currdir,$$depth,$$count);
11722:                 }
11723:                 if ($is_dir) {
11724:                     $$depth ++;
11725:                     push(@{$hierarchy},$$count);
11726:                     $parent->{$$depth} = $$count;
11727:                     $result .=
11728:                         &recurse_extracted_archive("$currdir/$item",$docudom,
11729:                                                    $docuname,$depth,$count,
11730:                                                    $hierarchy,$dirorder,$children,
11731:                                                    $parent,$titles,$wantform);
11732:                     $$depth --;
11733:                     pop(@{$hierarchy});
11734:                 }
11735:             }
11736:         }
11737:     }
11738:     return $result;
11739: }
11740: 
11741: sub archive_hierarchy {
11742:     my ($depth,$count,$parent,$children) =@_;
11743:     if ((ref($parent) eq 'HASH') && (ref($children) eq 'HASH')) {
11744:         if (exists($parent->{$depth})) {
11745:              $children->{$parent->{$depth}} .= $count.':';
11746:         }
11747:     }
11748:     return;
11749: }
11750: 
11751: sub archive_row {
11752:     my ($is_dir,$item,$currdir,$depth,$count) = @_;
11753:     my ($name) = ($item =~ m{([^/]+)$});
11754:     my %choices = &Apache::lonlocal::texthash (
11755:                                        'display'    => 'Add as file',
11756:                                        'dependency' => 'Include as dependency',
11757:                                        'discard'    => 'Discard',
11758:                                       );
11759:     if ($is_dir) {
11760:         $choices{'display'} = &mt('Add as folder'); 
11761:     }
11762:     my $output = &start_data_table_row().'<td align="right">'.$count.'</td>'."\n";
11763:     my $offset = 0;
11764:     foreach my $action ('display','dependency','discard') {
11765:         $offset ++;
11766:         if ($action ne 'display') {
11767:             $offset ++;
11768:         }  
11769:         $output .= '<td><span class="LC_nobreak">'.
11770:                    '<label><input type="radio" name="archive_'.$count.
11771:                    '" id="archive_'.$action.'_'.$count.'" value="'.$action.'"';
11772:         my $text = $choices{$action};
11773:         if ($is_dir) {
11774:             $output .= ' onclick="javascript:propagateCheck(this.form,'."'$count'".');"';
11775:             if ($action eq 'display') {
11776:                 $text = &mt('Add as folder');
11777:             }
11778:         } else {
11779:             $output .= ' onclick="javascript:dependencyCheck(this.form,'."$count,$offset".');"';
11780: 
11781:         }
11782:         $output .= ' />&nbsp;'.$choices{$action}.'</label></span>';
11783:         if ($action eq 'dependency') {
11784:             $output .= '<div id="arc_depon_'.$count.'" style="display:none;">'."\n".
11785:                        &mt('Used by:').'&nbsp;<select name="archive_dependent_on_'.$count.'" '.
11786:                        'onchange="propagateSelect(this.form,'."$count,$offset".')">'."\n".
11787:                        '<option value=""></option>'."\n".
11788:                        '</select>'."\n".
11789:                        '</div>';
11790:         } elsif ($action eq 'display') {
11791:             $output .= '<div id="arc_title_'.$count.'" style="display:none;">'."\n".
11792:                        &mt('Title:').'&nbsp;<input type="text" name="archive_title_'.$count.'" id="archive_title_'.$count.'" />'."\n".
11793:                        '</div>';
11794:         }
11795:         $output .= '</td>';
11796:     }
11797:     $output .= '<td><input type="hidden" name="archive_content_'.$count.'" value="'.
11798:                &HTML::Entities::encode("$currdir/$item",'"<>&').'" />'.('&nbsp;' x 2);
11799:     for (my $i=0; $i<$depth; $i++) {
11800:         $output .= ('<img src="/adm/lonIcons/whitespace1.gif" class="LC_docs_spacer" alt="" />' x2)."\n";
11801:     }
11802:     if ($is_dir) {
11803:         $output .= '<img src="/adm/lonIcons/navmap.folder.open.gif" alt="" />&nbsp;'."\n".
11804:                    '<input type="hidden" name="archive_directory" value="'.$count.'" />'."\n";
11805:     } else {
11806:         $output .= '<input type="hidden" name="archive_file" value="'.$count.'" />'."\n";
11807:     }
11808:     $output .= '&nbsp;'.$name.'</td>'."\n".
11809:                &end_data_table_row();
11810:     return $output;
11811: }
11812: 
11813: sub archive_options_form {
11814:     my ($form,$display,$count,$hiddenelem) = @_;
11815:     my %lt = &Apache::lonlocal::texthash(
11816:                perm => 'Permanently remove archive file?',
11817:                hows => 'How should each extracted item be incorporated in the course?',
11818:                cont => 'Content actions for all',
11819:                addf => 'Add as folder/file',
11820:                incd => 'Include as dependency for a displayed file',
11821:                disc => 'Discard',
11822:                no   => 'No',
11823:                yes  => 'Yes',
11824:                save => 'Save',
11825:     );
11826:     my $output = <<"END";
11827: <form name="$form" method="post" action="">
11828: <p><span class="LC_nobreak">$lt{'perm'}&nbsp;
11829: <label>
11830:   <input type="radio" name="archivedelete" value="0" checked="checked" />$lt{'no'}
11831: </label>
11832: &nbsp;
11833: <label>
11834:   <input type="radio" name="archivedelete" value="1" />$lt{'yes'}</label>
11835: </span>
11836: </p>
11837: <input type="hidden" name="phase" value="decompress_cleanup" />
11838: <br />$lt{'hows'}
11839: <div class="LC_columnSection">
11840:   <fieldset>
11841:     <legend>$lt{'cont'}</legend>
11842:     <input type="button" value="$lt{'addf'}" onclick="javascript:checkAll(document.$form,'display');" /> 
11843:     &nbsp;&nbsp;<input type="button" value="$lt{'incd'}" onclick="javascript:checkAll(document.$form,'dependency');" />
11844:     &nbsp;&nbsp;<input type="button" value="$lt{'disc'}" onclick="javascript:checkAll(document.$form,'discard');" />
11845:   </fieldset>
11846: </div>
11847: END
11848:     return $output.
11849:            &start_data_table()."\n".
11850:            $display."\n".
11851:            &end_data_table()."\n".
11852:            '<input type="hidden" name="archive_count" value="'.$count.'" />'.
11853:            $hiddenelem.
11854:            '<br /><input type="submit" name="archive_submit" value="'.$lt{'save'}.'" />'.
11855:            '</form>';
11856: }
11857: 
11858: sub archive_javascript {
11859:     my ($startcount,$numitems,$titles,$children) = @_;
11860:     return unless ((ref($titles) eq 'HASH') && (ref($children) eq 'HASH'));
11861:     my $maintitle = $env{'form.comment'};
11862:     my $scripttag = <<START;
11863: <script type="text/javascript">
11864: // <![CDATA[
11865: 
11866: function checkAll(form,prefix) {
11867:     var idstr =  new RegExp("^archive_"+prefix+"_\\\\d+\$");
11868:     for (var i=0; i < form.elements.length; i++) {
11869:         var id = form.elements[i].id;
11870:         if ((id != '') && (id != undefined)) {
11871:             if (idstr.test(id)) {
11872:                 if (form.elements[i].type == 'radio') {
11873:                     form.elements[i].checked = true;
11874:                     var nostart = i-$startcount;
11875:                     var offset = nostart%7;
11876:                     var count = (nostart-offset)/7;    
11877:                     dependencyCheck(form,count,offset);
11878:                 }
11879:             }
11880:         }
11881:     }
11882: }
11883: 
11884: function propagateCheck(form,count) {
11885:     if (count > 0) {
11886:         var startelement = $startcount + ((count-1) * 7);
11887:         for (var j=1; j<6; j++) {
11888:             if ((j != 2) && (j != 4)) {
11889:                 var item = startelement + j; 
11890:                 if (form.elements[item].type == 'radio') {
11891:                     if (form.elements[item].checked) {
11892:                         containerCheck(form,count,j);
11893:                         break;
11894:                     }
11895:                 }
11896:             }
11897:         }
11898:     }
11899: }
11900: 
11901: numitems = $numitems
11902: var titles = new Array(numitems);
11903: var parents = new Array(numitems);
11904: for (var i=0; i<numitems; i++) {
11905:     parents[i] = new Array;
11906: }
11907: var maintitle = '$maintitle';
11908: 
11909: START
11910: 
11911:     foreach my $container (sort { $a <=> $b } (keys(%{$children}))) {
11912:         my @contents = split(/:/,$children->{$container});
11913:         for (my $i=0; $i<@contents; $i ++) {
11914:             $scripttag .= 'parents['.$container.']['.$i.'] = '.$contents[$i]."\n";
11915:         }
11916:     }
11917: 
11918:     foreach my $key (sort { $a <=> $b } (keys(%{$titles}))) {
11919:         $scripttag .= "titles[$key] = '".$titles->{$key}."';\n";
11920:     }
11921: 
11922:     $scripttag .= <<END;
11923: 
11924: function containerCheck(form,count,offset) {
11925:     if (count > 0) {
11926:         dependencyCheck(form,count,offset);
11927:         var item = (offset+$startcount)+7*(count-1);
11928:         form.elements[item].checked = true;
11929:         if(Object.prototype.toString.call(parents[count]) === '[object Array]') {
11930:             if (parents[count].length > 0) {
11931:                 for (var j=0; j<parents[count].length; j++) {
11932:                     containerCheck(form,parents[count][j],offset);
11933:                 }
11934:             }
11935:         }
11936:     }
11937: }
11938: 
11939: function dependencyCheck(form,count,offset) {
11940:     if (count > 0) {
11941:         var chosen = (offset+$startcount)+7*(count-1);
11942:         var depitem = $startcount + ((count-1) * 7) + 4;
11943:         var currtype = form.elements[depitem].type;
11944:         if (form.elements[chosen].value == 'dependency') {
11945:             document.getElementById('arc_depon_'+count).style.display='block'; 
11946:             form.elements[depitem].options.length = 0;
11947:             form.elements[depitem].options[0] = new Option('Select','',true,true);
11948:             for (var i=1; i<=numitems; i++) {
11949:                 if (i == count) {
11950:                     continue;
11951:                 }
11952:                 var startelement = $startcount + (i-1) * 7;
11953:                 for (var j=1; j<6; j++) {
11954:                     if ((j != 2) && (j!= 4)) {
11955:                         var item = startelement + j;
11956:                         if (form.elements[item].type == 'radio') {
11957:                             if (form.elements[item].checked) {
11958:                                 if (form.elements[item].value == 'display') {
11959:                                     var n = form.elements[depitem].options.length;
11960:                                     form.elements[depitem].options[n] = new Option(titles[i],i,false,false);
11961:                                 }
11962:                             }
11963:                         }
11964:                     }
11965:                 }
11966:             }
11967:         } else {
11968:             document.getElementById('arc_depon_'+count).style.display='none';
11969:             form.elements[depitem].options.length = 0;
11970:             form.elements[depitem].options[0] = new Option('Select','',true,true);
11971:         }
11972:         titleCheck(form,count,offset);
11973:     }
11974: }
11975: 
11976: function propagateSelect(form,count,offset) {
11977:     if (count > 0) {
11978:         var item = (1+offset+$startcount)+7*(count-1);
11979:         var picked = form.elements[item].options[form.elements[item].selectedIndex].value; 
11980:         if (Object.prototype.toString.call(parents[count]) === '[object Array]') {
11981:             if (parents[count].length > 0) {
11982:                 for (var j=0; j<parents[count].length; j++) {
11983:                     containerSelect(form,parents[count][j],offset,picked);
11984:                 }
11985:             }
11986:         }
11987:     }
11988: }
11989: 
11990: function containerSelect(form,count,offset,picked) {
11991:     if (count > 0) {
11992:         var item = (offset+$startcount)+7*(count-1);
11993:         if (form.elements[item].type == 'radio') {
11994:             if (form.elements[item].value == 'dependency') {
11995:                 if (form.elements[item+1].type == 'select-one') {
11996:                     for (var i=0; i<form.elements[item+1].options.length; i++) {
11997:                         if (form.elements[item+1].options[i].value == picked) {
11998:                             form.elements[item+1].selectedIndex = i;
11999:                             break;
12000:                         }
12001:                     }
12002:                 }
12003:                 if (Object.prototype.toString.call(parents[count]) === '[object Array]') {
12004:                     if (parents[count].length > 0) {
12005:                         for (var j=0; j<parents[count].length; j++) {
12006:                             containerSelect(form,parents[count][j],offset,picked);
12007:                         }
12008:                     }
12009:                 }
12010:             }
12011:         }
12012:     }
12013: }
12014: 
12015: function titleCheck(form,count,offset) {
12016:     if (count > 0) {
12017:         var chosen = (offset+$startcount)+7*(count-1);
12018:         var depitem = $startcount + ((count-1) * 7) + 2;
12019:         var currtype = form.elements[depitem].type;
12020:         if (form.elements[chosen].value == 'display') {
12021:             document.getElementById('arc_title_'+count).style.display='block';
12022:             if ((count==1) && ((parents[count].length > 0) || (numitems == 1))) {
12023:                 document.getElementById('archive_title_'+count).value=maintitle;
12024:             }
12025:         } else {
12026:             document.getElementById('arc_title_'+count).style.display='none';
12027:             if (currtype == 'text') { 
12028:                 document.getElementById('archive_title_'+count).value='';
12029:             }
12030:         }
12031:     }
12032:     return;
12033: }
12034: 
12035: // ]]>
12036: </script>
12037: END
12038:     return $scripttag;
12039: }
12040: 
12041: sub process_extracted_files {
12042:     my ($context,$docudom,$docuname,$destination,$dir_root,$hiddenelem) = @_;
12043:     my $numitems = $env{'form.archive_count'};
12044:     return unless ($numitems);
12045:     my @ids=&Apache::lonnet::current_machine_ids();
12046:     my ($prefix,$pathtocheck,$dir,$ishome,$error,$warning,%toplevelitems,%is_dir,
12047:         %folders,%containers,%mapinner,%prompttofetch);
12048:     my $docuhome = &Apache::lonnet::homeserver($docuname,$docudom);
12049:     if (grep(/^\Q$docuhome\E$/,@ids)) {
12050:         $prefix = &LONCAPA::propath($docudom,$docuname);
12051:         $pathtocheck = "$dir_root/$destination";
12052:         $dir = $dir_root;
12053:         $ishome = 1;
12054:     } else {
12055:         $prefix = $Apache::lonnet::perlvar{'lonDocRoot'};
12056:         $pathtocheck = "$dir_root/$docudom/$docuname/$destination";
12057:         $dir = "$dir_root/$docudom/$docuname";    
12058:     }
12059:     my $currdir = "$dir_root/$destination";
12060:     (my $docstype,$mapinner{'0'}) = ($destination =~ m{^(docs|supplemental)/(\w+)/});
12061:     if ($env{'form.folderpath'}) {
12062:         my @items = split('&',$env{'form.folderpath'});
12063:         $folders{'0'} = $items[-2];
12064:         if ($env{'form.folderpath'} =~ /\:1$/) {
12065:             $containers{'0'}='page';
12066:         } else {
12067:             $containers{'0'}='sequence';
12068:         }
12069:     }
12070:     my @archdirs = &get_env_multiple('form.archive_directory');
12071:     if ($numitems) {
12072:         for (my $i=1; $i<=$numitems; $i++) {
12073:             my $path = $env{'form.archive_content_'.$i};
12074:             if ($path =~ m{^\Q$pathtocheck\E/([^/]+)$}) {
12075:                 my $item = $1;
12076:                 $toplevelitems{$item} = $i;
12077:                 if (grep(/^\Q$i\E$/,@archdirs)) {
12078:                     $is_dir{$item} = 1;
12079:                 }
12080:             }
12081:         }
12082:     }
12083:     my ($output,%children,%parent,%titles,%dirorder,$result);
12084:     if (keys(%toplevelitems) > 0) {
12085:         my @contents = sort(keys(%toplevelitems));
12086:         (my $count,undef) = &get_extracted($docudom,$docuname,$currdir,\%is_dir,\%children,
12087:                                            \%parent,\@contents,\%dirorder,\%titles);
12088:     }
12089:     my (%referrer,%orphaned,%todelete,%todeletedir,%newdest,%newseqid);
12090:     if ($numitems) {
12091:         for (my $i=1; $i<=$numitems; $i++) {
12092:             next if ($env{'form.archive_'.$i} eq 'dependency');
12093:             my $path = $env{'form.archive_content_'.$i};
12094:             if ($path =~ /^\Q$pathtocheck\E/) {
12095:                 if ($env{'form.archive_'.$i} eq 'discard') {
12096:                     if ($prefix ne '' && $path ne '') {
12097:                         if (-e $prefix.$path) {
12098:                             if ((@archdirs > 0) && 
12099:                                 (grep(/^\Q$i\E$/,@archdirs))) {
12100:                                 $todeletedir{$prefix.$path} = 1;
12101:                             } else {
12102:                                 $todelete{$prefix.$path} = 1;
12103:                             }
12104:                         }
12105:                     }
12106:                 } elsif ($env{'form.archive_'.$i} eq 'display') {
12107:                     my ($docstitle,$title,$url,$outer);
12108:                     ($title) = ($path =~ m{/([^/]+)$});
12109:                     $docstitle = $env{'form.archive_title_'.$i};
12110:                     if ($docstitle eq '') {
12111:                         $docstitle = $title;
12112:                     }
12113:                     $outer = 0;
12114:                     if (ref($dirorder{$i}) eq 'ARRAY') {
12115:                         if (@{$dirorder{$i}} > 0) {
12116:                             foreach my $item (reverse(@{$dirorder{$i}})) {
12117:                                 if ($env{'form.archive_'.$item} eq 'display') {
12118:                                     $outer = $item;
12119:                                     last;
12120:                                 }
12121:                             }
12122:                         }
12123:                     }
12124:                     my ($errtext,$fatal) = 
12125:                         &LONCAPA::map::mapread('/uploaded/'.$docudom.'/'.$docuname.
12126:                                                '/'.$folders{$outer}.'.'.
12127:                                                $containers{$outer});
12128:                     next if ($fatal);
12129:                     if ((@archdirs > 0) && (grep(/^\Q$i\E$/,@archdirs))) {
12130:                         if ($context eq 'coursedocs') {
12131:                             $mapinner{$i} = time;
12132:                             $folders{$i} = 'default_'.$mapinner{$i};
12133:                             $containers{$i} = 'sequence';
12134:                             my $url = '/uploaded/'.$docudom.'/'.$docuname.'/'.
12135:                                       $folders{$i}.'.'.$containers{$i};
12136:                             my $newidx = &LONCAPA::map::getresidx();
12137:                             $LONCAPA::map::resources[$newidx]=
12138:                                 $docstitle.':'.$url.':false:normal:res';
12139:                             push(@LONCAPA::map::order,$newidx);
12140:                             my ($outtext,$errtext) =
12141:                                 &LONCAPA::map::storemap('/uploaded/'.$docudom.'/'.
12142:                                                         $docuname.'/'.$folders{$outer}.
12143:                                                         '.'.$containers{$outer},1,1);
12144:                             $newseqid{$i} = $newidx;
12145:                             unless ($errtext) {
12146:                                 $result .=  '<li>'.&mt('Folder: [_1] added to course',$docstitle).'</li>'."\n";
12147:                             }
12148:                         }
12149:                     } else {
12150:                         if ($context eq 'coursedocs') {
12151:                             my $newidx=&LONCAPA::map::getresidx();
12152:                             my $url = '/uploaded/'.$docudom.'/'.$docuname.'/'.
12153:                                       $docstype.'/'.$mapinner{$outer}.'/'.$newidx.'/'.
12154:                                       $title;
12155:                             if (!-e "$prefix$dir/$docstype/$mapinner{$outer}") {
12156:                                 mkdir("$prefix$dir/$docstype/$mapinner{$outer}",0755);
12157:                             }
12158:                             if (!-e "$prefix$dir/$docstype/$mapinner{$outer}/$newidx") {
12159:                                 mkdir("$prefix$dir/$docstype/$mapinner{$outer}/$newidx");
12160:                             }
12161:                             if (-e "$prefix$dir/$docstype/$mapinner{$outer}/$newidx") {
12162:                                 system("mv $prefix$path $prefix$dir/$docstype/$mapinner{$outer}/$newidx/$title");
12163:                                 $newdest{$i} = "$prefix$dir/$docstype/$mapinner{$outer}/$newidx";
12164:                                 unless ($ishome) {
12165:                                     my $fetch = "$newdest{$i}/$title";
12166:                                     $fetch =~ s/^\Q$prefix$dir\E//;
12167:                                     $prompttofetch{$fetch} = 1;
12168:                                 }
12169:                             }
12170:                             $LONCAPA::map::resources[$newidx]=
12171:                                 $docstitle.':'.$url.':false:normal:res';
12172:                             push(@LONCAPA::map::order, $newidx);
12173:                             my ($outtext,$errtext)=
12174:                                 &LONCAPA::map::storemap('/uploaded/'.$docudom.'/'.
12175:                                                         $docuname.'/'.$folders{$outer}.
12176:                                                         '.'.$containers{$outer},1,1);
12177:                             unless ($errtext) {
12178:                                 if (-e "$prefix$dir/$docstype/$mapinner{$outer}/$newidx/$title") {
12179:                                     $result .= '<li>'.&mt('File: [_1] added to course',$docstitle).'</li>'."\n";
12180:                                 }
12181:                             }
12182:                         }
12183:                     }
12184:                 }
12185:             } else {
12186:                 $warning .= &mt('Item extracted from archive: [_1] has unexpected path.',$path).'<br />';
12187:             }
12188:         }
12189:         for (my $i=1; $i<=$numitems; $i++) {
12190:             next unless ($env{'form.archive_'.$i} eq 'dependency');
12191:             my $path = $env{'form.archive_content_'.$i};
12192:             if ($path =~ /^\Q$pathtocheck\E/) {
12193:                 my ($title) = ($path =~ m{/([^/]+)$});
12194:                 $referrer{$i} = $env{'form.archive_dependent_on_'.$i};
12195:                 if ($env{'form.archive_'.$referrer{$i}} eq 'display') {
12196:                     if (ref($dirorder{$i}) eq 'ARRAY') {
12197:                         my ($itemidx,$fullpath,$relpath);
12198:                         if (ref($dirorder{$referrer{$i}}) eq 'ARRAY') {
12199:                             my $container = $dirorder{$referrer{$i}}->[-1];
12200:                             for (my $j=0; $j<@{$dirorder{$i}}; $j++) {
12201:                                 if ($dirorder{$i}->[$j] eq $container) {
12202:                                     $itemidx = $j;
12203:                                 }
12204:                             }
12205:                         }
12206:                         if ($itemidx eq '') {
12207:                             $itemidx =  0;
12208:                         }
12209:                         if (grep(/^\Q$referrer{$i}\E$/,@archdirs)) {
12210:                             if ($mapinner{$referrer{$i}}) {
12211:                                 $fullpath = "$prefix$dir/$docstype/$mapinner{$referrer{$i}}";
12212:                                 for (my $j=$itemidx; $j<@{$dirorder{$i}}; $j++) {
12213:                                     if (grep(/^\Q$dirorder{$i}->[$j]\E$/,@archdirs)) {
12214:                                         unless (defined($newseqid{$dirorder{$i}->[$j]})) {
12215:                                             $fullpath .= '/'.$titles{$dirorder{$i}->[$j]};
12216:                                             $relpath .= '/'.$titles{$dirorder{$i}->[$j]};
12217:                                             if (!-e $fullpath) {
12218:                                                 mkdir($fullpath,0755);
12219:                                             }
12220:                                         }
12221:                                     } else {
12222:                                         last;
12223:                                     }
12224:                                 }
12225:                             }
12226:                         } elsif ($newdest{$referrer{$i}}) {
12227:                             $fullpath = $newdest{$referrer{$i}};
12228:                             for (my $j=$itemidx; $j<@{$dirorder{$i}}; $j++) {
12229:                                 if ($env{'form.archive_'.$dirorder{$i}->[$j]} eq 'discard') {
12230:                                     $orphaned{$i} = $env{'form.archive_'.$dirorder{$i}->[$j]};
12231:                                     last;
12232:                                 } elsif (grep(/^\Q$dirorder{$i}->[$j]\E$/,@archdirs)) {
12233:                                     unless (defined($newseqid{$dirorder{$i}->[$j]})) {
12234:                                         $fullpath .= '/'.$titles{$dirorder{$i}->[$j]};
12235:                                         $relpath .= '/'.$titles{$dirorder{$i}->[$j]};
12236:                                         if (!-e $fullpath) {
12237:                                             mkdir($fullpath,0755);
12238:                                         }
12239:                                     }
12240:                                 } else {
12241:                                     last;
12242:                                 }
12243:                             }
12244:                         }
12245:                         if ($fullpath ne '') {
12246:                             if (-e "$prefix$path") {
12247:                                 system("mv $prefix$path $fullpath/$title");
12248:                             }
12249:                             if (-e "$fullpath/$title") {
12250:                                 my $showpath;
12251:                                 if ($relpath ne '') {
12252:                                     $showpath = "$relpath/$title";
12253:                                 } else {
12254:                                     $showpath = "/$title";
12255:                                 }
12256:                                 $result .= '<li>'.&mt('[_1] included as a dependency',$showpath).'</li>'."\n";
12257:                             }
12258:                             unless ($ishome) {
12259:                                 my $fetch = "$fullpath/$title";
12260:                                 $fetch =~ s/^\Q$prefix$dir\E//;
12261:                                 $prompttofetch{$fetch} = 1;
12262:                             }
12263:                         }
12264:                     }
12265:                 } elsif ($env{'form.archive_'.$referrer{$i}} eq 'discard') {
12266:                     $warning .= &mt('[_1] is a dependency of [_2], which was discarded.',
12267:                                     $path,$env{'form.archive_content_'.$referrer{$i}}).'<br />';
12268:                 }
12269:             } else {
12270:                 $warning .= &mt('Item extracted from archive: [_1] has unexpected path.',$path).'<br />';
12271:             }
12272:         }
12273:         if (keys(%todelete)) {
12274:             foreach my $key (keys(%todelete)) {
12275:                 unlink($key);
12276:             }
12277:         }
12278:         if (keys(%todeletedir)) {
12279:             foreach my $key (keys(%todeletedir)) {
12280:                 rmdir($key);
12281:             }
12282:         }
12283:         foreach my $dir (sort(keys(%is_dir))) {
12284:             if (($pathtocheck ne '') && ($dir ne ''))  {
12285:                 &cleanup_empty_dirs($prefix."$pathtocheck/$dir");
12286:             }
12287:         }
12288:         if ($result ne '') {
12289:             $output .= '<ul>'."\n".
12290:                        $result."\n".
12291:                        '</ul>';
12292:         }
12293:         unless ($ishome) {
12294:             my $replicationfail;
12295:             foreach my $item (keys(%prompttofetch)) {
12296:                 my $fetchresult= &Apache::lonnet::reply('fetchuserfile:'.$item,$docuhome);
12297:                 unless ($fetchresult eq 'ok') {
12298:                     $replicationfail .= '<li>'.$item.'</li>'."\n";
12299:                 }
12300:             }
12301:             if ($replicationfail) {
12302:                 $output .= '<p class="LC_error">'.
12303:                            &mt('Course home server failed to retrieve:').'<ul>'.
12304:                            $replicationfail.
12305:                            '</ul></p>';
12306:             }
12307:         }
12308:     } else {
12309:         $warning = &mt('No items found in archive.');
12310:     }
12311:     if ($error) {
12312:         $output .= '<p class="LC_error">'.&mt('Not extracted.').'<br />'.
12313:                    $error.'</p>'."\n";
12314:     }
12315:     if ($warning) {
12316:         $output .= '<p class="LC_warning">'.$warning.'</p>'."\n";
12317:     }
12318:     return $output;
12319: }
12320: 
12321: sub cleanup_empty_dirs {
12322:     my ($path) = @_;
12323:     if (($path ne '') && (-d $path)) {
12324:         if (opendir(my $dirh,$path)) {
12325:             my @dircontents = grep(!/^\./,readdir($dirh));
12326:             my $numitems = 0;
12327:             foreach my $item (@dircontents) {
12328:                 if (-d "$path/$item") {
12329:                     &cleanup_empty_dirs("$path/$item");
12330:                     if (-e "$path/$item") {
12331:                         $numitems ++;
12332:                     }
12333:                 } else {
12334:                     $numitems ++;
12335:                 }
12336:             }
12337:             if ($numitems == 0) {
12338:                 rmdir($path);
12339:             }
12340:             closedir($dirh);
12341:         }
12342:     }
12343:     return;
12344: }
12345: 
12346: =pod
12347: 
12348: =item * &get_folder_hierarchy()
12349: 
12350: Provides hierarchy of names of folders/sub-folders containing the current
12351: item,
12352: 
12353: Inputs: 3
12354:      - $navmap - navmaps object
12355: 
12356:      - $map - url for map (either the trigger itself, or map containing
12357:                            the resource, which is the trigger).
12358: 
12359:      - $showitem - 1 => show title for map itself; 0 => do not show.
12360: 
12361: Outputs: 1 @pathitems - array of folder/subfolder names.
12362: 
12363: =cut
12364: 
12365: sub get_folder_hierarchy {
12366:     my ($navmap,$map,$showitem) = @_;
12367:     my @pathitems;
12368:     if (ref($navmap)) {
12369:         my $mapres = $navmap->getResourceByUrl($map);
12370:         if (ref($mapres)) {
12371:             my $pcslist = $mapres->map_hierarchy();
12372:             if ($pcslist ne '') {
12373:                 my @pcs = split(/,/,$pcslist);
12374:                 foreach my $pc (@pcs) {
12375:                     if ($pc == 1) {
12376:                         push(@pathitems,&mt('Main Content'));
12377:                     } else {
12378:                         my $res = $navmap->getByMapPc($pc);
12379:                         if (ref($res)) {
12380:                             my $title = $res->compTitle();
12381:                             $title =~ s/\W+/_/g;
12382:                             if ($title ne '') {
12383:                                 push(@pathitems,$title);
12384:                             }
12385:                         }
12386:                     }
12387:                 }
12388:             }
12389:             if ($showitem) {
12390:                 if ($mapres->{ID} eq '0.0') {
12391:                     push(@pathitems,&mt('Main Content'));
12392:                 } else {
12393:                     my $maptitle = $mapres->compTitle();
12394:                     $maptitle =~ s/\W+/_/g;
12395:                     if ($maptitle ne '') {
12396:                         push(@pathitems,$maptitle);
12397:                     }
12398:                 }
12399:             }
12400:         }
12401:     }
12402:     return @pathitems;
12403: }
12404: 
12405: =pod
12406: 
12407: =item * &get_turnedin_filepath()
12408: 
12409: Determines path in a user's portfolio file for storage of files uploaded
12410: to a specific essayresponse or dropbox item.
12411: 
12412: Inputs: 3 required + 1 optional.
12413: $symb is symb for resource, $uname and $udom are for current user (required).
12414: $caller is optional (can be "submission", if routine is called when storing
12415: an upoaded file when "Submit Answer" button was pressed).
12416: 
12417: Returns array containing $path and $multiresp. 
12418: $path is path in portfolio.  $multiresp is 1 if this resource contains more
12419: than one file upload item.  Callers of routine should append partid as a 
12420: subdirectory to $path in cases where $multiresp is 1.
12421: 
12422: Called by: homework/essayresponse.pm and homework/structuretags.pm
12423: 
12424: =cut
12425: 
12426: sub get_turnedin_filepath {
12427:     my ($symb,$uname,$udom,$caller) = @_;
12428:     my ($map,$resid,$resurl)=&Apache::lonnet::decode_symb($symb);
12429:     my $turnindir;
12430:     my %userhash = &Apache::lonnet::userenvironment($udom,$uname,'turnindir');
12431:     $turnindir = $userhash{'turnindir'};
12432:     my ($path,$multiresp);
12433:     if ($turnindir eq '') {
12434:         if ($caller eq 'submission') {
12435:             $turnindir = &mt('turned in');
12436:             $turnindir =~ s/\W+/_/g;
12437:             my %newhash = (
12438:                             'turnindir' => $turnindir,
12439:                           );
12440:             &Apache::lonnet::put('environment',\%newhash,$udom,$uname);
12441:         }
12442:     }
12443:     if ($turnindir ne '') {
12444:         $path = '/'.$turnindir.'/';
12445:         my ($multipart,$turnin,@pathitems);
12446:         my $navmap = Apache::lonnavmaps::navmap->new();
12447:         if (defined($navmap)) {
12448:             my $mapres = $navmap->getResourceByUrl($map);
12449:             if (ref($mapres)) {
12450:                 my $pcslist = $mapres->map_hierarchy();
12451:                 if ($pcslist ne '') {
12452:                     foreach my $pc (split(/,/,$pcslist)) {
12453:                         my $res = $navmap->getByMapPc($pc);
12454:                         if (ref($res)) {
12455:                             my $title = $res->compTitle();
12456:                             $title =~ s/\W+/_/g;
12457:                             if ($title ne '') {
12458:                                 if (($pc > 1) && (length($title) > 12)) {
12459:                                     $title = substr($title,0,12);
12460:                                 }
12461:                                 push(@pathitems,$title);
12462:                             }
12463:                         }
12464:                     }
12465:                 }
12466:                 my $maptitle = $mapres->compTitle();
12467:                 $maptitle =~ s/\W+/_/g;
12468:                 if ($maptitle ne '') {
12469:                     if (length($maptitle) > 12) {
12470:                         $maptitle = substr($maptitle,0,12);
12471:                     }
12472:                     push(@pathitems,$maptitle);
12473:                 }
12474:                 unless ($env{'request.state'} eq 'construct') {
12475:                     my $res = $navmap->getBySymb($symb);
12476:                     if (ref($res)) {
12477:                         my $partlist = $res->parts();
12478:                         my $totaluploads = 0;
12479:                         if (ref($partlist) eq 'ARRAY') {
12480:                             foreach my $part (@{$partlist}) {
12481:                                 my @types = $res->responseType($part);
12482:                                 my @ids = $res->responseIds($part);
12483:                                 for (my $i=0; $i < scalar(@ids); $i++) {
12484:                                     if ($types[$i] eq 'essay') {
12485:                                         my $partid = $part.'_'.$ids[$i];
12486:                                         if (&Apache::lonnet::EXT("resource.$partid.uploadedfiletypes") ne '') {
12487:                                             $totaluploads ++;
12488:                                         }
12489:                                     }
12490:                                 }
12491:                             }
12492:                             if ($totaluploads > 1) {
12493:                                 $multiresp = 1;
12494:                             }
12495:                         }
12496:                     }
12497:                 }
12498:             } else {
12499:                 return;
12500:             }
12501:         } else {
12502:             return;
12503:         }
12504:         my $restitle=&Apache::lonnet::gettitle($symb);
12505:         $restitle =~ s/\W+/_/g;
12506:         if ($restitle eq '') {
12507:             $restitle = ($resurl =~ m{/[^/]+$});
12508:             if ($restitle eq '') {
12509:                 $restitle = time;
12510:             }
12511:         }
12512:         if (length($restitle) > 12) {
12513:             $restitle = substr($restitle,0,12);
12514:         }
12515:         push(@pathitems,$restitle);
12516:         $path .= join('/',@pathitems);
12517:     }
12518:     return ($path,$multiresp);
12519: }
12520: 
12521: =pod
12522: 
12523: =back
12524: 
12525: =head1 CSV Upload/Handling functions
12526: 
12527: =over 4
12528: 
12529: =item * &upfile_store($r)
12530: 
12531: Store uploaded file, $r should be the HTTP Request object,
12532: needs $env{'form.upfile'}
12533: returns $datatoken to be put into hidden field
12534: 
12535: =cut
12536: 
12537: sub upfile_store {
12538:     my $r=shift;
12539:     $env{'form.upfile'}=~s/\r/\n/gs;
12540:     $env{'form.upfile'}=~s/\f/\n/gs;
12541:     $env{'form.upfile'}=~s/\n+/\n/gs;
12542:     $env{'form.upfile'}=~s/\n+$//gs;
12543: 
12544:     my $datatoken=$env{'user.name'}.'_'.$env{'user.domain'}.
12545: 	'_enroll_'.$env{'request.course.id'}.'_'.time.'_'.$$;
12546:     {
12547:         my $datafile = $r->dir_config('lonDaemons').
12548:                            '/tmp/'.$datatoken.'.tmp';
12549:         if ( open(my $fh,">$datafile") ) {
12550:             print $fh $env{'form.upfile'};
12551:             close($fh);
12552:         }
12553:     }
12554:     return $datatoken;
12555: }
12556: 
12557: =pod
12558: 
12559: =item * &load_tmp_file($r)
12560: 
12561: Load uploaded file from tmp, $r should be the HTTP Request object,
12562: needs $env{'form.datatoken'},
12563: sets $env{'form.upfile'} to the contents of the file
12564: 
12565: =cut
12566: 
12567: sub load_tmp_file {
12568:     my $r=shift;
12569:     my @studentdata=();
12570:     {
12571:         my $studentfile = $r->dir_config('lonDaemons').
12572:                               '/tmp/'.$env{'form.datatoken'}.'.tmp';
12573:         if ( open(my $fh,"<$studentfile") ) {
12574:             @studentdata=<$fh>;
12575:             close($fh);
12576:         }
12577:     }
12578:     $env{'form.upfile'}=join('',@studentdata);
12579: }
12580: 
12581: =pod
12582: 
12583: =item * &upfile_record_sep()
12584: 
12585: Separate uploaded file into records
12586: returns array of records,
12587: needs $env{'form.upfile'} and $env{'form.upfiletype'}
12588: 
12589: =cut
12590: 
12591: sub upfile_record_sep {
12592:     if ($env{'form.upfiletype'} eq 'xml') {
12593:     } else {
12594: 	my @records;
12595: 	foreach my $line (split(/\n/,$env{'form.upfile'})) {
12596: 	    if ($line=~/^\s*$/) { next; }
12597: 	    push(@records,$line);
12598: 	}
12599: 	return @records;
12600:     }
12601: }
12602: 
12603: =pod
12604: 
12605: =item * &record_sep($record)
12606: 
12607: Separate a record into fields $record should be an item from the upfile_record_sep(), needs $env{'form.upfiletype'}
12608: 
12609: =cut
12610: 
12611: sub takeleft {
12612:     my $index=shift;
12613:     return substr('0000'.$index,-4,4);
12614: }
12615: 
12616: sub record_sep {
12617:     my $record=shift;
12618:     my %components=();
12619:     if ($env{'form.upfiletype'} eq 'xml') {
12620:     } elsif ($env{'form.upfiletype'} eq 'space') {
12621:         my $i=0;
12622:         foreach my $field (split(/\s+/,$record)) {
12623:             $field=~s/^(\"|\')//;
12624:             $field=~s/(\"|\')$//;
12625:             $components{&takeleft($i)}=$field;
12626:             $i++;
12627:         }
12628:     } elsif ($env{'form.upfiletype'} eq 'tab') {
12629:         my $i=0;
12630:         foreach my $field (split(/\t/,$record)) {
12631:             $field=~s/^(\"|\')//;
12632:             $field=~s/(\"|\')$//;
12633:             $components{&takeleft($i)}=$field;
12634:             $i++;
12635:         }
12636:     } else {
12637:         my $separator=',';
12638:         if ($env{'form.upfiletype'} eq 'semisv') {
12639:             $separator=';';
12640:         }
12641:         my $i=0;
12642: # the character we are looking for to indicate the end of a quote or a record 
12643:         my $looking_for=$separator;
12644: # do not add the characters to the fields
12645:         my $ignore=0;
12646: # we just encountered a separator (or the beginning of the record)
12647:         my $just_found_separator=1;
12648: # store the field we are working on here
12649:         my $field='';
12650: # work our way through all characters in record
12651:         foreach my $character ($record=~/(.)/g) {
12652:             if ($character eq $looking_for) {
12653:                if ($character ne $separator) {
12654: # Found the end of a quote, again looking for separator
12655:                   $looking_for=$separator;
12656:                   $ignore=1;
12657:                } else {
12658: # Found a separator, store away what we got
12659:                   $components{&takeleft($i)}=$field;
12660: 	          $i++;
12661:                   $just_found_separator=1;
12662:                   $ignore=0;
12663:                   $field='';
12664:                }
12665:                next;
12666:             }
12667: # single or double quotation marks after a separator indicate beginning of a quote
12668: # we are now looking for the end of the quote and need to ignore separators
12669:             if ((($character eq '"') || ($character eq "'")) && ($just_found_separator))  {
12670:                $looking_for=$character;
12671:                next;
12672:             }
12673: # ignore would be true after we reached the end of a quote
12674:             if ($ignore) { next; }
12675:             if (($just_found_separator) && ($character=~/\s/)) { next; }
12676:             $field.=$character;
12677:             $just_found_separator=0; 
12678:         }
12679: # catch the very last entry, since we never encountered the separator
12680:         $components{&takeleft($i)}=$field;
12681:     }
12682:     return %components;
12683: }
12684: 
12685: ######################################################
12686: ######################################################
12687: 
12688: =pod
12689: 
12690: =item * &upfile_select_html()
12691: 
12692: Return HTML code to select a file from the users machine and specify 
12693: the file type.
12694: 
12695: =cut
12696: 
12697: ######################################################
12698: ######################################################
12699: sub upfile_select_html {
12700:     my %Types = (
12701:                  csv   => &mt('CSV (comma separated values, spreadsheet)'),
12702:                  semisv => &mt('Semicolon separated values'),
12703:                  space => &mt('Space separated'),
12704:                  tab   => &mt('Tabulator separated'),
12705: #                 xml   => &mt('HTML/XML'),
12706:                  );
12707:     my $Str = '<input type="file" name="upfile" size="50" />'.
12708:         '<br />'.&mt('Type').': <select name="upfiletype">';
12709:     foreach my $type (sort(keys(%Types))) {
12710:         $Str .= '<option value="'.$type.'" >'.$Types{$type}."</option>\n";
12711:     }
12712:     $Str .= "</select>\n";
12713:     return $Str;
12714: }
12715: 
12716: sub get_samples {
12717:     my ($records,$toget) = @_;
12718:     my @samples=({});
12719:     my $got=0;
12720:     foreach my $rec (@$records) {
12721: 	my %temp = &record_sep($rec);
12722: 	if (! grep(/\S/, values(%temp))) { next; }
12723: 	if (%temp) {
12724: 	    $samples[$got]=\%temp;
12725: 	    $got++;
12726: 	    if ($got == $toget) { last; }
12727: 	}
12728:     }
12729:     return \@samples;
12730: }
12731: 
12732: ######################################################
12733: ######################################################
12734: 
12735: =pod
12736: 
12737: =item * &csv_print_samples($r,$records)
12738: 
12739: Prints a table of sample values from each column uploaded $r is an
12740: Apache Request ref, $records is an arrayref from
12741: &Apache::loncommon::upfile_record_sep
12742: 
12743: =cut
12744: 
12745: ######################################################
12746: ######################################################
12747: sub csv_print_samples {
12748:     my ($r,$records) = @_;
12749:     my $samples = &get_samples($records,5);
12750: 
12751:     $r->print(&mt('Samples').'<br />'.&start_data_table().
12752:               &start_data_table_header_row());
12753:     foreach my $sample (sort({$a <=> $b} keys(%{ $samples->[0] }))) { 
12754:         $r->print('<th>'.&mt('Column [_1]',($sample+1)).'</th>'); }
12755:     $r->print(&end_data_table_header_row());
12756:     foreach my $hash (@$samples) {
12757: 	$r->print(&start_data_table_row());
12758: 	foreach my $sample (sort({$a <=> $b} keys(%{ $samples->[0] }))) {
12759: 	    $r->print('<td>');
12760: 	    if (defined($$hash{$sample})) { $r->print($$hash{$sample}); }
12761: 	    $r->print('</td>');
12762: 	}
12763: 	$r->print(&end_data_table_row());
12764:     }
12765:     $r->print(&end_data_table().'<br />'."\n");
12766: }
12767: 
12768: ######################################################
12769: ######################################################
12770: 
12771: =pod
12772: 
12773: =item * &csv_print_select_table($r,$records,$d)
12774: 
12775: Prints a table to create associations between values and table columns.
12776: 
12777: $r is an Apache Request ref,
12778: $records is an arrayref from &Apache::loncommon::upfile_record_sep,
12779: $d is an array of 2 element arrays (internal name, displayed name,defaultcol)
12780: 
12781: =cut
12782: 
12783: ######################################################
12784: ######################################################
12785: sub csv_print_select_table {
12786:     my ($r,$records,$d) = @_;
12787:     my $i=0;
12788:     my $samples = &get_samples($records,1);
12789:     $r->print(&mt('Associate columns with student attributes.')."\n".
12790: 	      &start_data_table().&start_data_table_header_row().
12791:               '<th>'.&mt('Attribute').'</th>'.
12792:               '<th>'.&mt('Column').'</th>'.
12793:               &end_data_table_header_row()."\n");
12794:     foreach my $array_ref (@$d) {
12795: 	my ($value,$display,$defaultcol)=@{ $array_ref };
12796: 	$r->print(&start_data_table_row().'<td>'.$display.'</td>');
12797: 
12798: 	$r->print('<td><select name="f'.$i.'"'.
12799: 		  ' onchange="javascript:flip(this.form,'.$i.');">');
12800: 	$r->print('<option value="none"></option>');
12801: 	foreach my $sample (sort({$a <=> $b} keys(%{ $samples->[0] }))) {
12802: 	    $r->print('<option value="'.$sample.'"'.
12803:                       ($sample eq $defaultcol ? ' selected="selected" ' : '').
12804:                       '>'.&mt('Column [_1]',($sample+1)).'</option>');
12805: 	}
12806: 	$r->print('</select></td>'.&end_data_table_row()."\n");
12807: 	$i++;
12808:     }
12809:     $r->print(&end_data_table());
12810:     $i--;
12811:     return $i;
12812: }
12813: 
12814: ######################################################
12815: ######################################################
12816: 
12817: =pod
12818: 
12819: =item * &csv_samples_select_table($r,$records,$d)
12820: 
12821: Prints a table of sample values from the upload and can make associate samples to internal names.
12822: 
12823: $r is an Apache Request ref,
12824: $records is an arrayref from &Apache::loncommon::upfile_record_sep,
12825: $d is an array of 2 element arrays (internal name, displayed name)
12826: 
12827: =cut
12828: 
12829: ######################################################
12830: ######################################################
12831: sub csv_samples_select_table {
12832:     my ($r,$records,$d) = @_;
12833:     my $i=0;
12834:     #
12835:     my $max_samples = 5;
12836:     my $samples = &get_samples($records,$max_samples);
12837:     $r->print(&start_data_table().
12838:               &start_data_table_header_row().'<th>'.
12839:               &mt('Field').'</th><th>'.&mt('Samples').'</th>'.
12840:               &end_data_table_header_row());
12841: 
12842:     foreach my $key (sort(keys(%{ $samples->[0] }))) {
12843: 	$r->print(&start_data_table_row().'<td><select name="f'.$i.'"'.
12844: 		  ' onchange="javascript:flip(this.form,'.$i.');">');
12845: 	foreach my $option (@$d) {
12846: 	    my ($value,$display,$defaultcol)=@{ $option };
12847: 	    $r->print('<option value="'.$value.'"'.
12848:                       ($i eq $defaultcol ? ' selected="selected" ':'').'>'.
12849:                       $display.'</option>');
12850: 	}
12851: 	$r->print('</select></td><td>');
12852: 	foreach my $line (0..($max_samples-1)) {
12853: 	    if (defined($samples->[$line]{$key})) { 
12854: 		$r->print($samples->[$line]{$key}."<br />\n"); 
12855: 	    }
12856: 	}
12857: 	$r->print('</td>'.&end_data_table_row());
12858: 	$i++;
12859:     }
12860:     $r->print(&end_data_table());
12861:     $i--;
12862:     return($i);
12863: }
12864: 
12865: ######################################################
12866: ######################################################
12867: 
12868: =pod
12869: 
12870: =item * &clean_excel_name($name)
12871: 
12872: Returns a replacement for $name which does not contain any illegal characters.
12873: 
12874: =cut
12875: 
12876: ######################################################
12877: ######################################################
12878: sub clean_excel_name {
12879:     my ($name) = @_;
12880:     $name =~ s/[:\*\?\/\\]//g;
12881:     if (length($name) > 31) {
12882:         $name = substr($name,0,31);
12883:     }
12884:     return $name;
12885: }
12886: 
12887: =pod
12888: 
12889: =item * &check_if_partid_hidden($id,$symb,$udom,$uname)
12890: 
12891: Returns either 1 or undef
12892: 
12893: 1 if the part is to be hidden, undef if it is to be shown
12894: 
12895: Arguments are:
12896: 
12897: $id the id of the part to be checked
12898: $symb, optional the symb of the resource to check
12899: $udom, optional the domain of the user to check for
12900: $uname, optional the username of the user to check for
12901: 
12902: =cut
12903: 
12904: sub check_if_partid_hidden {
12905:     my ($id,$symb,$udom,$uname) = @_;
12906:     my $hiddenparts=&Apache::lonnet::EXT('resource.0.hiddenparts',
12907: 					 $symb,$udom,$uname);
12908:     my $truth=1;
12909:     #if the string starts with !, then the list is the list to show not hide
12910:     if ($hiddenparts=~s/^\s*!//) { $truth=undef; }
12911:     my @hiddenlist=split(/,/,$hiddenparts);
12912:     foreach my $checkid (@hiddenlist) {
12913: 	if ($checkid =~ /^\s*\Q$id\E\s*$/) { return $truth; }
12914:     }
12915:     return !$truth;
12916: }
12917: 
12918: 
12919: ############################################################
12920: ############################################################
12921: 
12922: =pod
12923: 
12924: =back 
12925: 
12926: =head1 cgi-bin script and graphing routines
12927: 
12928: =over 4
12929: 
12930: =item * &get_cgi_id()
12931: 
12932: Inputs: none
12933: 
12934: Returns an id which can be used to pass environment variables
12935: to various cgi-bin scripts.  These environment variables will
12936: be removed from the users environment after a given time by
12937: the routine &Apache::lonnet::transfer_profile_to_env.
12938: 
12939: =cut
12940: 
12941: ############################################################
12942: ############################################################
12943: my $uniq=0;
12944: sub get_cgi_id {
12945:     $uniq=($uniq+1)%100000;
12946:     return (time.'_'.$$.'_'.$uniq);
12947: }
12948: 
12949: ############################################################
12950: ############################################################
12951: 
12952: =pod
12953: 
12954: =item * &DrawBarGraph()
12955: 
12956: Facilitates the plotting of data in a (stacked) bar graph.
12957: Puts plot definition data into the users environment in order for 
12958: graph.png to plot it.  Returns an <img> tag for the plot.
12959: The bars on the plot are labeled '1','2',...,'n'.
12960: 
12961: Inputs:
12962: 
12963: =over 4
12964: 
12965: =item $Title: string, the title of the plot
12966: 
12967: =item $xlabel: string, text describing the X-axis of the plot
12968: 
12969: =item $ylabel: string, text describing the Y-axis of the plot
12970: 
12971: =item $Max: scalar, the maximum Y value to use in the plot
12972: If $Max is < any data point, the graph will not be rendered.
12973: 
12974: =item $colors: array ref holding the colors to be used for the data sets when
12975: they are plotted.  If undefined, default values will be used.
12976: 
12977: =item $labels: array ref holding the labels to use on the x-axis for the bars.
12978: 
12979: =item @Values: An array of array references.  Each array reference holds data
12980: to be plotted in a stacked bar chart.
12981: 
12982: =item If the final element of @Values is a hash reference the key/value
12983: pairs will be added to the graph definition.
12984: 
12985: =back
12986: 
12987: Returns:
12988: 
12989: An <img> tag which references graph.png and the appropriate identifying
12990: information for the plot.
12991: 
12992: =cut
12993: 
12994: ############################################################
12995: ############################################################
12996: sub DrawBarGraph {
12997:     my ($Title,$xlabel,$ylabel,$Max,$colors,$labels,@Values)=@_;
12998:     #
12999:     if (! defined($colors)) {
13000:         $colors = ['#33ff00', 
13001:                   '#0033cc', '#990000', '#aaaa66', '#663399', '#ff9933',
13002:                   '#66ccff', '#ff9999', '#cccc33', '#660000', '#33cc66',
13003:                   ]; 
13004:     }
13005:     my $extra_settings = {};
13006:     if (ref($Values[-1]) eq 'HASH') {
13007:         $extra_settings = pop(@Values);
13008:     }
13009:     #
13010:     my $identifier = &get_cgi_id();
13011:     my $id = 'cgi.'.$identifier;        
13012:     if (! @Values || ref($Values[0]) ne 'ARRAY') {
13013:         return '';
13014:     }
13015:     #
13016:     my @Labels;
13017:     if (defined($labels)) {
13018:         @Labels = @$labels;
13019:     } else {
13020:         for (my $i=0;$i<@{$Values[0]};$i++) {
13021:             push (@Labels,$i+1);
13022:         }
13023:     }
13024:     #
13025:     my $NumBars = scalar(@{$Values[0]});
13026:     if ($NumBars < scalar(@Labels)) { $NumBars = scalar(@Labels); }
13027:     my %ValuesHash;
13028:     my $NumSets=1;
13029:     foreach my $array (@Values) {
13030:         next if (! ref($array));
13031:         $ValuesHash{$id.'.data.'.$NumSets++} = 
13032:             join(',',@$array);
13033:     }
13034:     #
13035:     my ($height,$width,$xskip,$bar_width) = (200,120,1,15);
13036:     if ($NumBars < 3) {
13037:         $width = 120+$NumBars*32;
13038:         $xskip = 1;
13039:         $bar_width = 30;
13040:     } elsif ($NumBars < 5) {
13041:         $width = 120+$NumBars*20;
13042:         $xskip = 1;
13043:         $bar_width = 20;
13044:     } elsif ($NumBars < 10) {
13045:         $width = 120+$NumBars*15;
13046:         $xskip = 1;
13047:         $bar_width = 15;
13048:     } elsif ($NumBars <= 25) {
13049:         $width = 120+$NumBars*11;
13050:         $xskip = 5;
13051:         $bar_width = 8;
13052:     } elsif ($NumBars <= 50) {
13053:         $width = 120+$NumBars*8;
13054:         $xskip = 5;
13055:         $bar_width = 4;
13056:     } else {
13057:         $width = 120+$NumBars*8;
13058:         $xskip = 5;
13059:         $bar_width = 4;
13060:     }
13061:     #
13062:     $Max = 1 if ($Max < 1);
13063:     if ( int($Max) < $Max ) {
13064:         $Max++;
13065:         $Max = int($Max);
13066:     }
13067:     $Title  = '' if (! defined($Title));
13068:     $xlabel = '' if (! defined($xlabel));
13069:     $ylabel = '' if (! defined($ylabel));
13070:     $ValuesHash{$id.'.title'}    = &escape($Title);
13071:     $ValuesHash{$id.'.xlabel'}   = &escape($xlabel);
13072:     $ValuesHash{$id.'.ylabel'}   = &escape($ylabel);
13073:     $ValuesHash{$id.'.y_max_value'} = $Max;
13074:     $ValuesHash{$id.'.NumBars'}  = $NumBars;
13075:     $ValuesHash{$id.'.NumSets'}  = $NumSets;
13076:     $ValuesHash{$id.'.PlotType'} = 'bar';
13077:     $ValuesHash{$id.'.Colors'}   = join(',',@{$colors});
13078:     $ValuesHash{$id.'.height'}   = $height;
13079:     $ValuesHash{$id.'.width'}    = $width;
13080:     $ValuesHash{$id.'.xskip'}    = $xskip;
13081:     $ValuesHash{$id.'.bar_width'} = $bar_width;
13082:     $ValuesHash{$id.'.labels'} = join(',',@Labels);
13083:     #
13084:     # Deal with other parameters
13085:     while (my ($key,$value) = each(%$extra_settings)) {
13086:         $ValuesHash{$id.'.'.$key} = $value;
13087:     }
13088:     #
13089:     &Apache::lonnet::appenv(\%ValuesHash);
13090:     return '<img src="/cgi-bin/graph.png?'.$identifier.'" border="1" />';
13091: }
13092: 
13093: ############################################################
13094: ############################################################
13095: 
13096: =pod
13097: 
13098: =item * &DrawXYGraph()
13099: 
13100: Facilitates the plotting of data in an XY graph.
13101: Puts plot definition data into the users environment in order for 
13102: graph.png to plot it.  Returns an <img> tag for the plot.
13103: 
13104: Inputs:
13105: 
13106: =over 4
13107: 
13108: =item $Title: string, the title of the plot
13109: 
13110: =item $xlabel: string, text describing the X-axis of the plot
13111: 
13112: =item $ylabel: string, text describing the Y-axis of the plot
13113: 
13114: =item $Max: scalar, the maximum Y value to use in the plot
13115: If $Max is < any data point, the graph will not be rendered.
13116: 
13117: =item $colors: Array ref containing the hex color codes for the data to be 
13118: plotted in.  If undefined, default values will be used.
13119: 
13120: =item $Xlabels: Array ref containing the labels to be used for the X-axis.
13121: 
13122: =item $Ydata: Array ref containing Array refs.  
13123: Each of the contained arrays will be plotted as a separate curve.
13124: 
13125: =item %Values: hash indicating or overriding any default values which are 
13126: passed to graph.png.  
13127: Possible values are: width, xskip, x_ticks, x_tick_offset, among others.
13128: 
13129: =back
13130: 
13131: Returns:
13132: 
13133: An <img> tag which references graph.png and the appropriate identifying
13134: information for the plot.
13135: 
13136: =cut
13137: 
13138: ############################################################
13139: ############################################################
13140: sub DrawXYGraph {
13141:     my ($Title,$xlabel,$ylabel,$Max,$colors,$Xlabels,$Ydata,%Values)=@_;
13142:     #
13143:     # Create the identifier for the graph
13144:     my $identifier = &get_cgi_id();
13145:     my $id = 'cgi.'.$identifier;
13146:     #
13147:     $Title  = '' if (! defined($Title));
13148:     $xlabel = '' if (! defined($xlabel));
13149:     $ylabel = '' if (! defined($ylabel));
13150:     my %ValuesHash = 
13151:         (
13152:          $id.'.title'  => &escape($Title),
13153:          $id.'.xlabel' => &escape($xlabel),
13154:          $id.'.ylabel' => &escape($ylabel),
13155:          $id.'.y_max_value'=> $Max,
13156:          $id.'.labels'     => join(',',@$Xlabels),
13157:          $id.'.PlotType'   => 'XY',
13158:          );
13159:     #
13160:     if (defined($colors) && ref($colors) eq 'ARRAY') {
13161:         $ValuesHash{$id.'.Colors'}   = join(',',@{$colors});
13162:     }
13163:     #
13164:     if (! ref($Ydata) || ref($Ydata) ne 'ARRAY') {
13165:         return '';
13166:     }
13167:     my $NumSets=1;
13168:     foreach my $array (@{$Ydata}){
13169:         next if (! ref($array));
13170:         $ValuesHash{$id.'.data.'.$NumSets++} = join(',',@$array);
13171:     }
13172:     $ValuesHash{$id.'.NumSets'} = $NumSets-1;
13173:     #
13174:     # Deal with other parameters
13175:     while (my ($key,$value) = each(%Values)) {
13176:         $ValuesHash{$id.'.'.$key} = $value;
13177:     }
13178:     #
13179:     &Apache::lonnet::appenv(\%ValuesHash);
13180:     return '<img src="/cgi-bin/graph.png?'.$identifier.'" border="1" />';
13181: }
13182: 
13183: ############################################################
13184: ############################################################
13185: 
13186: =pod
13187: 
13188: =item * &DrawXYYGraph()
13189: 
13190: Facilitates the plotting of data in an XY graph with two Y axes.
13191: Puts plot definition data into the users environment in order for 
13192: graph.png to plot it.  Returns an <img> tag for the plot.
13193: 
13194: Inputs:
13195: 
13196: =over 4
13197: 
13198: =item $Title: string, the title of the plot
13199: 
13200: =item $xlabel: string, text describing the X-axis of the plot
13201: 
13202: =item $ylabel: string, text describing the Y-axis of the plot
13203: 
13204: =item $colors: Array ref containing the hex color codes for the data to be 
13205: plotted in.  If undefined, default values will be used.
13206: 
13207: =item $Xlabels: Array ref containing the labels to be used for the X-axis.
13208: 
13209: =item $Ydata1: The first data set
13210: 
13211: =item $Min1: The minimum value of the left Y-axis
13212: 
13213: =item $Max1: The maximum value of the left Y-axis
13214: 
13215: =item $Ydata2: The second data set
13216: 
13217: =item $Min2: The minimum value of the right Y-axis
13218: 
13219: =item $Max2: The maximum value of the left Y-axis
13220: 
13221: =item %Values: hash indicating or overriding any default values which are 
13222: passed to graph.png.  
13223: Possible values are: width, xskip, x_ticks, x_tick_offset, among others.
13224: 
13225: =back
13226: 
13227: Returns:
13228: 
13229: An <img> tag which references graph.png and the appropriate identifying
13230: information for the plot.
13231: 
13232: =cut
13233: 
13234: ############################################################
13235: ############################################################
13236: sub DrawXYYGraph {
13237:     my ($Title,$xlabel,$ylabel,$colors,$Xlabels,$Ydata1,$Min1,$Max1,
13238:                                         $Ydata2,$Min2,$Max2,%Values)=@_;
13239:     #
13240:     # Create the identifier for the graph
13241:     my $identifier = &get_cgi_id();
13242:     my $id = 'cgi.'.$identifier;
13243:     #
13244:     $Title  = '' if (! defined($Title));
13245:     $xlabel = '' if (! defined($xlabel));
13246:     $ylabel = '' if (! defined($ylabel));
13247:     my %ValuesHash = 
13248:         (
13249:          $id.'.title'  => &escape($Title),
13250:          $id.'.xlabel' => &escape($xlabel),
13251:          $id.'.ylabel' => &escape($ylabel),
13252:          $id.'.labels' => join(',',@$Xlabels),
13253:          $id.'.PlotType' => 'XY',
13254:          $id.'.NumSets' => 2,
13255:          $id.'.two_axes' => 1,
13256:          $id.'.y1_max_value' => $Max1,
13257:          $id.'.y1_min_value' => $Min1,
13258:          $id.'.y2_max_value' => $Max2,
13259:          $id.'.y2_min_value' => $Min2,
13260:          );
13261:     #
13262:     if (defined($colors) && ref($colors) eq 'ARRAY') {
13263:         $ValuesHash{$id.'.Colors'}   = join(',',@{$colors});
13264:     }
13265:     #
13266:     if (! ref($Ydata1) || ref($Ydata1) ne 'ARRAY' ||
13267:         ! ref($Ydata2) || ref($Ydata2) ne 'ARRAY'){
13268:         return '';
13269:     }
13270:     my $NumSets=1;
13271:     foreach my $array ($Ydata1,$Ydata2){
13272:         next if (! ref($array));
13273:         $ValuesHash{$id.'.data.'.$NumSets++} = join(',',@$array);
13274:     }
13275:     #
13276:     # Deal with other parameters
13277:     while (my ($key,$value) = each(%Values)) {
13278:         $ValuesHash{$id.'.'.$key} = $value;
13279:     }
13280:     #
13281:     &Apache::lonnet::appenv(\%ValuesHash);
13282:     return '<img src="/cgi-bin/graph.png?'.$identifier.'" border="1" />';
13283: }
13284: 
13285: ############################################################
13286: ############################################################
13287: 
13288: =pod
13289: 
13290: =back 
13291: 
13292: =head1 Statistics helper routines?  
13293: 
13294: Bad place for them but what the hell.
13295: 
13296: =over 4
13297: 
13298: =item * &chartlink()
13299: 
13300: Returns a link to the chart for a specific student.  
13301: 
13302: Inputs:
13303: 
13304: =over 4
13305: 
13306: =item $linktext: The text of the link
13307: 
13308: =item $sname: The students username
13309: 
13310: =item $sdomain: The students domain
13311: 
13312: =back
13313: 
13314: =back
13315: 
13316: =cut
13317: 
13318: ############################################################
13319: ############################################################
13320: sub chartlink {
13321:     my ($linktext, $sname, $sdomain) = @_;
13322:     my $link = '<a href="/adm/statistics?reportSelected=student_assessment'.
13323:         '&amp;SelectedStudent='.&escape($sname.':'.$sdomain).
13324:         '&amp;chartoutputmode='.HTML::Entities::encode('html, with all links').
13325:        '">'.$linktext.'</a>';
13326: }
13327: 
13328: #######################################################
13329: #######################################################
13330: 
13331: =pod
13332: 
13333: =head1 Course Environment Routines
13334: 
13335: =over 4
13336: 
13337: =item * &restore_course_settings()
13338: 
13339: =item * &store_course_settings()
13340: 
13341: Restores/Store indicated form parameters from the course environment.
13342: Will not overwrite existing values of the form parameters.
13343: 
13344: Inputs: 
13345: a scalar describing the data (e.g. 'chart', 'problem_analysis')
13346: 
13347: a hash ref describing the data to be stored.  For example:
13348:    
13349: %Save_Parameters = ('Status' => 'scalar',
13350:     'chartoutputmode' => 'scalar',
13351:     'chartoutputdata' => 'scalar',
13352:     'Section' => 'array',
13353:     'Group' => 'array',
13354:     'StudentData' => 'array',
13355:     'Maps' => 'array');
13356: 
13357: Returns: both routines return nothing
13358: 
13359: =back
13360: 
13361: =cut
13362: 
13363: #######################################################
13364: #######################################################
13365: sub store_course_settings {
13366:     return &store_settings($env{'request.course.id'},@_);
13367: }
13368: 
13369: sub store_settings {
13370:     # save to the environment
13371:     # appenv the same items, just to be safe
13372:     my $udom  = $env{'user.domain'};
13373:     my $uname = $env{'user.name'};
13374:     my ($context,$prefix,$Settings) = @_;
13375:     my %SaveHash;
13376:     my %AppHash;
13377:     while (my ($setting,$type) = each(%$Settings)) {
13378:         my $basename = join('.','internal',$context,$prefix,$setting);
13379:         my $envname = 'environment.'.$basename;
13380:         if (exists($env{'form.'.$setting})) {
13381:             # Save this value away
13382:             if ($type eq 'scalar' &&
13383:                 (! exists($env{$envname}) || 
13384:                  $env{$envname} ne $env{'form.'.$setting})) {
13385:                 $SaveHash{$basename} = $env{'form.'.$setting};
13386:                 $AppHash{$envname}   = $env{'form.'.$setting};
13387:             } elsif ($type eq 'array') {
13388:                 my $stored_form;
13389:                 if (ref($env{'form.'.$setting})) {
13390:                     $stored_form = join(',',
13391:                                         map {
13392:                                             &escape($_);
13393:                                         } sort(@{$env{'form.'.$setting}}));
13394:                 } else {
13395:                     $stored_form = 
13396:                         &escape($env{'form.'.$setting});
13397:                 }
13398:                 # Determine if the array contents are the same.
13399:                 if ($stored_form ne $env{$envname}) {
13400:                     $SaveHash{$basename} = $stored_form;
13401:                     $AppHash{$envname}   = $stored_form;
13402:                 }
13403:             }
13404:         }
13405:     }
13406:     my $put_result = &Apache::lonnet::put('environment',\%SaveHash,
13407:                                           $udom,$uname);
13408:     if ($put_result !~ /^(ok|delayed)/) {
13409:         &Apache::lonnet::logthis('unable to save form parameters, '.
13410:                                  'got error:'.$put_result);
13411:     }
13412:     # Make sure these settings stick around in this session, too
13413:     &Apache::lonnet::appenv(\%AppHash);
13414:     return;
13415: }
13416: 
13417: sub restore_course_settings {
13418:     return &restore_settings($env{'request.course.id'},@_);
13419: }
13420: 
13421: sub restore_settings {
13422:     my ($context,$prefix,$Settings) = @_;
13423:     while (my ($setting,$type) = each(%$Settings)) {
13424:         next if (exists($env{'form.'.$setting}));
13425:         my $envname = 'environment.internal.'.$context.'.'.$prefix.
13426:             '.'.$setting;
13427:         if (exists($env{$envname})) {
13428:             if ($type eq 'scalar') {
13429:                 $env{'form.'.$setting} = $env{$envname};
13430:             } elsif ($type eq 'array') {
13431:                 $env{'form.'.$setting} = [ 
13432:                                            map { 
13433:                                                &unescape($_); 
13434:                                            } split(',',$env{$envname})
13435:                                            ];
13436:             }
13437:         }
13438:     }
13439: }
13440: 
13441: #######################################################
13442: #######################################################
13443: 
13444: =pod
13445: 
13446: =head1 Domain E-mail Routines  
13447: 
13448: =over 4
13449: 
13450: =item * &build_recipient_list()
13451: 
13452: Build recipient lists for following types of e-mail:
13453: (a) Error Reports, (b) Package Updates, (c) lonstatus warnings/errors
13454: (d) Help requests, (e) Course requests needing approval, (f) loncapa
13455: module change checking, student/employee ID conflict checks, as
13456: generated by lonerrorhandler.pm, CHECKRPMS, loncron,
13457: lonsupportreq.pm, loncoursequeueadmin.pm, searchcat.pl respectively.
13458: 
13459: Inputs:
13460: defmail (scalar - email address of default recipient),
13461: mailing type (scalar: errormail, packagesmail, helpdeskmail,
13462: requestsmail, updatesmail, or idconflictsmail).
13463: 
13464: defdom (domain for which to retrieve configuration settings),
13465: 
13466: origmail (scalar - email address of recipient from loncapa.conf,
13467: i.e., predates configuration by DC via domainprefs.pm
13468: 
13469: Returns: comma separated list of addresses to which to send e-mail.
13470: 
13471: =back
13472: 
13473: =cut
13474: 
13475: ############################################################
13476: ############################################################
13477: sub build_recipient_list {
13478:     my ($defmail,$mailing,$defdom,$origmail) = @_;
13479:     my @recipients;
13480:     my $otheremails;
13481:     my %domconfig =
13482:          &Apache::lonnet::get_dom('configuration',['contacts'],$defdom);
13483:     if (ref($domconfig{'contacts'}) eq 'HASH') {
13484:         if (exists($domconfig{'contacts'}{$mailing})) {
13485:             if (ref($domconfig{'contacts'}{$mailing}) eq 'HASH') {
13486:                 my @contacts = ('adminemail','supportemail');
13487:                 foreach my $item (@contacts) {
13488:                     if ($domconfig{'contacts'}{$mailing}{$item}) {
13489:                         my $addr = $domconfig{'contacts'}{$item}; 
13490:                         if (!grep(/^\Q$addr\E$/,@recipients)) {
13491:                             push(@recipients,$addr);
13492:                         }
13493:                     }
13494:                     $otheremails = $domconfig{'contacts'}{$mailing}{'others'};
13495:                 }
13496:             }
13497:         } elsif ($origmail ne '') {
13498:             push(@recipients,$origmail);
13499:         }
13500:     } elsif ($origmail ne '') {
13501:         push(@recipients,$origmail);
13502:     }
13503:     if (defined($defmail)) {
13504:         if ($defmail ne '') {
13505:             push(@recipients,$defmail);
13506:         }
13507:     }
13508:     if ($otheremails) {
13509:         my @others;
13510:         if ($otheremails =~ /,/) {
13511:             @others = split(/,/,$otheremails);
13512:         } else {
13513:             push(@others,$otheremails);
13514:         }
13515:         foreach my $addr (@others) {
13516:             if (!grep(/^\Q$addr\E$/,@recipients)) {
13517:                 push(@recipients,$addr);
13518:             }
13519:         }
13520:     }
13521:     my $recipientlist = join(',',@recipients); 
13522:     return $recipientlist;
13523: }
13524: 
13525: ############################################################
13526: ############################################################
13527: 
13528: =pod
13529: 
13530: =head1 Course Catalog Routines
13531: 
13532: =over 4
13533: 
13534: =item * &gather_categories()
13535: 
13536: Converts category definitions - keys of categories hash stored in  
13537: coursecategories in configuration.db on the primary library server in a 
13538: domain - to an array.  Also generates javascript and idx hash used to 
13539: generate Domain Coordinator interface for editing Course Categories.
13540: 
13541: Inputs:
13542: 
13543: categories (reference to hash of category definitions).
13544: 
13545: cats (reference to array of arrays/hashes which encapsulates hierarchy of
13546:       categories and subcategories).
13547: 
13548: idx (reference to hash of counters used in Domain Coordinator interface for 
13549:       editing Course Categories).
13550: 
13551: jsarray (reference to array of categories used to create Javascript arrays for
13552:          Domain Coordinator interface for editing Course Categories).
13553: 
13554: Returns: nothing
13555: 
13556: Side effects: populates cats, idx and jsarray. 
13557: 
13558: =cut
13559: 
13560: sub gather_categories {
13561:     my ($categories,$cats,$idx,$jsarray) = @_;
13562:     my %counters;
13563:     my $num = 0;
13564:     foreach my $item (keys(%{$categories})) {
13565:         my ($cat,$container,$depth) = map { &unescape($_); } split(/:/,$item);
13566:         if ($container eq '' && $depth == 0) {
13567:             $cats->[$depth][$categories->{$item}] = $cat;
13568:         } else {
13569:             $cats->[$depth]{$container}[$categories->{$item}] = $cat;
13570:         }
13571:         my ($escitem,$tail) = split(/:/,$item,2);
13572:         if ($counters{$tail} eq '') {
13573:             $counters{$tail} = $num;
13574:             $num ++;
13575:         }
13576:         if (ref($idx) eq 'HASH') {
13577:             $idx->{$item} = $counters{$tail};
13578:         }
13579:         if (ref($jsarray) eq 'ARRAY') {
13580:             push(@{$jsarray->[$counters{$tail}]},$item);
13581:         }
13582:     }
13583:     return;
13584: }
13585: 
13586: =pod
13587: 
13588: =item * &extract_categories()
13589: 
13590: Used to generate breadcrumb trails for course categories.
13591: 
13592: Inputs:
13593: 
13594: categories (reference to hash of category definitions).
13595: 
13596: cats (reference to array of arrays/hashes which encapsulates hierarchy of
13597:       categories and subcategories).
13598: 
13599: trails (reference to array of breacrumb trails for each category).
13600: 
13601: allitems (reference to hash - key is category key 
13602:          (format: escaped(name):escaped(parent category):depth in hierarchy).
13603: 
13604: idx (reference to hash of counters used in Domain Coordinator interface for
13605:       editing Course Categories).
13606: 
13607: jsarray (reference to array of categories used to create Javascript arrays for
13608:          Domain Coordinator interface for editing Course Categories).
13609: 
13610: subcats (reference to hash of arrays containing all subcategories within each 
13611:          category, -recursive)
13612: 
13613: Returns: nothing
13614: 
13615: Side effects: populates trails and allitems hash references.
13616: 
13617: =cut
13618: 
13619: sub extract_categories {
13620:     my ($categories,$cats,$trails,$allitems,$idx,$jsarray,$subcats) = @_;
13621:     if (ref($categories) eq 'HASH') {
13622:         &gather_categories($categories,$cats,$idx,$jsarray);
13623:         if (ref($cats->[0]) eq 'ARRAY') {
13624:             for (my $i=0; $i<@{$cats->[0]}; $i++) {
13625:                 my $name = $cats->[0][$i];
13626:                 my $item = &escape($name).'::0';
13627:                 my $trailstr;
13628:                 if ($name eq 'instcode') {
13629:                     $trailstr = &mt('Official courses (with institutional codes)');
13630:                 } elsif ($name eq 'communities') {
13631:                     $trailstr = &mt('Communities');
13632:                 } else {
13633:                     $trailstr = $name;
13634:                 }
13635:                 if ($allitems->{$item} eq '') {
13636:                     push(@{$trails},$trailstr);
13637:                     $allitems->{$item} = scalar(@{$trails})-1;
13638:                 }
13639:                 my @parents = ($name);
13640:                 if (ref($cats->[1]{$name}) eq 'ARRAY') {
13641:                     for (my $j=0; $j<@{$cats->[1]{$name}}; $j++) {
13642:                         my $category = $cats->[1]{$name}[$j];
13643:                         if (ref($subcats) eq 'HASH') {
13644:                             push(@{$subcats->{$item}},&escape($category).':'.&escape($name).':1');
13645:                         }
13646:                         &recurse_categories($cats,2,$category,$trails,$allitems,\@parents,$subcats);
13647:                     }
13648:                 } else {
13649:                     if (ref($subcats) eq 'HASH') {
13650:                         $subcats->{$item} = [];
13651:                     }
13652:                 }
13653:             }
13654:         }
13655:     }
13656:     return;
13657: }
13658: 
13659: =pod
13660: 
13661: =item * &recurse_categories()
13662: 
13663: Recursively used to generate breadcrumb trails for course categories.
13664: 
13665: Inputs:
13666: 
13667: cats (reference to array of arrays/hashes which encapsulates hierarchy of
13668:       categories and subcategories).
13669: 
13670: depth (current depth in hierarchy of categories and sub-categories - 0 indexed).
13671: 
13672: category (current course category, for which breadcrumb trail is being generated).
13673: 
13674: trails (reference to array of breadcrumb trails for each category).
13675: 
13676: allitems (reference to hash - key is category key
13677:          (format: escaped(name):escaped(parent category):depth in hierarchy).
13678: 
13679: parents (array containing containers directories for current category, 
13680:          back to top level). 
13681: 
13682: Returns: nothing
13683: 
13684: Side effects: populates trails and allitems hash references
13685: 
13686: =cut
13687: 
13688: sub recurse_categories {
13689:     my ($cats,$depth,$category,$trails,$allitems,$parents,$subcats) = @_;
13690:     my $shallower = $depth - 1;
13691:     if (ref($cats->[$depth]{$category}) eq 'ARRAY') {
13692:         for (my $k=0; $k<@{$cats->[$depth]{$category}}; $k++) {
13693:             my $name = $cats->[$depth]{$category}[$k];
13694:             my $item = &escape($category).':'.&escape($parents->[-1]).':'.$shallower;
13695:             my $trailstr = join(' -&gt; ',(@{$parents},$category));
13696:             if ($allitems->{$item} eq '') {
13697:                 push(@{$trails},$trailstr);
13698:                 $allitems->{$item} = scalar(@{$trails})-1;
13699:             }
13700:             my $deeper = $depth+1;
13701:             push(@{$parents},$category);
13702:             if (ref($subcats) eq 'HASH') {
13703:                 my $subcat = &escape($name).':'.$category.':'.$depth;
13704:                 for (my $j=@{$parents}; $j>=0; $j--) {
13705:                     my $higher;
13706:                     if ($j > 0) {
13707:                         $higher = &escape($parents->[$j]).':'.
13708:                                   &escape($parents->[$j-1]).':'.$j;
13709:                     } else {
13710:                         $higher = &escape($parents->[$j]).'::'.$j;
13711:                     }
13712:                     push(@{$subcats->{$higher}},$subcat);
13713:                 }
13714:             }
13715:             &recurse_categories($cats,$deeper,$name,$trails,$allitems,$parents,
13716:                                 $subcats);
13717:             pop(@{$parents});
13718:         }
13719:     } else {
13720:         my $item = &escape($category).':'.&escape($parents->[-1]).':'.$shallower;
13721:         my $trailstr = join(' -&gt; ',(@{$parents},$category));
13722:         if ($allitems->{$item} eq '') {
13723:             push(@{$trails},$trailstr);
13724:             $allitems->{$item} = scalar(@{$trails})-1;
13725:         }
13726:     }
13727:     return;
13728: }
13729: 
13730: =pod
13731: 
13732: =item * &assign_categories_table()
13733: 
13734: Create a datatable for display of hierarchical categories in a domain,
13735: with checkboxes to allow a course to be categorized. 
13736: 
13737: Inputs:
13738: 
13739: cathash - reference to hash of categories defined for the domain (from
13740:           configuration.db)
13741: 
13742: currcat - scalar with an & separated list of categories assigned to a course. 
13743: 
13744: type    - scalar contains course type (Course or Community).
13745: 
13746: Returns: $output (markup to be displayed) 
13747: 
13748: =cut
13749: 
13750: sub assign_categories_table {
13751:     my ($cathash,$currcat,$type) = @_;
13752:     my $output;
13753:     if (ref($cathash) eq 'HASH') {
13754:         my (@cats,@trails,%allitems,%idx,@jsarray,@path,$maxdepth);
13755:         &extract_categories($cathash,\@cats,\@trails,\%allitems,\%idx,\@jsarray);
13756:         $maxdepth = scalar(@cats);
13757:         if (@cats > 0) {
13758:             my $itemcount = 0;
13759:             if (ref($cats[0]) eq 'ARRAY') {
13760:                 my @currcategories;
13761:                 if ($currcat ne '') {
13762:                     @currcategories = split('&',$currcat);
13763:                 }
13764:                 my $table;
13765:                 for (my $i=0; $i<@{$cats[0]}; $i++) {
13766:                     my $parent = $cats[0][$i];
13767:                     next if ($parent eq 'instcode');
13768:                     if ($type eq 'Community') {
13769:                         next unless ($parent eq 'communities');
13770:                     } else {
13771:                         next if ($parent eq 'communities');
13772:                     }
13773:                     my $css_class = $itemcount%2?' class="LC_odd_row"':'';
13774:                     my $item = &escape($parent).'::0';
13775:                     my $checked = '';
13776:                     if (@currcategories > 0) {
13777:                         if (grep(/^\Q$item\E$/,@currcategories)) {
13778:                             $checked = ' checked="checked"';
13779:                         }
13780:                     }
13781:                     my $parent_title = $parent;
13782:                     if ($parent eq 'communities') {
13783:                         $parent_title = &mt('Communities');
13784:                     }
13785:                     $table .= '<tr '.$css_class.'><td><span class="LC_nobreak">'.
13786:                               '<input type="checkbox" name="usecategory" value="'.
13787:                               $item.'"'.$checked.' />'.$parent_title.'</span>'.
13788:                               '<input type="hidden" name="catname" value="'.$parent.'" /></td>';
13789:                     my $depth = 1;
13790:                     push(@path,$parent);
13791:                     $table .= &assign_category_rows($itemcount,\@cats,$depth,$parent,\@path,\@currcategories);
13792:                     pop(@path);
13793:                     $table .= '</tr><tr><td colspan="'.$maxdepth.'" class="LC_row_separator"></td></tr>';
13794:                     $itemcount ++;
13795:                 }
13796:                 if ($itemcount) {
13797:                     $output = &Apache::loncommon::start_data_table().
13798:                               $table.
13799:                               &Apache::loncommon::end_data_table();
13800:                 }
13801:             }
13802:         }
13803:     }
13804:     return $output;
13805: }
13806: 
13807: =pod
13808: 
13809: =item * &assign_category_rows()
13810: 
13811: Create a datatable row for display of nested categories in a domain,
13812: with checkboxes to allow a course to be categorized,called recursively.
13813: 
13814: Inputs:
13815: 
13816: itemcount - track row number for alternating colors
13817: 
13818: cats - reference to array of arrays/hashes which encapsulates hierarchy of
13819:       categories and subcategories.
13820: 
13821: depth - current depth in hierarchy of categories and sub-categories - 0 indexed.
13822: 
13823: parent - parent of current category item
13824: 
13825: path - Array containing all categories back up through the hierarchy from the
13826:        current category to the top level.
13827: 
13828: currcategories - reference to array of current categories assigned to the course
13829: 
13830: Returns: $output (markup to be displayed).
13831: 
13832: =cut
13833: 
13834: sub assign_category_rows {
13835:     my ($itemcount,$cats,$depth,$parent,$path,$currcategories) = @_;
13836:     my ($text,$name,$item,$chgstr);
13837:     if (ref($cats) eq 'ARRAY') {
13838:         my $maxdepth = scalar(@{$cats});
13839:         if (ref($cats->[$depth]) eq 'HASH') {
13840:             if (ref($cats->[$depth]{$parent}) eq 'ARRAY') {
13841:                 my $numchildren = @{$cats->[$depth]{$parent}};
13842:                 my $css_class = $itemcount%2?' class="LC_odd_row"':'';
13843:                 $text .= '<td><table class="LC_data_table">';
13844:                 for (my $j=0; $j<$numchildren; $j++) {
13845:                     $name = $cats->[$depth]{$parent}[$j];
13846:                     $item = &escape($name).':'.&escape($parent).':'.$depth;
13847:                     my $deeper = $depth+1;
13848:                     my $checked = '';
13849:                     if (ref($currcategories) eq 'ARRAY') {
13850:                         if (@{$currcategories} > 0) {
13851:                             if (grep(/^\Q$item\E$/,@{$currcategories})) {
13852:                                 $checked = ' checked="checked"';
13853:                             }
13854:                         }
13855:                     }
13856:                     $text .= '<tr><td><span class="LC_nobreak"><label>'.
13857:                              '<input type="checkbox" name="usecategory" value="'.
13858:                              $item.'"'.$checked.' />'.$name.'</label></span>'.
13859:                              '<input type="hidden" name="catname" value="'.$name.'" />'.
13860:                              '</td><td>';
13861:                     if (ref($path) eq 'ARRAY') {
13862:                         push(@{$path},$name);
13863:                         $text .= &assign_category_rows($itemcount,$cats,$deeper,$name,$path,$currcategories);
13864:                         pop(@{$path});
13865:                     }
13866:                     $text .= '</td></tr>';
13867:                 }
13868:                 $text .= '</table></td>';
13869:             }
13870:         }
13871:     }
13872:     return $text;
13873: }
13874: 
13875: =pod
13876: 
13877: =back
13878: 
13879: =cut
13880: 
13881: ############################################################
13882: ############################################################
13883: 
13884: 
13885: sub commit_customrole {
13886:     my ($udom,$uname,$url,$three,$four,$five,$start,$end,$context) = @_;
13887:     my $output = &mt('Assigning custom role').' "'.$five.'" by '.$four.':'.$three.' in '.$url.
13888:                          ($start?', '.&mt('starting').' '.localtime($start):'').
13889:                          ($end?', ending '.localtime($end):'').': <b>'.
13890:               &Apache::lonnet::assigncustomrole(
13891:                  $udom,$uname,$url,$three,$four,$five,$end,$start,undef,undef,$context).
13892:                  '</b><br />';
13893:     return $output;
13894: }
13895: 
13896: sub commit_standardrole {
13897:     my ($udom,$uname,$url,$three,$start,$end,$one,$two,$sec,$context,$credits) = @_;
13898:     my ($output,$logmsg,$linefeed);
13899:     if ($context eq 'auto') {
13900:         $linefeed = "\n";
13901:     } else {
13902:         $linefeed = "<br />\n";
13903:     }  
13904:     if ($three eq 'st') {
13905:         my $result = &commit_studentrole(\$logmsg,$udom,$uname,$url,$three,$start,$end,
13906:                                          $one,$two,$sec,$context,$credits);
13907:         if (($result =~ /^error/) || ($result eq 'not_in_class') || 
13908:             ($result eq 'unknown_course') || ($result eq 'refused')) {
13909:             $output = $logmsg.' '.&mt('Error: ').$result."\n"; 
13910:         } else {
13911:             $output = $logmsg.$linefeed.&mt('Assigning').' '.$three.' in '.$url.
13912:                ($start?', '.&mt('starting').' '.localtime($start):'').
13913:                ($end?', '.&mt('ending').' '.localtime($end):'').': ';
13914:             if ($context eq 'auto') {
13915:                 $output .= $result.$linefeed.&mt('Add to classlist').': ok';
13916:             } else {
13917:                $output .= '<b>'.$result.'</b>'.$linefeed.
13918:                &mt('Add to classlist').': <b>ok</b>';
13919:             }
13920:             $output .= $linefeed;
13921:         }
13922:     } else {
13923:         $output = &mt('Assigning').' '.$three.' in '.$url.
13924:                ($start?', '.&mt('starting').' '.localtime($start):'').
13925:                ($end?', '.&mt('ending').' '.localtime($end):'').': ';
13926:         my $result = &Apache::lonnet::assignrole($udom,$uname,$url,$three,$end,$start,'','',$context);
13927:         if ($context eq 'auto') {
13928:             $output .= $result.$linefeed;
13929:         } else {
13930:             $output .= '<b>'.$result.'</b>'.$linefeed;
13931:         }
13932:     }
13933:     return $output;
13934: }
13935: 
13936: sub commit_studentrole {
13937:     my ($logmsg,$udom,$uname,$url,$three,$start,$end,$one,$two,$sec,$context,
13938:         $credits) = @_;
13939:     my ($result,$linefeed,$oldsecurl,$newsecurl);
13940:     if ($context eq 'auto') {
13941:         $linefeed = "\n";
13942:     } else {
13943:         $linefeed = '<br />'."\n";
13944:     }
13945:     if (defined($one) && defined($two)) {
13946:         my $cid=$one.'_'.$two;
13947:         my $oldsec=&Apache::lonnet::getsection($udom,$uname,$cid);
13948:         my $secchange = 0;
13949:         my $expire_role_result;
13950:         my $modify_section_result;
13951:         if ($oldsec ne '-1') { 
13952:             if ($oldsec ne $sec) {
13953:                 $secchange = 1;
13954:                 my $now = time;
13955:                 my $uurl='/'.$cid;
13956:                 $uurl=~s/\_/\//g;
13957:                 if ($oldsec) {
13958:                     $uurl.='/'.$oldsec;
13959:                 }
13960:                 $oldsecurl = $uurl;
13961:                 $expire_role_result = 
13962:                     &Apache::lonnet::assignrole($udom,$uname,$uurl,'st',$now,'','',$context);
13963:                 if ($env{'request.course.sec'} ne '') { 
13964:                     if ($expire_role_result eq 'refused') {
13965:                         my @roles = ('st');
13966:                         my @statuses = ('previous');
13967:                         my @roledoms = ($one);
13968:                         my $withsec = 1;
13969:                         my %roleshash = 
13970:                             &Apache::lonnet::get_my_roles($uname,$udom,'userroles',
13971:                                               \@statuses,\@roles,\@roledoms,$withsec);
13972:                         if (defined ($roleshash{$two.':'.$one.':st:'.$oldsec})) {
13973:                             my ($oldstart,$oldend) = 
13974:                                 split(':',$roleshash{$two.':'.$one.':st:'.$oldsec});
13975:                             if ($oldend > 0 && $oldend <= $now) {
13976:                                 $expire_role_result = 'ok';
13977:                             }
13978:                         }
13979:                     }
13980:                 }
13981:                 $result = $expire_role_result;
13982:             }
13983:         }
13984:         if (($expire_role_result eq 'ok') || ($secchange == 0)) {
13985:             $modify_section_result = 
13986:                 &Apache::lonnet::modify_student_enrollment($udom,$uname,undef,undef,
13987:                                                            undef,undef,undef,$sec,
13988:                                                            $end,$start,'','',$cid,
13989:                                                            '',$context,$credits);
13990:             if ($modify_section_result =~ /^ok/) {
13991:                 if ($secchange == 1) {
13992:                     if ($sec eq '') {
13993:                         $$logmsg .= &mt('Section for [_1] switched from (possibly expired) old section: [_2] to student role without a section.',$uname,$oldsec).$linefeed;
13994:                     } else {
13995:                         $$logmsg .= &mt('Section for [_1] switched from (possibly expired) old section: [_2] to new section: [_3].',$uname,$oldsec,$sec).$linefeed;
13996:                     }
13997:                 } elsif ($oldsec eq '-1') {
13998:                     if ($sec eq '') {
13999:                         $$logmsg .= &mt('New student role without a section for [_1] in course [_2].',$uname,$cid).$linefeed;
14000:                     } else {
14001:                         $$logmsg .= &mt('New student role for [_1] in section [_2] in course [_3].',$uname,$sec,$cid).$linefeed;
14002:                     }
14003:                 } else {
14004:                     if ($sec eq '') {
14005:                         $$logmsg .= &mt('Student [_1] assigned to course [_2] without a section.',$uname,$cid).$linefeed;
14006:                     } else {
14007:                         $$logmsg .= &mt('Student [_1] assigned to section [_2] in course [_3].',$uname,$sec,$cid).$linefeed;
14008:                     }
14009:                 }
14010:             } else {
14011:                 if ($secchange) {       
14012:                     $$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;
14013:                 } else {
14014:                     $$logmsg .= &mt('Error when attempting to modify role for [_1] for section: "[_2]" in course [_3] -error:',$uname,$sec,$cid).' '.$modify_section_result.$linefeed;
14015:                 }
14016:             }
14017:             $result = $modify_section_result;
14018:         } elsif ($secchange == 1) {
14019:             if ($oldsec eq '') {
14020:                 $$logmsg .= &mt('Error when attempting to expire existing role without a section for [_1] in course [_2] -error: ',$uname,$cid).' '.$expire_role_result.$linefeed;
14021:             } else {
14022:                 $$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;
14023:             }
14024:             if ($expire_role_result eq 'refused') {
14025:                 my $newsecurl = '/'.$cid;
14026:                 $newsecurl =~ s/\_/\//g;
14027:                 if ($sec ne '') {
14028:                     $newsecurl.='/'.$sec;
14029:                 }
14030:                 if (&Apache::lonnet::allowed('cst',$newsecurl) && !(&Apache::lonnet::allowed('cst',$oldsecurl))) {
14031:                     if ($sec eq '') {
14032:                         $$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;
14033:                     } else {
14034:                         $$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;
14035:                     }
14036:                 }
14037:             }
14038:         }
14039:     } else {
14040:         $$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;
14041:         $result = "error: incomplete course id\n";
14042:     }
14043:     return $result;
14044: }
14045: 
14046: sub show_role_extent {
14047:     my ($scope,$context,$role) = @_;
14048:     $scope =~ s{^/}{};
14049:     my @courseroles = &Apache::lonuserutils::roles_by_context('course',1);
14050:     push(@courseroles,'co');
14051:     my @authorroles = &Apache::lonuserutils::roles_by_context('author');
14052:     if (($context eq 'course') || (grep(/^\Q$role\E/,@courseroles))) {
14053:         $scope =~ s{/}{_};
14054:         return '<span class="LC_cusr_emph">'.$env{'course.'.$scope.'.description'}.'</span>';
14055:     } elsif (($context eq 'author') || (grep(/^\Q$role\E/,@authorroles))) {
14056:         my ($audom,$auname) = split(/\//,$scope);
14057:         return &mt('[_1] Author Space','<span class="LC_cusr_emph">'.
14058:                    &Apache::loncommon::plainname($auname,$audom).'</span>');
14059:     } else {
14060:         $scope =~ s{/$}{};
14061:         return &mt('Domain: [_1]','<span class="LC_cusr_emph">'.
14062:                    &Apache::lonnet::domain($scope,'description').'</span>');
14063:     }
14064: }
14065: 
14066: ############################################################
14067: ############################################################
14068: 
14069: sub check_clone {
14070:     my ($args,$linefeed) = @_;
14071:     my $cloneid='/'.$args->{'clonedomain'}.'/'.$args->{'clonecourse'};
14072:     my ($clonecrsudom,$clonecrsunum)= &LONCAPA::split_courseid($cloneid);
14073:     my $clonehome=&Apache::lonnet::homeserver($clonecrsunum,$clonecrsudom);
14074:     my $clonemsg;
14075:     my $can_clone = 0;
14076:     my $lctype = lc($args->{'crstype'});
14077:     if ($lctype ne 'community') {
14078:         $lctype = 'course';
14079:     }
14080:     if ($clonehome eq 'no_host') {
14081:         if ($args->{'crstype'} eq 'Community') {
14082:             $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'});
14083:         } else {
14084:             $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'});
14085:         }     
14086:     } else {
14087: 	my %clonedesc = &Apache::lonnet::coursedescription($cloneid,{'one_time' => 1});
14088:         if ($args->{'crstype'} eq 'Community') {
14089:             if ($clonedesc{'type'} ne 'Community') {
14090:                  $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'});
14091:                 return ($can_clone, $clonemsg, $cloneid, $clonehome);
14092:             }
14093:         }
14094: 	if (($env{'request.role.domain'} eq $args->{'clonedomain'}) && 
14095:             (&Apache::lonnet::allowed('ccc',$env{'request.role.domain'}))) {
14096: 	    $can_clone = 1;
14097: 	} else {
14098: 	    my %clonehash = &Apache::lonnet::get('environment',['cloners'],
14099: 						 $args->{'clonedomain'},$args->{'clonecourse'});
14100: 	    my @cloners = split(/,/,$clonehash{'cloners'});
14101:             if (grep(/^\*$/,@cloners)) {
14102:                 $can_clone = 1;
14103:             } elsif (grep(/^\*\:\Q$args->{'ccdomain'}\E$/,@cloners)) {
14104:                 $can_clone = 1;
14105:             } else {
14106:                 my $ccrole = 'cc';
14107:                 if ($args->{'crstype'} eq 'Community') {
14108:                     $ccrole = 'co';
14109:                 }
14110: 	        my %roleshash =
14111: 		    &Apache::lonnet::get_my_roles($args->{'ccuname'},
14112: 					 $args->{'ccdomain'},
14113:                                          'userroles',['active'],[$ccrole],
14114: 					 [$args->{'clonedomain'}]);
14115: 	        if (($roleshash{$args->{'clonecourse'}.':'.$args->{'clonedomain'}.':'.$ccrole}) || (grep(/^\Q$args->{'ccuname'}\E:\Q$args->{'ccdomain'}\E$/,@cloners))) {
14116:                     $can_clone = 1;
14117:                 } elsif (&Apache::lonnet::is_course_owner($args->{'clonedomain'},$args->{'clonecourse'},$args->{'ccuname'},$args->{'ccdomain'})) {
14118:                     $can_clone = 1;
14119:                 } else {
14120:                     if ($args->{'crstype'} eq 'Community') {
14121:                         $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'});
14122:                     } else {
14123:                         $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'});
14124:                     }
14125: 	        }
14126: 	    }
14127:         }
14128:     }
14129:     return ($can_clone, $clonemsg, $cloneid, $clonehome);
14130: }
14131: 
14132: sub construct_course {
14133:     my ($args,$logmsg,$courseid,$crsudom,$crsunum,$udom,$uname,$context,$cnum,$category,$coderef) = @_;
14134:     my $outcome;
14135:     my $linefeed =  '<br />'."\n";
14136:     if ($context eq 'auto') {
14137:         $linefeed = "\n";
14138:     }
14139: 
14140: #
14141: # Are we cloning?
14142: #
14143:     my ($can_clone, $clonemsg, $cloneid, $clonehome);
14144:     if (($args->{'clonecourse'}) && ($args->{'clonedomain'})) {
14145: 	($can_clone, $clonemsg, $cloneid, $clonehome) = &check_clone($args,$linefeed);
14146: 	if ($context ne 'auto') {
14147:             if ($clonemsg ne '') {
14148: 	        $clonemsg = '<span class="LC_error">'.$clonemsg.'</span>';
14149:             }
14150: 	}
14151: 	$outcome .= $clonemsg.$linefeed;
14152: 
14153:         if (!$can_clone) {
14154: 	    return (0,$outcome);
14155: 	}
14156:     }
14157: 
14158: #
14159: # Open course
14160: #
14161:     my $crstype = lc($args->{'crstype'});
14162:     my %cenv=();
14163:     $$courseid=&Apache::lonnet::createcourse($args->{'course_domain'},
14164:                                              $args->{'cdescr'},
14165:                                              $args->{'curl'},
14166:                                              $args->{'course_home'},
14167:                                              $args->{'nonstandard'},
14168:                                              $args->{'crscode'},
14169:                                              $args->{'ccuname'}.':'.
14170:                                              $args->{'ccdomain'},
14171:                                              $args->{'crstype'},
14172:                                              $cnum,$context,$category);
14173: 
14174:     # Note: The testing routines depend on this being output; see 
14175:     # Utils::Course. This needs to at least be output as a comment
14176:     # if anyone ever decides to not show this, and Utils::Course::new
14177:     # will need to be suitably modified.
14178:     $outcome .= &mt('New LON-CAPA [_1] ID: [_2]',$crstype,$$courseid).$linefeed;
14179:     if ($$courseid =~ /^error:/) {
14180:         return (0,$outcome);
14181:     }
14182: 
14183: #
14184: # Check if created correctly
14185: #
14186:     ($$crsudom,$$crsunum)= &LONCAPA::split_courseid($$courseid);
14187:     my $crsuhome=&Apache::lonnet::homeserver($$crsunum,$$crsudom);
14188:     if ($crsuhome eq 'no_host') {
14189:         $outcome .= &mt('Course creation failed, unrecognized course home server.').$linefeed;
14190:         return (0,$outcome);
14191:     }
14192:     $outcome .= &mt('Created on').': '.$crsuhome.$linefeed;
14193: 
14194: #
14195: # Do the cloning
14196: #   
14197:     if ($can_clone && $cloneid) {
14198: 	$clonemsg = &mt('Cloning [_1] from [_2]',$crstype,$clonehome);
14199: 	if ($context ne 'auto') {
14200: 	    $clonemsg = '<span class="LC_success">'.$clonemsg.'</span>';
14201: 	}
14202: 	$outcome .= $clonemsg.$linefeed;
14203: 	my %oldcenv=&Apache::lonnet::dump('environment',$$crsudom,$$crsunum);
14204: # Copy all files
14205: 	&Apache::lonclonecourse::copycoursefiles($cloneid,$$courseid,$args->{'datemode'},$args->{'dateshift'});
14206: # Restore URL
14207: 	$cenv{'url'}=$oldcenv{'url'};
14208: # Restore title
14209: 	$cenv{'description'}=$oldcenv{'description'};
14210: # Restore creation date, creator and creation context.
14211:         $cenv{'internal.created'}=$oldcenv{'internal.created'};
14212:         $cenv{'internal.creator'}=$oldcenv{'internal.creator'};
14213:         $cenv{'internal.creationcontext'}=$oldcenv{'internal.creationcontext'};
14214: # Mark as cloned
14215: 	$cenv{'clonedfrom'}=$cloneid;
14216: # Need to clone grading mode
14217:         my %newenv=&Apache::lonnet::get('environment',['grading'],$$crsudom,$$crsunum);
14218:         $cenv{'grading'}=$newenv{'grading'};
14219: # Do not clone these environment entries
14220:         &Apache::lonnet::del('environment',
14221:                   ['default_enrollment_start_date',
14222:                    'default_enrollment_end_date',
14223:                    'question.email',
14224:                    'policy.email',
14225:                    'comment.email',
14226:                    'pch.users.denied',
14227:                    'plc.users.denied',
14228:                    'hidefromcat',
14229:                    'checkforpriv',
14230:                    'categories',
14231:                    'internal.uniquecode'],
14232:                    $$crsudom,$$crsunum);
14233:         if ($args->{'textbook'}) {
14234:             $cenv{'internal.textbook'} = $args->{'textbook'};
14235:         }
14236:     }
14237: 
14238: #
14239: # Set environment (will override cloned, if existing)
14240: #
14241:     my @sections = ();
14242:     my @xlists = ();
14243:     if ($args->{'crstype'}) {
14244:         $cenv{'type'}=$args->{'crstype'};
14245:     }
14246:     if ($args->{'crsid'}) {
14247:         $cenv{'courseid'}=$args->{'crsid'};
14248:     }
14249:     if ($args->{'crscode'}) {
14250:         $cenv{'internal.coursecode'}=$args->{'crscode'};
14251:     }
14252:     if ($args->{'crsquota'} ne '') {
14253:         $cenv{'internal.coursequota'}=$args->{'crsquota'};
14254:     } else {
14255:         $cenv{'internal.coursequota'}=$args->{'crsquota'} = 20;
14256:     }
14257:     if ($args->{'ccuname'}) {
14258:         $cenv{'internal.courseowner'} = $args->{'ccuname'}.
14259:                                         ':'.$args->{'ccdomain'};
14260:     } else {
14261:         $cenv{'internal.courseowner'} = $args->{'curruser'};
14262:     }
14263:     if ($args->{'defaultcredits'}) {
14264:         $cenv{'internal.defaultcredits'} = $args->{'defaultcredits'};
14265:     }
14266:     my @badclasses = (); # Used to accumulate sections/crosslistings that did not pass classlist access check for course owner.
14267:     if ($args->{'crssections'}) {
14268:         $cenv{'internal.sectionnums'} = '';
14269:         if ($args->{'crssections'} =~ m/,/) {
14270:             @sections = split/,/,$args->{'crssections'};
14271:         } else {
14272:             $sections[0] = $args->{'crssections'};
14273:         }
14274:         if (@sections > 0) {
14275:             foreach my $item (@sections) {
14276:                 my ($sec,$gp) = split/:/,$item;
14277:                 my $class = $args->{'crscode'}.$sec;
14278:                 my $addcheck = &Apache::lonnet::auto_new_course($$crsunum,$$crsudom,$class,$cenv{'internal.courseowner'});
14279:                 $cenv{'internal.sectionnums'} .= $item.',';
14280:                 unless ($addcheck eq 'ok') {
14281:                     push @badclasses, $class;
14282:                 }
14283:             }
14284:             $cenv{'internal.sectionnums'} =~ s/,$//;
14285:         }
14286:     }
14287: # do not hide course coordinator from staff listing, 
14288: # even if privileged
14289:     $cenv{'nothideprivileged'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
14290: # add course coordinator's domain to domains to check for privileged users
14291: # if different to course domain
14292:     if ($$crsudom ne $args->{'ccdomain'}) {
14293:         $cenv{'checkforpriv'} = $args->{'ccdomain'};
14294:     }
14295: # add crosslistings
14296:     if ($args->{'crsxlist'}) {
14297:         $cenv{'internal.crosslistings'}='';
14298:         if ($args->{'crsxlist'} =~ m/,/) {
14299:             @xlists = split/,/,$args->{'crsxlist'};
14300:         } else {
14301:             $xlists[0] = $args->{'crsxlist'};
14302:         }
14303:         if (@xlists > 0) {
14304:             foreach my $item (@xlists) {
14305:                 my ($xl,$gp) = split/:/,$item;
14306:                 my $addcheck =  &Apache::lonnet::auto_new_course($$crsunum,$$crsudom,$xl,$cenv{'internal.courseowner'});
14307:                 $cenv{'internal.crosslistings'} .= $item.',';
14308:                 unless ($addcheck eq 'ok') {
14309:                     push @badclasses, $xl;
14310:                 }
14311:             }
14312:             $cenv{'internal.crosslistings'} =~ s/,$//;
14313:         }
14314:     }
14315:     if ($args->{'autoadds'}) {
14316:         $cenv{'internal.autoadds'}=$args->{'autoadds'};
14317:     }
14318:     if ($args->{'autodrops'}) {
14319:         $cenv{'internal.autodrops'}=$args->{'autodrops'};
14320:     }
14321: # check for notification of enrollment changes
14322:     my @notified = ();
14323:     if ($args->{'notify_owner'}) {
14324:         if ($args->{'ccuname'} ne '') {
14325:             push(@notified,$args->{'ccuname'}.':'.$args->{'ccdomain'});
14326:         }
14327:     }
14328:     if ($args->{'notify_dc'}) {
14329:         if ($uname ne '') { 
14330:             push(@notified,$uname.':'.$udom);
14331:         }
14332:     }
14333:     if (@notified > 0) {
14334:         my $notifylist;
14335:         if (@notified > 1) {
14336:             $notifylist = join(',',@notified);
14337:         } else {
14338:             $notifylist = $notified[0];
14339:         }
14340:         $cenv{'internal.notifylist'} = $notifylist;
14341:     }
14342:     if (@badclasses > 0) {
14343:         my %lt=&Apache::lonlocal::texthash(
14344:                 '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',
14345:                 'dnhr' => 'does not have rights to access enrollment in these classes',
14346:                 'adby' => 'as determined by the policies of your institution on access to official classlists'
14347:         );
14348:         my $badclass_msg = $cenv{'internal.courseowner'}.') - '.$lt{'dnhr'}.
14349:                            ' ('.$lt{'adby'}.')';
14350:         if ($context eq 'auto') {
14351:             $outcome .= $badclass_msg.$linefeed;
14352:             $outcome .= '<div class="LC_warning">'.$badclass_msg.$linefeed.'<ul>'."\n";
14353:             foreach my $item (@badclasses) {
14354:                 if ($context eq 'auto') {
14355:                     $outcome .= " - $item\n";
14356:                 } else {
14357:                     $outcome .= "<li>$item</li>\n";
14358:                 }
14359:             }
14360:             if ($context eq 'auto') {
14361:                 $outcome .= $linefeed;
14362:             } else {
14363:                 $outcome .= "</ul><br /><br /></div>\n";
14364:             }
14365:         } 
14366:     }
14367:     if ($args->{'no_end_date'}) {
14368:         $args->{'endaccess'} = 0;
14369:     }
14370:     $cenv{'internal.autostart'}=$args->{'enrollstart'};
14371:     $cenv{'internal.autoend'}=$args->{'enrollend'};
14372:     $cenv{'default_enrollment_start_date'}=$args->{'startaccess'};
14373:     $cenv{'default_enrollment_end_date'}=$args->{'endaccess'};
14374:     if ($args->{'showphotos'}) {
14375:       $cenv{'internal.showphotos'}=$args->{'showphotos'};
14376:     }
14377:     $cenv{'internal.authtype'} = $args->{'authtype'};
14378:     $cenv{'internal.autharg'} = $args->{'autharg'}; 
14379:     if ( ($cenv{'internal.authtype'} =~ /^krb/) && ($cenv{'internal.autoadds'} == 1)) {
14380:         if (! defined($cenv{'internal.autharg'}) || $cenv{'internal.autharg'}  eq '') {
14381:             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'); 
14382:             if ($context eq 'auto') {
14383:                 $outcome .= $krb_msg;
14384:             } else {
14385:                 $outcome .= '<span class="LC_error">'.$krb_msg.'</span>';
14386:             }
14387:             $outcome .= $linefeed;
14388:         }
14389:     }
14390:     if (($args->{'ccdomain'}) && ($args->{'ccuname'})) {
14391:        if ($args->{'setpolicy'}) {
14392:            $cenv{'policy.email'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
14393:        }
14394:        if ($args->{'setcontent'}) {
14395:            $cenv{'question.email'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
14396:        }
14397:     }
14398:     if ($args->{'reshome'}) {
14399: 	$cenv{'reshome'}=$args->{'reshome'}.'/';
14400: 	$cenv{'reshome'}=~s/\/+$/\//;
14401:     }
14402: #
14403: # course has keyed access
14404: #
14405:     if ($args->{'setkeys'}) {
14406:        $cenv{'keyaccess'}='yes';
14407:     }
14408: # if specified, key authority is not course, but user
14409: # only active if keyaccess is yes
14410:     if ($args->{'keyauth'}) {
14411: 	my ($user,$domain) = split(':',$args->{'keyauth'});
14412: 	$user = &LONCAPA::clean_username($user);
14413: 	$domain = &LONCAPA::clean_username($domain);
14414: 	if ($user ne '' && $domain ne '') {
14415: 	    $cenv{'keyauth'}=$user.':'.$domain;
14416: 	}
14417:     }
14418: 
14419: #
14420: #  generate and store uniquecode (available to course requester), if course should have one.
14421: #
14422:     if ($args->{'uniquecode'}) {
14423:         my ($code,$error) = &make_unique_code($$crsudom,$$crsunum);
14424:         if ($code) {
14425:             $cenv{'internal.uniquecode'} = $code;
14426:             my %crsinfo =
14427:                 &Apache::lonnet::courseiddump($$crsudom,'.',1,'.','.',$$crsunum,undef,undef,'.');
14428:             if (ref($crsinfo{$$crsudom.'_'.$$crsunum}) eq 'HASH') {
14429:                 $crsinfo{$$crsudom.'_'.$$crsunum}{'uniquecode'} = $code;
14430:                 my $putres = &Apache::lonnet::courseidput($$crsudom,\%crsinfo,$crsuhome,'notime');
14431:             }
14432:             if (ref($coderef)) {
14433:                 $$coderef = $code;
14434:             }
14435:         }
14436:     }
14437: 
14438:     if ($args->{'disresdis'}) {
14439:         $cenv{'pch.roles.denied'}='st';
14440:     }
14441:     if ($args->{'disablechat'}) {
14442:         $cenv{'plc.roles.denied'}='st';
14443:     }
14444: 
14445:     # Record we've not yet viewed the Course Initialization Helper for this 
14446:     # course
14447:     $cenv{'course.helper.not.run'} = 1;
14448:     #
14449:     # Use new Randomseed
14450:     #
14451:     $cenv{'rndseed'}=&Apache::lonnet::latest_rnd_algorithm_id();;
14452:     $cenv{'receiptalg'}=&Apache::lonnet::latest_receipt_algorithm_id();;
14453:     #
14454:     # The encryption code and receipt prefix for this course
14455:     #
14456:     $cenv{'internal.encseed'}=$Apache::lonnet::perlvar{'lonReceipt'}.$$.time.int(rand(9999));
14457:     $cenv{'internal.encpref'}=100+int(9*rand(99));
14458:     #
14459:     # By default, use standard grading
14460:     if (!defined($cenv{'grading'})) { $cenv{'grading'} = 'standard'; }
14461: 
14462:     $outcome .= $linefeed.&mt('Setting environment').': '.                 
14463:           &Apache::lonnet::put('environment',\%cenv,$$crsudom,$$crsunum).$linefeed;
14464: #
14465: # Open all assignments
14466: #
14467:     if ($args->{'openall'}) {
14468:        my $storeunder=$$crsudom.'_'.$$crsunum.'.0.opendate';
14469:        my %storecontent = ($storeunder         => time,
14470:                            $storeunder.'.type' => 'date_start');
14471:        
14472:        $outcome .= &mt('Opening all assignments').': '.&Apache::lonnet::cput
14473:                  ('resourcedata',\%storecontent,$$crsudom,$$crsunum).$linefeed;
14474:    }
14475: #
14476: # Set first page
14477: #
14478:     unless (($args->{'nonstandard'}) || ($args->{'firstres'} eq 'blank')
14479: 	    || ($cloneid)) {
14480: 	use LONCAPA::map;
14481: 	$outcome .= &mt('Setting first resource').': ';
14482: 
14483: 	my $map = '/uploaded/'.$$crsudom.'/'.$$crsunum.'/default.sequence';
14484:         my ($errtext,$fatal)=&LONCAPA::map::mapread($map);
14485: 
14486:         $outcome .= ($fatal?$errtext:'read ok').' - ';
14487:         my $title; my $url;
14488:         if ($args->{'firstres'} eq 'syl') {
14489: 	    $title=&mt('Syllabus');
14490:             $url='/public/'.$$crsudom.'/'.$$crsunum.'/syllabus';
14491:         } else {
14492:             $title=&mt('Table of Contents');
14493:             $url='/adm/navmaps';
14494:         }
14495: 
14496:         $LONCAPA::map::resources[1]=$title.':'.$url.':false:start:res';
14497: 	(my $outtext,$errtext) = &LONCAPA::map::storemap($map,1);
14498: 
14499: 	if ($errtext) { $fatal=2; }
14500:         $outcome .= ($fatal?$errtext:'write ok').$linefeed;
14501:     }
14502: 
14503:     return (1,$outcome);
14504: }
14505: 
14506: sub make_unique_code {
14507:     my ($cdom,$cnum) = @_;
14508:     # get lock on uniquecodes db
14509:     my $lockhash = {
14510:                       $cnum."\0".'uniquecodes' => $env{'user.name'}.
14511:                                                   ':'.$env{'user.domain'},
14512:                    };
14513:     my $tries = 0;
14514:     my $gotlock = &Apache::lonnet::newput_dom('uniquecodes',$lockhash,$cdom);
14515:     my ($code,$error);
14516: 
14517:     while (($gotlock ne 'ok') && ($tries<3)) {
14518:         $tries ++;
14519:         sleep 1;
14520:         $gotlock = &Apache::lonnet::newput_dom('uniquecodes',$lockhash,$cdom);
14521:     }
14522:     if ($gotlock eq 'ok') {
14523:         my %currcodes = &Apache::lonnet::dump_dom('uniquecodes',$cdom);
14524:         my $gotcode;
14525:         my $attempts = 0;
14526:         while ((!$gotcode) && ($attempts < 100)) {
14527:             $code = &generate_code();
14528:             if (!exists($currcodes{$code})) {
14529:                 $gotcode = 1;
14530:                 unless (&Apache::lonnet::newput_dom('uniquecodes',{ $code => $cnum },$cdom) eq 'ok') {
14531:                     $error = 'nostore';
14532:                 }
14533:             }
14534:             $attempts ++;
14535:         }
14536:         my @del_lock = ($cnum."\0".'uniquecodes');
14537:         my $dellockoutcome = &Apache::lonnet::del_dom('uniquecodes',\@del_lock,$cdom);
14538:     } else {
14539:         $error = 'nolock';
14540:     }
14541:     return ($code,$error);
14542: }
14543: 
14544: sub generate_code {
14545:     my $code;
14546:     my @letts = qw(B C D G H J K M N P Q R S T V W X Z);
14547:     for (my $i=0; $i<6; $i++) {
14548:         my $lettnum = int (rand 2);
14549:         my $item = '';
14550:         if ($lettnum) {
14551:             $item = $letts[int( rand(18) )];
14552:         } else {
14553:             $item = 1+int( rand(8) );
14554:         }
14555:         $code .= $item;
14556:     }
14557:     return $code;
14558: }
14559: 
14560: ############################################################
14561: ############################################################
14562: 
14563: #SD
14564: # only Community and Course, or anything else?
14565: sub course_type {
14566:     my ($cid) = @_;
14567:     if (!defined($cid)) {
14568:         $cid = $env{'request.course.id'};
14569:     }
14570:     if (defined($env{'course.'.$cid.'.type'})) {
14571:         return $env{'course.'.$cid.'.type'};
14572:     } else {
14573:         return 'Course';
14574:     }
14575: }
14576: 
14577: sub group_term {
14578:     my $crstype = &course_type();
14579:     my %names = (
14580:                   'Course' => 'group',
14581:                   'Community' => 'group',
14582:                 );
14583:     return $names{$crstype};
14584: }
14585: 
14586: sub course_types {
14587:     my @types = ('official','unofficial','community','textbook');
14588:     my %typename = (
14589:                          official   => 'Official course',
14590:                          unofficial => 'Unofficial course',
14591:                          community  => 'Community',
14592:                          textbook   => 'Textbook course',
14593:                    );
14594:     return (\@types,\%typename);
14595: }
14596: 
14597: sub icon {
14598:     my ($file)=@_;
14599:     my $curfext = lc((split(/\./,$file))[-1]);
14600:     my $iconname=$Apache::lonnet::perlvar{'lonIconsURL'}.'/unknown.gif';
14601:     my $embstyle = &Apache::loncommon::fileembstyle($curfext);
14602:     if (!(!defined($embstyle) || $embstyle eq 'unk' || $embstyle eq 'hdn')) {
14603: 	if (-e  $Apache::lonnet::perlvar{'lonDocRoot'}.'/'.
14604: 	          $Apache::lonnet::perlvar{'lonIconsURL'}.'/'.
14605: 	            $curfext.".gif") {
14606: 	    $iconname=$Apache::lonnet::perlvar{'lonIconsURL'}.'/'.
14607: 		$curfext.".gif";
14608: 	}
14609:     }
14610:     return &lonhttpdurl($iconname);
14611: } 
14612: 
14613: sub lonhttpdurl {
14614: #
14615: # Had been used for "small fry" static images on separate port 8080.
14616: # Modify here if lightweight http functionality desired again.
14617: # Currently eliminated due to increasing firewall issues.
14618: #
14619:     my ($url)=@_;
14620:     return $url;
14621: }
14622: 
14623: sub connection_aborted {
14624:     my ($r)=@_;
14625:     $r->print(" ");$r->rflush();
14626:     my $c = $r->connection;
14627:     return $c->aborted();
14628: }
14629: 
14630: #    Escapes strings that may have embedded 's that will be put into
14631: #    strings as 'strings'.
14632: sub escape_single {
14633:     my ($input) = @_;
14634:     $input =~ s/\\/\\\\/g;	# Escape the \'s..(must be first)>
14635:     $input =~ s/\'/\\\'/g;	# Esacpe the 's....
14636:     return $input;
14637: }
14638: 
14639: #  Same as escape_single, but escape's "'s  This 
14640: #  can be used for  "strings"
14641: sub escape_double {
14642:     my ($input) = @_;
14643:     $input =~ s/\\/\\\\/g;	# Escape the /'s..(must be first)>
14644:     $input =~ s/\"/\\\"/g;	# Esacpe the "s....
14645:     return $input;
14646: }
14647:  
14648: #   Escapes the last element of a full URL.
14649: sub escape_url {
14650:     my ($url)   = @_;
14651:     my @urlslices = split(/\//, $url,-1);
14652:     my $lastitem = &escape(pop(@urlslices));
14653:     return &HTML::Entities::encode(join('/',@urlslices),"'").'/'.$lastitem;
14654: }
14655: 
14656: sub compare_arrays {
14657:     my ($arrayref1,$arrayref2) = @_;
14658:     my (@difference,%count);
14659:     @difference = ();
14660:     %count = ();
14661:     if ((ref($arrayref1) eq 'ARRAY') && (ref($arrayref2) eq 'ARRAY')) {
14662:         foreach my $element (@{$arrayref1}, @{$arrayref2}) { $count{$element}++; }
14663:         foreach my $element (keys(%count)) {
14664:             if ($count{$element} == 1) {
14665:                 push(@difference,$element);
14666:             }
14667:         }
14668:     }
14669:     return @difference;
14670: }
14671: 
14672: # -------------------------------------------------------- Initialize user login
14673: sub init_user_environment {
14674:     my ($r, $username, $domain, $authhost, $form, $args) = @_;
14675:     my $lonids=$Apache::lonnet::perlvar{'lonIDsDir'};
14676: 
14677:     my $public=($username eq 'public' && $domain eq 'public');
14678: 
14679: # See if old ID present, if so, remove
14680: 
14681:     my ($filename,$cookie,$userroles,$firstaccenv,$timerintenv);
14682:     my $now=time;
14683: 
14684:     if ($public) {
14685: 	my $max_public=100;
14686: 	my $oldest;
14687: 	my $oldest_time=0;
14688: 	for(my $next=1;$next<=$max_public;$next++) {
14689: 	    if (-e $lonids."/publicuser_$next.id") {
14690: 		my $mtime=(stat($lonids."/publicuser_$next.id"))[9];
14691: 		if ($mtime<$oldest_time || !$oldest_time) {
14692: 		    $oldest_time=$mtime;
14693: 		    $oldest=$next;
14694: 		}
14695: 	    } else {
14696: 		$cookie="publicuser_$next";
14697: 		last;
14698: 	    }
14699: 	}
14700: 	if (!$cookie) { $cookie="publicuser_$oldest"; }
14701:     } else {
14702: 	# if this isn't a robot, kill any existing non-robot sessions
14703: 	if (!$args->{'robot'}) {
14704: 	    opendir(DIR,$lonids);
14705: 	    while ($filename=readdir(DIR)) {
14706: 		if ($filename=~/^$username\_\d+\_$domain\_$authhost\.id$/) {
14707: 		    unlink($lonids.'/'.$filename);
14708: 		}
14709: 	    }
14710: 	    closedir(DIR);
14711: # If there is a undeleted lockfile for the user's paste buffer remove it.
14712:             my $namespace = 'nohist_courseeditor';
14713:             my $lockingkey = 'paste'."\0".'locked_num';
14714:             my %lockhash = &Apache::lonnet::get($namespace,[$lockingkey],
14715:                                                 $domain,$username);
14716:             if (exists($lockhash{$lockingkey})) {
14717:                 my $delresult = &Apache::lonnet::del($namespace,[$lockingkey],$domain,$username);
14718:                 unless ($delresult eq 'ok') {
14719:                     &Apache::lonnet::logthis("Failed to delete paste buffer locking key in $namespace for ".$username.":".$domain." Result was: $delresult");
14720:                 }
14721:             }
14722: 	}
14723: # Give them a new cookie
14724: 	my $id = ($args->{'robot'} ? 'robot'.$args->{'robot'}
14725: 		                   : $now.$$.int(rand(10000)));
14726: 	$cookie="$username\_$id\_$domain\_$authhost";
14727:     
14728: # Initialize roles
14729: 
14730: 	($userroles,$firstaccenv,$timerintenv) = 
14731:             &Apache::lonnet::rolesinit($domain,$username,$authhost);
14732:     }
14733: # ------------------------------------ Check browser type and MathML capability
14734: 
14735:     my ($httpbrowser,$clientbrowser,$clientversion,$clientmathml,$clientunicode,
14736:         $clientos,$clientmobile,$clientinfo,$clientosversion) = &decode_user_agent($r);
14737: 
14738: # ------------------------------------------------------------- Get environment
14739: 
14740:     my %userenv = &Apache::lonnet::dump('environment',$domain,$username);
14741:     my ($tmp) = keys(%userenv);
14742:     if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
14743:     } else {
14744: 	undef(%userenv);
14745:     }
14746:     if (($userenv{'interface'}) && (!$form->{'interface'})) {
14747: 	$form->{'interface'}=$userenv{'interface'};
14748:     }
14749:     if ($userenv{'texengine'} eq 'ttm') { $clientmathml=1; }
14750: 
14751: # --------------- Do not trust query string to be put directly into environment
14752:     foreach my $option ('interface','localpath','localres') {
14753:         $form->{$option}=~s/[\n\r\=]//gs;
14754:     }
14755: # --------------------------------------------------------- Write first profile
14756: 
14757:     {
14758: 	my %initial_env = 
14759: 	    ("user.name"          => $username,
14760: 	     "user.domain"        => $domain,
14761: 	     "user.home"          => $authhost,
14762: 	     "browser.type"       => $clientbrowser,
14763: 	     "browser.version"    => $clientversion,
14764: 	     "browser.mathml"     => $clientmathml,
14765: 	     "browser.unicode"    => $clientunicode,
14766: 	     "browser.os"         => $clientos,
14767:              "browser.mobile"     => $clientmobile,
14768:              "browser.info"       => $clientinfo,
14769:              "browser.osversion"  => $clientosversion,
14770: 	     "server.domain"      => $Apache::lonnet::perlvar{'lonDefDomain'},
14771: 	     "request.course.fn"  => '',
14772: 	     "request.course.uri" => '',
14773: 	     "request.course.sec" => '',
14774: 	     "request.role"       => 'cm',
14775: 	     "request.role.adv"   => $env{'user.adv'},
14776: 	     "request.host"       => $ENV{'REMOTE_ADDR'},);
14777: 
14778:         if ($form->{'localpath'}) {
14779: 	    $initial_env{"browser.localpath"}  = $form->{'localpath'};
14780: 	    $initial_env{"browser.localres"}   = $form->{'localres'};
14781:         }
14782: 	
14783: 	if ($form->{'interface'}) {
14784: 	    $form->{'interface'}=~s/\W//gs;
14785: 	    $initial_env{"browser.interface"} = $form->{'interface'};
14786: 	    $env{'browser.interface'}=$form->{'interface'};
14787: 	}
14788: 
14789:         if ($form->{'iptoken'}) {
14790:             my $lonhost = $r->dir_config('lonHostID');
14791:             $initial_env{"user.noloadbalance"} = $lonhost;
14792:             $env{'user.noloadbalance'} = $lonhost;
14793:         }
14794: 
14795:         my %is_adv = ( is_adv => $env{'user.adv'} );
14796:         my %domdef;
14797:         unless ($domain eq 'public') {
14798:             %domdef = &Apache::lonnet::get_domain_defaults($domain);
14799:         }
14800: 
14801:         foreach my $tool ('aboutme','blog','webdav','portfolio') {
14802:             $userenv{'availabletools.'.$tool} = 
14803:                 &Apache::lonnet::usertools_access($username,$domain,$tool,'reload',
14804:                                                   undef,\%userenv,\%domdef,\%is_adv);
14805:         }
14806: 
14807:         foreach my $crstype ('official','unofficial','community','textbook') {
14808:             $userenv{'canrequest.'.$crstype} =
14809:                 &Apache::lonnet::usertools_access($username,$domain,$crstype,
14810:                                                   'reload','requestcourses',
14811:                                                   \%userenv,\%domdef,\%is_adv);
14812:         }
14813: 
14814:         $userenv{'canrequest.author'} =
14815:             &Apache::lonnet::usertools_access($username,$domain,'requestauthor',
14816:                                         'reload','requestauthor',
14817:                                         \%userenv,\%domdef,\%is_adv);
14818:         my %reqauthor = &Apache::lonnet::get('requestauthor',['author_status','author'],
14819:                                              $domain,$username);
14820:         my $reqstatus = $reqauthor{'author_status'};
14821:         if ($reqstatus eq 'approval' || $reqstatus eq 'approved') {
14822:             if (ref($reqauthor{'author'}) eq 'HASH') {
14823:                 $userenv{'requestauthorqueued'} = $reqstatus.':'.
14824:                                                   $reqauthor{'author'}{'timestamp'};
14825:             }
14826:         }
14827: 
14828: 	$env{'user.environment'} = "$lonids/$cookie.id";
14829: 
14830: 	if (tie(my %disk_env,'GDBM_File',"$lonids/$cookie.id",
14831: 		 &GDBM_WRCREAT(),0640)) {
14832: 	    &_add_to_env(\%disk_env,\%initial_env);
14833: 	    &_add_to_env(\%disk_env,\%userenv,'environment.');
14834: 	    &_add_to_env(\%disk_env,$userroles);
14835:             if (ref($firstaccenv) eq 'HASH') {
14836:                 &_add_to_env(\%disk_env,$firstaccenv);
14837:             }
14838:             if (ref($timerintenv) eq 'HASH') {
14839:                 &_add_to_env(\%disk_env,$timerintenv);
14840:             }
14841: 	    if (ref($args->{'extra_env'})) {
14842: 		&_add_to_env(\%disk_env,$args->{'extra_env'});
14843: 	    }
14844: 	    untie(%disk_env);
14845: 	} else {
14846: 	    &Apache::lonnet::logthis("<span style=\"color:blue;\">WARNING: ".
14847: 			   'Could not create environment storage in lonauth: '.$!.'</span>');
14848: 	    return 'error: '.$!;
14849: 	}
14850:     }
14851:     $env{'request.role'}='cm';
14852:     $env{'request.role.adv'}=$env{'user.adv'};
14853:     $env{'browser.type'}=$clientbrowser;
14854: 
14855:     return $cookie;
14856: 
14857: }
14858: 
14859: sub _add_to_env {
14860:     my ($idf,$env_data,$prefix) = @_;
14861:     if (ref($env_data) eq 'HASH') {
14862:         while (my ($key,$value) = each(%$env_data)) {
14863: 	    $idf->{$prefix.$key} = $value;
14864: 	    $env{$prefix.$key}   = $value;
14865:         }
14866:     }
14867: }
14868: 
14869: # --- Get the symbolic name of a problem and the url
14870: sub get_symb {
14871:     my ($request,$silent) = @_;
14872:     (my $url=$env{'form.url'}) =~ s-^https?\://($ENV{'SERVER_NAME'}|$ENV{'HTTP_HOST'})--;
14873:     my $symb=($env{'form.symb'} ne '' ? $env{'form.symb'} : (&Apache::lonnet::symbread($url)));
14874:     if ($symb eq '') {
14875:         if (!$silent) {
14876:             if (ref($request)) { 
14877:                 $request->print("Unable to handle ambiguous references:$url:.");
14878:             }
14879:             return ();
14880:         }
14881:     }
14882:     &Apache::lonenc::check_decrypt(\$symb);
14883:     return ($symb);
14884: }
14885: 
14886: # --------------------------------------------------------------Get annotation
14887: 
14888: sub get_annotation {
14889:     my ($symb,$enc) = @_;
14890: 
14891:     my $key = $symb;
14892:     if (!$enc) {
14893:         $key =
14894:             &Apache::lonnet::clutter((&Apache::lonnet::decode_symb($symb))[2]);
14895:     }
14896:     my %annotation=&Apache::lonnet::get('nohist_annotations',[$key]);
14897:     return $annotation{$key};
14898: }
14899: 
14900: sub clean_symb {
14901:     my ($symb,$delete_enc) = @_;
14902: 
14903:     &Apache::lonenc::check_decrypt(\$symb);
14904:     my $enc = $env{'request.enc'};
14905:     if ($delete_enc) {
14906:         delete($env{'request.enc'});
14907:     }
14908: 
14909:     return ($symb,$enc);
14910: }
14911: 
14912: ############################################################
14913: ############################################################
14914: 
14915: =pod
14916: 
14917: =head1 Routines for building display used to search for courses
14918: 
14919: 
14920: =over 4
14921: 
14922: =item * &build_filters()
14923: 
14924: Create markup for a table used to set filters to use when selecting
14925: courses in a domain.  Used by lonpickcourse.pm, lonmodifycourse.pm
14926: and quotacheck.pl
14927: 
14928: 
14929: Inputs:
14930: 
14931: filterlist - anonymous array of fields to include as potential filters
14932: 
14933: crstype - course type
14934: 
14935: roleelement - fifth arg in selectcourse_link() populates fifth arg in javascript: opencrsbrowser() function, used
14936:               to pop-open a course selector (will contain "extra element").
14937: 
14938: multelement - if multiple course selections will be allowed, this will be a hidden form element: name: multiple; value: 1
14939: 
14940: filter - anonymous hash of criteria and their values
14941: 
14942: action - form action
14943: 
14944: numfiltersref - ref to scalar (count of number of elements in institutional codes -- e.g., 4 for year, semester, department, and number)
14945: 
14946: caller - caller context (e.g., set to 'modifycourse' when routine is called from lonmodifycourse.pm)
14947: 
14948: cloneruname - username of owner of new course who wants to clone
14949: 
14950: clonerudom - domain of owner of new course who wants to clone
14951: 
14952: typeelem - text to use for left column in row containing course type (i.e., Course, Community or Course/Community)
14953: 
14954: codetitlesref - reference to array of titles of components in institutional codes (official courses)
14955: 
14956: codedom - domain
14957: 
14958: formname - value of form element named "form".
14959: 
14960: fixeddom - domain, if fixed.
14961: 
14962: prevphase - value to assign to form element named "phase" when going back to the previous screen
14963: 
14964: cnameelement - name of form element in form on opener page which will receive title of selected course
14965: 
14966: cnumelement - name of form element in form on opener page which will receive courseID  of selected course
14967: 
14968: cdomelement - name of form element in form on opener page which will receive domain of selected course
14969: 
14970: setroles - includes access constraint identifier when setting a roles-based condition for acces to a portfolio file
14971: 
14972: clonetext - hidden form elements containing list of courses cloneable by intended course owner when DC creates a course
14973: 
14974: clonewarning - warning message about missing information for intended course owner when DC creates a course
14975: 
14976: 
14977: Returns: $output - HTML for display of search criteria, and hidden form elements.
14978: 
14979: 
14980: Side Effects: None
14981: 
14982: =cut
14983: 
14984: # ---------------------------------------------- search for courses based on last activity etc.
14985: 
14986: sub build_filters {
14987:     my ($filterlist,$crstype,$roleelement,$multelement,$filter,$action,
14988:         $numtitlesref,$caller,$cloneruname,$clonerudom,$typeelement,
14989:         $codetitlesref,$codedom,$formname,$fixeddom,$prevphase,
14990:         $cnameelement,$cnumelement,$cdomelement,$setroles,
14991:         $clonetext,$clonewarning) = @_;
14992:     my ($list,$jscript);
14993:     my $onchange = 'javascript:updateFilters(this)';
14994:     my ($domainselectform,$sincefilterform,$createdfilterform,
14995:         $ownerdomselectform,$persondomselectform,$instcodeform,
14996:         $typeselectform,$instcodetitle);
14997:     if ($formname eq '') {
14998:         $formname = $caller;
14999:     }
15000:     foreach my $item (@{$filterlist}) {
15001:         unless (($item eq 'descriptfilter') || ($item eq 'instcodefilter') ||
15002:                 ($item eq 'sincefilter') || ($item eq 'createdfilter')) {
15003:             if ($item eq 'domainfilter') {
15004:                 $filter->{$item} = &LONCAPA::clean_domain($filter->{$item});
15005:             } elsif ($item eq 'coursefilter') {
15006:                 $filter->{$item} = &LONCAPA::clean_courseid($filter->{$item});
15007:             } elsif ($item eq 'ownerfilter') {
15008:                 $filter->{$item} = &LONCAPA::clean_username($filter->{$item});
15009:             } elsif ($item eq 'ownerdomfilter') {
15010:                 $filter->{'ownerdomfilter'} =
15011:                     &LONCAPA::clean_domain($filter->{$item});
15012:                 $ownerdomselectform = &select_dom_form($filter->{'ownerdomfilter'},
15013:                                                        'ownerdomfilter',1);
15014:             } elsif ($item eq 'personfilter') {
15015:                 $filter->{$item} = &LONCAPA::clean_username($filter->{$item});
15016:             } elsif ($item eq 'persondomfilter') {
15017:                 $persondomselectform = &select_dom_form($filter->{'persondomfilter'},
15018:                                                         'persondomfilter',1);
15019:             } else {
15020:                 $filter->{$item} =~ s/\W//g;
15021:             }
15022:             if (!$filter->{$item}) {
15023:                 $filter->{$item} = '';
15024:             }
15025:         }
15026:         if ($item eq 'domainfilter') {
15027:             my $allow_blank = 1;
15028:             if ($formname eq 'portform') {
15029:                 $allow_blank=0;
15030:             } elsif ($formname eq 'studentform') {
15031:                 $allow_blank=0;
15032:             }
15033:             if ($fixeddom) {
15034:                 $domainselectform = '<input type="hidden" name="domainfilter"'.
15035:                                     ' value="'.$codedom.'" />'.
15036:                                     &Apache::lonnet::domain($codedom,'description');
15037:             } else {
15038:                 $domainselectform = &select_dom_form($filter->{$item},
15039:                                                      'domainfilter',
15040:                                                       $allow_blank,'',$onchange);
15041:             }
15042:         } else {
15043:             $list->{$item} = &HTML::Entities::encode($filter->{$item},'<>&"');
15044:         }
15045:     }
15046: 
15047:     # last course activity filter and selection
15048:     $sincefilterform = &timebased_select_form('sincefilter',$filter);
15049: 
15050:     # course created filter and selection
15051:     if (exists($filter->{'createdfilter'})) {
15052:         $createdfilterform = &timebased_select_form('createdfilter',$filter);
15053:     }
15054: 
15055:     my %lt = &Apache::lonlocal::texthash(
15056:                 'cac' => "$crstype Activity",
15057:                 'ccr' => "$crstype Created",
15058:                 'cde' => "$crstype Title",
15059:                 'cdo' => "$crstype Domain",
15060:                 'ins' => 'Institutional Code',
15061:                 'inc' => 'Institutional Categorization',
15062:                 'cow' => "$crstype Owner/Co-owner",
15063:                 'cop' => "$crstype Personnel Includes",
15064:                 'cog' => 'Type',
15065:              );
15066: 
15067:     if (($formname eq 'ccrs') || ($formname eq 'requestcrs')) {
15068:         my $typeval = 'Course';
15069:         if ($crstype eq 'Community') {
15070:             $typeval = 'Community';
15071:         }
15072:         $typeselectform = '<input type="hidden" name="type" value="'.$typeval.'" />';
15073:     } else {
15074:         $typeselectform =  '<select name="type" size="1"';
15075:         if ($onchange) {
15076:             $typeselectform .= ' onchange="'.$onchange.'"';
15077:         }
15078:         $typeselectform .= '>'."\n";
15079:         foreach my $posstype ('Course','Community') {
15080:             $typeselectform.='<option value="'.$posstype.'"'.
15081:                 ($posstype eq $crstype ? ' selected="selected" ' : ''). ">".&mt($posstype)."</option>\n";
15082:         }
15083:         $typeselectform.="</select>";
15084:     }
15085: 
15086:     my ($cloneableonlyform,$cloneabletitle);
15087:     if (exists($filter->{'cloneableonly'})) {
15088:         my $cloneableon = '';
15089:         my $cloneableoff = ' checked="checked"';
15090:         if ($filter->{'cloneableonly'}) {
15091:             $cloneableon = $cloneableoff;
15092:             $cloneableoff = '';
15093:         }
15094:         $cloneableonlyform = '<span class="LC_nobreak"><label><input type="radio" name="cloneableonly" value="1" '.$cloneableon.'/>&nbsp;'.&mt('Required').'</label>'.('&nbsp;'x3).'<label><input type="radio" name="cloneableonly" value="" '.$cloneableoff.' />&nbsp;'.&mt('No restriction').'</label></span>';
15095:         if ($formname eq 'ccrs') {
15096:             $cloneabletitle = &mt('Cloneable for [_1]',$cloneruname.':'.$clonerudom);
15097:         } else {
15098:             $cloneabletitle = &mt('Cloneable by you');
15099:         }
15100:     }
15101:     my $officialjs;
15102:     if ($crstype eq 'Course') {
15103:         if (exists($filter->{'instcodefilter'})) {
15104: #            if (($fixeddom) || ($formname eq 'requestcrs') ||
15105: #                ($formname eq 'modifycourse') || ($formname eq 'filterpicker')) {
15106:             if ($codedom) {
15107:                 $officialjs = 1;
15108:                 ($instcodeform,$jscript,$$numtitlesref) =
15109:                     &Apache::courseclassifier::instcode_selectors($codedom,'filterpicker',
15110:                                                                   $officialjs,$codetitlesref);
15111:                 if ($jscript) {
15112:                     $jscript = '<script type="text/javascript">'."\n".
15113:                                '// <![CDATA['."\n".
15114:                                $jscript."\n".
15115:                                '// ]]>'."\n".
15116:                                '</script>'."\n";
15117:                 }
15118:             }
15119:             if ($instcodeform eq '') {
15120:                 $instcodeform =
15121:                     '<input type="text" name="instcodefilter" size="10" value="'.
15122:                     $list->{'instcodefilter'}.'" />';
15123:                 $instcodetitle = $lt{'ins'};
15124:             } else {
15125:                 $instcodetitle = $lt{'inc'};
15126:             }
15127:             if ($fixeddom) {
15128:                 $instcodetitle .= '<br />('.$codedom.')';
15129:             }
15130:         }
15131:     }
15132:     my $output = qq|
15133: <form method="post" name="filterpicker" action="$action">
15134: <input type="hidden" name="form" value="$formname" />
15135: |;
15136:     if ($formname eq 'modifycourse') {
15137:         $output .= '<input type="hidden" name="phase" value="courselist" />'."\n".
15138:                    '<input type="hidden" name="prevphase" value="'.
15139:                    $prevphase.'" />'."\n";
15140:     } elsif ($formname eq 'quotacheck') {
15141:         $output .= qq|
15142: <input type="hidden" name="sortby" value="" />
15143: <input type="hidden" name="sortorder" value="" />
15144: |;
15145:     } else {
15146:         my $name_input;
15147:         if ($cnameelement ne '') {
15148:             $name_input = '<input type="hidden" name="cnameelement" value="'.
15149:                           $cnameelement.'" />';
15150:         }
15151:         $output .= qq|
15152: <input type="hidden" name="cnumelement" value="$cnumelement" />
15153: <input type="hidden" name="cdomelement" value="$cdomelement" />
15154: $name_input
15155: $roleelement
15156: $multelement
15157: $typeelement
15158: |;
15159:         if ($formname eq 'portform') {
15160:             $output .= '<input type="hidden" name="setroles" value="'.$setroles.'" />'."\n";
15161:         }
15162:     }
15163:     if ($fixeddom) {
15164:         $output .= '<input type="hidden" name="fixeddom" value="'.$fixeddom.'" />'."\n";
15165:     }
15166:     $output .= "<br />\n".&Apache::lonhtmlcommon::start_pick_box();
15167:     if ($sincefilterform) {
15168:         $output .= &Apache::lonhtmlcommon::row_title($lt{'cac'})
15169:                   .$sincefilterform
15170:                   .&Apache::lonhtmlcommon::row_closure();
15171:     }
15172:     if ($createdfilterform) {
15173:         $output .= &Apache::lonhtmlcommon::row_title($lt{'ccr'})
15174:                   .$createdfilterform
15175:                   .&Apache::lonhtmlcommon::row_closure();
15176:     }
15177:     if ($domainselectform) {
15178:         $output .= &Apache::lonhtmlcommon::row_title($lt{'cdo'})
15179:                   .$domainselectform
15180:                   .&Apache::lonhtmlcommon::row_closure();
15181:     }
15182:     if ($typeselectform) {
15183:         if (($formname eq 'ccrs') || ($formname eq 'requestcrs')) {
15184:             $output .= $typeselectform;
15185:         } else {
15186:             $output .= &Apache::lonhtmlcommon::row_title($lt{'cog'})
15187:                       .$typeselectform
15188:                       .&Apache::lonhtmlcommon::row_closure();
15189:         }
15190:     }
15191:     if ($instcodeform) {
15192:         $output .= &Apache::lonhtmlcommon::row_title($instcodetitle)
15193:                   .$instcodeform
15194:                   .&Apache::lonhtmlcommon::row_closure();
15195:     }
15196:     if (exists($filter->{'ownerfilter'})) {
15197:         $output .= &Apache::lonhtmlcommon::row_title($lt{'cow'}).
15198:                    '<table><tr><td>'.&mt('Username').'<br />'.
15199:                    '<input type="text" name="ownerfilter" size="20" value="'.
15200:                    $list->{'ownerfilter'}.'" /></td><td>'.&mt('Domain').'<br />'.
15201:                    $ownerdomselectform.'</td></tr></table>'.
15202:                    &Apache::lonhtmlcommon::row_closure();
15203:     }
15204:     if (exists($filter->{'personfilter'})) {
15205:         $output .= &Apache::lonhtmlcommon::row_title($lt{'cop'}).
15206:                    '<table><tr><td>'.&mt('Username').'<br />'.
15207:                    '<input type="text" name="personfilter" size="20" value="'.
15208:                    $list->{'personfilter'}.'" /></td><td>'.&mt('Domain').'<br />'.
15209:                    $persondomselectform.'</td></tr></table>'.
15210:                    &Apache::lonhtmlcommon::row_closure();
15211:     }
15212:     if (exists($filter->{'coursefilter'})) {
15213:         $output .= &Apache::lonhtmlcommon::row_title(&mt('LON-CAPA course ID'))
15214:                   .'<input type="text" name="coursefilter" size="25" value="'
15215:                   .$list->{'coursefilter'}.'" />'
15216:                   .&Apache::lonhtmlcommon::row_closure();
15217:     }
15218:     if ($cloneableonlyform) {
15219:         $output .= &Apache::lonhtmlcommon::row_title($cloneabletitle).
15220:                    $cloneableonlyform.&Apache::lonhtmlcommon::row_closure();
15221:     }
15222:     if (exists($filter->{'descriptfilter'})) {
15223:         $output .= &Apache::lonhtmlcommon::row_title($lt{'cde'})
15224:                   .'<input type="text" name="descriptfilter" size="40" value="'
15225:                   .$list->{'descriptfilter'}.'" />'
15226:                   .&Apache::lonhtmlcommon::row_closure(1);
15227:     }
15228:     $output .= &Apache::lonhtmlcommon::end_pick_box().'<p>'.$clonetext."\n".
15229:                '<input type="hidden" name="updater" value="" />'."\n".
15230:                '<input type="submit" name="gosearch" value="'.
15231:                &mt('Search').'" /></p>'."\n".'</form>'."\n".'<hr />'."\n";
15232:     return $jscript.$clonewarning.$output;
15233: }
15234: 
15235: =pod
15236: 
15237: =item * &timebased_select_form()
15238: 
15239: Create markup for a dropdown list used to select a time-based
15240: filter e.g., Course Activity, Course Created, when searching for courses
15241: or communities
15242: 
15243: Inputs:
15244: 
15245: item - name of form element (sincefilter or createdfilter)
15246: 
15247: filter - anonymous hash of criteria and their values
15248: 
15249: Returns: HTML for a select box contained a blank, then six time selections,
15250:          with value set in incoming form variables currently selected.
15251: 
15252: Side Effects: None
15253: 
15254: =cut
15255: 
15256: sub timebased_select_form {
15257:     my ($item,$filter) = @_;
15258:     if (ref($filter) eq 'HASH') {
15259:         $filter->{$item} =~ s/[^\d-]//g;
15260:         if (!$filter->{$item}) { $filter->{$item}=-1; }
15261:         return &select_form(
15262:                             $filter->{$item},
15263:                             $item,
15264:                             {      '-1' => '',
15265:                                 '86400' => &mt('today'),
15266:                                '604800' => &mt('last week'),
15267:                               '2592000' => &mt('last month'),
15268:                               '7776000' => &mt('last three months'),
15269:                              '15552000' => &mt('last six months'),
15270:                              '31104000' => &mt('last year'),
15271:                     'select_form_order' =>
15272:                            ['-1','86400','604800','2592000','7776000',
15273:                             '15552000','31104000']});
15274:     }
15275: }
15276: 
15277: =pod
15278: 
15279: =item * &js_changer()
15280: 
15281: Create script tag containing Javascript used to submit course search form
15282: when course type or domain is changed, and also to hide 'Searching ...' on
15283: page load completion for page showing search result.
15284: 
15285: Inputs: None
15286: 
15287: Returns: markup containing updateFilters() and hideSearching() javascript functions.
15288: 
15289: Side Effects: None
15290: 
15291: =cut
15292: 
15293: sub js_changer {
15294:     return <<ENDJS;
15295: <script type="text/javascript">
15296: // <![CDATA[
15297: function updateFilters(caller) {
15298:     if (typeof(caller) != "undefined") {
15299:         document.filterpicker.updater.value = caller.name;
15300:     }
15301:     document.filterpicker.submit();
15302: }
15303: 
15304: function hideSearching() {
15305:     if (document.getElementById('searching')) {
15306:         document.getElementById('searching').style.display = 'none';
15307:     }
15308:     return;
15309: }
15310: 
15311: // ]]>
15312: </script>
15313: 
15314: ENDJS
15315: }
15316: 
15317: =pod
15318: 
15319: =item * &search_courses()
15320: 
15321: Process selected filters form course search form and pass to lonnet::courseiddump
15322: to retrieve a hash for which keys are courseIDs which match the selected filters.
15323: 
15324: Inputs:
15325: 
15326: dom - domain being searched
15327: 
15328: type - course type ('Course' or 'Community' or '.' if any).
15329: 
15330: filter - anonymous hash of criteria and their values
15331: 
15332: numtitles - for institutional codes - number of categories
15333: 
15334: cloneruname - optional username of new course owner
15335: 
15336: clonerudom - optional domain of new course owner
15337: 
15338: domcloner - Optional "domcloner" flag; has value=1 if user has ccc priv in domain being filtered by,
15339:             (used when DC is using course creation form)
15340: 
15341: codetitles - reference to array of titles of components in institutional codes (official courses).
15342: 
15343: 
15344: Returns: %courses - hash of courses satisfying search criteria, keys = course IDs, values are corresponding colon-separated escaped description, institutional code, owner and type.
15345: 
15346: 
15347: Side Effects: None
15348: 
15349: =cut
15350: 
15351: 
15352: sub search_courses {
15353:     my ($dom,$type,$filter,$numtitles,$cloneruname,$clonerudom,$domcloner,$codetitles) = @_;
15354:     my (%courses,%showcourses,$cloner);
15355:     if (($filter->{'ownerfilter'} ne '') ||
15356:         ($filter->{'ownerdomfilter'} ne '')) {
15357:         $filter->{'combownerfilter'} = $filter->{'ownerfilter'}.':'.
15358:                                        $filter->{'ownerdomfilter'};
15359:     }
15360:     foreach my $item ('descriptfilter','coursefilter','combownerfilter') {
15361:         if (!$filter->{$item}) {
15362:             $filter->{$item}='.';
15363:         }
15364:     }
15365:     my $now = time;
15366:     my $timefilter =
15367:        ($filter->{'sincefilter'}==-1?1:$now-$filter->{'sincefilter'});
15368:     my ($createdbefore,$createdafter);
15369:     if (($filter->{'createdfilter'} ne '') && ($filter->{'createdfilter'} !=-1)) {
15370:         $createdbefore = $now;
15371:         $createdafter = $now-$filter->{'createdfilter'};
15372:     }
15373:     my ($instcodefilter,$regexpok);
15374:     if ($numtitles) {
15375:         if ($env{'form.official'} eq 'on') {
15376:             $instcodefilter =
15377:                 &Apache::courseclassifier::instcode_search_str($dom,$numtitles,$codetitles);
15378:             $regexpok = 1;
15379:         } elsif ($env{'form.official'} eq 'off') {
15380:             $instcodefilter = &Apache::courseclassifier::instcode_search_str($dom,$numtitles,$codetitles);
15381:             unless ($instcodefilter eq '') {
15382:                 $regexpok = -1;
15383:             }
15384:         }
15385:     } else {
15386:         $instcodefilter = $filter->{'instcodefilter'};
15387:     }
15388:     if ($instcodefilter eq '') { $instcodefilter = '.'; }
15389:     if ($type eq '') { $type = '.'; }
15390: 
15391:     if (($clonerudom ne '') && ($cloneruname ne '')) {
15392:         $cloner = $cloneruname.':'.$clonerudom;
15393:     }
15394:     %courses = &Apache::lonnet::courseiddump($dom,
15395:                                              $filter->{'descriptfilter'},
15396:                                              $timefilter,
15397:                                              $instcodefilter,
15398:                                              $filter->{'combownerfilter'},
15399:                                              $filter->{'coursefilter'},
15400:                                              undef,undef,$type,$regexpok,undef,undef,
15401:                                              undef,undef,$cloner,$env{'form.cc_clone'},
15402:                                              $filter->{'cloneableonly'},
15403:                                              $createdbefore,$createdafter,undef,
15404:                                              $domcloner);
15405:     if (($filter->{'personfilter'} ne '') && ($filter->{'persondomfilter'} ne '')) {
15406:         my $ccrole;
15407:         if ($type eq 'Community') {
15408:             $ccrole = 'co';
15409:         } else {
15410:             $ccrole = 'cc';
15411:         }
15412:         my %rolehash = &Apache::lonnet::get_my_roles($filter->{'personfilter'},
15413:                                                      $filter->{'persondomfilter'},
15414:                                                      'userroles',undef,
15415:                                                      [$ccrole,'in','ad','ep','ta','cr'],
15416:                                                      $dom);
15417:         foreach my $role (keys(%rolehash)) {
15418:             my ($cnum,$cdom,$courserole) = split(':',$role);
15419:             my $cid = $cdom.'_'.$cnum;
15420:             if (exists($courses{$cid})) {
15421:                 if (ref($courses{$cid}) eq 'HASH') {
15422:                     if (ref($courses{$cid}{roles}) eq 'ARRAY') {
15423:                         if (!grep(/^\Q$courserole\E$/,@{$courses{$cid}{roles}})) {
15424:                             push (@{$courses{$cid}{roles}},$courserole);
15425:                         }
15426:                     } else {
15427:                         $courses{$cid}{roles} = [$courserole];
15428:                     }
15429:                     $showcourses{$cid} = $courses{$cid};
15430:                 }
15431:             }
15432:         }
15433:         %courses = %showcourses;
15434:     }
15435:     return %courses;
15436: }
15437: 
15438: =pod
15439: 
15440: =back
15441: 
15442: =head1 Routines for version requirements for current course.
15443: 
15444: =over 4
15445: 
15446: =item * &check_release_required()
15447: 
15448: Compares required LON-CAPA version with version on server, and
15449: if required version is newer looks for a server with the required version.
15450: 
15451: Looks first at servers in user's owen domain; if none suitable, looks at
15452: servers in course's domain are permitted to host sessions for user's domain.
15453: 
15454: Inputs:
15455: 
15456: $loncaparev - Version on current server (format: Major.Minor.Subrelease-datestamp)
15457: 
15458: $courseid - Course ID of current course
15459: 
15460: $rolecode - User's current role in course (for switchserver query string).
15461: 
15462: $required - LON-CAPA version needed by course (format: Major.Minor).
15463: 
15464: 
15465: Returns:
15466: 
15467: $switchserver - query string tp append to /adm/switchserver call (if
15468:                 current server's LON-CAPA version is too old.
15469: 
15470: $warning - Message is displayed if no suitable server could be found.
15471: 
15472: =cut
15473: 
15474: sub check_release_required {
15475:     my ($loncaparev,$courseid,$rolecode,$required) = @_;
15476:     my ($switchserver,$warning);
15477:     if ($required ne '') {
15478:         my ($reqdmajor,$reqdminor) = ($required =~ /^(\d+)\.(\d+)$/);
15479:         my ($major,$minor) = ($loncaparev =~ /^\'?(\d+)\.(\d+)\.[\w.\-]+\'?$/);
15480:         if ($reqdmajor ne '' && $reqdminor ne '') {
15481:             my $otherserver;
15482:             if (($major eq '' && $minor eq '') ||
15483:                 (($reqdmajor > $major) || (($reqdmajor == $major) && ($reqdminor > $minor)))) {
15484:                 my ($userdomserver) = &Apache::lonnet::choose_server($env{'user.domain'},undef,$required,1);
15485:                 my $switchlcrev =
15486:                     &Apache::lonnet::get_server_loncaparev($env{'user.domain'},
15487:                                                            $userdomserver);
15488:                 my ($swmajor,$swminor) = ($switchlcrev =~ /^\'?(\d+)\.(\d+)\.[\w.\-]+\'?$/);
15489:                 if (($swmajor eq '' && $swminor eq '') || ($reqdmajor > $swmajor) ||
15490:                     (($reqdmajor == $swmajor) && ($reqdminor > $swminor))) {
15491:                     my $cdom = $env{'course.'.$courseid.'.domain'};
15492:                     if ($cdom ne $env{'user.domain'}) {
15493:                         my ($coursedomserver,$coursehostname) = &Apache::lonnet::choose_server($cdom,undef,$required,1);
15494:                         my $serverhomeID = &Apache::lonnet::get_server_homeID($coursehostname);
15495:                         my $serverhomedom = &Apache::lonnet::host_domain($serverhomeID);
15496:                         my %defdomdefaults = &Apache::lonnet::get_domain_defaults($serverhomedom);
15497:                         my %udomdefaults = &Apache::lonnet::get_domain_defaults($env{'user.domain'});
15498:                         my $remoterev = &Apache::lonnet::get_server_loncaparev($serverhomedom,$coursedomserver);
15499:                         my $canhost =
15500:                             &Apache::lonnet::can_host_session($env{'user.domain'},
15501:                                                               $coursedomserver,
15502:                                                               $remoterev,
15503:                                                               $udomdefaults{'remotesessions'},
15504:                                                               $defdomdefaults{'hostedsessions'});
15505: 
15506:                         if ($canhost) {
15507:                             $otherserver = $coursedomserver;
15508:                         } else {
15509:                             $warning = &mt('Requires LON-CAPA version [_1].',$env{'course.'.$courseid.'.internal.releaserequired'}).'<br />'. &mt("No suitable server could be found amongst servers in either your own domain or in the course's domain.");
15510:                         }
15511:                     } else {
15512:                         $warning = &mt('Requires LON-CAPA version [_1].',$env{'course.'.$courseid.'.internal.releaserequired'}).'<br />'.&mt("No suitable server could be found amongst servers in your own domain (which is also the course's domain).");
15513:                     }
15514:                 } else {
15515:                     $otherserver = $userdomserver;
15516:                 }
15517:             }
15518:             if ($otherserver ne '') {
15519:                 $switchserver = 'otherserver='.$otherserver.'&amp;role='.$rolecode;
15520:             }
15521:         }
15522:     }
15523:     return ($switchserver,$warning);
15524: }
15525: 
15526: =pod
15527: 
15528: =item * &check_release_result()
15529: 
15530: Inputs:
15531: 
15532: $switchwarning - Warning message if no suitable server found to host session.
15533: 
15534: $switchserver - query string to append to /adm/switchserver containing lonHostID
15535:                 and current role.
15536: 
15537: Returns: HTML to display with information about requirement to switch server.
15538:          Either displaying warning with link to Roles/Courses screen or
15539:          display link to switchserver.
15540: 
15541: =cut
15542: 
15543: sub check_release_result {
15544:     my ($switchwarning,$switchserver) = @_;
15545:     my $output = &start_page('Selected course unavailable on this server').
15546:                  '<p class="LC_warning">';
15547:     if ($switchwarning) {
15548:         $output .= $switchwarning.'<br /><a href="/adm/roles">';
15549:         if (&show_course()) {
15550:             $output .= &mt('Display courses');
15551:         } else {
15552:             $output .= &mt('Display roles');
15553:         }
15554:         $output .= '</a>';
15555:     } elsif ($switchserver) {
15556:         $output .= &mt('This course requires a newer version of LON-CAPA than is installed on this server.').
15557:                    '<br />'.
15558:                    '<a href="/adm/switchserver?'.$switchserver.'">'.
15559:                    &mt('Switch Server').
15560:                    '</a>';
15561:     }
15562:     $output .= '</p>'.&end_page();
15563:     return $output;
15564: }
15565: 
15566: =pod
15567: 
15568: =item * &needs_coursereinit()
15569: 
15570: Determine if course contents stored for user's session needs to be
15571: refreshed, because content has changed since "Big Hash" last tied.
15572: 
15573: Check for change is made if time last checked is more than 10 minutes ago
15574: (by default).
15575: 
15576: Inputs:
15577: 
15578: $loncaparev - Version on current server (format: Major.Minor.Subrelease-datestamp)
15579: 
15580: $interval (optional) - Time which may elapse (in s) between last check for content
15581:                        change in current course. (default: 600 s).
15582: 
15583: Returns: an array; first element is:
15584: 
15585: =over 4
15586: 
15587: 'switch' - if content updates mean user's session
15588:            needs to be switched to a server running a newer LON-CAPA version
15589: 
15590: 'update' - if course session needs to be refreshed (i.e., Big Hash needs to be reloaded)
15591:            on current server hosting user's session
15592: 
15593: ''       - if no action required.
15594: 
15595: =back
15596: 
15597: If first item element is 'switch':
15598: 
15599: second item is $switchwarning - Warning message if no suitable server found to host session.
15600: 
15601: third item is $switchserver - query string to append to /adm/switchserver containing lonHostID
15602:                               and current role.
15603: 
15604: otherwise: no other elements returned.
15605: 
15606: =back
15607: 
15608: =cut
15609: 
15610: sub needs_coursereinit {
15611:     my ($loncaparev,$interval) = @_;
15612:     return() unless ($env{'request.course.id'} && $env{'request.course.tied'});
15613:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
15614:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
15615:     my $now = time;
15616:     if ($interval eq '') {
15617:         $interval = 600;
15618:     }
15619:     if (($now-$env{'request.course.timechecked'})>$interval) {
15620:         my $lastchange = &Apache::lonnet::get_coursechange($cdom,$cnum);
15621:         &Apache::lonnet::appenv({'request.course.timechecked'=>$now});
15622:         if ($lastchange > $env{'request.course.tied'}) {
15623:             my %curr_reqd_hash = &Apache::lonnet::userenvironment($cdom,$cnum,'internal.releaserequired');
15624:             if ($curr_reqd_hash{'internal.releaserequired'} ne '') {
15625:                 my $required = $env{'course.'.$cdom.'_'.$cnum.'.internal.releaserequired'};
15626:                 if ($curr_reqd_hash{'internal.releaserequired'} ne $required) {
15627:                     &Apache::lonnet::appenv({'course.'.$cdom.'_'.$cnum.'.internal.releaserequired' =>
15628:                                              $curr_reqd_hash{'internal.releaserequired'}});
15629:                     my ($switchserver,$switchwarning) =
15630:                         &check_release_required($loncaparev,$cdom.'_'.$cnum,$env{'request.role'},
15631:                                                 $curr_reqd_hash{'internal.releaserequired'});
15632:                     if ($switchwarning ne '' || $switchserver ne '') {
15633:                         return ('switch',$switchwarning,$switchserver);
15634:                     }
15635:                 }
15636:             }
15637:             return ('update');
15638:         }
15639:     }
15640:     return ();
15641: }
15642: 
15643: sub update_content_constraints {
15644:     my ($cdom,$cnum,$chome,$cid) = @_;
15645:     my %curr_reqd_hash = &Apache::lonnet::userenvironment($cdom,$cnum,'internal.releaserequired');
15646:     my ($reqdmajor,$reqdminor) = split(/\./,$curr_reqd_hash{'internal.releaserequired'});
15647:     my %checkresponsetypes;
15648:     foreach my $key (keys(%Apache::lonnet::needsrelease)) {
15649:         my ($item,$name,$value) = split(/:/,$key);
15650:         if ($item eq 'resourcetag') {
15651:             if ($name eq 'responsetype') {
15652:                 $checkresponsetypes{$value} = $Apache::lonnet::needsrelease{$key}
15653:             }
15654:         }
15655:     }
15656:     my $navmap = Apache::lonnavmaps::navmap->new();
15657:     if (defined($navmap)) {
15658:         my %allresponses;
15659:         foreach my $res ($navmap->retrieveResources(undef,sub { $_[0]->is_problem() },1,0)) {
15660:             my %responses = $res->responseTypes();
15661:             foreach my $key (keys(%responses)) {
15662:                 next unless(exists($checkresponsetypes{$key}));
15663:                 $allresponses{$key} += $responses{$key};
15664:             }
15665:         }
15666:         foreach my $key (keys(%allresponses)) {
15667:             my ($major,$minor) = split(/\./,$checkresponsetypes{$key});
15668:             if (($major > $reqdmajor) || ($major == $reqdmajor && $minor > $reqdminor)) {
15669:                 ($reqdmajor,$reqdminor) = ($major,$minor);
15670:             }
15671:         }
15672:         undef($navmap);
15673:     }
15674:     unless (($reqdmajor eq '') && ($reqdminor eq '')) {
15675:         &Apache::lonnet::update_released_required($reqdmajor.'.'.$reqdminor,$cdom,$cnum,$chome,$cid);
15676:     }
15677:     return;
15678: }
15679: 
15680: sub allmaps_incourse {
15681:     my ($cdom,$cnum,$chome,$cid) = @_;
15682:     if ($cdom eq '' || $cnum eq '' || $chome eq '' || $cid eq '') {
15683:         $cid = $env{'request.course.id'};
15684:         $cdom = $env{'course.'.$cid.'.domain'};
15685:         $cnum = $env{'course.'.$cid.'.num'};
15686:         $chome = $env{'course.'.$cid.'.home'};
15687:     }
15688:     my %allmaps = ();
15689:     my $lastchange =
15690:         &Apache::lonnet::get_coursechange($cdom,$cnum);
15691:     if ($lastchange > $env{'request.course.tied'}) {
15692:         my ($furl,$ferr) = &Apache::lonuserstate::readmap("$cdom/$cnum");
15693:         unless ($ferr) {
15694:             &update_content_constraints($cdom,$cnum,$chome,$cid);
15695:         }
15696:     }
15697:     my $navmap = Apache::lonnavmaps::navmap->new();
15698:     if (defined($navmap)) {
15699:         foreach my $res ($navmap->retrieveResources(undef,sub { $_[0]->is_map() },1,0,1)) {
15700:             $allmaps{$res->src()} = 1;
15701:         }
15702:     }
15703:     return \%allmaps;
15704: }
15705: 
15706: sub parse_supplemental_title {
15707:     my ($title) = @_;
15708: 
15709:     my ($foldertitle,$renametitle);
15710:     if ($title =~ /&amp;&amp;&amp;/) {
15711:         $title = &HTML::Entites::decode($title);
15712:     }
15713:     if ($title =~ m/^(\d+)___&&&___($match_username)___&&&___($match_domain)___&&&___(.*)$/) {
15714:         $renametitle=$4;
15715:         my ($time,$uname,$udom) = ($1,$2,$3);
15716:         $foldertitle=&Apache::lontexconvert::msgtexconverted($4);
15717:         my $name =  &plainname($uname,$udom);
15718:         $name = &HTML::Entities::encode($name,'"<>&\'');
15719:         $renametitle = &HTML::Entities::encode($renametitle,'"<>&\'');
15720:         $title='<i>'.&Apache::lonlocal::locallocaltime($time).'</i> '.
15721:             $name.': <br />'.$foldertitle;
15722:     }
15723:     if (wantarray) {
15724:         return ($title,$foldertitle,$renametitle);
15725:     }
15726:     return $title;
15727: }
15728: 
15729: sub recurse_supplemental {
15730:     my ($cnum,$cdom,$suppmap,$numfiles,$errors) = @_;
15731:     if ($suppmap) {
15732:         my ($errtext,$fatal) = &LONCAPA::map::mapread('/uploaded/'.$cdom.'/'.$cnum.'/'.$suppmap);
15733:         if ($fatal) {
15734:             $errors ++;
15735:         } else {
15736:             if ($#LONCAPA::map::resources > 0) {
15737:                 foreach my $res (@LONCAPA::map::resources) {
15738:                     my ($title,$src,$ext,$type,$status)=split(/\:/,$res);
15739:                     if (($src ne '') && ($status eq 'res')) {
15740:                         if ($src =~ m{^\Q/uploaded/$cdom/$cnum/\E(supplemental_\d+\.sequence)$}) {
15741:                             ($numfiles,$errors) = &recurse_supplemental($cnum,$cdom,$1,$numfiles,$errors);
15742:                         } else {
15743:                             $numfiles ++;
15744:                         }
15745:                     }
15746:                 }
15747:             }
15748:         }
15749:     }
15750:     return ($numfiles,$errors);
15751: }
15752: 
15753: sub symb_to_docspath {
15754:     my ($symb) = @_;
15755:     return unless ($symb);
15756:     my ($mapurl,$id,$resurl) = &Apache::lonnet::decode_symb($symb);
15757:     if ($resurl=~/\.(sequence|page)$/) {
15758:         $mapurl=$resurl;
15759:     } elsif ($resurl eq 'adm/navmaps') {
15760:         $mapurl=$env{'course.'.$env{'request.course.id'}.'.url'};
15761:     }
15762:     my $mapresobj;
15763:     my $navmap = Apache::lonnavmaps::navmap->new();
15764:     if (ref($navmap)) {
15765:         $mapresobj = $navmap->getResourceByUrl($mapurl);
15766:     }
15767:     $mapurl=~s{^.*/([^/]+)\.(\w+)$}{$1};
15768:     my $type=$2;
15769:     my $path;
15770:     if (ref($mapresobj)) {
15771:         my $pcslist = $mapresobj->map_hierarchy();
15772:         if ($pcslist ne '') {
15773:             foreach my $pc (split(/,/,$pcslist)) {
15774:                 next if ($pc <= 1);
15775:                 my $res = $navmap->getByMapPc($pc);
15776:                 if (ref($res)) {
15777:                     my $thisurl = $res->src();
15778:                     $thisurl=~s{^.*/([^/]+)\.\w+$}{$1};
15779:                     my $thistitle = $res->title();
15780:                     $path .= '&'.
15781:                              &Apache::lonhtmlcommon::entity_encode($thisurl).'&'.
15782:                              &escape($thistitle).
15783:                              ':'.$res->randompick().
15784:                              ':'.$res->randomout().
15785:                              ':'.$res->encrypted().
15786:                              ':'.$res->randomorder().
15787:                              ':'.$res->is_page();
15788:                 }
15789:             }
15790:         }
15791:         $path =~ s/^\&//;
15792:         my $maptitle = $mapresobj->title();
15793:         if ($mapurl eq 'default') {
15794:             $maptitle = 'Main Content';
15795:         }
15796:         $path .= (($path ne '')? '&' : '').
15797:                  &Apache::lonhtmlcommon::entity_encode($mapurl).'&'.
15798:                  &escape($maptitle).
15799:                  ':'.$mapresobj->randompick().
15800:                  ':'.$mapresobj->randomout().
15801:                  ':'.$mapresobj->encrypted().
15802:                  ':'.$mapresobj->randomorder().
15803:                  ':'.$mapresobj->is_page();
15804:     } else {
15805:         my $maptitle = &Apache::lonnet::gettitle($mapurl);
15806:         my $ispage = (($type eq 'page')? 1 : '');
15807:         if ($mapurl eq 'default') {
15808:             $maptitle = 'Main Content';
15809:         }
15810:         $path = &Apache::lonhtmlcommon::entity_encode($mapurl).'&'.
15811:                 &escape($maptitle).':::::'.$ispage;
15812:     }
15813:     unless ($mapurl eq 'default') {
15814:         $path = 'default&'.
15815:                 &escape('Main Content').
15816:                 ':::::&'.$path;
15817:     }
15818:     return $path;
15819: }
15820: 
15821: sub captcha_display {
15822:     my ($context,$lonhost) = @_;
15823:     my ($output,$error);
15824:     my ($captcha,$pubkey,$privkey) = &get_captcha_config($context,$lonhost);
15825:     if ($captcha eq 'original') {
15826:         $output = &create_captcha();
15827:         unless ($output) {
15828:             $error = 'captcha';
15829:         }
15830:     } elsif ($captcha eq 'recaptcha') {
15831:         $output = &create_recaptcha($pubkey);
15832:         unless ($output) {
15833:             $error = 'recaptcha';
15834:         }
15835:     }
15836:     return ($output,$error,$captcha);
15837: }
15838: 
15839: sub captcha_response {
15840:     my ($context,$lonhost) = @_;
15841:     my ($captcha_chk,$captcha_error);
15842:     my ($captcha,$pubkey,$privkey) = &get_captcha_config($context,$lonhost);
15843:     if ($captcha eq 'original') {
15844:         ($captcha_chk,$captcha_error) = &check_captcha();
15845:     } elsif ($captcha eq 'recaptcha') {
15846:         $captcha_chk = &check_recaptcha($privkey);
15847:     } else {
15848:         $captcha_chk = 1;
15849:     }
15850:     return ($captcha_chk,$captcha_error);
15851: }
15852: 
15853: sub get_captcha_config {
15854:     my ($context,$lonhost) = @_;
15855:     my ($captcha,$pubkey,$privkey,$hashtocheck);
15856:     my $hostname = &Apache::lonnet::hostname($lonhost);
15857:     my $serverhomeID = &Apache::lonnet::get_server_homeID($hostname);
15858:     my $serverhomedom = &Apache::lonnet::host_domain($serverhomeID);
15859:     if ($context eq 'usercreation') {
15860:         my %domconfig = &Apache::lonnet::get_dom('configuration',[$context],$serverhomedom);
15861:         if (ref($domconfig{$context}) eq 'HASH') {
15862:             $hashtocheck = $domconfig{$context}{'cancreate'};
15863:             if (ref($hashtocheck) eq 'HASH') {
15864:                 if ($hashtocheck->{'captcha'} eq 'recaptcha') {
15865:                     if (ref($hashtocheck->{'recaptchakeys'}) eq 'HASH') {
15866:                         $pubkey = $hashtocheck->{'recaptchakeys'}{'public'};
15867:                         $privkey = $hashtocheck->{'recaptchakeys'}{'private'};
15868:                     }
15869:                     if ($privkey && $pubkey) {
15870:                         $captcha = 'recaptcha';
15871:                     } else {
15872:                         $captcha = 'original';
15873:                     }
15874:                 } elsif ($hashtocheck->{'captcha'} ne 'notused') {
15875:                     $captcha = 'original';
15876:                 }
15877:             }
15878:         } else {
15879:             $captcha = 'captcha';
15880:         }
15881:     } elsif ($context eq 'login') {
15882:         my %domconfhash = &Apache::loncommon::get_domainconf($serverhomedom);
15883:         if ($domconfhash{$serverhomedom.'.login.captcha'} eq 'recaptcha') {
15884:             $pubkey = $domconfhash{$serverhomedom.'.login.recaptchakeys_public'};
15885:             $privkey = $domconfhash{$serverhomedom.'.login.recaptchakeys_private'};
15886:             if ($privkey && $pubkey) {
15887:                 $captcha = 'recaptcha';
15888:             } else {
15889:                 $captcha = 'original';
15890:             }
15891:         } elsif ($domconfhash{$serverhomedom.'.login.captcha'} eq 'original') {
15892:             $captcha = 'original';
15893:         }
15894:     }
15895:     return ($captcha,$pubkey,$privkey);
15896: }
15897: 
15898: sub create_captcha {
15899:     my %captcha_params = &captcha_settings();
15900:     my ($output,$maxtries,$tries) = ('',10,0);
15901:     while ($tries < $maxtries) {
15902:         $tries ++;
15903:         my $captcha = Authen::Captcha->new (
15904:                                            output_folder => $captcha_params{'output_dir'},
15905:                                            data_folder   => $captcha_params{'db_dir'},
15906:                                           );
15907:         my $md5sum = $captcha->generate_code($captcha_params{'numchars'});
15908: 
15909:         if (-e $Apache::lonnet::perlvar{'lonCaptchaDir'}.'/'.$md5sum.'.png') {
15910:             $output = '<input type="hidden" name="crypt" value="'.$md5sum.'" />'."\n".
15911:                       &mt('Type in the letters/numbers shown below').'&nbsp;'.
15912:                       '<input type="text" size="5" name="code" value="" autocomplete="off" />'.
15913:                       '<br />'.
15914:                       '<img src="'.$captcha_params{'www_output_dir'}.'/'.$md5sum.'.png" alt="captcha" />';
15915:             last;
15916:         }
15917:     }
15918:     return $output;
15919: }
15920: 
15921: sub captcha_settings {
15922:     my %captcha_params = (
15923:                            output_dir     => $Apache::lonnet::perlvar{'lonCaptchaDir'},
15924:                            www_output_dir => "/captchaspool",
15925:                            db_dir         => $Apache::lonnet::perlvar{'lonCaptchaDb'},
15926:                            numchars       => '5',
15927:                          );
15928:     return %captcha_params;
15929: }
15930: 
15931: sub check_captcha {
15932:     my ($captcha_chk,$captcha_error);
15933:     my $code = $env{'form.code'};
15934:     my $md5sum = $env{'form.crypt'};
15935:     my %captcha_params = &captcha_settings();
15936:     my $captcha = Authen::Captcha->new(
15937:                       output_folder => $captcha_params{'output_dir'},
15938:                       data_folder   => $captcha_params{'db_dir'},
15939:                   );
15940:     $captcha_chk = $captcha->check_code($code,$md5sum);
15941:     my %captcha_hash = (
15942:                         0       => 'Code not checked (file error)',
15943:                        -1      => 'Failed: code expired',
15944:                        -2      => 'Failed: invalid code (not in database)',
15945:                        -3      => 'Failed: invalid code (code does not match crypt)',
15946:     );
15947:     if ($captcha_chk != 1) {
15948:         $captcha_error = $captcha_hash{$captcha_chk}
15949:     }
15950:     return ($captcha_chk,$captcha_error);
15951: }
15952: 
15953: sub create_recaptcha {
15954:     my ($pubkey) = @_;
15955:     my $use_ssl;
15956:     if ($ENV{'SERVER_PORT'} == 443) {
15957:         $use_ssl = 1;
15958:     }
15959:     my $captcha = Captcha::reCAPTCHA->new;
15960:     return $captcha->get_options_setter({theme => 'white'})."\n".
15961:            $captcha->get_html($pubkey,undef,$use_ssl).
15962:            &mt('If either word is hard to read, [_1] will replace them.',
15963:                '<img src="/res/adm/pages/refresh.gif" alt="reCAPTCHA refresh" />').
15964:            '<br /><br />';
15965: }
15966: 
15967: sub check_recaptcha {
15968:     my ($privkey) = @_;
15969:     my $captcha_chk;
15970:     my $captcha = Captcha::reCAPTCHA->new;
15971:     my $captcha_result =
15972:         $captcha->check_answer(
15973:                                 $privkey,
15974:                                 $ENV{'REMOTE_ADDR'},
15975:                                 $env{'form.recaptcha_challenge_field'},
15976:                                 $env{'form.recaptcha_response_field'},
15977:                               );
15978:     if ($captcha_result->{is_valid}) {
15979:         $captcha_chk = 1;
15980:     }
15981:     return $captcha_chk;
15982: }
15983: 
15984: sub emailusername_info {
15985:     my @fields = ('firstname','lastname','institution','web','location','officialemail');
15986:     my %titles = &Apache::lonlocal::texthash (
15987:                      lastname      => 'Last Name',
15988:                      firstname     => 'First Name',
15989:                      institution   => 'School/college/university',
15990:                      location      => "School's city, state/province, country",
15991:                      web           => "School's web address",
15992:                      officialemail => 'E-mail address at institution (if different)',
15993:                  );
15994:     return (\@fields,\%titles);
15995: }
15996: 
15997: sub cleanup_html {
15998:     my ($incoming) = @_;
15999:     my $outgoing;
16000:     if ($incoming ne '') {
16001:         $outgoing = $incoming;
16002:         $outgoing =~ s/;/&#059;/g;
16003:         $outgoing =~ s/\#/&#035;/g;
16004:         $outgoing =~ s/\&/&#038;/g;
16005:         $outgoing =~ s/</&#060;/g;
16006:         $outgoing =~ s/>/&#062;/g;
16007:         $outgoing =~ s/\(/&#040/g;
16008:         $outgoing =~ s/\)/&#041;/g;
16009:         $outgoing =~ s/"/&#034;/g;
16010:         $outgoing =~ s/'/&#039;/g;
16011:         $outgoing =~ s/\$/&#036;/g;
16012:         $outgoing =~ s{/}{&#047;}g;
16013:         $outgoing =~ s/=/&#061;/g;
16014:         $outgoing =~ s/\\/&#092;/g
16015:     }
16016:     return $outgoing;
16017: }
16018: 
16019: # Checks for critical messages and returns a redirect url if one exists.
16020: # $interval indicates how often to check for messages.
16021: sub critical_redirect {
16022:     my ($interval) = @_;
16023:     if ((time-$env{'user.criticalcheck.time'})>$interval) {
16024:         my @what=&Apache::lonnet::dump('critical', $env{'user.domain'},
16025:                                         $env{'user.name'});
16026:         &Apache::lonnet::appenv({'user.criticalcheck.time'=>time});
16027:         my $redirecturl;
16028:         if ($what[0]) {
16029:             if (($what[0] ne 'con_lost') && ($what[0]!~/^error\:/)) {
16030:                 $redirecturl='/adm/email?critical=display';
16031:                 my $url=&Apache::lonnet::absolute_url().$redirecturl;
16032:                 return (1, $url);
16033:             }
16034:         }
16035:     }
16036:     return ();
16037: }
16038: 
16039: # Use:
16040: #   my $answer=reply("encrypt:passwd:$udom:$uname:$upass",$tryserver);
16041: #
16042: ##################################################
16043: #          password associated functions         #
16044: ##################################################
16045: sub des_keys {
16046:     # Make a new key for DES encryption.
16047:     # Each key has two parts which are returned separately.
16048:     # Please note:  Each key must be passed through the &hex function
16049:     # before it is output to the web browser.  The hex versions cannot
16050:     # be used to decrypt.
16051:     my @hexstr=('0','1','2','3','4','5','6','7',
16052:                 '8','9','a','b','c','d','e','f');
16053:     my $lkey='';
16054:     for (0..7) {
16055:         $lkey.=$hexstr[rand(15)];
16056:     }
16057:     my $ukey='';
16058:     for (0..7) {
16059:         $ukey.=$hexstr[rand(15)];
16060:     }
16061:     return ($lkey,$ukey);
16062: }
16063: 
16064: sub des_decrypt {
16065:     my ($key,$cyphertext) = @_;
16066:     my $keybin=pack("H16",$key);
16067:     my $cypher;
16068:     if ($Crypt::DES::VERSION>=2.03) {
16069:         $cypher=new Crypt::DES $keybin;
16070:     } else {
16071:         $cypher=new DES $keybin;
16072:     }
16073:     my $plaintext=
16074:         $cypher->decrypt(unpack("a8",pack("H16",substr($cyphertext,0,16))));
16075:     $plaintext.=
16076:         $cypher->decrypt(unpack("a8",pack("H16",substr($cyphertext,16,16))));
16077:     $plaintext=substr($plaintext,1,ord(substr($plaintext,0,1)) );
16078:     return $plaintext;
16079: }
16080: 
16081: 1;
16082: __END__;
16083: 

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